Here, we will discuss the solution to Javelin from AIO 2024.
N students participated in a javelin throwing event. A student is a current leader if they threw further than everyone before them. How many different current leaders were there during the competition?
We consider the students one at a time while storing the furthest distance that a student has thrown so far (we will call this value best_throw). There are two cases:
We can code this solution using a for loop and an if statement. Below you can see this solution written in Python and C++. I suggest trying to code the solution yourself and only look at our code after you finish or if you get stuck.
# Open the input and output files.
input_file = open("javelin.txt", "r")
output_file = open("javelout.txt", "w")
# Read the value of N and the distances from the input file.
N = int(input_file.readline().strip())
input_line = input_file.readline().strip()
D = list(map(int, input_line.split()))
# Compute the answer
answer = 0
best_throw = 0
for d in D:
if d > best_throw:
# Student i is the current winner
best_throw = d
answer += 1
# Write the answer to the output file.
output_file.write("%d\n" % (answer))
# Finally, close the input/output files.
input_file.close()
output_file.close()
#include <cstdio>
int N;
int D[200005];
int main(void) {
/* Open the input and output files. */
FILE *input_file = fopen("javelin.txt", "r");
FILE *output_file = fopen("javelout.txt", "w");
/* Read the value of N and the distances from the input file. */
fscanf(input_file, "%d", &N);
for (int i = 0; i < N; i++) {
fscanf(input_file, "%d", &D[i]);
}
// Compute the answer
int best_throw = 0;
int answer = 0;
for (int i = 0; i < N; i++) {
if (D[i] > best_throw) {
// Student i is the current winner
best_throw = D[i];
answer++;
}
}
/* Write the answer to the output file. */
fprintf(output_file, "%d\n", answer);
/* Finally, close the input/output files. */
fclose(input_file);
fclose(output_file);
}