This page brings together tasks from various district competitions for primary schools. Each task has a separate statement, input, output and examples, together with detailed instructions and a C++ solution that you can show once you have tried to solve it yourself. There is a quiz at the end of the page.
You can test tasks 13–30 on the site takprog.petlja.org (you need to log in). The tests there check the output exactly as in the original tasks, so for these tasks the output words are left in Serbian, with their meaning explained.
District computer science competition – 2016
The tasks are taken from the site of the Mathematical Society of Serbia, computer science competitions: dms.rs/informatika-osnovne-skole
Write a program PRODUCT that finds the largest product that can be obtained if a multiplication sign is put between two digits of a positive number N.
Input
Standard input contains the number N (100 ≤ N ≤ 999).
Output
On the only line of standard output print the largest product.
Example 1
Input
795
Output
665
Explanation
The splits of the number 795 are 7 · 95 = 665 and 79 · 5 = 395; the larger is 665.
Example 2
Input
100
Output
0
Explanation
The splits are 1 · 00 = 0 and 10 · 0 = 0.
Example 3
Input
105
Output
50
Explanation
The splits are 1 · 05 = 5 and 10 · 5 = 50.
Instructions and solution
Instructions — the idea of the solution
1. Two possible splits
A three-digit number abc can be split in two ways: a · bc and ab · c. The multiplication sign goes either after the first or after the second digit.
2. Separating the digits
Integer division and remainder give the parts of the number: n / 100 is the first digit, n % 100 the last two digits, n / 10 the first two digits, and n % 10 the last digit.
3. Comparison
We calculate both products and print the larger one (the function max). Zeros in the middle (e.g. 105) are not a problem: n % 100 is then just 5.
C++ solution
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
// Split 1: the first digit and the last two digits
int product1 = (n / 100) * (n % 100);
// Split 2: the first two digits and the last digit
int product2 = (n / 10) * (n % 10);
cout << max(product1, product2) << endl;
return 0;
}
Explanation: Since N always has three digits, there are only two splits, so no loops are needed.
Three programmers – A, B and C (in that order) entered a contest for choosing the winning video game. The jury gives each game two marks – a mark for design (the first mark) and a mark for functionality (the second mark). Write a program CONTEST that finds which programmer won first place.
The winner is chosen like this: for each game both marks are added up, and the programmer whose game has the largest sum wins. If several programmers have the same largest sum, the one who got the higher mark for design wins. If there is still a tie, the one who presented the game to the jury first wins (the order of presentation is A, B, C).
Input
Standard input contains, on one line, three pairs of natural numbers (none greater than 1000) separated by spaces. The first pair are the marks of the first programmer, the second pair the marks of the second, and the third pair the marks of the third programmer.
Output
Print one of the letters A, B or C, depending on which programmer won.
Example 1
Input
5 6 7 4 5 3
Output
B
Explanation
The sums are 11, 11 and 8. Programmers A and B have the same sum, but B has a higher mark for design (7 against 5).
Example 2
Input
14 18 17 7 18 7
Output
A
Explanation
The sums are 14 + 18 = 32, 17 + 7 = 24 and 18 + 7 = 25, so the winner is A. (In the original collection this input is given with the output B, which is an obvious mistake: by the rules A wins.)
Instructions and solution
Instructions — the idea of the solution
1. Sums and design marks
For each programmer we store the design mark and the sum of both marks. Two arrays of three elements each are enough.
2. Finding the winner
Assume that programmer A is in the lead. Then we check B and C in turn: a new programmer takes the lead only if they have a strictly larger sum, or the same sum and a strictly higher design mark.
3. Why this also handles the third condition
Since we change the leader only for a strictly better result, in a complete tie the earlier programmer stays in the lead – and that is exactly the one who presented the game first.
4. Printing
The index of the winner (0, 1 or 2) is turned into a letter with the expression (char)('A' + index).
C++ solution
#include <iostream>
using namespace std;
int main() {
int design[3], sum[3];
for (int i = 0; i < 3; i++) {
int functionality;
cin >> design[i] >> functionality;
sum[i] = design[i] + functionality;
}
int winner = 0; // programmer A is in the lead for now
for (int i = 1; i < 3; i++) {
if (sum[i] > sum[winner] ||
(sum[i] == sum[winner] && design[i] > design[winner])) {
winner = i;
}
}
cout << (char)('A' + winner) << endl;
return 0;
}
Explanation: The older solution checked three cases of sums by hand and did not cover ties on the design mark or on the order of presentation (for some inputs it printed nothing). Here all three criteria are covered by one comparison.
We say that a number is beautiful if all its digits are different from each other. Write a program BEAUTY that finds how many beautiful numbers there are in the given segment [m, n].
Input
The first line of standard input contains two whole numbers m and n separated by a space.
Constraints: 0 ≤ m ≤ n ≤ 10 000 000.
Output
Print to standard output one whole number – the number of beautiful numbers in the segment.
Example
Input
90 91
Output
2
Explanation
Both numbers, 90 and 91, have different digits.
Instructions and solution
Instructions — the idea of the solution
1. A helper function
We make a function beautiful(x) that returns true if all the digits of the number x are different.
2. Checking the digits
We take the digits with x % 10 and shorten the number with x /= 10. With the array seen[10] we remember which digits we have already met; if a digit appears a second time, the number is not beautiful.
3. The number 0
For x = 0 the loop must run at least once, so we use do { ... } while (x > 0). The number 0 has one digit, so it is beautiful.
4. Counting
With a for loop we go through all the numbers from m to n and count those for which the function returns true. For at most 10 million numbers, with at most 8 digits, this is fast enough.
C++ solution
#include <iostream>
using namespace std;
// Returns true if all the digits of x are different from each other
bool beautiful(int x) {
bool seen[10] = {false};
do {
int digit = x % 10;
if (seen[digit]) {
return false;
}
seen[digit] = true;
x /= 10;
} while (x > 0);
return true;
}
int main() {
int m, n;
cin >> m >> n;
int counter = 0;
for (int i = m; i <= n; i++) {
if (beautiful(i)) {
counter++;
}
}
cout << counter << endl;
return 0;
}
Explanation: The array seen is much simpler than comparing every digit with every other digit, because we check each digit only once.
District computer science competition – 2019
The tasks are taken from the site of the Mathematical Society of Serbia, computer science competitions: dms.rs/informatika-osnovne-skole
Five programmers spend one day at the company. For each of them we know the hour and minute of arrival and the hour and minute of departure. Write a program that finds whether they can hold a joint meeting (at which all of them must be present) and, if they can, the longest possible length of such a meeting (in hours and minutes).
Input
Each of the five lines of standard input contains four whole numbers separated by spaces: the hour and minute of arrival and the hour and minute of departure of one programmer.
Output
Print to standard output the length of the meeting, with the number of hours and the number of minutes separated by one space, or the word no if the meeting cannot be held.
The last arrival is at 12:33, and the first departure at 12:30, so they are never all at the company at the same time.
Instructions and solution
Instructions — the idea of the solution
1. All times in minutes
We convert the time into minutes from midnight: hour * 60 + minute. This way times are easy to compare and subtract.
2. The common interval
They are all at the company at the same time only when the last of them arrives, which is the moment max of all arrivals, and this lasts until the first of them leaves, i.e. min of all departures.
3. Checking and printing
If earliest departure − latest arrival is greater than zero, the meeting is possible. The length in hours is / 60, and in minutes % 60. Otherwise we print no.
C++ solution
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int latestArrival = 0; // latest arrival (in minutes from midnight)
int earliestDeparture = 24 * 60; // earliest departure
for (int i = 0; i < 5; i++) {
int sd, md, so, mo;
cin >> sd >> md >> so >> mo;
latestArrival = max(latestArrival, sd * 60 + md);
earliestDeparture = min(earliestDeparture, so * 60 + mo);
}
int duration = earliestDeparture - latestArrival;
if (duration > 0) {
cout << duration / 60 << " " << duration % 60 << endl;
} else {
cout << "no" << endl;
}
return 0;
}
Explanation: If the last arrival is at the same time as the first departure, the length is 0 and we do not count such a meeting as possible.
A transport company runs ship lines between its home port and several (at most 5) other port cities. Exactly one ship runs on each line: it leaves the home port, takes passengers to its destination, and then brings other passengers back to the home port.
All the ships leave the home port at the same time, and for each of them we know how many days it needs to travel and come back to the home port (assume that each trip and return is completed within one calendar year). Write a program that finds after how many days all the ships will meet again in the home port. Note that, although a solution always exists, it can be a very large number.
Input
The number of lines (at most 5) is entered from standard input, and then, for each line, the number of days the ship needs to travel and come back.
Output
Print to standard output the required number of days.
Example
Input
3
15
24
60
Output
120
Explanation
The ships are together in the port after LCM(15, 24, 60) = 120 days.
Instructions and solution
Instructions — the idea of the solution
1. What is asked
A ship with a round trip of t days is in the port on days t, 2t, 3t, .... All the ships are together in the port on the first day that is divisible by all the trip lengths – that is their least common multiple (LCM).
2. LCM using the GCD
For two numbers, LCM(a, b) = a / GCD(a, b) * b. We calculate the GCD with Euclid's algorithm: while b != 0, we replace (a, b) with the pair (b, a % b).
3. More numbers
We calculate the LCM of several numbers step by step: we start from 1 and “build” each number read into the result so far.
4. Data type
The result can be much larger than the largest input number (e.g. for numbers around 360 and up to five ships it goes over a billion), so we use long long. We divide before multiplying to keep the intermediate result as small as possible.
C++ solution
#include <iostream>
using namespace std;
long long gcd(long long a, long long b) {
while (b != 0) {
long long remainder = a % b;
a = b;
b = remainder;
}
return a;
}
int main() {
int n;
cin >> n;
long long lcm = 1;
for (int i = 0; i < n; i++) {
long long days;
cin >> days;
lcm = lcm / gcd(lcm, days) * days; // LCM(lcm, days)
}
cout << lcm << endl;
return 0;
}
Explanation: For the example: LCM(1, 15) = 15, LCM(15, 24) = 120, LCM(120, 60) = 120.
Write a program that calculates and prints the quotient of the natural numbers m and n (less than a million) with the given number of decimal places k (1 ≤ k ≤ 1000). Do not round the result – just cut off the decimals after the last required one. Show the result with a decimal comma (not a decimal point), as is usual in Serbia.
Input
The numbers k, m and n are read from standard input in that order (each on a separate line).
Output
Print the quotient m / n with exactly k decimal places, with a decimal comma.
Example 1
Input
20
1
7
Output
0,14285714285714285714
Example 2
Input
7
1
2
Output
0,5000000
Instructions and solution
Instructions — the idea of the solution
1. Why not real numbers
The type double stores about 15–16 digits, but up to 1000 decimal places are required. That is why we calculate the decimals by “long division” – digit by digit, with whole numbers only.
2. The whole-number part
We print m / n (integer division), and then the comma. What is left is the remainder remainder = m % n.
3. Each next decimal place
We multiply the remainder by 10 (like when we “bring down a zero”). The next decimal is remainder / n, and the new remainder remainder % n. We repeat this k times.
4. Example
For 1 / 7: remainder 1 → 10 : 7 = 1 (remainder 3) → 30 : 7 = 4 (remainder 2) → 20 : 7 = 2 (remainder 6) → ... so we get 0,142857...
C++ solution
#include <iostream>
using namespace std;
int main() {
int k, m, n;
cin >> k >> m >> n;
cout << m / n << ","; // whole-number part of the quotient
int remainder = m % n;
for (int i = 0; i < k; i++) {
remainder *= 10;
cout << remainder / n; // next decimal place
remainder %= n;
}
cout << endl;
return 0;
}
Explanation: Cutting off (not rounding) happens “by itself”, because we print exactly k digits and do not look at what would come next.
The police, trying to catch a hacker, managed to get hold of some messages the hackers exchange. Each message is one number. Encryption experts concluded that the number is a sequence of codes for accessing some computers. Each code contains only the digits from 0 to 5, the end of a code is marked by the digit 6 or by the end of the number, and the digits 7, 8 and 9 are used for masking and should be ignored. This way hackers can send several codes in one number, but the number 0 cannot be a code.
Write a program that, for the number K entered, prints the codes hidden in it (in any order) and how many codes there are in that number.
Input
The number K is read from standard input.
Output
On the first line print the codes (the words The codes are:, followed by the codes separated by spaces), and on the second line the number of codes sent.
Example
Input
23675
Output
The codes are: 5 23
2 codes were sent
Explanation
The digits 2 and 3 form one code, the digit 6 ends it, the digit 7 is ignored, and the digit 5 is the second code.
Instructions and solution
Instructions — the idea of the solution
1. The number as a string
We read the number K as a string (string) and go through its characters one by one.
2. Rules for each digit
We add the digits 0–5 to the current code; the digit 6 ends the code; we skip the digits 7, 8 and 9.
3. The end of the number
The end of the number also ends a code. The easiest way is to add one more six to the string, so that the last code ends in the same way as the others.
4. A code must make sense
An empty code (e.g. two sixes in a row) is not counted. A code made only of zeros is the number 0, which cannot be a code, so it is not counted either.
5. Printing
We store the codes in a vector. Since the order does not matter, we print them from the last to the first so that the output matches the example (5 23).
C++ solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string k;
cin >> k;
vector<string> codes;
string current = "";
for (char c : k + "6") { // an extra six closes the last code
if (c >= '0' && c <= '5') {
current += c;
} else if (c == '6') {
// the code ends; the number 0 cannot be a code
bool onlyZeros = true;
for (char x : current) {
if (x != '0') onlyZeros = false;
}
if (!current.empty() && !onlyZeros) {
codes.push_back(current);
}
current = "";
}
// the digits 7, 8 and 9 are ignored
}
cout << "The codes are:";
for (int i = (int)codes.size() - 1; i >= 0; i--) { // the order does not matter
cout << " " << codes[i];
}
cout << endl;
cout << codes.size() << " codes were sent" << endl;
return 0;
}
Explanation: Assumption: a code that starts with zero (e.g. 05) is printed as it is written. The task does not say how such cases are treated.
Other district competitions – combined
Tasks from the district competitions in 2009 and 2018 (the link to the site dms.rs is given at the top of the page).
At the big P.O.S.O.T. computer games tournament there are team competitions in which two teams play against each other. In the first round, three teams labelled with the numbers 1, 2 and 3 played in group O.S. The first game was played by teams 1 and 2, and their points were recorded (for team 1 as R11, and for team 2 as R12). In the second game teams 1 and 3 played (points R21 and R23), and then teams 2 and 3 (points R32 and R33).
A game is won by the team with more points. If the teams have the same number of points in a game, neither team gets a win. After all three games the winner of the round is decided: it is the team with the largest number of wins. If two teams have the same number of wins, which is larger than the number of wins of the third team, or if all three teams are level, extra games are played, marked DP (from the Serbian dodatne partije, extra games).
Write a program GROUPOS that reads the values R11, R12, R21, R23, R32 and R33 in order, and then finds and prints which team is the winner, or prints that extra games are played (DP).
Input
The numbers R11, R12, R21, R23, R32 and R33 are entered on one line, in that order.
Output
Print the label of the winning team (1, 2 or 3) or DP.
Example 1
Input
56 254 104 198 156 148
Output
2
Explanation
R11 = 56, R12 = 254, R21 = 104, R23 = 198, R32 = 156, R33 = 148. Team 2 won twice, team 3 once, team 1 never.
Example 2
Input
156 154 104 104 256 137
Output
DP
Explanation
Team 1 won the first game, the second game was a draw, and team 2 won the third. Teams 1 and 2 have one win each, so DP is played.
Instructions and solution
Instructions — the idea of the solution
1. Win counters
For each team we introduce a win counter and set it to 0.
2. Three games
For each game we compare the points of the two teams: more points means we increase the winner's counter by 1, and in a tie we do nothing.
3. The winner
If a team has strictly more wins than both the others, it is the winner. In all other cases (two teams level at the top, or all three level) we print DP.
C++ solution
#include <iostream>
using namespace std;
int main() {
int R11, R12, R21, R23, R32, R33;
cin >> R11 >> R12 >> R21 >> R23 >> R32 >> R33;
int p1 = 0, p2 = 0, p3 = 0; // number of wins of each team
// game 1: teams 1 and 2
if (R11 > R12) p1++;
else if (R11 < R12) p2++;
// game 2: teams 1 and 3
if (R21 > R23) p1++;
else if (R21 < R23) p3++;
// game 3: teams 2 and 3
if (R32 > R33) p2++;
else if (R32 < R33) p3++;
if (p1 > p2 && p1 > p3) cout << 1 << endl;
else if (p2 > p1 && p2 > p3) cout << 2 << endl;
else if (p3 > p1 && p3 > p2) cout << 3 << endl;
else cout << "DP" << endl;
return 0;
}
Explanation: The older solution was correct; here it has only been tidied up and comments have been added.
In one of the games Žarko plays at the P.O.S.O.T. tournament, the character he controls has to get through a room with sensors. The sensors are placed on the floor of the room in N parallel lines across the width of the room. The first line, which is closest to Žarko's character, has only one sensor, exactly in the middle of the room. The second line has three sensors, with the middle one exactly behind the sensor in the first line. The third line has 5 sensors, with the middle three exactly behind the sensors in the second line, and the other two one on each side.
Each next line has two more sensors, one added on the left and one on the right compared with the previous line. The distance between two neighbouring sensors in each line is the same and is R centimetres. Sensors placed this way form a triangle. The room is large enough for all the planned sensors.
Žarko's character in the game must go straight through the middle of the room to the other side, and it will activate all the sensors it passes over. If Žarko knows that his character is S centimetres wide, he needs to work out how many sensors his character will activate. Write a program SENSORS that finds the number of activated sensors for the values N, R and S entered.
Figure 1: District 2009: the task “Sensors”
Input
The number of lines N, the distance between sensors R and the width of the character S are entered on one line (R and S are real numbers).
Output
Print the number of activated sensors.
Example
Input
5 1.1 5.4
Output
19
Explanation
The lines have 1, 3, 5, 7 and 9 sensors, but a character 5.4 cm wide covers only the sensors at a distance of at most 2.7 cm from the middle, which are the two on each side (at 1.1 and 2.2 cm). So: 1 + 3 + 5 + 5 + 5 = 19.
Instructions and solution
Instructions — the idea of the solution
1. Which sensors are in a line
Let the middle of the room be at zero. In the line with number i (starting from 0) the sensors are at distances 0, ±R, ±2R, ..., ±i·R from the middle, so there are 2i + 1 sensors in it.
2. What the character covers
A character of width S covers the part of the floor from −S/2 to S/2. A sensor at distance k·R is activated if k·R ≤ S/2, i.e. 2·k·R ≤ S.
3. The farthest activated sensor
We find the largest k for which 2·k·R ≤ S (with a loop: we increase k while the condition holds). Sensors farther away are never activated, however many lines there are.
4. Sum over the lines
In line i, 2·min(i, k) + 1 sensors are activated. We add this up for i from 0 to N − 1.
5. Real numbers
Comparing real numbers can go wrong because of rounding, so we add a small extra 1e-9 to S. The assumption is that a sensor the character only touches with its edge is counted as activated.
C++ solution
#include <iostream>
using namespace std;
int main() {
int n;
double r, s;
cin >> n >> r >> s;
// How many sensors on each side of the middle are activated (at most):
// the sensor in the k-th place from the middle is k*r away from the middle,
// so a character of width s touches it if k*r <= s/2.
int k = 0;
while ((k + 1) * 2 * r <= s + 1e-9) {
k++;
}
int total = 0;
for (int i = 0; i < n; i++) { // i = number of sensors to the left of the middle in this line
int on_each_side = (i < k) ? i : k;
total += 2 * on_each_side + 1;
}
cout << total << endl;
return 0;
}
Explanation: Check on the example: R = 1.1, S = 5.4 gives k = 2 (because 2·2·1.1 = 4.4 ≤ 5.4, and 2·3·1.1 = 6.6 > 5.4), so the lines have 1, 3, 5, 5, 5 sensors.
The sum of the interior angles of every triangle is 180 degrees. A triangle is acute if all three of its angles are acute (less than 90 degrees), right-angled if one of its angles is a right angle (equal to 90 degrees), and obtuse if one of its angles is obtuse (greater than 90 degrees). Write a program that reads the sizes of two angles of a triangle in degrees (whole numbers, each on a separate line), decides whether the triangle is acute, right-angled or obtuse, and prints the corresponding text.
Input
The whole numbers – the sizes of two angles of the triangle in degrees – are entered on two lines.
Output
Print one of the words acute, right or obtuse (as in the examples).
Example 1
Input
30
60
Output
right
Explanation
The third angle is 180 − 30 − 60 = 90.
Example 2
Input
18
18
Output
obtuse
Explanation
The third angle is 180 − 18 − 18 = 144.
Example 3
Input
75
60
Output
acute
Explanation
The third angle is 45, so all three angles are acute.
Instructions and solution
Instructions — the idea of the solution
1. The third angle
The sum of the angles is 180°, so the third angle is 180 − a − b.
2. The order of the checks
First we check whether some angle is equal to 90° (right-angled). Then whether some angle is greater than 90° (obtuse). If neither holds, the triangle is acute.
3. Be careful
We do not do the check only for the angles entered – the third angle can also be right or obtuse (examples 1 and 2).
C++ solution
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int c = 180 - a - b; // the third angle
if (a == 90 || b == 90 || c == 90) {
cout << "right" << endl;
} else if (a > 90 || b > 90 || c > 90) {
cout << "obtuse" << endl;
} else {
cout << "acute" << endl;
}
return 0;
}
Explanation: A triangle cannot have two angles that are not acute, so the order of the checks does not matter, but checking all three angles is required.
Mirko is a young programmer who is trying to program a game of noughts and crosses (tic-tac-toe). He is close to finishing, but he needs a little help. He came up with the idea that the user chooses with the mouse the square into which their symbol will be written. The playing field consists of 9 squares (arranged in three rows and three columns) and each square is 100 by 100 pixels (the field is 300 by 300 pixels).
We know the position of the pixel that was clicked with the mouse. We need to find the number of the square that contains that pixel. The position of the pixel is given by the numbers (coordinates) of that pixel horizontally and vertically, counting from the bottom left corner of the field (the pixels are numbered from 1 to 300). The squares are numbered from 1 to 9, row by row, starting from the bottom left corner of the field upwards, as shown in the picture.
Figure 2: Numbering of the squares in the task Noughts and crosses
Input
Two whole numbers (from 1 to 300) are entered on one line: the horizontal coordinate of the pixel and the vertical coordinate.
Output
Print the number of the square (from 1 to 9) that contains that pixel.
Example 1
Input
1 1
Output
1
Example 2
Input
120 280
Output
8
Example 3
Input
100 201
Output
7
Example 4
Input
101 200
Output
5
Instructions and solution
Instructions — the idea of the solution
1. Column and row
Each square has a side of 100 pixels. Pixels 1–100 are in the first column, 101–200 in the second, 201–300 in the third. Since pixels are numbered from 1, we subtract 1 from the coordinate: column = (x − 1) / 100 gives 0, 1 or 2.
2. Why the subtraction
Without the subtraction, pixel 100 would give 100 / 100 = 1, i.e. the wrong column. With the subtraction it is (100 − 1) / 100 = 0, which is correct.
3. The same for the row
row = (y − 1) / 100, where rows are counted from the bottom up.
4. The number of the square
Before the square in a given row there are row full rows of 3 squares each, so the required number is row * 3 + column + 1.
C++ solution
#include <iostream>
using namespace std;
int main() {
int x, y;
cin >> x >> y;
int column = (x - 1) / 100; // 0, 1 or 2 (from left to right)
int row = (y - 1) / 100; // 0, 1 or 2 (from the bottom up)
cout << row * 3 + column + 1 << endl;
return 0;
}
Explanation: The older instructions wrongly said to divide by 30; the correct thing is to divide by 100 (the side of a square), after subtracting 1 from the coordinate. Check: the pixel (100, 201) gives column 0 and row 2, so square 7.
At the big P.O.S.O.T. computer games tournament Žarko played four games. After the games he decided that it was easier for him to follow the change in score between two games than the exact number of points. So he remembered that:
in the second game he had exactly 1042 points more than in the first,
in the third game he had as many as in the first and second together,
in the fourth game he had half as many as in the third.
After the end he knew the exact number of points he had scored in the fourth game. Write a program ZARKO that, for the number of points C scored in the fourth game, calculates how many points Žarko scored in the first game.
Input
The number C – the number of points in the fourth game – is read from standard input.
Output
Print the number of points in the first game.
Example
Input
2845
Output
2324
Explanation
First game: 2324, second: 3366, third: 5690, fourth: 2845.
Instructions and solution
Instructions — the idea of the solution
1. Name the unknown
Let p be the number of points in the first game.
2. The other games in terms of p
Second: p + 1042. Third: p + (p + 1042) = 2p + 1042. Fourth: (2p + 1042) / 2 = p + 521.
3. The solution
We got C = p + 521, i.e. p = C − 521. The program reads C and prints C − 521.
C++ solution
#include <iostream>
using namespace std;
int main() {
int c;
cin >> c;
// Let p be the number of points in the first game:
// second game: p + 1042
// third game: p + (p + 1042) = 2p + 1042
// fourth game: (2p + 1042) / 2 = p + 521
// So c = p + 521, i.e. p = c - 521.
cout << c - 521 << endl;
return 0;
}
Explanation: Check: for C = 2845, p = 2324; then the second, third and fourth games are 3366, 5690 and 2845, which matches the conditions of the task.
Travelling from Agrad to Begrad, Maja passes four signposts (not necessarily in the order in which they are given in the input). The signpost with number i is described by two numbers: ai and bi – this means that the signpost is ai kilometres from Agrad and bi kilometres from Begrad.
However, one signpost is wrong. Find which one.
Input
Each of the four lines of standard input contains two numbers ai and bi. Maja does not like long journeys, so all the numbers in the input are less than 109.
Output
Print to standard output exactly one number – the number of the signpost that is wrong.
Example
Input
2 9
8 3
9 4
5 6
Output
3
Explanation
The signposts are numbered 1, 2, 3 and 4 in order. The sums are 11, 11, 13 and 11, so the third signpost is wrong.
Instructions and solution
Instructions — the idea of the solution
1. The key idea
On a correct signpost the sum a + b is equal to the total length of the road from Agrad to Begrad, so it is the same for all the correct signposts.
2. Three the same, one different
Three sums are equal and one is different. We need to find the one that is different.
3. Analysing the cases
If the sums of the first and second signposts are equal, the wrong one is the third or the fourth: the third is wrong if it differs from the first, otherwise the fourth is wrong. If the sums of the first and second differ, one of them is wrong: if the third is equal to the first, the second is wrong, otherwise the first.
4. Data type
The sum of two numbers less than 109 can go over the limit of the type int, so we use long long.
C++ solution
#include <iostream>
using namespace std;
int main() {
long long a[4], b[4], sum[4];
for (int i = 0; i < 4; i++) {
cin >> a[i] >> b[i];
sum[i] = a[i] + b[i]; // should be the same for all the signposts
}
if (sum[0] == sum[1]) {
// the first two agree, so the third or the fourth is wrong
if (sum[2] != sum[0]) cout << 3 << endl;
else cout << 4 << endl;
} else {
// one of the first two is wrong; the third decides which
if (sum[2] == sum[0]) cout << 2 << endl;
else cout << 1 << endl;
}
return 0;
}
Explanation: The solution needs no loops and no sorting, only four additions and a few comparisons.
A natural number n (n ≤ 109) is given. Find the product of the prime digits in that number.
Input
Exactly one natural number n is entered from standard input.
Output
Print to standard output one natural number – the product of the prime digits in that number. If the number has no prime digits, print -1.
Note. We say that a natural number is prime if it has exactly two different divisors in the set of natural numbers. The numbers 0 and 1 are not prime.
Example 1
Input
52483579
Output
1050
Explanation
The product of the prime digits is 5 · 2 · 3 · 5 · 7 = 1050.
Example 2
Input
186
Output
-1
Explanation
The digits 1, 8 and 6 are not prime.
Example 3
Input
1026
Output
2
Instructions and solution
Instructions — the idea of the solution
1. Which digits are prime
The one-digit prime numbers are 2, 3, 5 and 7. The digits 0, 1, 4, 6, 8 and 9 are not prime.
2. Extracting the digits
We extract the digits of the number from the end with a loop: n % 10 is the last digit, and n /= 10 removes it.
3. The product, and the case with no prime digits
The product starts at 1 and is multiplied by the prime digits. Since 1 is also the product of the “empty set”, we use a separate logical variable to remember whether we have met any prime digit at all. If we have not, we print -1.
C++ solution
#include <iostream>
using namespace std;
int main() {
long long n;
cin >> n;
long long product = 1;
bool hasPrimes = false;
while (n > 0) {
int digit = n % 10;
// the prime digits: 2, 3, 5 and 7
if (digit == 2 || digit == 3 || digit == 5 || digit == 7) {
product *= digit;
hasPrimes = true;
}
n /= 10;
}
if (hasPrimes) cout << product << endl;
else cout << -1 << endl;
return 0;
}
Explanation: The largest possible product is 79 = 40 353 607, which fits in an int, but long long does no harm.
We are given a string that contains single words and sentences separated by spaces, where the sentences are enclosed in square brackets. Write a program that finds all the words and sentences written.
Input
A string of at most 10 000 characters, made of lowercase letters of the English alphabet, spaces and square brackets, is read from standard input. The string is written correctly and contains words and sentences. The string does not contain several consecutive spaces.
Output
Print to standard output each word or sentence on a separate line.
Example 1
Input
[hello everyone] good morning [how are you] bye
Output
hello everyone
good
morning
how are you
bye
Example 2
Input
hello everyone
Output
hello
everyone
Example 3
Input
Today is [a competition] [in programming]
Output
Today
is
a competition
in programming
Instructions and solution
Instructions — the idea of the solution
1. Reading the whole line
Since the string contains spaces, we read it with getline(cin, s), not with cin >> s.
2. Going through the string
With the index i we go from left to right. We skip a space. If the character at position i is [, the sentence lasts until the first closing bracket ]; otherwise it is the ordinary beginning of a word, which lasts until the next space (or the end of the string).
3. Cutting out the parts
We cut out a part of the string with s.substr(start, length). For a sentence we cut out the content between the brackets, without the brackets themselves.
4. Continuing
After processing, we continue from the first position after the word, or after the closing bracket.
C++ solution
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s);
int n = s.size();
int i = 0;
while (i < n) {
if (s[i] == ' ') { // skip spaces
i++;
} else if (s[i] == '[') { // sentence: up to the closing bracket
int j = i + 1;
while (s[j] != ']') j++;
cout << s.substr(i + 1, j - i - 1) << endl;
i = j + 1;
} else { // ordinary word: up to the first space
int j = i;
while (j < n && s[j] != ' ') j++;
cout << s.substr(i, j - i) << endl;
i = j;
}
}
return 0;
}
Explanation: Brackets are not nested, so for each [ it is enough to find the first ] after it.
We say that a pair of competitors is good if the difference between the points of the two competitors is at most k. Find the number of good pairs in the competition.
Input
The first line of standard input contains the number of competitors n (n ≤ 105). The second line contains n natural numbers less than 105 – the points of the competitors. The third line contains the largest allowed difference in points k (1 ≤ k ≤ 105).
In 50% of the tests n ≤ 103. In the other tests the number of competitors is large, so an efficient solution is expected for 100% of the points.
Output
Print to standard output exactly one whole number – the number of good pairs.
Example 1
Input
6
1 12 2 9 5 8
4
Output
8
Explanation
The good pairs are the competitors with the points (1,2), (1,5), (12,9), (12,8), (2,5), (9,5), (9,8) and (5,8).
Example 2
Input
10
15 3 24 17 9 16 3 22 19 8
5
Output
14
Instructions and solution
Instructions — the idea of the solution
1. A slow solution
Checking every pair (two loops) gives about n²/2 comparisons, and for n = 105 that is 5 billion. Enough for 50% of the points, but not for all of them.
2. Sorting
When the points are sorted, all the competitors that form a good pair with a given competitor are in one continuous block just before them.
3. Two pointers
For each competitor right (in order) we move left to the right while points[right] − points[left] > k. Then all the competitors from left to right − 1 form good pairs with competitor right, so we add right − left.
4. Complexity and type
The pointer left only moves forward, so after sorting the work is linear: O(n log n) in total. The number of pairs can be about 5·109, so the counter must be long long.
C++ solution
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, k;
cin >> n;
vector<int> points(n);
for (int i = 0; i < n; i++) cin >> points[i];
cin >> k;
sort(points.begin(), points.end());
long long pairs = 0;
int left = 0;
for (int right = 0; right < n; right++) {
// move the left end while the difference is too large
while (points[right] - points[left] > k) {
left++;
}
// competitor "right" forms a good pair with everyone in [left, right)
pairs += right - left;
}
cout << pairs << endl;
return 0;
}
Explanation: Each pair is counted exactly once: when “right” is at the larger (later) of the two competitors.
If we know the lengths of the sides of several triangles, find the value of the largest perimeter of those triangles.
Input
The number n (1 ≤ n ≤ 100) is entered from standard input, and then on the next n lines three natural numbers each, which are the lengths of the sides of a triangle (all the triples of numbers satisfy the triangle inequalities).
Output
Print to standard output the largest perimeter of a triangle.
Example
Input
3
3 4 5
10 3 11
5 7 8
Output
24
Explanation
The perimeters are 12, 24 and 20; the largest is 24.
Instructions and solution
Instructions — the idea of the solution
1. Perimeter
The perimeter of a triangle is the sum of its three sides: a + b + c.
2. The largest perimeter
We remember the largest perimeter so far in the variable largestPerimeter (starting value 0, because perimeters are positive). After each triangle read we update it with max.
3. Be careful
We do not need to check the triples separately: the task guarantees that they are all triangles.
C++ solution
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
int largestPerimeter = 0;
for (int i = 0; i < n; i++) {
int a, b, c;
cin >> a >> b >> c;
largestPerimeter = max(largestPerimeter, a + b + c);
}
cout << largestPerimeter << endl;
return 0;
}
Explanation: We do not need to store all the triangles in an array – it is enough to calculate the perimeter of each one and compare it with the largest so far.
What you need to know first: Operators, loops, arrays Optional:Vectors · Maps in C++
Task statement
Ivan wrote down the results of the 4 quarter-final matches, 2 semi-final matches and the final match of the knockout stage of a tournament (7 matches in total). The results given in the input are not sorted (for example, the last line of the input does not necessarily mean that this match was played last). Find the winner and the runner-up of the tournament.
Input
Seven lines of standard input contain 2 names each, separated by one space. The first name on a line is the winner, and the second the loser of that match. All the names consist of at least one and at most 10 letters of the English alphabet.
Output
On the first line of standard output print the winner of the tournament. On the second line print the runner-up of the tournament.
Example
Input
Bojan Aleksa
Vanja Goran
Emil Zivadin
Emil Vanja
Vanja Bojan
Emil Dusan
Dusan Djordje
Output
Emil
Vanja
Explanation
In the quarter-finals: Emil beat Živadin, Dušan beat Đorđe, Bojan beat Aleksa, Vanja beat Goran. In the semi-finals Emil beat Dušan, and Vanja beat Bojan. In the final Emil beat Vanja.
Instructions and solution
Instructions — the idea of the solution
1. How many wins each player has
In a knockout tournament with 8 players, the winner wins 3 matches (quarter-final, semi-final, final), the finalist wins 2 matches (quarter-final, semi-final) and loses the final, the beaten semi-finalists have 1 win, and the others 0.
2. Counting
For each name we store the number of wins in a dictionary map<string, int>. When reading each match we increase the number of wins only for the first name (the winner).
3. The result
The winner of the tournament is the name with 3 wins, and the runner-up the name with 2 wins.
4. An alternative
The same can be concluded without counting wins: the winner of the tournament is the only name that never appears as a loser.
C++ solution
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> wins; // name -> number of matches won
for (int i = 0; i < 7; i++) {
string winner, loser;
cin >> winner >> loser;
wins[winner]++;
}
string first, second;
for (auto &entry : wins) {
if (entry.second == 3) first = entry.first; // tournament winner: 3 wins
if (entry.second == 2) second = entry.first; // finalist: 2 wins, and lost the final
}
cout << first << endl << second << endl;
return 0;
}
Explanation: The order of the matches in the input does not matter, because we rely only on the total number of wins of each player.
In a children's game every child stands next to their own tree, except one, whom we call the tailor. The tailor has no tree to stand next to, but goes from child to child asking: “Who has the scissors?”. The child asked answers with the name of one of the other children. While the tailor is moving towards the child named, all the other children try to swap places, and the tailor tries to take a tree by reaching it before the other child, or at least at the same time. If the tailor succeeds, the child left without a tree takes over the tailor's role.
In this task we assume that all the children move at the same speed and that the tailor immediately notices every swap that starts and heads for the nearer of the two temporarily free trees. The first child is trying to work out with how many other children it could swap places without the tailor being a threat. Can you help?
Figure 3: The task Scissors – district computer science competition, 8th grade, 2023/24
Input
The first line of standard input contains two whole numbers separated by a space – the coordinates of the tailor. The second line contains one whole number n, the number of trees, i.e. the number of children who are not the tailor (n ≤ 50). Each of the next n lines contains two whole numbers separated by a space – the coordinates of one child (the first child given is the one making the estimate). All the coordinates are in the interval [0, 30000].
Output
Print to standard output one whole number – the number of children with whom the first child can safely swap places.
Example 1
Input
19 7
5
11 11
3 17
8 4
14 3
18 15
Output
1
Explanation
The first child is at (11, 11). Only the swap with the child at (8, 4) is safe: the children run about 7.6, while the tailor is about 8.9 away from the nearer tree.
Example 2
Input
100 100
4
50 50
150 50
50 150
150 150
Output
0
Explanation
The tailor is in the middle, so for every swap he is closer to one of the free trees than the distance the children need to run.
Instructions and solution
Instructions — the idea of the solution
1. What “safe” means
Let the first child be at tree P, and the other child at tree Q. The children run the distance |PQ|. The tailor runs to the nearer of the two free trees, a distance of min(|KP|, |KQ|). Since the tailor wins even when he arrives at the same time, the swap is safe only if min(|KP|, |KQ|) > |PQ|.
2. Comparing without square roots
The distance between two points is the square root of dx² + dy². Taking the square root is not needed because all distances are non-negative – it is enough to compare the squares of the distances, using whole numbers (with no rounding errors). The square of a distance can reach about 1.8·109, so we use long long.
3. A loop over the children
The first child is first in the list. For each of the other n − 1 children we calculate three squared distances and increase the counter if the swap is safe.
4. Checking on the example
For example 1, the swap with the child at (14, 3) is not safe because the tailor is closer to the tree at (14, 3) than the distance the children run; for the child at (18, 15) the distances are equal, which means the tailor arrives at the same time and the swap is not safe. The only safe swap is with the child at (8, 4).
C++ solution
#include <iostream>
using namespace std;
long long squaredDistance(long long a, long long b, long long c, long long d) {
// squared distance between the points (a, b) and (c, d)
return (a - c) * (a - c) + (b - d) * (b - d);
}
int main() {
long long kx, ky;
int n;
cin >> kx >> ky >> n;
long long x[50], y[50];
for (int i = 0; i < n; i++) cin >> x[i] >> y[i];
int safe = 0;
for (int j = 1; j < n; j++) { // child 0 is the first child
long long between = squaredDistance(x[0], y[0], x[j], y[j]); // how far the children run
long long tailorTo0 = squaredDistance(kx, ky, x[0], y[0]);
long long tailorToJ = squaredDistance(kx, ky, x[j], y[j]);
long long tailor = (tailorTo0 < tailorToJ) ? tailorTo0 : tailorToJ;
// the tailor must be strictly farther from the nearer tree than the children run
if (tailor > between) {
safe++;
}
}
cout << safe << endl;
return 0;
}
Explanation: Assumption: the first child in the list is the one making the estimate; this is confirmed by both given examples. The picture for the task shows the condition for a good swap.
Mika gave Pera N (N ≤ 2·105) pieces of string of whole-number lengths (all the strings are shorter than 1018). Pera throws away exactly one string from the set he was given. After Pera throws away that string, he wants to cut the remaining strings into pieces of the same length (all the pieces must be of equal length, regardless of which string they came from). Pera wants to throw away the string after which he could cut the remaining N − 1 strings into pieces as long as possible. What is that length?
Remember that your solution must be efficient enough – it must run in less than 1 second.
Input
The first line of standard input contains a natural number N – the number of strings (N ≤ 2·105). The second line contains exactly N natural numbers – the lengths of the strings (all the strings are shorter than 1018).
Extra constraints. The tests are divided into three disjoint groups:
40 points: N ≤ 103 and 1 ≤ Ai ≤ 104;
20 points: N ≤ 4·104 and 1 ≤ Ai ≤ 104;
40 points: N ≤ 2·105 and 1 ≤ Ai ≤ 1018.
Output
Print to standard output exactly one natural number – the maximum length into which we can cut the strings so that all the pieces left are of the same length.
Example 1
Input
3
8 39 12
Output
4
Explanation
Pera can throw away the string of length 39. Then he can cut the remaining two strings into pieces of length 4. If he threw away the string of length 8, the maximum length would be 3, and if he threw away the string of length 12, it would be 1. So the maximum length is 4.
Example 2
Input
4
10 13 12 8
Output
2
Instructions and solution
Instructions — the idea of the solution
1. What the required length is
A piece of length d can be cut from every remaining string only if d divides the length of that string. The largest such d is the greatest common divisor (GCD) of all the remaining lengths.
2. A slow solution
For each string thrown away, calculating the GCD of the others needs O(N²) GCD calculations, which is too slow for N = 2·105.
3. Prefixes and suffixes
We calculate left[i] – the GCD of the first i strings, and right[i] – the GCD of the strings from position i to the end. When we throw away string i, the GCD of the others is GCD(left[i], right[i+1]).
4. Starting values
We take the GCD of an empty set as 0, because GCD(0, x) = x.
5. The result and the type
Of all the strings thrown away, we choose the one with the largest GCD obtained. The values reach 1018, so long long is required.
C++ solution
#include <iostream>
#include <vector>
using namespace std;
long long gcd(long long a, long long b) {
while (b != 0) {
long long remainder = a % b;
a = b;
b = remainder;
}
return a;
}
int main() {
int n;
cin >> n;
vector<long long> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
// left[i] = GCD of the first i strings, right[i] = GCD of the strings from position i to the end
vector<long long> left(n + 1, 0), right(n + 2, 0);
for (int i = 0; i < n; i++) left[i + 1] = gcd(left[i], a[i]);
for (int i = n - 1; i >= 0; i--) right[i] = gcd(right[i + 1], a[i]);
long long best = 0;
for (int i = 0; i < n; i++) {
// throw away string i: the strings to its left and to its right remain
long long obtained = gcd(left[i], right[i + 1]);
if (obtained > best) best = obtained;
}
cout << best << endl;
return 0;
}
Explanation: The total complexity is O(N log A), where A is the largest length, because each of the 3N GCD calculations takes O(log A).
What you need to know first: Operators, loops, arrays Optional:Vectors
Task statement
In the quiz “Who Wants to Be a Millionaire?” contestants answer questions that have 4 possible answers (a, b, c, d). The contestants have three lifelines:
Ask the audience – 100 viewers vote for one of the 4 answers, and the contestant can see how many people voted for each answer.
Fifty-fifty – the computer randomly removes two wrong answers and leaves the player one correct and one wrong answer.
Phone a friend – the contestant phones a friend, who says what they think the correct answer is.
Darko has reached the second-to-last question and still has all three lifelines. Since he does not know the answer, he decided on the following tactic: first he will ask the audience, and if one answer has more votes than all the others together, he will choose it. If no answer meets the condition, he will use fifty-fifty. When two answers are left, Darko will choose the one that has at least 20 more audience votes than the other. If still no answer meets the condition, Darko will phone a friend and answer as the friend tells him. Find Darko's final answer to the second-to-last question.
Input
The first line of standard input contains 4 whole numbers separated by spaces, which are the numbers of viewers who voted for the answers a, b, c and d, in that order. All these numbers are between 0 and 100 and their sum is 100.
If needed (i.e. if Darko did not give an answer based on the first lifeline), the second line contains two different letters (from the set a, b, c, d) separated by a space, which are the answers the computer left for Darko.
If needed (i.e. if Darko did not give an answer based on the second lifeline either), the last line contains one letter – the answer the friend suggests. That letter is certainly one of those the computer left as a possible answer.
Output
On the only line of standard output print one letter (a, b, c or d), the final answer Darko gave.
Example 1
Input
12 17 11 60
Output
d
Explanation
More viewers voted for answer d than for all the others together, so Darko immediately decides on that answer and does not use the other lifelines.
Example 2
Input
12 17 34 37
b c
c
Output
c
Explanation
No answer has the necessary majority, so Darko asks for fifty-fifty. The answers b and c are left, whose difference in audience votes (17 and 34) is less than 20, so Darko phones a friend and answers c.
One answer has more votes than all the others together if it has more than half of the votes. Since there are 100 votes in total, the condition is votes[i] > 50. If there is such an answer, we print it and end the program.
2. The second lifeline: fifty-fifty
Only then do we read the second line (two letters). We read the votes for a letter from the array: votes[letter - 'a']. If one of these two answers has at least 20 more votes, that is the answer.
3. The third lifeline: a friend
If no condition is met, we read the third line and print the letter the friend suggested.
4. The order of reading
It is important to read the second and third lines only when they are needed – the input does not contain them when the answer is known earlier.
C++ solution
#include <iostream>
using namespace std;
int main() {
int votes[4];
for (int i = 0; i < 4; i++) cin >> votes[i];
// Lifeline 1: the audience. One answer must have more votes than all the others together,
// and since there are 100 votes in total, that means more than 50.
for (int i = 0; i < 4; i++) {
if (votes[i] > 50) {
cout << (char)('a' + i) << endl;
return 0;
}
}
// Lifeline 2: fifty-fifty
char first, second;
cin >> first >> second;
int votesFirst = votes[first - 'a'];
int votesSecond = votes[second - 'a'];
if (votesFirst - votesSecond >= 20) {
cout << first << endl;
return 0;
}
if (votesSecond - votesFirst >= 20) {
cout << second << endl;
return 0;
}
// Lifeline 3: phone a friend
char friendAnswer;
cin >> friendAnswer;
cout << friendAnswer << endl;
return 0;
}
Explanation: The conditions are “strictly more than half” for the audience and “at least 20 more” (i.e. a difference ≥ 20) for fifty-fifty.
What you need to know first: Operators, loops, arrays Optional:Vectors
Task statement
Write a program that checks how many valid arrangements there are of two pictures of known sizes on a sheet of paper of known size, such that the edges of the pictures are parallel to the edges of the paper, the pictures are shown whole and they do not overlap. The pictures may not be rotated, but the paper may (it can be placed either in the horizontal “landscape” orientation or in the vertical “portrait” orientation). The pictures may be placed either one below the other or one next to the other, on paper turned either horizontally or vertically (so there are at most 4 possible arrangements, and some of them may be invalid because the pictures are too large).
Input
The sizes (width and height) of the paper, the sizes of the first picture and the sizes of the second picture are entered from standard input.
Output
Print to standard output a number from 0 to 4, the number of possible ways to arrange the pictures on the paper.
The paper can be in two orientations (the width and height swap places), and the pictures in two arrangements (one next to the other or one below the other): 4 possibilities in total.
2. One next to the other
The combined width is w1 + w2, and the height needed is the larger of the two heights, max(h1, h2). The arrangement is valid if w1 + w2 ≤ paper width and max(h1, h2) ≤ paper height.
3. One below the other
The width needed is max(w1, w2), and the height h1 + h2. The arrangement is valid if max(w1, w2) ≤ width and h1 + h2 ≤ height.
4. Orientations of the paper
We make a function that, for given paper sizes, counts the valid arrangements (0, 1 or 2), and we call it twice: for (width, height) and for (height, width).
C++ solution
#include <iostream>
#include <algorithm>
using namespace std;
// Can pictures of size (w1,h1) and (w2,h2) be arranged
// on paper of width pw and height ph, one next to the other or one above the other?
int arrangements(int pw, int ph, int w1, int h1, int w2, int h2) {
int count = 0;
// one next to the other
if (w1 + w2 <= pw && max(h1, h2) <= ph) count++;
// one below the other
if (max(w1, w2) <= pw && h1 + h2 <= ph) count++;
return count;
}
int main() {
int width, height, w1, h1, w2, h2;
cin >> width >> height >> w1 >> h1 >> w2 >> h2;
int total = 0;
total += arrangements(width, height, w1, h1, w2, h2); // paper horizontal
total += arrangements(height, width, w1, h1, w2, h2); // paper vertical (turned)
cout << total << endl;
return 0;
}
Explanation: The pictures are not rotated, so their sizes stay the same in all arrangements; only the orientation of the paper changes.
For each position in an array of whole numbers, find the product of all the elements of the array except the element at that position.
Input
The number n (1 ≤ n ≤ 105) is read from standard input, and then the elements of the array (numbers from −10 to 10); it is guaranteed that each of the required products is a number between −109 and 109.
Output
Print to standard output the required products separated by spaces.
Example 1
Input
5
1 2 3 4 5
Output
120 60 40 30 24
Example 2
Input
5
1 2 0 4 5
Output
0 0 40 0 0
Instructions and solution
Instructions — the idea of the solution
1. A slow solution
Multiplying all the other elements for each position is O(n²), which is slow for n = 105.
2. The total product and division
We calculate the product of all the elements and divide it by the element at the position. This does not work if there are zeros in the array – division by zero is not allowed.
3. Zeros
We calculate the product only from the elements different from zero, and count the zeros. If there are no zeros, the result at position i is product / a[i]. If there is exactly one zero, the result at its position is product, and 0 everywhere else. If there are two or more zeros, all the results are 0.
4. Data type
The product of the elements different from zero can be 10 times larger than the required results, so we use long long.
C++ solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
int zeros = 0; // how many zeros there are in the array
long long product = 1; // product of all the elements different from zero
for (int i = 0; i < n; i++) {
if (a[i] == 0) zeros++;
else product *= a[i];
}
for (int i = 0; i < n; i++) {
long long result;
if (zeros >= 2) {
result = 0; // at least one zero remains in every product
} else if (zeros == 1) {
result = (a[i] == 0) ? product : 0;
} else {
result = product / a[i];
}
cout << result << (i + 1 < n ? " " : "\n");
}
return 0;
}
Explanation: The division is exact because product is divisible by each of its factors.
We are given an array of n whole numbers and one whole number x. Write a program that finds the k numbers from the array nearest to the number x (if two numbers are at the same distance from x, the smaller one is chosen). The distance is the absolute value of the difference of the numbers.
Input
The numbers n (1 ≤ n ≤ 105), k (1 ≤ k ≤ n) and x (1 ≤ x ≤ 109) are entered on the first line of standard input, separated by spaces. Then the next line contains n whole numbers ai (1 ≤ ai ≤ 109), the elements of the array, also separated by spaces.
Output
Print to standard output the required k numbers separated by spaces, in non-decreasing order.
Example 1
Input
7 4 4
7 4 2 3 1 5 6
Output
2 3 4 5
Explanation
Of all the numbers entered, the 4 numbers nearest to the number 4 are 2, 3, 4 and 5. The other numbers have a larger difference from the number 4.
Example 2
Input
5 3 2
3 1 3 1 3
Output
1 1 3
Example 3
Input
5 3 20
5 3 2 4 1
Output
3 4 5
Instructions and solution
Instructions — the idea of the solution
1. Sorting by distance
We sort the array so that numbers with a smaller distance from x come first. For the same distance the smaller number comes first – which is exactly the rule from the task.
2. The comparison function
We pass to sort a function that, for two numbers p and q, compares |p − x| and |q − x|, and when they are equal, p and q.
3. The first k
After this sorting, the required k numbers are the first k elements.
4. Non-decreasing output
The output must be in non-decreasing order, so we sort those first k elements again (with ordinary comparison) before printing.
C++ solution
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main() {
int n, k;
long long x;
cin >> n >> k >> x;
vector<long long> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
// sort by distance from x, and for the same distance the smaller number first
sort(a.begin(), a.end(), [x](long long p, long long q) {
long long dp = llabs(p - x), dq = llabs(q - x);
if (dp != dq) return dp < dq;
return p < q;
});
// take the first k and print them in non-decreasing order
sort(a.begin(), a.begin() + k);
for (int i = 0; i < k; i++) {
cout << a[i] << (i + 1 < k ? " " : "\n");
}
return 0;
}
Explanation: The two sorts give a complexity of O(n log n), which is enough for n = 105.
What you need to know first: Operators, loops, arrays Optional:Vectors
Task statement
A company that sells online uses robots to deliver the goods bought. The customers that the robot Mile will serve tomorrow all live on the same side of the same street. For each address Mile knows its coordinate, i.e. the distance from the beginning of the street to that building. Mile is programmed to visit the addresses in the order in which they are given to him.
Write a program that, for the given number of deliveries and the given coordinates of the buildings (the distances of the buildings from the beginning of the street), calculates and prints the total distance the robot Mile will travel from the first to the last delivery.
Input
The first line of standard input contains a natural number n, not greater than 30. Each of the next n lines contains one unsigned whole number – the distance from the beginning of the street to the next building (i.e. the coordinate of the building) to which an order should be delivered. These numbers are not greater than 10000.
Output
Print to standard output only one whole number – the total length of the route the robot Mile travels.
Example 1
Input
5
2
7
7
1
3
Output
13
Explanation
The positions of the buildings in the order of delivery are 2, 7, 7, 1, 3. Mile first goes from position 2 to position 7, then from 7 to 7 (a delivery in the same building), then from 7 to 1 and finally from 1 to 3. The distances travelled are 5, 0, 6, 2, and their sum is 13.
Example 2
Input
1
7
Output
0
Explanation
The first and the last delivery are the same delivery, so Mile does not move at all and the distance travelled is 0.
Instructions and solution
Instructions — the idea of the solution
1. The distance between two buildings
Since all the buildings are on the same street, the distance between two buildings is the absolute value of the difference of their coordinates: abs(a − b).
2. Reading without an array
It is enough to remember the coordinate of the previous building. We read the first building separately, and then for each next one we add abs(current − previous) to the total route and update previous.
3. The case n = 1
The loop for the remaining buildings is then not executed, so the result is 0 – with no special check.
C++ solution
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int n;
cin >> n;
int total = 0;
int previous;
cin >> previous; // first building
for (int i = 1; i < n; i++) {
int current;
cin >> current;
total += abs(current - previous); // route from the previous building to this one
previous = current;
}
cout << total << endl;
return 0;
}
Explanation: The earlier solution was written in C#; here the same algorithm is in C++, as in the other tasks.
A teacher gave Perica homework in which, from 4 given decimal digits, he has to find the difference between the largest and the smallest four-digit number that can be made from those digits. Write a program that, from the 4 decimal digits entered, will help Perica check whether he did his homework correctly.
Input
Each of the 4 lines of standard input contains one decimal digit, at least one of which is not zero.
Output
Print to standard output only one natural number, the difference between the largest and the smallest four-digit number that can be made from the given digits.
Example 1
Input
3
7
5
9
Output
6174
Explanation
The largest four-digit number that can be made is 9753, and the smallest 3579. The difference is 9753 − 3579 = 6174.
Example 2
Input
2
0
5
6
Output
4464
Explanation
The largest number is 6520, and the smallest 2056. The difference is 6520 − 2056 = 4464. The task asks for a four-digit number, so the number must not start with zero – that is why the smallest number is not 0256.
Example 3
Input
0
0
5
0
Output
0
Explanation
The largest and the smallest four-digit number are the same: 5000. The difference is 0.
Instructions and solution
Instructions — the idea of the solution
1. Digits in an array
We read the four digits into an array and sort them in ascending order.
2. The largest number
We get the largest number when the digits are arranged in descending order, i.e. we read the sorted array from the end to the beginning.
3. The smallest number
We get the smallest number with the digits in ascending order, but the first digit must not be 0. So we find the first digit different from zero and swap it with the digit in the first place; the other digits stay in ascending order.
4. The difference
We form the numbers as c0 · 1000 + c1 · 100 + c2 · 10 + c3 and print the difference between the largest and the smallest.
5. Check
For the digits 0, 0, 1, 2: the largest is 2100, and the smallest 1002 (not 0012), so the difference is 1098.
C++ solution
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int c[4];
for (int i = 0; i < 4; i++) cin >> c[i];
sort(c, c + 4); // ascending: c[0] <= c[1] <= c[2] <= c[3]
// largest number: digits from the largest to the smallest
int largest = c[3] * 1000 + c[2] * 100 + c[1] * 10 + c[0];
// smallest number: digits in ascending order, but the first digit must not be 0
int j = 0;
while (c[j] == 0) j++; // first digit different from zero (there is at least one)
swap(c[0], c[j]);
int smallest = c[0] * 1000 + c[1] * 100 + c[2] * 10 + c[3];
cout << largest - smallest << endl;
return 0;
}
Explanation: The condition “at least one digit is not zero” guarantees that the first non-zero digit exists, so the loop that looks for it always stops.
Two players are playing noughts and crosses. The game is played on a 3×3 board on which the players take turns writing a cross or a nought. The winner is the player who manages to write 3 of their signs in one row, one column or one diagonal. For the given final position of the game, decide whether the cross player won, the nought player won, or the game ended in a draw.
Input
Each of the three lines of standard input contains three characters x, o or *. The first line of the input describes how the first row of the board is filled, and so on. The mark x means a cross, o a nought, and * that the cell is empty at the end of the game.
Output
If the cross won, print the character x; if the nought won, print o; and if it is a draw, print nereseno (Serbian for “draw”; this is the original word checked by the tests on petlja.org).
Example 1
Input
x*x
ox*
xoo
Output
x
Explanation
The cross has three signs on the anti-diagonal.
Example 2
Input
xxo
oox
xox
Output
nereseno
Instructions and solution
Instructions — the idea of the solution
1. The board as strings of 3 characters
We read each row as a string of 3 characters; then t[i][j] is the character in row i and column j.
2. Eight lines
There are eight winning lines: three rows, three columns and two diagonals. For player p we check whether all three cells of some line are equal to p.
3. For both players
We run the same code for 'x', and then for 'o'. The empty cell * is never a winning sign, because we check only x and o.
4. A draw
If neither player has a line, we print nereseno.
C++ solution
#include <iostream>
#include <string>
using namespace std;
int main() {
string t[3];
for (int i = 0; i < 3; i++) cin >> t[i];
// check for both players
char players[2] = {'x', 'o'};
for (char p : players) {
bool won = false;
for (int i = 0; i < 3; i++) {
if (t[i][0] == p && t[i][1] == p && t[i][2] == p) won = true; // row i
if (t[0][i] == p && t[1][i] == p && t[2][i] == p) won = true; // column i
}
if (t[0][0] == p && t[1][1] == p && t[2][2] == p) won = true; // main diagonal
if (t[0][2] == p && t[1][1] == p && t[2][0] == p) won = true; // anti-diagonal
if (won) {
cout << p << endl;
return 0;
}
}
cout << "nereseno" << endl;
return 0;
}
Explanation: The assumption is that the input is a valid final position, in which both players cannot win.
Write a program that, for the string entered, finds the absolute value of the difference between the number of digits and the number of letters in that string. Lowercase and capital letters of the English alphabet count as letters.
Input
The only line of standard input contains a string of at most 20 characters. Besides lowercase and capital letters of the English alphabet and digits, the string may contain spaces and other ASCII characters (letters of other alphabets will not appear).
Output
Print the required value to standard output.
Example
Input
Programming 1
Output
10
Explanation
The string has 11 letters and 1 digit, so the difference is 10.
Instructions and solution
Instructions — the idea of the solution
1. The whole line
The string may contain spaces, so we read it with getline(cin, s). An ordinary cin >> s would stop at the first space.
2. Classifying the characters
We go through all the characters. A character is a digit if it is between '0' and '9', and a letter if it is between 'a' and 'z' or between 'A' and 'Z'. We do not count anything else (spaces, punctuation marks).
3. The result
We print abs(digits − letters) – the absolute value, because there can be either fewer or more letters than digits.
C++ solution
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
string s;
getline(cin, s); // the string may contain spaces
int digits = 0, letters = 0;
for (char c : s) {
if (c >= '0' && c <= '9') {
digits++;
} else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
letters++;
}
}
cout << abs(digits - letters) << endl;
return 0;
}
Explanation: We do not need to store the digits or the letters – two counters are enough.
We need to simulate a banking system for k different users. Each user has an account with a starting balance of 0. Two kinds of operations need to be supported:
upit x – finds how many users have exactly x dinars in their account (upit is Serbian for “query”; this is the original keyword used in the tests on petlja.org);
name x – adds x dinars to the account of the person called name (x can also be negative).
Write a program that supports carrying out n such operations.
Input
The numbers n and k are entered from standard input. After that, one operation is entered on each of n lines.
Output
For each query (an operation of the first kind) print the answer, each on a separate line.
Example
Input
6 4
marko 2
milan 5
dragana 4
upit 0
milan -1
upit 4
Output
1
2
Explanation
After the first three operations Marko has 2, Milan 5 and Dragana 4 dinars, and the fourth user 0 – exactly one account has 0 dinars. When Milan loses 1 dinar, both Milan and Dragana have 4 dinars.
Instructions and solution
Instructions — the idea of the solution
1. What we need to know
We can answer the question “how many accounts have exactly x dinars” immediately if we always keep the number of accounts for each balance. That is why we need two maps.
2. Two maps
map<string, long long> balance stores the balance of each user (0 by default), and map<long long, int> accountCount stores how many accounts have a given balance.
3. The start
At the start all k users have 0 dinars, so accountCount[0] = k. This is important: users we have not seen yet are also counted in the query upit 0.
4. A payment
For the operation name x: the old balance is balance[name]. We decrease accountCount[old], set the new balance old + x and increase accountCount[new].
5. A query
For upit x we print accountCount[x]. If the balance x does not exist in the map, the map creates it automatically with the value 0.
C++ solution
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
map<string, long long> balance; // account balance of each user
map<long long, int> accountCount; // how many accounts have exactly the given balance
accountCount[0] = k; // at the start all k accounts have 0 dinars
for (int i = 0; i < n; i++) {
string word;
long long x;
cin >> word >> x;
if (word == "upit") {
cout << accountCount[x] << endl;
} else {
long long old = balance[word]; // if the user has not been seen, the balance is 0
accountCount[old]--; // the account leaves the old balance ...
balance[word] = old + x;
accountCount[old + x]++; // ... and moves to the new one
}
}
return 0;
}
Explanation: Each operation takes O(log n). The assumption is that no user is called “upit”.
Flags are stuck into the ground along a meadow (for each flag a whole-number x-coordinate is known). This annoyed the moles, who took action, and each of them dug a hole somewhere along the meadow (for each hole a whole-number x-coordinate is known). Around each hole the ground becomes unstable, and all the flags at a distance of at most d from some hole collapse (including those at distance d). Write a program that finds how many flags are left after all the holes have been dug.
Input
The first line of standard input contains the number of flags m (1 ≤ m ≤ 105), and the second the whole-number coordinates of all the flags (whole numbers between 0 and 109) separated by single spaces.
The third line contains the number of holes n (1 ≤ n ≤ 105), and the fourth the whole-number coordinates of all the holes (whole numbers between 0 and 109), also separated by single spaces. Finally, the fifth line contains the number d (1 ≤ d ≤ 109).
Extra constraints. In tests worth 49% of the points, also 1 ≤ m ≤ 100 and 1 ≤ n ≤ 100; in tests worth 51% of the points there are no extra constraints.
Output
Print to standard output the number of flags left.
Example
Input
3
4 5 8
4
10 9 1 8
2
Output
2
Explanation
The flag at 8 collapses because of the hole at 8. The flags at 4 and 5 are at a distance of 3 > 2 from the nearest hole, so they are left.
Instructions and solution
Instructions — the idea of the solution
1. A slow solution
Checking every hole for every flag is O(m·n), which is 1010 comparisons – too many. It is enough for the first group of tests (m, n ≤ 100).
2. Only two holes matter
If the holes are sorted, only two of all the holes can be nearest to the flag z: the first hole to the right of it (or at it) and the last hole to the left of it. If neither of these two is at a distance ≤ d, no hole knocks it down.
3. Binary search
We find the first hole that is not to the left of the flag with the function lower_bound in O(log n). The hole just before it is the nearest one on the left.
4. Counting
We count the flags for which neither of the two nearest holes is close enough. The complexity is O(n log n + m log n).
C++ solution
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int m, n;
cin >> m;
vector<long long> flags(m);
for (int i = 0; i < m; i++) cin >> flags[i];
cin >> n;
vector<long long> holes(n);
for (int i = 0; i < n; i++) cin >> holes[i];
long long d;
cin >> d;
sort(holes.begin(), holes.end());
int remaining = 0;
for (int i = 0; i < m; i++) {
long long z = flags[i];
bool collapsed = false;
// first hole that is not to the left of the flag
auto it = lower_bound(holes.begin(), holes.end(), z);
if (it != holes.end() && *it - z <= d) collapsed = true; // nearest on the right
if (it != holes.begin() && z - *(it - 1) <= d) collapsed = true; // nearest on the left
if (!collapsed) remaining++;
}
cout << remaining << endl;
return 0;
}
Explanation: An alternative without binary search: sort both the flags and the holes and walk through them with two pointers.
Quiz: check what you have learned
Ten short questions about the ideas from the tasks on this page. Choose an answer – you will immediately see whether it is correct and why.
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.