contestId int64 0 1.01k | index stringclasses 40
values | name stringlengths 2 54 | type stringclasses 2
values | rating int64 0 3.4k | tags listlengths 0 7 | title stringclasses 393
values | time-limit stringclasses 7
values | memory-limit stringclasses 6
values | problem-description stringlengths 0 2.97k | input-specification stringlengths 4 1.87k | output-specification stringlengths 4 1.12k | demo-input listlengths 0 7 | demo-output listlengths 0 7 | note stringlengths 0 5.24k | points float64 0 3.5k | test_cases listlengths 0 402 | creationTimeSeconds int64 1.37B 1.7B | relativeTimeSeconds int64 8 2.15B | programmingLanguage stringclasses 3
values | verdict stringclasses 1
value | testset stringclasses 9
values | passedTestCount int64 1 402 | timeConsumedMillis int64 15 8.06k | memoryConsumedBytes int64 0 514M | code stringlengths 11 61.4k | prompt stringlengths 297 7.35k | response stringlengths 25 61.4k | score float64 2.82 3.99 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
313 | A | Ilya and Bank Account | PROGRAMMING | 900 | [
"implementation",
"number theory"
] | null | null | Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money.
Ilya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance.
Ilya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift. | The single line contains integer *n* (10<=β€<=|*n*|<=β€<=109) β the state of Ilya's bank account. | In a single line print an integer β the maximum state of the bank account that Ilya can get. | [
"2230\n",
"-10\n",
"-100003\n"
] | [
"2230\n",
"0\n",
"-10000\n"
] | In the first test sample Ilya doesn't profit from using the present.
In the second test sample you can delete digit 1 and get the state of the account equal to 0. | 500 | [
{
"input": "2230",
"output": "2230"
},
{
"input": "-10",
"output": "0"
},
{
"input": "-100003",
"output": "-10000"
},
{
"input": "544883178",
"output": "544883178"
},
{
"input": "-847251738",
"output": "-84725173"
},
{
"input": "423654797",
"output... | 1,699,464,912 | 2,147,483,647 | Python 3 | OK | TESTS | 47 | 92 | 0 | n=str(input())
m = n
if n[0] == '-':
if int(n[-2]) <= int(n[-1]):
m=n[:-1]
else:
m=n[:-2]+n[-1]
m=int(m)
print(m)
| Title: Ilya and Bank Account
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money.
Ilya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance.
Ilya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift.
Input Specification:
The single line contains integer *n* (10<=β€<=|*n*|<=β€<=109) β the state of Ilya's bank account.
Output Specification:
In a single line print an integer β the maximum state of the bank account that Ilya can get.
Demo Input:
['2230\n', '-10\n', '-100003\n']
Demo Output:
['2230\n', '0\n', '-10000\n']
Note:
In the first test sample Ilya doesn't profit from using the present.
In the second test sample you can delete digit 1 and get the state of the account equal to 0. | ```python
n=str(input())
m = n
if n[0] == '-':
if int(n[-2]) <= int(n[-1]):
m=n[:-1]
else:
m=n[:-2]+n[-1]
m=int(m)
print(m)
``` | 3 | |
907 | B | Tic-Tac-Toe | PROGRAMMING | 1,400 | [
"implementation"
] | null | null | Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.
The game is played on the following field.
Players are making moves by turns. At first move a player can put his chip in any cell of any small field. For following moves, there are some restrictions: if during last move the opposite player put his chip to cell with coordinates (*x**l*,<=*y**l*) in some small field, the next move should be done in one of the cells of the small field with coordinates (*x**l*,<=*y**l*). For example, if in the first move a player puts his chip to lower left cell of central field, then the second player on his next move should put his chip into some cell of lower left field (pay attention to the first test case). If there are no free cells in the required field, the player can put his chip to any empty cell on any field.
You are given current state of the game and coordinates of cell in which the last move was done. You should find all cells in which the current player can put his chip.
A hare works as a postman in the forest, he likes to foul bears. Sometimes he changes the game field a bit, so the current state of the game could be unreachable. However, after his changes the cell where the last move was done is not empty. You don't need to find if the state is unreachable or not, just output possible next moves according to the rules. | First 11 lines contains descriptions of table with 9 rows and 9 columns which are divided into 9 small fields by spaces and empty lines. Each small field is described by 9 characters without spaces and empty lines. character "x" (ASCII-code 120) means that the cell is occupied with chip of the first player, character "o" (ASCII-code 111) denotes a field occupied with chip of the second player, character "." (ASCII-code 46) describes empty cell.
The line after the table contains two integers *x* and *y* (1<=β€<=*x*,<=*y*<=β€<=9). They describe coordinates of the cell in table where the last move was done. Rows in the table are numbered from up to down and columns are numbered from left to right.
It's guaranteed that cell where the last move was done is filled with "x" or "o". Also, it's guaranteed that there is at least one empty cell. It's not guaranteed that current state of game is reachable. | Output the field in same format with characters "!" (ASCII-code 33) on positions where the current player can put his chip. All other cells should not be modified. | [
"... ... ...\n... ... ...\n... ... ...\n\n... ... ...\n... ... ...\n... x.. ...\n\n... ... ...\n... ... ...\n... ... ...\n6 4\n",
"xoo x.. x..\nooo ... ...\nooo ... ...\n\nx.. x.. x..\n... ... ...\n... ... ...\n\nx.. x.. x..\n... ... ...\n... ... ...\n7 4\n",
"o.. ... ...\n... ... ...\n... ... ...\n\n... xxx ..... | [
"... ... ... \n... ... ... \n... ... ... \n\n... ... ... \n... ... ... \n... x.. ... \n\n!!! ... ... \n!!! ... ... \n!!! ... ... \n\n",
"xoo x!! x!! \nooo !!! !!! \nooo !!! !!! \n\nx!! x!! x!! \n!!! !!! !!! \n!!! !!! !!! \n\nx!! x!! x!! \n!!! !!! !!! \n!!! !!! !!! \n\n",
"o!! !!! !!! \n!!! !!! !!! \n!!! !!! !!!... | In the first test case the first player made a move to lower left cell of central field, so the second player can put a chip only to cells of lower left field.
In the second test case the last move was done to upper left cell of lower central field, however all cells in upper left field are occupied, so the second player can put his chip to any empty cell.
In the third test case the last move was done to central cell of central field, so current player can put his chip to any cell of central field, which is already occupied, so he can move anywhere. Pay attention that this state of the game is unreachable. | 1,000 | [
{
"input": "... ... ...\n... ... ...\n... ... ...\n\n... ... ...\n... ... ...\n... x.. ...\n\n... ... ...\n... ... ...\n... ... ...\n6 4",
"output": "... ... ... \n... ... ... \n... ... ... \n\n... ... ... \n... ... ... \n... x.. ... \n\n!!! ... ... \n!!! ... ... \n!!! ... ... "
},
{
"input": "xoo x... | 1,514,041,282 | 3,382 | Python 3 | OK | TESTS | 20 | 62 | 5,632,000 | field = [[""]*9 for i in range(9)]
z = 0
for i in range(3):
temp2 = input()
for z2 in range(len(temp2)):
if temp2[z2] != " ":
field[i][z] = temp2[z2]
z+= 1
z = 0
input()
for i in range(3,6):
temp2 = input()
for z2 in range(len(temp2)):
if temp2[z2] != " ":
field[i][z] = temp2[z2]
z+= 1
z = 0
input()
for i in range(6,9):
temp2 = input()
for z2 in range(len(temp2)):
if temp2[z2] != " ":
field[i][z] = temp2[z2]
z+= 1
z = 0
x, y = map(int,input().split())
x2 = ((y-1) % 3) * 3
y2 = ((x-1) % 3) * 3
temp = 0
for i in range(3):
for j in range(3):
if field[y2+i][x2+j] == ".":
field[y2+i][x2+j] = "!"
temp += 1
if temp == 0:
for i in range(9):
for j in range(9):
if field[i][j] == ".":
field[i][j] = "!"
for i in range(9):
for j in range(9):
if j % 3 == 0 and j != 0:
print("",end=" ")
print(field[i][j],end="")
if i % 3 == 2 and i != 8:
print()
print()
| Title: Tic-Tac-Toe
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.
The game is played on the following field.
Players are making moves by turns. At first move a player can put his chip in any cell of any small field. For following moves, there are some restrictions: if during last move the opposite player put his chip to cell with coordinates (*x**l*,<=*y**l*) in some small field, the next move should be done in one of the cells of the small field with coordinates (*x**l*,<=*y**l*). For example, if in the first move a player puts his chip to lower left cell of central field, then the second player on his next move should put his chip into some cell of lower left field (pay attention to the first test case). If there are no free cells in the required field, the player can put his chip to any empty cell on any field.
You are given current state of the game and coordinates of cell in which the last move was done. You should find all cells in which the current player can put his chip.
A hare works as a postman in the forest, he likes to foul bears. Sometimes he changes the game field a bit, so the current state of the game could be unreachable. However, after his changes the cell where the last move was done is not empty. You don't need to find if the state is unreachable or not, just output possible next moves according to the rules.
Input Specification:
First 11 lines contains descriptions of table with 9 rows and 9 columns which are divided into 9 small fields by spaces and empty lines. Each small field is described by 9 characters without spaces and empty lines. character "x" (ASCII-code 120) means that the cell is occupied with chip of the first player, character "o" (ASCII-code 111) denotes a field occupied with chip of the second player, character "." (ASCII-code 46) describes empty cell.
The line after the table contains two integers *x* and *y* (1<=β€<=*x*,<=*y*<=β€<=9). They describe coordinates of the cell in table where the last move was done. Rows in the table are numbered from up to down and columns are numbered from left to right.
It's guaranteed that cell where the last move was done is filled with "x" or "o". Also, it's guaranteed that there is at least one empty cell. It's not guaranteed that current state of game is reachable.
Output Specification:
Output the field in same format with characters "!" (ASCII-code 33) on positions where the current player can put his chip. All other cells should not be modified.
Demo Input:
['... ... ...\n... ... ...\n... ... ...\n\n... ... ...\n... ... ...\n... x.. ...\n\n... ... ...\n... ... ...\n... ... ...\n6 4\n', 'xoo x.. x..\nooo ... ...\nooo ... ...\n\nx.. x.. x..\n... ... ...\n... ... ...\n\nx.. x.. x..\n... ... ...\n... ... ...\n7 4\n', 'o.. ... ...\n... ... ...\n... ... ...\n\n... xxx ...\n... xox ...\n... ooo ...\n\n... ... ...\n... ... ...\n... ... ...\n5 5\n']
Demo Output:
['... ... ... \n... ... ... \n... ... ... \n\n... ... ... \n... ... ... \n... x.. ... \n\n!!! ... ... \n!!! ... ... \n!!! ... ... \n\n', 'xoo x!! x!! \nooo !!! !!! \nooo !!! !!! \n\nx!! x!! x!! \n!!! !!! !!! \n!!! !!! !!! \n\nx!! x!! x!! \n!!! !!! !!! \n!!! !!! !!! \n\n', 'o!! !!! !!! \n!!! !!! !!! \n!!! !!! !!! \n\n!!! xxx !!! \n!!! xox !!! \n!!! ooo !!! \n\n!!! !!! !!! \n!!! !!! !!! \n!!! !!! !!! \n\n']
Note:
In the first test case the first player made a move to lower left cell of central field, so the second player can put a chip only to cells of lower left field.
In the second test case the last move was done to upper left cell of lower central field, however all cells in upper left field are occupied, so the second player can put his chip to any empty cell.
In the third test case the last move was done to central cell of central field, so current player can put his chip to any cell of central field, which is already occupied, so he can move anywhere. Pay attention that this state of the game is unreachable. | ```python
field = [[""]*9 for i in range(9)]
z = 0
for i in range(3):
temp2 = input()
for z2 in range(len(temp2)):
if temp2[z2] != " ":
field[i][z] = temp2[z2]
z+= 1
z = 0
input()
for i in range(3,6):
temp2 = input()
for z2 in range(len(temp2)):
if temp2[z2] != " ":
field[i][z] = temp2[z2]
z+= 1
z = 0
input()
for i in range(6,9):
temp2 = input()
for z2 in range(len(temp2)):
if temp2[z2] != " ":
field[i][z] = temp2[z2]
z+= 1
z = 0
x, y = map(int,input().split())
x2 = ((y-1) % 3) * 3
y2 = ((x-1) % 3) * 3
temp = 0
for i in range(3):
for j in range(3):
if field[y2+i][x2+j] == ".":
field[y2+i][x2+j] = "!"
temp += 1
if temp == 0:
for i in range(9):
for j in range(9):
if field[i][j] == ".":
field[i][j] = "!"
for i in range(9):
for j in range(9):
if j % 3 == 0 and j != 0:
print("",end=" ")
print(field[i][j],end="")
if i % 3 == 2 and i != 8:
print()
print()
``` | 3 | |
137 | B | Permutation | PROGRAMMING | 1,000 | [
"greedy"
] | null | null | "Hey, it's homework time" β thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.
The sequence of *n* integers is called a permutation if it contains all integers from 1 to *n* exactly once.
You are given an arbitrary sequence *a*1,<=*a*2,<=...,<=*a**n* containing *n* integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer). | The first line of the input data contains an integer *n* (1<=β€<=*n*<=β€<=5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers *a**i* (1<=β€<=*a**i*<=β€<=5000,<=1<=β€<=*i*<=β€<=*n*). | Print the only number β the minimum number of changes needed to get the permutation. | [
"3\n3 1 2\n",
"2\n2 2\n",
"5\n5 3 3 3 1\n"
] | [
"0\n",
"1\n",
"2\n"
] | The first sample contains the permutation, which is why no replacements are required.
In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.
In the third sample we can replace the second element with number 4 and the fourth element with number 2. | 1,000 | [
{
"input": "3\n3 1 2",
"output": "0"
},
{
"input": "2\n2 2",
"output": "1"
},
{
"input": "5\n5 3 3 3 1",
"output": "2"
},
{
"input": "5\n6 6 6 6 6",
"output": "5"
},
{
"input": "10\n1 1 2 2 8 8 7 7 9 9",
"output": "5"
},
{
"input": "8\n9 8 7 6 5 4 3 2"... | 1,435,950,845 | 245 | Python 3 | OK | TESTS | 48 | 124 | 512,000 | n = int(input())
a = input().split()
d = {}
for i in a:
t = int(i)
if t in d:
d[t] += 1
else:
d[t] = 1
res = 0
for i in range(1, n+1):
if i not in d:
res += 1
print(res)
| Title: Permutation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
"Hey, it's homework time" β thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.
The sequence of *n* integers is called a permutation if it contains all integers from 1 to *n* exactly once.
You are given an arbitrary sequence *a*1,<=*a*2,<=...,<=*a**n* containing *n* integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).
Input Specification:
The first line of the input data contains an integer *n* (1<=β€<=*n*<=β€<=5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers *a**i* (1<=β€<=*a**i*<=β€<=5000,<=1<=β€<=*i*<=β€<=*n*).
Output Specification:
Print the only number β the minimum number of changes needed to get the permutation.
Demo Input:
['3\n3 1 2\n', '2\n2 2\n', '5\n5 3 3 3 1\n']
Demo Output:
['0\n', '1\n', '2\n']
Note:
The first sample contains the permutation, which is why no replacements are required.
In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.
In the third sample we can replace the second element with number 4 and the fourth element with number 2. | ```python
n = int(input())
a = input().split()
d = {}
for i in a:
t = int(i)
if t in d:
d[t] += 1
else:
d[t] = 1
res = 0
for i in range(1, n+1):
if i not in d:
res += 1
print(res)
``` | 3 | |
200 | B | Drinks | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the *n* drinks and mixed them. Then he wondered, how much orange juice the cocktail has.
Find the volume fraction of orange juice in the final drink. | The first input line contains a single integer *n* (1<=β€<=*n*<=β€<=100) β the number of orange-containing drinks in Vasya's fridge. The second line contains *n* integers *p**i* (0<=β€<=*p**i*<=β€<=100) β the volume fraction of orange juice in the *i*-th drink, in percent. The numbers are separated by a space. | Print the volume fraction in percent of orange juice in Vasya's cocktail. The answer will be considered correct if the absolute or relative error does not exceed 10<=<=-<=4. | [
"3\n50 50 100\n",
"4\n0 25 50 75\n"
] | [
"66.666666666667\n",
"37.500000000000\n"
] | Note to the first sample: let's assume that Vasya takes *x* milliliters of each drink from the fridge. Then the volume of pure juice in the cocktail will equal <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c1fac6e64d3a8ee6a5ac138cbe51e60039b22473.png" style="max-width: 100.0%;max-height: 100.0%;"/> milliliters. The total cocktail's volume equals 3Β·*x* milliliters, so the volume fraction of the juice in the cocktail equals <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ceb0664e55a1f9f5fa1243ec74680a4665a4d58d.png" style="max-width: 100.0%;max-height: 100.0%;"/>, that is, 66.(6) percent. | 500 | [
{
"input": "3\n50 50 100",
"output": "66.666666666667"
},
{
"input": "4\n0 25 50 75",
"output": "37.500000000000"
},
{
"input": "3\n0 1 8",
"output": "3.000000000000"
},
{
"input": "5\n96 89 93 95 70",
"output": "88.600000000000"
},
{
"input": "7\n62 41 78 4 38 39... | 1,685,079,310 | 2,147,483,647 | Python 3 | OK | TESTS | 31 | 92 | 0 | n=int(input())
print(sum(list(map(int,input().split())))/n) | Title: Drinks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the *n* drinks and mixed them. Then he wondered, how much orange juice the cocktail has.
Find the volume fraction of orange juice in the final drink.
Input Specification:
The first input line contains a single integer *n* (1<=β€<=*n*<=β€<=100) β the number of orange-containing drinks in Vasya's fridge. The second line contains *n* integers *p**i* (0<=β€<=*p**i*<=β€<=100) β the volume fraction of orange juice in the *i*-th drink, in percent. The numbers are separated by a space.
Output Specification:
Print the volume fraction in percent of orange juice in Vasya's cocktail. The answer will be considered correct if the absolute or relative error does not exceed 10<=<=-<=4.
Demo Input:
['3\n50 50 100\n', '4\n0 25 50 75\n']
Demo Output:
['66.666666666667\n', '37.500000000000\n']
Note:
Note to the first sample: let's assume that Vasya takes *x* milliliters of each drink from the fridge. Then the volume of pure juice in the cocktail will equal <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c1fac6e64d3a8ee6a5ac138cbe51e60039b22473.png" style="max-width: 100.0%;max-height: 100.0%;"/> milliliters. The total cocktail's volume equals 3Β·*x* milliliters, so the volume fraction of the juice in the cocktail equals <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ceb0664e55a1f9f5fa1243ec74680a4665a4d58d.png" style="max-width: 100.0%;max-height: 100.0%;"/>, that is, 66.(6) percent. | ```python
n=int(input())
print(sum(list(map(int,input().split())))/n)
``` | 3 | |
713 | C | Sonya and Problem Wihtout a Legend | PROGRAMMING | 2,300 | [
"dp",
"sortings"
] | null | null | Sonya was unable to think of a story for this problem, so here comes the formal description.
You are given the array containing *n* positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0. | The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=3000)Β β the length of the array.
Next line contains *n* integer *a**i* (1<=β€<=*a**i*<=β€<=109). | Print the minimum number of operation required to make the array strictly increasing. | [
"7\n2 1 5 11 5 9 11\n",
"5\n5 4 3 2 1\n"
] | [
"9\n",
"12\n"
] | In the first sample, the array is going to look as follows:
2 3 5 6 7 9 11
|2β-β2|β+β|1β-β3|β+β|5β-β5|β+β|11β-β6|β+β|5β-β7|β+β|9β-β9|β+β|11β-β11|β=β9
And for the second sample:
1 2 3 4 5
|5β-β1|β+β|4β-β2|β+β|3β-β3|β+β|2β-β4|β+β|1β-β5|β=β12 | 2,000 | [
{
"input": "7\n2 1 5 11 5 9 11",
"output": "9"
},
{
"input": "5\n5 4 3 2 1",
"output": "12"
},
{
"input": "2\n1 1000",
"output": "0"
},
{
"input": "2\n1000 1",
"output": "1000"
},
{
"input": "5\n100 80 60 70 90",
"output": "54"
},
{
"input": "10\n10 16... | 1,583,323,835 | 2,147,483,647 | PyPy 3 | OK | TESTS | 57 | 249 | 11,366,400 | from bisect import bisect_left as BL
n = int(input())
graph = [(-99**9, 0)] # x, slope
ans = 0
for i,a in enumerate(map(int,input().split())):
a-= i
new = []
turnj = BL(graph, (a,99**9)) - 1
if turnj != len(graph)-1:
ans+= graph[-1][0] - a
# add |x-a|
for j in range(turnj):
x, sl = graph[j]
new.append((x, sl-1))
for j in range(turnj, len(graph)):
x, sl = graph[j]
if j == turnj:
new.append((x, sl-1))
new.append((a, sl+1))
else: new.append((x, sl+1))
# remove positive slopes
graph = new
while graph[-1][1] > 0: x, sl = graph.pop()
if graph[-1][1] != 0: graph.append((x, 0))
print(ans) | Title: Sonya and Problem Wihtout a Legend
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Sonya was unable to think of a story for this problem, so here comes the formal description.
You are given the array containing *n* positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.
Input Specification:
The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=3000)Β β the length of the array.
Next line contains *n* integer *a**i* (1<=β€<=*a**i*<=β€<=109).
Output Specification:
Print the minimum number of operation required to make the array strictly increasing.
Demo Input:
['7\n2 1 5 11 5 9 11\n', '5\n5 4 3 2 1\n']
Demo Output:
['9\n', '12\n']
Note:
In the first sample, the array is going to look as follows:
2 3 5 6 7 9 11
|2β-β2|β+β|1β-β3|β+β|5β-β5|β+β|11β-β6|β+β|5β-β7|β+β|9β-β9|β+β|11β-β11|β=β9
And for the second sample:
1 2 3 4 5
|5β-β1|β+β|4β-β2|β+β|3β-β3|β+β|2β-β4|β+β|1β-β5|β=β12 | ```python
from bisect import bisect_left as BL
n = int(input())
graph = [(-99**9, 0)] # x, slope
ans = 0
for i,a in enumerate(map(int,input().split())):
a-= i
new = []
turnj = BL(graph, (a,99**9)) - 1
if turnj != len(graph)-1:
ans+= graph[-1][0] - a
# add |x-a|
for j in range(turnj):
x, sl = graph[j]
new.append((x, sl-1))
for j in range(turnj, len(graph)):
x, sl = graph[j]
if j == turnj:
new.append((x, sl-1))
new.append((a, sl+1))
else: new.append((x, sl+1))
# remove positive slopes
graph = new
while graph[-1][1] > 0: x, sl = graph.pop()
if graph[-1][1] != 0: graph.append((x, 0))
print(ans)
``` | 3 | |
877 | A | Alex and broken contest | PROGRAMMING | 1,100 | [
"implementation",
"strings"
] | null | null | One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems.
But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest by its name.
It is known, that problem is from this contest if and only if its name contains one of Alex's friends' name exactly once. His friends' names are "Danil", "Olya", "Slava", "Ann" and "Nikita".
Names are case sensitive. | The only line contains string from lowercase and uppercase letters and "_" symbols of length, not more than 100 β the name of the problem. | Print "YES", if problem is from this contest, and "NO" otherwise. | [
"Alex_and_broken_contest\n",
"NikitaAndString\n",
"Danil_and_Olya\n"
] | [
"NO",
"YES",
"NO"
] | none | 500 | [
{
"input": "Alex_and_broken_contest",
"output": "NO"
},
{
"input": "NikitaAndString",
"output": "YES"
},
{
"input": "Danil_and_Olya",
"output": "NO"
},
{
"input": "Slava____and_the_game",
"output": "YES"
},
{
"input": "Olya_and_energy_drinks",
"output": "YES"
... | 1,684,211,447 | 2,147,483,647 | Python 3 | OK | TESTS | 55 | 62 | 921,600 | import re
str = 'Danil|Olya|Slava|Ann|Nikita'
if (len(re.findall(str, input())) == 1):
print('YES')
else:
print('NO')
| Title: Alex and broken contest
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems.
But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest by its name.
It is known, that problem is from this contest if and only if its name contains one of Alex's friends' name exactly once. His friends' names are "Danil", "Olya", "Slava", "Ann" and "Nikita".
Names are case sensitive.
Input Specification:
The only line contains string from lowercase and uppercase letters and "_" symbols of length, not more than 100 β the name of the problem.
Output Specification:
Print "YES", if problem is from this contest, and "NO" otherwise.
Demo Input:
['Alex_and_broken_contest\n', 'NikitaAndString\n', 'Danil_and_Olya\n']
Demo Output:
['NO', 'YES', 'NO']
Note:
none | ```python
import re
str = 'Danil|Olya|Slava|Ann|Nikita'
if (len(re.findall(str, input())) == 1):
print('YES')
else:
print('NO')
``` | 3 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are *n* lanes of *m* desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to *n* from the left to the right, the desks in a lane are numbered from 1 to *m* starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture).
The organizers numbered all the working places from 1 to 2*nm*. The places are numbered by lanes (i.Β e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i.Β e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right.
Santa Clause knows that his place has number *k*. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right! | The only line contains three integers *n*, *m* and *k* (1<=β€<=*n*,<=*m*<=β€<=10<=000, 1<=β€<=*k*<=β€<=2*nm*)Β β the number of lanes, the number of desks in each lane and the number of Santa Claus' place. | Print two integers: the number of lane *r*, the number of desk *d*, and a character *s*, which stands for the side of the desk Santa Claus. The character *s* should be "L", if Santa Clause should sit on the left, and "R" if his place is on the right. | [
"4 3 9\n",
"4 3 24\n",
"2 4 4\n"
] | [
"2 2 L\n",
"4 3 R\n",
"1 2 R\n"
] | The first and the second samples are shown on the picture. The green place corresponds to Santa Claus' place in the first example, the blue place corresponds to Santa Claus' place in the second example.
In the third sample there are two lanes with four desks in each, and Santa Claus has the fourth place. Thus, his place is in the first lane at the second desk on the right. | 0 | [
{
"input": "4 3 9",
"output": "2 2 L"
},
{
"input": "4 3 24",
"output": "4 3 R"
},
{
"input": "2 4 4",
"output": "1 2 R"
},
{
"input": "3 10 24",
"output": "2 2 R"
},
{
"input": "10 3 59",
"output": "10 3 L"
},
{
"input": "10000 10000 160845880",
"... | 1,482,657,384 | 684 | Python 3 | OK | TESTS | 46 | 77 | 4,608,000 | ins = list(map(int, input().split()))
n = ins[0]
m = ins[1]
k = ins[2]
koln = 1
kolm = 1
while k > 2*m:
k -= 2*m
koln+=1
while k > 2:
k-=2
kolm += 1
if k == 1:
print(koln,kolm,"L")
else:
print(koln, kolm, "R") | Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are *n* lanes of *m* desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to *n* from the left to the right, the desks in a lane are numbered from 1 to *m* starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture).
The organizers numbered all the working places from 1 to 2*nm*. The places are numbered by lanes (i.Β e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i.Β e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right.
Santa Clause knows that his place has number *k*. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right!
Input Specification:
The only line contains three integers *n*, *m* and *k* (1<=β€<=*n*,<=*m*<=β€<=10<=000, 1<=β€<=*k*<=β€<=2*nm*)Β β the number of lanes, the number of desks in each lane and the number of Santa Claus' place.
Output Specification:
Print two integers: the number of lane *r*, the number of desk *d*, and a character *s*, which stands for the side of the desk Santa Claus. The character *s* should be "L", if Santa Clause should sit on the left, and "R" if his place is on the right.
Demo Input:
['4 3 9\n', '4 3 24\n', '2 4 4\n']
Demo Output:
['2 2 L\n', '4 3 R\n', '1 2 R\n']
Note:
The first and the second samples are shown on the picture. The green place corresponds to Santa Claus' place in the first example, the blue place corresponds to Santa Claus' place in the second example.
In the third sample there are two lanes with four desks in each, and Santa Claus has the fourth place. Thus, his place is in the first lane at the second desk on the right. | ```python
ins = list(map(int, input().split()))
n = ins[0]
m = ins[1]
k = ins[2]
koln = 1
kolm = 1
while k > 2*m:
k -= 2*m
koln+=1
while k > 2:
k-=2
kolm += 1
if k == 1:
print(koln,kolm,"L")
else:
print(koln, kolm, "R")
``` | 3 | |
749 | A | Bachgold Problem | PROGRAMMING | 800 | [
"greedy",
"implementation",
"math",
"number theory"
] | null | null | Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisorsΒ β 1 and *k*. | The only line of the input contains a single integer *n* (2<=β€<=*n*<=β€<=100<=000). | The first line of the output contains a single integer *k*Β β maximum possible number of primes in representation.
The second line should contain *k* primes with their sum equal to *n*. You can print them in any order. If there are several optimal solution, print any of them. | [
"5\n",
"6\n"
] | [
"2\n2 3\n",
"3\n2 2 2\n"
] | none | 500 | [
{
"input": "5",
"output": "2\n2 3"
},
{
"input": "6",
"output": "3\n2 2 2"
},
{
"input": "2",
"output": "1\n2"
},
{
"input": "3",
"output": "1\n3"
},
{
"input": "99999",
"output": "49999\n2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ... | 1,696,413,180 | 2,147,483,647 | Python 3 | OK | TESTS | 41 | 77 | 1,024,000 | a = int(input())
print(a // 2)
b = [2] * (a // 2)
if a % 2 == 0:
print(*b)
else:
b[-1] = 3
print(*b) | Title: Bachgold Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisorsΒ β 1 and *k*.
Input Specification:
The only line of the input contains a single integer *n* (2<=β€<=*n*<=β€<=100<=000).
Output Specification:
The first line of the output contains a single integer *k*Β β maximum possible number of primes in representation.
The second line should contain *k* primes with their sum equal to *n*. You can print them in any order. If there are several optimal solution, print any of them.
Demo Input:
['5\n', '6\n']
Demo Output:
['2\n2 3\n', '3\n2 2 2\n']
Note:
none | ```python
a = int(input())
print(a // 2)
b = [2] * (a // 2)
if a % 2 == 0:
print(*b)
else:
b[-1] = 3
print(*b)
``` | 3 | |
348 | A | Mafia | PROGRAMMING | 1,600 | [
"binary search",
"math",
"sortings"
] | null | null | One day *n* friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other *n*<=-<=1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the *i*-th person wants to play *a**i* rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | The first line contains integer *n* (3<=β€<=*n*<=β€<=105). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=109) β the *i*-th number in the list is the number of rounds the *i*-th person wants to play. | In a single line print a single integer β the minimum number of game rounds the friends need to let the *i*-th person play at least *a**i* rounds.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | [
"3\n3 2 2\n",
"4\n2 2 2 2\n"
] | [
"4\n",
"3\n"
] | You don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | 500 | [
{
"input": "3\n3 2 2",
"output": "4"
},
{
"input": "4\n2 2 2 2",
"output": "3"
},
{
"input": "7\n9 7 7 8 8 7 8",
"output": "9"
},
{
"input": "10\n13 12 10 13 13 14 10 10 12 12",
"output": "14"
},
{
"input": "10\n94 96 91 95 99 94 96 92 95 99",
"output": "106"
... | 1,694,163,899 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 34 | 216 | 15,872,000 | from cmath import inf
import math
import sys
from os import path
#import bisect
#import math
from functools import reduce
import collections
import sys
if (path.exists('CP/input.txt')):
sys.stdout = open('CP/output.txt', 'w')
sys.stdin = open('CP/input.txt', 'r')
def ok(mid,arr,maxi):
d = 0
for x in arr:
d += (mid - x)
#print(d)
if(d>=mid):
return True
return False
def answer():
n = int(input())
arr = list(map(int,input().split()))
l,r = 0,(2**31 - 1)
for x in arr:
l = max(l,x)
maxi = l
ans=-1
while(l<=r):
#print(l," ",r)
mid = (l+r)//2
#print(mid)
if(ok(mid,arr,maxi)):
ans = mid
r=mid-1
else:
l=mid+1
print(ans)
#t = int(input())
t=1
for _ in range(t):
answer() | Title: Mafia
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day *n* friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other *n*<=-<=1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the *i*-th person wants to play *a**i* rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
Input Specification:
The first line contains integer *n* (3<=β€<=*n*<=β€<=105). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=109) β the *i*-th number in the list is the number of rounds the *i*-th person wants to play.
Output Specification:
In a single line print a single integer β the minimum number of game rounds the friends need to let the *i*-th person play at least *a**i* rounds.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Demo Input:
['3\n3 2 2\n', '4\n2 2 2 2\n']
Demo Output:
['4\n', '3\n']
Note:
You don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | ```python
from cmath import inf
import math
import sys
from os import path
#import bisect
#import math
from functools import reduce
import collections
import sys
if (path.exists('CP/input.txt')):
sys.stdout = open('CP/output.txt', 'w')
sys.stdin = open('CP/input.txt', 'r')
def ok(mid,arr,maxi):
d = 0
for x in arr:
d += (mid - x)
#print(d)
if(d>=mid):
return True
return False
def answer():
n = int(input())
arr = list(map(int,input().split()))
l,r = 0,(2**31 - 1)
for x in arr:
l = max(l,x)
maxi = l
ans=-1
while(l<=r):
#print(l," ",r)
mid = (l+r)//2
#print(mid)
if(ok(mid,arr,maxi)):
ans = mid
r=mid-1
else:
l=mid+1
print(ans)
#t = int(input())
t=1
for _ in range(t):
answer()
``` | 3 | |
677 | A | Vanya and Fence | PROGRAMMING | 800 | [
"implementation"
] | null | null | Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard? | The first line of the input contains two integers *n* and *h* (1<=β€<=*n*<=β€<=1000, 1<=β€<=*h*<=β€<=1000)Β β the number of friends and the height of the fence, respectively.
The second line contains *n* integers *a**i* (1<=β€<=*a**i*<=β€<=2*h*), the *i*-th of them is equal to the height of the *i*-th person. | Print a single integerΒ β the minimum possible valid width of the road. | [
"3 7\n4 5 14\n",
"6 1\n1 1 1 1 1 1\n",
"6 5\n7 6 8 9 10 5\n"
] | [
"4\n",
"6\n",
"11\n"
] | In the first sample, only person number 3 must bend down, so the required width is equal to 1β+β1β+β2β=β4.
In the second sample, all friends are short enough and no one has to bend, so the width 1β+β1β+β1β+β1β+β1β+β1β=β6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2β+β2β+β2β+β2β+β2β+β1β=β11. | 500 | [
{
"input": "3 7\n4 5 14",
"output": "4"
},
{
"input": "6 1\n1 1 1 1 1 1",
"output": "6"
},
{
"input": "6 5\n7 6 8 9 10 5",
"output": "11"
},
{
"input": "10 420\n214 614 297 675 82 740 174 23 255 15",
"output": "13"
},
{
"input": "10 561\n657 23 1096 487 785 66 481... | 1,691,168,574 | 2,147,483,647 | Python 3 | OK | TESTS | 29 | 46 | 0 |
n,h=map(int, input().split())
a= list(map(int, input().strip().split())) [:n]
c=0
for i in a:
if(i>h):
c+=2
else:
c+=1
print(c) | Title: Vanya and Fence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input Specification:
The first line of the input contains two integers *n* and *h* (1<=β€<=*n*<=β€<=1000, 1<=β€<=*h*<=β€<=1000)Β β the number of friends and the height of the fence, respectively.
The second line contains *n* integers *a**i* (1<=β€<=*a**i*<=β€<=2*h*), the *i*-th of them is equal to the height of the *i*-th person.
Output Specification:
Print a single integerΒ β the minimum possible valid width of the road.
Demo Input:
['3 7\n4 5 14\n', '6 1\n1 1 1 1 1 1\n', '6 5\n7 6 8 9 10 5\n']
Demo Output:
['4\n', '6\n', '11\n']
Note:
In the first sample, only person number 3 must bend down, so the required width is equal to 1β+β1β+β2β=β4.
In the second sample, all friends are short enough and no one has to bend, so the width 1β+β1β+β1β+β1β+β1β+β1β=β6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2β+β2β+β2β+β2β+β2β+β1β=β11. | ```python
n,h=map(int, input().split())
a= list(map(int, input().strip().split())) [:n]
c=0
for i in a:
if(i>h):
c+=2
else:
c+=1
print(c)
``` | 3 | |
731 | A | Night at the Museum | PROGRAMMING | 800 | [
"implementation",
"strings"
] | null | null | Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it. | The only line of input contains the name of some exhibitΒ β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters. | Print one integerΒ β the minimum number of rotations of the wheel, required to print the name given in the input. | [
"zeus\n",
"map\n",
"ares\n"
] | [
"18\n",
"35\n",
"34\n"
] | To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise), 1. from 'z' to 'e' (5 clockwise rotations), 1. from 'e' to 'u' (10 rotations counterclockwise), 1. from 'u' to 's' (2 counterclockwise rotations). | 500 | [
{
"input": "zeus",
"output": "18"
},
{
"input": "map",
"output": "35"
},
{
"input": "ares",
"output": "34"
},
{
"input": "l",
"output": "11"
},
{
"input": "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv",
"... | 1,663,185,732 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 44 | 62 | 0 | wheel = input()
counter = 0
pointer = 'a'
for c in wheel:
distance = abs(ord(pointer) - ord(c))
if distance < 13:
counter += distance
else:
counter += (26 - distance)
pointer = c
print(counter) | Title: Night at the Museum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input Specification:
The only line of input contains the name of some exhibitΒ β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output Specification:
Print one integerΒ β the minimum number of rotations of the wheel, required to print the name given in the input.
Demo Input:
['zeus\n', 'map\n', 'ares\n']
Demo Output:
['18\n', '35\n', '34\n']
Note:
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise), 1. from 'z' to 'e' (5 clockwise rotations), 1. from 'e' to 'u' (10 rotations counterclockwise), 1. from 'u' to 's' (2 counterclockwise rotations). | ```python
wheel = input()
counter = 0
pointer = 'a'
for c in wheel:
distance = abs(ord(pointer) - ord(c))
if distance < 13:
counter += distance
else:
counter += (26 - distance)
pointer = c
print(counter)
``` | 3 | |
431 | A | Black Square | PROGRAMMING | 800 | [
"implementation"
] | null | null | Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly *a**i* calories on touching the *i*-th strip.
You've got a string *s*, describing the process of the game and numbers *a*1,<=*a*2,<=*a*3,<=*a*4. Calculate how many calories Jury needs to destroy all the squares? | The first line contains four space-separated integers *a*1, *a*2, *a*3, *a*4 (0<=β€<=*a*1,<=*a*2,<=*a*3,<=*a*4<=β€<=104).
The second line contains string *s* (1<=β€<=|*s*|<=β€<=105), where the *Ρ*-th character of the string equals "1", if on the *i*-th second of the game the square appears on the first strip, "2", if it appears on the second strip, "3", if it appears on the third strip, "4", if it appears on the fourth strip. | Print a single integer β the total number of calories that Jury wastes. | [
"1 2 3 4\n123214\n",
"1 5 3 2\n11221\n"
] | [
"13\n",
"13\n"
] | none | 500 | [
{
"input": "1 2 3 4\n123214",
"output": "13"
},
{
"input": "1 5 3 2\n11221",
"output": "13"
},
{
"input": "5 5 5 1\n3422",
"output": "16"
},
{
"input": "4 3 2 1\n2",
"output": "3"
},
{
"input": "5651 6882 6954 4733\n2442313421",
"output": "60055"
},
{
... | 1,687,535,146 | 2,147,483,647 | Python 3 | OK | TESTS | 49 | 62 | 102,400 | sList = [int(x) for x in input().split()][:4]
game = input()
count = 0
for i in game:
count += sList[int(i)-1]
print(count)
| Title: Black Square
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly *a**i* calories on touching the *i*-th strip.
You've got a string *s*, describing the process of the game and numbers *a*1,<=*a*2,<=*a*3,<=*a*4. Calculate how many calories Jury needs to destroy all the squares?
Input Specification:
The first line contains four space-separated integers *a*1, *a*2, *a*3, *a*4 (0<=β€<=*a*1,<=*a*2,<=*a*3,<=*a*4<=β€<=104).
The second line contains string *s* (1<=β€<=|*s*|<=β€<=105), where the *Ρ*-th character of the string equals "1", if on the *i*-th second of the game the square appears on the first strip, "2", if it appears on the second strip, "3", if it appears on the third strip, "4", if it appears on the fourth strip.
Output Specification:
Print a single integer β the total number of calories that Jury wastes.
Demo Input:
['1 2 3 4\n123214\n', '1 5 3 2\n11221\n']
Demo Output:
['13\n', '13\n']
Note:
none | ```python
sList = [int(x) for x in input().split()][:4]
game = input()
count = 0
for i in game:
count += sList[int(i)-1]
print(count)
``` | 3 | |
835 | A | Key races | PROGRAMMING | 800 | [
"math"
] | null | null | Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *t*2 milliseconds.
If connection ping (delay) is *t* milliseconds, the competition passes for a participant as follows:
1. Exactly after *t* milliseconds after the start of the competition the participant receives the text to be entered. 1. Right after that he starts to type it. 1. Exactly *t* milliseconds after he ends typing all the text, the site receives information about it.
The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.
Given the length of the text and the information about participants, determine the result of the game. | The first line contains five integers *s*, *v*1, *v*2, *t*1, *t*2 (1<=β€<=*s*,<=*v*1,<=*v*2,<=*t*1,<=*t*2<=β€<=1000)Β β the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant. | If the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw print "Friendship". | [
"5 1 2 1 2\n",
"3 3 1 1 1\n",
"4 5 3 1 5\n"
] | [
"First\n",
"Second\n",
"Friendship\n"
] | In the first example, information on the success of the first participant comes in 7 milliseconds, of the second participantΒ β in 14 milliseconds. So, the first wins.
In the second example, information on the success of the first participant comes in 11 milliseconds, of the second participantΒ β in 5 milliseconds. So, the second wins.
In the third example, information on the success of the first participant comes in 22 milliseconds, of the second participantΒ β in 22 milliseconds. So, it is be a draw. | 500 | [
{
"input": "5 1 2 1 2",
"output": "First"
},
{
"input": "3 3 1 1 1",
"output": "Second"
},
{
"input": "4 5 3 1 5",
"output": "Friendship"
},
{
"input": "1000 1000 1000 1000 1000",
"output": "Friendship"
},
{
"input": "1 1 1 1 1",
"output": "Friendship"
},
... | 1,663,772,699 | 2,147,483,647 | Python 3 | OK | TESTS | 32 | 46 | 0 | s, v_1, v_2, t_1, t_2 = map(int, input().split())
if (result_1 := s * v_1 + 2 * t_1) != (result_2 := s * v_2 + 2 * t_2):
if result_1 > result_2:
print('Second')
else:
print('First')
else:
print('Friendship') | Title: Key races
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *t*2 milliseconds.
If connection ping (delay) is *t* milliseconds, the competition passes for a participant as follows:
1. Exactly after *t* milliseconds after the start of the competition the participant receives the text to be entered. 1. Right after that he starts to type it. 1. Exactly *t* milliseconds after he ends typing all the text, the site receives information about it.
The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.
Given the length of the text and the information about participants, determine the result of the game.
Input Specification:
The first line contains five integers *s*, *v*1, *v*2, *t*1, *t*2 (1<=β€<=*s*,<=*v*1,<=*v*2,<=*t*1,<=*t*2<=β€<=1000)Β β the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant.
Output Specification:
If the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw print "Friendship".
Demo Input:
['5 1 2 1 2\n', '3 3 1 1 1\n', '4 5 3 1 5\n']
Demo Output:
['First\n', 'Second\n', 'Friendship\n']
Note:
In the first example, information on the success of the first participant comes in 7 milliseconds, of the second participantΒ β in 14 milliseconds. So, the first wins.
In the second example, information on the success of the first participant comes in 11 milliseconds, of the second participantΒ β in 5 milliseconds. So, the second wins.
In the third example, information on the success of the first participant comes in 22 milliseconds, of the second participantΒ β in 22 milliseconds. So, it is be a draw. | ```python
s, v_1, v_2, t_1, t_2 = map(int, input().split())
if (result_1 := s * v_1 + 2 * t_1) != (result_2 := s * v_2 + 2 * t_2):
if result_1 > result_2:
print('Second')
else:
print('First')
else:
print('Friendship')
``` | 3 | |
387 | B | George and Round | PROGRAMMING | 1,200 | [
"brute force",
"greedy",
"two pointers"
] | null | null | George decided to prepare a Codesecrof round, so he has prepared *m* problems for the round. Let's number the problems with integers 1 through *m*. George estimates the *i*-th problem's complexity by integer *b**i*.
To make the round good, he needs to put at least *n* problems there. Besides, he needs to have at least one problem with complexity exactly *a*1, at least one with complexity exactly *a*2, ..., and at least one with complexity exactly *a**n*. Of course, the round can also have problems with other complexities.
George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity *c* to any positive integer complexity *d* (*c*<=β₯<=*d*), by changing limits on the input data.
However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the *m* he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity. | The first line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=3000) β the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a*1<=<<=*a*2<=<<=...<=<<=*a**n*<=β€<=106) β the requirements for the complexity of the problems in a good round. The third line contains space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=β€<=*b*1<=β€<=*b*2...<=β€<=*b**m*<=β€<=106) β the complexities of the problems prepared by George. | Print a single integer β the answer to the problem. | [
"3 5\n1 2 3\n1 2 2 3 3\n",
"3 5\n1 2 3\n1 1 1 1 1\n",
"3 1\n2 3 4\n1\n"
] | [
"0\n",
"2\n",
"3\n"
] | In the first sample the set of the prepared problems meets the requirements for a good round.
In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.
In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2,β3,β4. | 1,000 | [
{
"input": "3 5\n1 2 3\n1 2 2 3 3",
"output": "0"
},
{
"input": "3 5\n1 2 3\n1 1 1 1 1",
"output": "2"
},
{
"input": "3 1\n2 3 4\n1",
"output": "3"
},
{
"input": "29 100\n20 32 41 67 72 155 331 382 399 412 465 470 484 511 515 529 616 637 679 715 733 763 826 843 862 903 925 97... | 1,548,161,892 | 2,147,483,647 | Python 3 | OK | TESTS | 41 | 109 | 614,400 | n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
jb = 0
cnt = 0
for ai in a:
while jb < m and b[jb] < ai:
jb += 1
if jb == m:
break
cnt += 1
jb += 1
print(len(a) - cnt)
| Title: George and Round
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
George decided to prepare a Codesecrof round, so he has prepared *m* problems for the round. Let's number the problems with integers 1 through *m*. George estimates the *i*-th problem's complexity by integer *b**i*.
To make the round good, he needs to put at least *n* problems there. Besides, he needs to have at least one problem with complexity exactly *a*1, at least one with complexity exactly *a*2, ..., and at least one with complexity exactly *a**n*. Of course, the round can also have problems with other complexities.
George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity *c* to any positive integer complexity *d* (*c*<=β₯<=*d*), by changing limits on the input data.
However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the *m* he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=3000) β the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a*1<=<<=*a*2<=<<=...<=<<=*a**n*<=β€<=106) β the requirements for the complexity of the problems in a good round. The third line contains space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=β€<=*b*1<=β€<=*b*2...<=β€<=*b**m*<=β€<=106) β the complexities of the problems prepared by George.
Output Specification:
Print a single integer β the answer to the problem.
Demo Input:
['3 5\n1 2 3\n1 2 2 3 3\n', '3 5\n1 2 3\n1 1 1 1 1\n', '3 1\n2 3 4\n1\n']
Demo Output:
['0\n', '2\n', '3\n']
Note:
In the first sample the set of the prepared problems meets the requirements for a good round.
In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.
In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2,β3,β4. | ```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
jb = 0
cnt = 0
for ai in a:
while jb < m and b[jb] < ai:
jb += 1
if jb == m:
break
cnt += 1
jb += 1
print(len(a) - cnt)
``` | 3 | |
527 | A | Playing with Paper | PROGRAMMING | 1,100 | [
"implementation",
"math"
] | null | null | One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular *a* mm <=Γ<= *b* mm sheet of paper (*a*<=><=*b*). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part.
After making a paper ship from the square piece, Vasya looked on the remaining (*a*<=-<=*b*) mm <=Γ<= *b* mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop.
Can you determine how many ships Vasya will make during the lesson? | The first line of the input contains two integers *a*, *b* (1<=β€<=*b*<=<<=*a*<=β€<=1012) β the sizes of the original sheet of paper. | Print a single integer β the number of ships that Vasya will make. | [
"2 1\n",
"10 7\n",
"1000000000000 1\n"
] | [
"2\n",
"6\n",
"1000000000000\n"
] | Pictures to the first and second sample test. | 500 | [
{
"input": "2 1",
"output": "2"
},
{
"input": "10 7",
"output": "6"
},
{
"input": "1000000000000 1",
"output": "1000000000000"
},
{
"input": "3 1",
"output": "3"
},
{
"input": "4 1",
"output": "4"
},
{
"input": "3 2",
"output": "3"
},
{
"in... | 1,592,812,484 | 2,147,483,647 | PyPy 3 | OK | TESTS | 46 | 140 | 0 | a,b = list(map(int,input().split()))
ans = 0
while True:
if b>a:
a,b = b,a
if a%b==0:
ans+=a//b
break
else:
ans+=a//b
a = a%b
print(ans) | Title: Playing with Paper
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular *a* mm <=Γ<= *b* mm sheet of paper (*a*<=><=*b*). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part.
After making a paper ship from the square piece, Vasya looked on the remaining (*a*<=-<=*b*) mm <=Γ<= *b* mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop.
Can you determine how many ships Vasya will make during the lesson?
Input Specification:
The first line of the input contains two integers *a*, *b* (1<=β€<=*b*<=<<=*a*<=β€<=1012) β the sizes of the original sheet of paper.
Output Specification:
Print a single integer β the number of ships that Vasya will make.
Demo Input:
['2 1\n', '10 7\n', '1000000000000 1\n']
Demo Output:
['2\n', '6\n', '1000000000000\n']
Note:
Pictures to the first and second sample test. | ```python
a,b = list(map(int,input().split()))
ans = 0
while True:
if b>a:
a,b = b,a
if a%b==0:
ans+=a//b
break
else:
ans+=a//b
a = a%b
print(ans)
``` | 3 | |
125 | A | Measuring Lengths in Baden | PROGRAMMING | 1,400 | [
"math"
] | null | null | Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to *n* centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch. | The only line contains an integer *n* (1<=β€<=*n*<=β€<=10000). | Print two non-negative space-separated integers *a* and *b*, where *a* is the numbers of feet and *b* is the number of inches. | [
"42\n",
"5\n"
] | [
"1 2\n",
"0 2\n"
] | none | 1,000 | [
{
"input": "42",
"output": "1 2"
},
{
"input": "5",
"output": "0 2"
},
{
"input": "24",
"output": "0 8"
},
{
"input": "1",
"output": "0 0"
},
{
"input": "2",
"output": "0 1"
},
{
"input": "3",
"output": "0 1"
},
{
"input": "4",
"output"... | 1,597,230,293 | 2,147,483,647 | Python 3 | OK | TESTS | 22 | 216 | 6,656,000 | x = int(input())
x = (x+1)//3
print(x//12, x%12)
| Title: Measuring Lengths in Baden
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to *n* centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input Specification:
The only line contains an integer *n* (1<=β€<=*n*<=β€<=10000).
Output Specification:
Print two non-negative space-separated integers *a* and *b*, where *a* is the numbers of feet and *b* is the number of inches.
Demo Input:
['42\n', '5\n']
Demo Output:
['1 2\n', '0 2\n']
Note:
none | ```python
x = int(input())
x = (x+1)//3
print(x//12, x%12)
``` | 3 | |
1,005 | B | Delete from the Left | PROGRAMMING | 900 | [
"brute force",
"implementation",
"strings"
] | null | null | You are given two strings $s$ and $t$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $1$. You can't choose a string if it is empty.
For example:
- by applying a move to the string "where", the result is the string "here", - by applying a move to the string "a", the result is an empty string "".
You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.
Write a program that finds the minimum number of moves to make two given strings $s$ and $t$ equal. | The first line of the input contains $s$. In the second line of the input contains $t$. Both strings consist only of lowercase Latin letters. The number of letters in each string is between 1 and $2\cdot10^5$, inclusive. | Output the fewest number of moves required. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the given strings. | [
"test\nwest\n",
"codeforces\nyes\n",
"test\nyes\n",
"b\nab\n"
] | [
"2\n",
"9\n",
"7\n",
"1\n"
] | In the first example, you should apply the move once to the first string and apply the move once to the second string. As a result, both strings will be equal to "est".
In the second example, the move should be applied to the string "codeforces" $8$ times. As a result, the string becomes "codeforces" $\to$ "es". The move should be applied to the string "yes" once. The result is the same string "yes" $\to$ "es".
In the third example, you can make the strings equal only by completely deleting them. That is, in the end, both strings will be empty.
In the fourth example, the first character of the second string should be deleted. | 0 | [
{
"input": "test\nwest",
"output": "2"
},
{
"input": "codeforces\nyes",
"output": "9"
},
{
"input": "test\nyes",
"output": "7"
},
{
"input": "b\nab",
"output": "1"
},
{
"input": "z\nz",
"output": "0"
},
{
"input": "abacabadabacaba\nabacabadacaba",
... | 1,636,077,207 | 2,147,483,647 | Python 3 | OK | TESTS | 28 | 124 | 5,734,400 | string1 = input()
string2 = input()
same = 0
minn = min(len(string1),len(string2))
for i in range(minn):
if string1[-1-i]==string2[-1-i]:
same += 2
else:
break
print((len(string1)+len(string2))-same) | Title: Delete from the Left
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two strings $s$ and $t$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $1$. You can't choose a string if it is empty.
For example:
- by applying a move to the string "where", the result is the string "here", - by applying a move to the string "a", the result is an empty string "".
You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.
Write a program that finds the minimum number of moves to make two given strings $s$ and $t$ equal.
Input Specification:
The first line of the input contains $s$. In the second line of the input contains $t$. Both strings consist only of lowercase Latin letters. The number of letters in each string is between 1 and $2\cdot10^5$, inclusive.
Output Specification:
Output the fewest number of moves required. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the given strings.
Demo Input:
['test\nwest\n', 'codeforces\nyes\n', 'test\nyes\n', 'b\nab\n']
Demo Output:
['2\n', '9\n', '7\n', '1\n']
Note:
In the first example, you should apply the move once to the first string and apply the move once to the second string. As a result, both strings will be equal to "est".
In the second example, the move should be applied to the string "codeforces" $8$ times. As a result, the string becomes "codeforces" $\to$ "es". The move should be applied to the string "yes" once. The result is the same string "yes" $\to$ "es".
In the third example, you can make the strings equal only by completely deleting them. That is, in the end, both strings will be empty.
In the fourth example, the first character of the second string should be deleted. | ```python
string1 = input()
string2 = input()
same = 0
minn = min(len(string1),len(string2))
for i in range(minn):
if string1[-1-i]==string2[-1-i]:
same += 2
else:
break
print((len(string1)+len(string2))-same)
``` | 3 | |
546 | A | Soldier and Bananas | PROGRAMMING | 800 | [
"brute force",
"implementation",
"math"
] | null | null | A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*Β·*k* dollars for the *i*-th banana).
He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas? | The first line contains three positive integers *k*,<=*n*,<=*w* (1<=<=β€<=<=*k*,<=*w*<=<=β€<=<=1000, 0<=β€<=*n*<=β€<=109), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants. | Output one integer β the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0. | [
"3 17 4\n"
] | [
"13"
] | none | 500 | [
{
"input": "3 17 4",
"output": "13"
},
{
"input": "1 2 1",
"output": "0"
},
{
"input": "1 1 1",
"output": "0"
},
{
"input": "1 5 6",
"output": "16"
},
{
"input": "1 1000000000 1",
"output": "0"
},
{
"input": "1000 0 1000",
"output": "500500000"
}... | 1,694,183,550 | 2,147,483,647 | Python 3 | OK | TESTS | 15 | 46 | 0 | while True:
try:
a, b, c = map(int, input().split())
t = sum(i * a for i in range(1, c + 1))
res = max(0, t - b)
print(res)
except EOFError:
break
| Title: Soldier and Bananas
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*Β·*k* dollars for the *i*-th banana).
He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas?
Input Specification:
The first line contains three positive integers *k*,<=*n*,<=*w* (1<=<=β€<=<=*k*,<=*w*<=<=β€<=<=1000, 0<=β€<=*n*<=β€<=109), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants.
Output Specification:
Output one integer β the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0.
Demo Input:
['3 17 4\n']
Demo Output:
['13']
Note:
none | ```python
while True:
try:
a, b, c = map(int, input().split())
t = sum(i * a for i in range(1, c + 1))
res = max(0, t - b)
print(res)
except EOFError:
break
``` | 3 | |
554 | B | Ohana Cleans Up | PROGRAMMING | 1,200 | [
"brute force",
"greedy",
"strings"
] | null | null | Ohana Matsumae is trying to clean a room, which is divided up into an *n* by *n* grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.
Return the maximum number of rows that she can make completely clean. | The first line of input will be a single integer *n* (1<=β€<=*n*<=β€<=100).
The next *n* lines will describe the state of the room. The *i*-th line will contain a binary string with *n* characters denoting the state of the *i*-th row of the room. The *j*-th character on this line is '1' if the *j*-th square in the *i*-th row is clean, and '0' if it is dirty. | The output should be a single line containing an integer equal to a maximum possible number of rows that are completely clean. | [
"4\n0101\n1000\n1111\n0101\n",
"3\n111\n111\n111\n"
] | [
"2\n",
"3\n"
] | In the first sample, Ohana can sweep the 1st and 3rd columns. This will make the 1st and 4th row be completely clean.
In the second sample, everything is already clean, so Ohana doesn't need to do anything. | 500 | [
{
"input": "4\n0101\n1000\n1111\n0101",
"output": "2"
},
{
"input": "3\n111\n111\n111",
"output": "3"
},
{
"input": "10\n0100000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000",
"output": "9"
},
{
"input": "1\n1"... | 1,606,082,537 | 2,147,483,647 | Python 3 | OK | TESTS | 36 | 124 | 409,600 | from collections import defaultdict
n = int(input())
ans = 0
rows = defaultdict()
for _ in range(n):
row = str(input())
if row in rows:
rows[row] += 1
else:
rows[row] = 1
curr = rows[row]
if curr > ans:
ans = curr
print(ans)
| Title: Ohana Cleans Up
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ohana Matsumae is trying to clean a room, which is divided up into an *n* by *n* grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.
Return the maximum number of rows that she can make completely clean.
Input Specification:
The first line of input will be a single integer *n* (1<=β€<=*n*<=β€<=100).
The next *n* lines will describe the state of the room. The *i*-th line will contain a binary string with *n* characters denoting the state of the *i*-th row of the room. The *j*-th character on this line is '1' if the *j*-th square in the *i*-th row is clean, and '0' if it is dirty.
Output Specification:
The output should be a single line containing an integer equal to a maximum possible number of rows that are completely clean.
Demo Input:
['4\n0101\n1000\n1111\n0101\n', '3\n111\n111\n111\n']
Demo Output:
['2\n', '3\n']
Note:
In the first sample, Ohana can sweep the 1st and 3rd columns. This will make the 1st and 4th row be completely clean.
In the second sample, everything is already clean, so Ohana doesn't need to do anything. | ```python
from collections import defaultdict
n = int(input())
ans = 0
rows = defaultdict()
for _ in range(n):
row = str(input())
if row in rows:
rows[row] += 1
else:
rows[row] = 1
curr = rows[row]
if curr > ans:
ans = curr
print(ans)
``` | 3 | |
298 | A | Snow Footprints | PROGRAMMING | 1,300 | [
"greedy",
"implementation"
] | null | null | There is a straight snowy road, divided into *n* blocks. The blocks are numbered from 1 to *n* from left to right. If one moves from the *i*-th block to the (*i*<=+<=1)-th block, he will leave a right footprint on the *i*-th block. Similarly, if one moves from the *i*-th block to the (*i*<=-<=1)-th block, he will leave a left footprint on the *i*-th block. If there already is a footprint on the *i*-th block, the new footprint will cover the old one.
At the beginning, there were no footprints. Then polar bear Alice starts from the *s*-th block, makes a sequence of moves and ends in the *t*-th block. It is known that Alice never moves outside of the road.
You are given the description of Alice's footprints. Your task is to find a pair of possible values of *s*,<=*t* by looking at the footprints. | The first line of the input contains integer *n* (3<=β€<=*n*<=β€<=1000).
The second line contains the description of the road β the string that consists of *n* characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint).
It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. | Print two space-separated integers β the values of *s* and *t*. If there are several possible solutions you can print any of them. | [
"9\n..RRLL...\n",
"11\n.RRRLLLLL..\n"
] | [
"3 4\n",
"7 5\n"
] | The first test sample is the one in the picture. | 500 | [
{
"input": "11\n.RRRLLLLL..",
"output": "7 5"
},
{
"input": "4\n.RL.",
"output": "3 2"
},
{
"input": "3\n.L.",
"output": "2 1"
},
{
"input": "3\n.R.",
"output": "2 3"
}
] | 1,548,536,535 | 2,147,483,647 | Python 3 | OK | TESTS | 23 | 186 | 0 | n=int(input())
s=input()
r=0
for i in range(n):
if s[i]=='R':
r=1
if r==0:
for i in range(n):
if s[i]=='L':
a=i
break
for j in range(i,n):
if s[j]=='.':
b=j
break
print(b,a)
else:
for i in range(n):
if s[i]!='.':
print(i+1,end=" ")
k=s[i]
break
if k=='L':
k='R'
else:
k='L'
q=0
for j in range(i,n):
if s[j]==k:
print(j)
q=1
break
elif s[j]=='.':
print(j+1)
q=1
break
if q==0:
print(n)
| Title: Snow Footprints
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is a straight snowy road, divided into *n* blocks. The blocks are numbered from 1 to *n* from left to right. If one moves from the *i*-th block to the (*i*<=+<=1)-th block, he will leave a right footprint on the *i*-th block. Similarly, if one moves from the *i*-th block to the (*i*<=-<=1)-th block, he will leave a left footprint on the *i*-th block. If there already is a footprint on the *i*-th block, the new footprint will cover the old one.
At the beginning, there were no footprints. Then polar bear Alice starts from the *s*-th block, makes a sequence of moves and ends in the *t*-th block. It is known that Alice never moves outside of the road.
You are given the description of Alice's footprints. Your task is to find a pair of possible values of *s*,<=*t* by looking at the footprints.
Input Specification:
The first line of the input contains integer *n* (3<=β€<=*n*<=β€<=1000).
The second line contains the description of the road β the string that consists of *n* characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint).
It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists.
Output Specification:
Print two space-separated integers β the values of *s* and *t*. If there are several possible solutions you can print any of them.
Demo Input:
['9\n..RRLL...\n', '11\n.RRRLLLLL..\n']
Demo Output:
['3 4\n', '7 5\n']
Note:
The first test sample is the one in the picture. | ```python
n=int(input())
s=input()
r=0
for i in range(n):
if s[i]=='R':
r=1
if r==0:
for i in range(n):
if s[i]=='L':
a=i
break
for j in range(i,n):
if s[j]=='.':
b=j
break
print(b,a)
else:
for i in range(n):
if s[i]!='.':
print(i+1,end=" ")
k=s[i]
break
if k=='L':
k='R'
else:
k='L'
q=0
for j in range(i,n):
if s[j]==k:
print(j)
q=1
break
elif s[j]=='.':
print(j+1)
q=1
break
if q==0:
print(n)
``` | 3 | |
281 | A | Word Capitalization | PROGRAMMING | 800 | [
"implementation",
"strings"
] | null | null | Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged. | A single line contains a non-empty word. This word consists of lowercase and uppercase English letters. The length of the word will not exceed 103. | Output the given word after capitalization. | [
"ApPLe\n",
"konjac\n"
] | [
"ApPLe\n",
"Konjac\n"
] | none | 500 | [
{
"input": "ApPLe",
"output": "ApPLe"
},
{
"input": "konjac",
"output": "Konjac"
},
{
"input": "a",
"output": "A"
},
{
"input": "A",
"output": "A"
},
{
"input": "z",
"output": "Z"
},
{
"input": "ABACABA",
"output": "ABACABA"
},
{
"input": "... | 1,698,515,903 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 25 | 124 | 0 | def solve(word):
return word[0].upper() + word[1:]
def main():
word = input().strip() # string values
print(solve(word))
if __name__ == "__main__":
main() | Title: Word Capitalization
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input Specification:
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters. The length of the word will not exceed 103.
Output Specification:
Output the given word after capitalization.
Demo Input:
['ApPLe\n', 'konjac\n']
Demo Output:
['ApPLe\n', 'Konjac\n']
Note:
none | ```python
def solve(word):
return word[0].upper() + word[1:]
def main():
word = input().strip() # string values
print(solve(word))
if __name__ == "__main__":
main()
``` | 3 | |
546 | A | Soldier and Bananas | PROGRAMMING | 800 | [
"brute force",
"implementation",
"math"
] | null | null | A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*Β·*k* dollars for the *i*-th banana).
He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas? | The first line contains three positive integers *k*,<=*n*,<=*w* (1<=<=β€<=<=*k*,<=*w*<=<=β€<=<=1000, 0<=β€<=*n*<=β€<=109), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants. | Output one integer β the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0. | [
"3 17 4\n"
] | [
"13"
] | none | 500 | [
{
"input": "3 17 4",
"output": "13"
},
{
"input": "1 2 1",
"output": "0"
},
{
"input": "1 1 1",
"output": "0"
},
{
"input": "1 5 6",
"output": "16"
},
{
"input": "1 1000000000 1",
"output": "0"
},
{
"input": "1000 0 1000",
"output": "500500000"
}... | 1,695,701,447 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 15 | 62 | 0 | number = input()
list = number.split()
cost = int(list[0])
money = int(list[1])
want = int(list[2])
for i in range(want):
current_cost = cost*(i + 1)
money -= current_cost
if money < 0:
money *= -1
print(money)
else:
print(0)
| Title: Soldier and Bananas
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*Β·*k* dollars for the *i*-th banana).
He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas?
Input Specification:
The first line contains three positive integers *k*,<=*n*,<=*w* (1<=<=β€<=<=*k*,<=*w*<=<=β€<=<=1000, 0<=β€<=*n*<=β€<=109), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants.
Output Specification:
Output one integer β the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0.
Demo Input:
['3 17 4\n']
Demo Output:
['13']
Note:
none | ```python
number = input()
list = number.split()
cost = int(list[0])
money = int(list[1])
want = int(list[2])
for i in range(want):
current_cost = cost*(i + 1)
money -= current_cost
if money < 0:
money *= -1
print(money)
else:
print(0)
``` | 3 | |
855 | A | Tom Riddle's Diary | PROGRAMMING | 800 | [
"brute force",
"implementation",
"strings"
] | null | null | Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.
He has names of *n* people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.
Formally, for a name *s**i* in the *i*-th line, output "YES" (without quotes) if there exists an index *j* such that *s**i*<==<=*s**j* and *j*<=<<=*i*, otherwise, output "NO" (without quotes). | First line of input contains an integer *n* (1<=β€<=*n*<=β€<=100)Β β the number of names in the list.
Next *n* lines each contain a string *s**i*, consisting of lowercase English letters. The length of each string is between 1 and 100. | Output *n* lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not.
You can print each letter in any case (upper or lower). | [
"6\ntom\nlucius\nginny\nharry\nginny\nharry\n",
"3\na\na\na\n"
] | [
"NO\nNO\nNO\nNO\nYES\nYES\n",
"NO\nYES\nYES\n"
] | In test case 1, for *i*β=β5 there exists *j*β=β3 such that *s*<sub class="lower-index">*i*</sub>β=β*s*<sub class="lower-index">*j*</sub> and *j*β<β*i*, which means that answer for *i*β=β5 is "YES". | 500 | [
{
"input": "6\ntom\nlucius\nginny\nharry\nginny\nharry",
"output": "NO\nNO\nNO\nNO\nYES\nYES"
},
{
"input": "3\na\na\na",
"output": "NO\nYES\nYES"
},
{
"input": "1\nzn",
"output": "NO"
},
{
"input": "9\nliyzmbjwnzryjokufuxcqtzwworjeoxkbaqrujrhdidqdvwdfzilwszgnzglnnbogaclckfnb... | 1,584,385,794 | 2,147,483,647 | Python 3 | OK | TESTS | 55 | 124 | 0 | n=int(input())
a=[]
for i in range(n):
c=0
a.append(input())
for j in range(0,i):
if j!=i:
if a[i]==a[j]:
c+=1
if c>0:
print("YES")
else:
print("NO") | Title: Tom Riddle's Diary
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.
He has names of *n* people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.
Formally, for a name *s**i* in the *i*-th line, output "YES" (without quotes) if there exists an index *j* such that *s**i*<==<=*s**j* and *j*<=<<=*i*, otherwise, output "NO" (without quotes).
Input Specification:
First line of input contains an integer *n* (1<=β€<=*n*<=β€<=100)Β β the number of names in the list.
Next *n* lines each contain a string *s**i*, consisting of lowercase English letters. The length of each string is between 1 and 100.
Output Specification:
Output *n* lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not.
You can print each letter in any case (upper or lower).
Demo Input:
['6\ntom\nlucius\nginny\nharry\nginny\nharry\n', '3\na\na\na\n']
Demo Output:
['NO\nNO\nNO\nNO\nYES\nYES\n', 'NO\nYES\nYES\n']
Note:
In test case 1, for *i*β=β5 there exists *j*β=β3 such that *s*<sub class="lower-index">*i*</sub>β=β*s*<sub class="lower-index">*j*</sub> and *j*β<β*i*, which means that answer for *i*β=β5 is "YES". | ```python
n=int(input())
a=[]
for i in range(n):
c=0
a.append(input())
for j in range(0,i):
if j!=i:
if a[i]==a[j]:
c+=1
if c>0:
print("YES")
else:
print("NO")
``` | 3 | |
902 | B | Coloring a Tree | PROGRAMMING | 1,200 | [
"dfs and similar",
"dsu",
"greedy"
] | null | null | You are given a rooted tree with *n* vertices. The vertices are numbered from 1 to *n*, the root is the vertex number 1.
Each vertex has a color, let's denote the color of vertex *v* by *c**v*. Initially *c**v*<==<=0.
You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex *v* and a color *x*, and then color all vectices in the subtree of *v* (including *v* itself) in color *x*. In other words, for every vertex *u*, such that the path from root to *u* passes through *v*, set *c**u*<==<=*x*.
It is guaranteed that you have to color each vertex in a color different from 0.
You can learn what a rooted tree is using the link: [https://en.wikipedia.org/wiki/Tree_(graph_theory)](https://en.wikipedia.org/wiki/Tree_(graph_theory)). | The first line contains a single integer *n* (2<=β€<=*n*<=β€<=104)Β β the number of vertices in the tree.
The second line contains *n*<=-<=1 integers *p*2,<=*p*3,<=...,<=*p**n* (1<=β€<=*p**i*<=<<=*i*), where *p**i* means that there is an edge between vertices *i* and *p**i*.
The third line contains *n* integers *c*1,<=*c*2,<=...,<=*c**n* (1<=β€<=*c**i*<=β€<=*n*), where *c**i* is the color you should color the *i*-th vertex into.
It is guaranteed that the given graph is a tree. | Print a single integerΒ β the minimum number of steps you have to perform to color the tree into given colors. | [
"6\n1 2 2 1 5\n2 1 1 1 1 1\n",
"7\n1 1 2 3 1 4\n3 3 1 1 1 2 3\n"
] | [
"3\n",
"5\n"
] | The tree from the first sample is shown on the picture (numbers are vetices' indices):
<img class="tex-graphics" src="https://espresso.codeforces.com/10324ccdc37f95343acc4f3c6050d8c334334ffa.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):
<img class="tex-graphics" src="https://espresso.codeforces.com/1c7bb267e2c1a006132248a43121400189309e2f.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On seond step we color all vertices in the subtree of vertex 5 into color 1:
<img class="tex-graphics" src="https://espresso.codeforces.com/2201a6d49b89ba850ff0d0bdcbb3f8e9dd3871a8.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On third step we color all vertices in the subtree of vertex 2 into color 1:
<img class="tex-graphics" src="https://espresso.codeforces.com/6fa977fcdebdde94c47695151e0427b33d0102c5.png" style="max-width: 100.0%;max-height: 100.0%;"/>
The tree from the second sample is shown on the picture (numbers are vetices' indices):
<img class="tex-graphics" src="https://espresso.codeforces.com/d70f9ae72a2ed429dd6531cac757e375dd3c953d.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):
<img class="tex-graphics" src="https://espresso.codeforces.com/7289e8895d0dd56c47b6b17969b9cf77b36786b5.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On second step we color all vertices in the subtree of vertex 3 into color 1:
<img class="tex-graphics" src="https://espresso.codeforces.com/819001df7229138db3a407713744d1e3be88b64e.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On third step we color all vertices in the subtree of vertex 6 into color 2:
<img class="tex-graphics" src="https://espresso.codeforces.com/80ebbd870a0a339636a21b9acdaf9de046458b43.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On fourth step we color all vertices in the subtree of vertex 4 into color 1:
<img class="tex-graphics" src="https://espresso.codeforces.com/ed836aa723ac0176abde4e32988e3ac205014e93.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On fith step we color all vertices in the subtree of vertex 7 into color 3:
<img class="tex-graphics" src="https://espresso.codeforces.com/8132909e11b41c27b8df2f0b0c10bc841f35e58a.png" style="max-width: 100.0%;max-height: 100.0%;"/> | 1,000 | [
{
"input": "6\n1 2 2 1 5\n2 1 1 1 1 1",
"output": "3"
},
{
"input": "7\n1 1 2 3 1 4\n3 3 1 1 1 2 3",
"output": "5"
},
{
"input": "2\n1\n2 2",
"output": "1"
},
{
"input": "3\n1 1\n2 2 2",
"output": "1"
},
{
"input": "4\n1 2 1\n1 2 3 4",
"output": "4"
},
{
... | 1,513,700,454 | 2,754 | Python 3 | OK | TESTS | 50 | 92 | 6,963,200 | N = int(input())
con = [0]
vert = [i for i in range(1,N+1)]
a = input().split(" ")
for i in range(N-1):
con.append(int(a[i])-1)
color=[]
a = input().split(" ")
for i in range(N):
color.append(int(a[i]))
cur = [color[0] for i in range(N)]
steps=1
for i in range(1,N):
if cur[con[i]]==color[i]:
cur[i] = color[i]
else:
steps+=1
cur[i] = color[i]
print(steps)
#print(con)
#print(color)
#print(vert)
| Title: Coloring a Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a rooted tree with *n* vertices. The vertices are numbered from 1 to *n*, the root is the vertex number 1.
Each vertex has a color, let's denote the color of vertex *v* by *c**v*. Initially *c**v*<==<=0.
You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex *v* and a color *x*, and then color all vectices in the subtree of *v* (including *v* itself) in color *x*. In other words, for every vertex *u*, such that the path from root to *u* passes through *v*, set *c**u*<==<=*x*.
It is guaranteed that you have to color each vertex in a color different from 0.
You can learn what a rooted tree is using the link: [https://en.wikipedia.org/wiki/Tree_(graph_theory)](https://en.wikipedia.org/wiki/Tree_(graph_theory)).
Input Specification:
The first line contains a single integer *n* (2<=β€<=*n*<=β€<=104)Β β the number of vertices in the tree.
The second line contains *n*<=-<=1 integers *p*2,<=*p*3,<=...,<=*p**n* (1<=β€<=*p**i*<=<<=*i*), where *p**i* means that there is an edge between vertices *i* and *p**i*.
The third line contains *n* integers *c*1,<=*c*2,<=...,<=*c**n* (1<=β€<=*c**i*<=β€<=*n*), where *c**i* is the color you should color the *i*-th vertex into.
It is guaranteed that the given graph is a tree.
Output Specification:
Print a single integerΒ β the minimum number of steps you have to perform to color the tree into given colors.
Demo Input:
['6\n1 2 2 1 5\n2 1 1 1 1 1\n', '7\n1 1 2 3 1 4\n3 3 1 1 1 2 3\n']
Demo Output:
['3\n', '5\n']
Note:
The tree from the first sample is shown on the picture (numbers are vetices' indices):
<img class="tex-graphics" src="https://espresso.codeforces.com/10324ccdc37f95343acc4f3c6050d8c334334ffa.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):
<img class="tex-graphics" src="https://espresso.codeforces.com/1c7bb267e2c1a006132248a43121400189309e2f.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On seond step we color all vertices in the subtree of vertex 5 into color 1:
<img class="tex-graphics" src="https://espresso.codeforces.com/2201a6d49b89ba850ff0d0bdcbb3f8e9dd3871a8.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On third step we color all vertices in the subtree of vertex 2 into color 1:
<img class="tex-graphics" src="https://espresso.codeforces.com/6fa977fcdebdde94c47695151e0427b33d0102c5.png" style="max-width: 100.0%;max-height: 100.0%;"/>
The tree from the second sample is shown on the picture (numbers are vetices' indices):
<img class="tex-graphics" src="https://espresso.codeforces.com/d70f9ae72a2ed429dd6531cac757e375dd3c953d.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):
<img class="tex-graphics" src="https://espresso.codeforces.com/7289e8895d0dd56c47b6b17969b9cf77b36786b5.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On second step we color all vertices in the subtree of vertex 3 into color 1:
<img class="tex-graphics" src="https://espresso.codeforces.com/819001df7229138db3a407713744d1e3be88b64e.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On third step we color all vertices in the subtree of vertex 6 into color 2:
<img class="tex-graphics" src="https://espresso.codeforces.com/80ebbd870a0a339636a21b9acdaf9de046458b43.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On fourth step we color all vertices in the subtree of vertex 4 into color 1:
<img class="tex-graphics" src="https://espresso.codeforces.com/ed836aa723ac0176abde4e32988e3ac205014e93.png" style="max-width: 100.0%;max-height: 100.0%;"/>
On fith step we color all vertices in the subtree of vertex 7 into color 3:
<img class="tex-graphics" src="https://espresso.codeforces.com/8132909e11b41c27b8df2f0b0c10bc841f35e58a.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
N = int(input())
con = [0]
vert = [i for i in range(1,N+1)]
a = input().split(" ")
for i in range(N-1):
con.append(int(a[i])-1)
color=[]
a = input().split(" ")
for i in range(N):
color.append(int(a[i]))
cur = [color[0] for i in range(N)]
steps=1
for i in range(1,N):
if cur[con[i]]==color[i]:
cur[i] = color[i]
else:
steps+=1
cur[i] = color[i]
print(steps)
#print(con)
#print(color)
#print(vert)
``` | 3 | |
144 | A | Arrival of the General | PROGRAMMING | 800 | [
"implementation"
] | null | null | A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.
For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.
Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct. | The first input line contains the only integer *n* (2<=β€<=*n*<=β€<=100) which represents the number of soldiers in the line. The second line contains integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers *a*1,<=*a*2,<=...,<=*a**n* are not necessarily different. | Print the only integer β the minimum number of seconds the colonel will need to form a line-up the general will like. | [
"4\n33 44 11 22\n",
"7\n10 10 58 31 63 40 76\n"
] | [
"2\n",
"10\n"
] | In the first sample the colonel will need to swap the first and second soldier and then the third and fourth soldier. That will take 2 seconds. The resulting position of the soldiers is (44, 33, 22, 11).
In the second sample the colonel may swap the soldiers in the following sequence:
1. (10, 10, 58, 31, 63, 40, 76) 1. (10, 58, 10, 31, 63, 40, 76) 1. (10, 58, 10, 31, 63, 76, 40) 1. (10, 58, 10, 31, 76, 63, 40) 1. (10, 58, 31, 10, 76, 63, 40) 1. (10, 58, 31, 76, 10, 63, 40) 1. (10, 58, 31, 76, 63, 10, 40) 1. (10, 58, 76, 31, 63, 10, 40) 1. (10, 76, 58, 31, 63, 10, 40) 1. (76, 10, 58, 31, 63, 10, 40) 1. (76, 10, 58, 31, 63, 40, 10) | 500 | [
{
"input": "4\n33 44 11 22",
"output": "2"
},
{
"input": "7\n10 10 58 31 63 40 76",
"output": "10"
},
{
"input": "2\n88 89",
"output": "1"
},
{
"input": "5\n100 95 100 100 88",
"output": "0"
},
{
"input": "7\n48 48 48 48 45 45 45",
"output": "0"
},
{
"... | 1,689,222,558 | 2,147,483,647 | Python 3 | OK | TESTS | 39 | 92 | 0 | n = int(input())
lst = list(map(int,input().split()))
a=0
b=100
max_ind=0
min_ind=0
for i in range(n):
if lst[i]>a:
a=lst[i]
max_ind = i
if lst[i]<=b:
b = lst[i]
min_ind = i
if max_ind<min_ind:
print(max_ind+(n-min_ind)-1)
else:
print(max_ind+((n-min_ind)-2)) | Title: Arrival of the General
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.
For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.
Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.
Input Specification:
The first input line contains the only integer *n* (2<=β€<=*n*<=β€<=100) which represents the number of soldiers in the line. The second line contains integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers *a*1,<=*a*2,<=...,<=*a**n* are not necessarily different.
Output Specification:
Print the only integer β the minimum number of seconds the colonel will need to form a line-up the general will like.
Demo Input:
['4\n33 44 11 22\n', '7\n10 10 58 31 63 40 76\n']
Demo Output:
['2\n', '10\n']
Note:
In the first sample the colonel will need to swap the first and second soldier and then the third and fourth soldier. That will take 2 seconds. The resulting position of the soldiers is (44, 33, 22, 11).
In the second sample the colonel may swap the soldiers in the following sequence:
1. (10, 10, 58, 31, 63, 40, 76) 1. (10, 58, 10, 31, 63, 40, 76) 1. (10, 58, 10, 31, 63, 76, 40) 1. (10, 58, 10, 31, 76, 63, 40) 1. (10, 58, 31, 10, 76, 63, 40) 1. (10, 58, 31, 76, 10, 63, 40) 1. (10, 58, 31, 76, 63, 10, 40) 1. (10, 58, 76, 31, 63, 10, 40) 1. (10, 76, 58, 31, 63, 10, 40) 1. (76, 10, 58, 31, 63, 10, 40) 1. (76, 10, 58, 31, 63, 40, 10) | ```python
n = int(input())
lst = list(map(int,input().split()))
a=0
b=100
max_ind=0
min_ind=0
for i in range(n):
if lst[i]>a:
a=lst[i]
max_ind = i
if lst[i]<=b:
b = lst[i]
min_ind = i
if max_ind<min_ind:
print(max_ind+(n-min_ind)-1)
else:
print(max_ind+((n-min_ind)-2))
``` | 3 | |
408 | A | Line to Cashier | PROGRAMMING | 900 | [
"implementation"
] | null | null | Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.
There are *n* cashiers at the exit from the supermarket. At the moment the queue for the *i*-th cashier already has *k**i* people. The *j*-th person standing in the queue to the *i*-th cashier has *m**i*,<=*j* items in the basket. Vasya knows that:
- the cashier needs 5 seconds to scan one item; - after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change.
Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers. | The first line contains integer *n* (1<=β€<=*n*<=β€<=100)Β β the number of cashes in the shop. The second line contains *n* space-separated integers: *k*1,<=*k*2,<=...,<=*k**n* (1<=β€<=*k**i*<=β€<=100), where *k**i* is the number of people in the queue to the *i*-th cashier.
The *i*-th of the next *n* lines contains *k**i* space-separated integers: *m**i*,<=1,<=*m**i*,<=2,<=...,<=*m**i*,<=*k**i* (1<=β€<=*m**i*,<=*j*<=β€<=100)Β β the number of products the *j*-th person in the queue for the *i*-th cash has. | Print a single integer β the minimum number of seconds Vasya needs to get to the cashier. | [
"1\n1\n1\n",
"4\n1 4 3 2\n100\n1 2 2 3\n1 9 1\n7 8\n"
] | [
"20\n",
"100\n"
] | In the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100Β·5β+β15β=β515 seconds. But if he chooses the second queue, he will need 1Β·5β+β2Β·5β+β2Β·5β+β3Β·5β+β4Β·15β=β100 seconds. He will need 1Β·5β+β9Β·5β+β1Β·5β+β3Β·15β=β100 seconds for the third one and 7Β·5β+β8Β·5β+β2Β·15β=β105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue. | 500 | [
{
"input": "1\n1\n1",
"output": "20"
},
{
"input": "4\n1 4 3 2\n100\n1 2 2 3\n1 9 1\n7 8",
"output": "100"
},
{
"input": "4\n5 4 5 5\n3 1 3 1 2\n3 1 1 3\n1 1 1 2 2\n2 2 1 1 3",
"output": "100"
},
{
"input": "5\n5 3 6 6 4\n7 5 3 3 9\n6 8 2\n1 10 8 5 9 2\n9 7 8 5 9 10\n9 8 3 3"... | 1,668,685,804 | 2,147,483,647 | Python 3 | OK | TESTS | 20 | 46 | 0 |
def solve():
n = int(input())
ak = [int(i) for i in input().split()]
ans = float("inf")
for i in range(n):
a = [int(k) for k in input().split()]
s = 0
for j in range(len(a)):
s+=a[j]*5
s+=15*ak[i]
ans = min(ans,s)
print(ans)
return
# t = int(input())
# for _ in range(t):
# solve()
solve() | Title: Line to Cashier
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.
There are *n* cashiers at the exit from the supermarket. At the moment the queue for the *i*-th cashier already has *k**i* people. The *j*-th person standing in the queue to the *i*-th cashier has *m**i*,<=*j* items in the basket. Vasya knows that:
- the cashier needs 5 seconds to scan one item; - after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change.
Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=100)Β β the number of cashes in the shop. The second line contains *n* space-separated integers: *k*1,<=*k*2,<=...,<=*k**n* (1<=β€<=*k**i*<=β€<=100), where *k**i* is the number of people in the queue to the *i*-th cashier.
The *i*-th of the next *n* lines contains *k**i* space-separated integers: *m**i*,<=1,<=*m**i*,<=2,<=...,<=*m**i*,<=*k**i* (1<=β€<=*m**i*,<=*j*<=β€<=100)Β β the number of products the *j*-th person in the queue for the *i*-th cash has.
Output Specification:
Print a single integer β the minimum number of seconds Vasya needs to get to the cashier.
Demo Input:
['1\n1\n1\n', '4\n1 4 3 2\n100\n1 2 2 3\n1 9 1\n7 8\n']
Demo Output:
['20\n', '100\n']
Note:
In the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100Β·5β+β15β=β515 seconds. But if he chooses the second queue, he will need 1Β·5β+β2Β·5β+β2Β·5β+β3Β·5β+β4Β·15β=β100 seconds. He will need 1Β·5β+β9Β·5β+β1Β·5β+β3Β·15β=β100 seconds for the third one and 7Β·5β+β8Β·5β+β2Β·15β=β105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue. | ```python
def solve():
n = int(input())
ak = [int(i) for i in input().split()]
ans = float("inf")
for i in range(n):
a = [int(k) for k in input().split()]
s = 0
for j in range(len(a)):
s+=a[j]*5
s+=15*ak[i]
ans = min(ans,s)
print(ans)
return
# t = int(input())
# for _ in range(t):
# solve()
solve()
``` | 3 | |
741 | B | Arpa's weak amphitheater and Mehrdad's valuable Hoses | PROGRAMMING | 1,600 | [
"dfs and similar",
"dp",
"dsu"
] | null | null | Just to remind, girls in Arpa's land are really nice.
Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight *w**i* and some beauty *b**i*. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses *x* and *y* are in the same friendship group if and only if there is a sequence of Hoses *a*1,<=*a*2,<=...,<=*a**k* such that *a**i* and *a**i*<=+<=1 are friends for each 1<=β€<=*i*<=<<=*k*, and *a*1<==<=*x* and *a**k*<==<=*y*.
Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most *w* weight on it.
Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than *w* and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed *w*. | The first line contains integers *n*, *m* and *w* (1<=<=β€<=<=*n*<=<=β€<=<=1000, , 1<=β€<=*w*<=β€<=1000)Β β the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited.
The second line contains *n* integers *w*1,<=*w*2,<=...,<=*w**n* (1<=β€<=*w**i*<=β€<=1000)Β β the weights of the Hoses.
The third line contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (1<=β€<=*b**i*<=β€<=106)Β β the beauties of the Hoses.
The next *m* lines contain pairs of friends, the *i*-th of them contains two integers *x**i* and *y**i* (1<=β€<=*x**i*,<=*y**i*<=β€<=*n*, *x**i*<=β <=*y**i*), meaning that Hoses *x**i* and *y**i* are friends. Note that friendship is bidirectional. All pairs (*x**i*,<=*y**i*) are distinct. | Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed *w*. | [
"3 1 5\n3 2 5\n2 4 2\n1 2\n",
"4 2 11\n2 4 6 6\n6 4 2 1\n1 2\n2 3\n"
] | [
"6\n",
"7\n"
] | In the first sample there are two friendship groups: Hoses {1,β2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.
In the second sample there are two friendship groups: Hoses {1,β2,β3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12β>β11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. | 1,000 | [
{
"input": "3 1 5\n3 2 5\n2 4 2\n1 2",
"output": "6"
},
{
"input": "4 2 11\n2 4 6 6\n6 4 2 1\n1 2\n2 3",
"output": "7"
},
{
"input": "10 5 100\n70 67 8 64 28 82 18 61 82 7\n596434 595982 237932 275698 361351 850374 936914 877996 789231 331012\n1 7\n2 4\n3 6\n5 7\n1 5",
"output": "238... | 1,606,089,124 | 2,147,483,647 | Python 3 | OK | TESTS | 68 | 842 | 614,400 | def g(x):
if x == t[x]: return x
t[x] = g(t[x])
return t[x]
f = lambda: map(int, input().split())
hoses, pairOfFriends, weight = f()
weightsAndBeauties = [(0, 0)] + list(zip(f(), f()))
t = list(range(hoses + 1))
for i in range(pairOfFriends):
f1, f2 = f()
f1, f2 = g(f1), g(f2)
if f1 != f2:
t[f2] = f1
p = [[] for j in range(hoses + 1)]
for i in range(1, hoses + 1):
p[g(i)].append(i)
beauties = [1] + [0] * weight
for q in p:
if len(q) > 1:
t = [weightsAndBeauties[i] for i in q]
t.append((sum(f1[0] for f1 in t), sum(f1[1] for f1 in t)))
t.sort(key=lambda f1: f1[0])
for j in range(weight, -1, -1):
if beauties[j]:
for w, b in t:
if j + w > weight:
break
else:
beauties[j + w] = max(beauties[j + w], beauties[j] + b)
elif len(q) == 1:
w, b = weightsAndBeauties[q[0]]
for j in range(weight - w, -1, -1):
if beauties[j]:
beauties[j + w] = max(beauties[j + w], beauties[j] + b)
maxBeauty = max(beauties) - 1
print(maxBeauty) | Title: Arpa's weak amphitheater and Mehrdad's valuable Hoses
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Just to remind, girls in Arpa's land are really nice.
Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight *w**i* and some beauty *b**i*. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses *x* and *y* are in the same friendship group if and only if there is a sequence of Hoses *a*1,<=*a*2,<=...,<=*a**k* such that *a**i* and *a**i*<=+<=1 are friends for each 1<=β€<=*i*<=<<=*k*, and *a*1<==<=*x* and *a**k*<==<=*y*.
Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most *w* weight on it.
Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than *w* and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed *w*.
Input Specification:
The first line contains integers *n*, *m* and *w* (1<=<=β€<=<=*n*<=<=β€<=<=1000, , 1<=β€<=*w*<=β€<=1000)Β β the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited.
The second line contains *n* integers *w*1,<=*w*2,<=...,<=*w**n* (1<=β€<=*w**i*<=β€<=1000)Β β the weights of the Hoses.
The third line contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (1<=β€<=*b**i*<=β€<=106)Β β the beauties of the Hoses.
The next *m* lines contain pairs of friends, the *i*-th of them contains two integers *x**i* and *y**i* (1<=β€<=*x**i*,<=*y**i*<=β€<=*n*, *x**i*<=β <=*y**i*), meaning that Hoses *x**i* and *y**i* are friends. Note that friendship is bidirectional. All pairs (*x**i*,<=*y**i*) are distinct.
Output Specification:
Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed *w*.
Demo Input:
['3 1 5\n3 2 5\n2 4 2\n1 2\n', '4 2 11\n2 4 6 6\n6 4 2 1\n1 2\n2 3\n']
Demo Output:
['6\n', '7\n']
Note:
In the first sample there are two friendship groups: Hoses {1,β2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.
In the second sample there are two friendship groups: Hoses {1,β2,β3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12β>β11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. | ```python
def g(x):
if x == t[x]: return x
t[x] = g(t[x])
return t[x]
f = lambda: map(int, input().split())
hoses, pairOfFriends, weight = f()
weightsAndBeauties = [(0, 0)] + list(zip(f(), f()))
t = list(range(hoses + 1))
for i in range(pairOfFriends):
f1, f2 = f()
f1, f2 = g(f1), g(f2)
if f1 != f2:
t[f2] = f1
p = [[] for j in range(hoses + 1)]
for i in range(1, hoses + 1):
p[g(i)].append(i)
beauties = [1] + [0] * weight
for q in p:
if len(q) > 1:
t = [weightsAndBeauties[i] for i in q]
t.append((sum(f1[0] for f1 in t), sum(f1[1] for f1 in t)))
t.sort(key=lambda f1: f1[0])
for j in range(weight, -1, -1):
if beauties[j]:
for w, b in t:
if j + w > weight:
break
else:
beauties[j + w] = max(beauties[j + w], beauties[j] + b)
elif len(q) == 1:
w, b = weightsAndBeauties[q[0]]
for j in range(weight - w, -1, -1):
if beauties[j]:
beauties[j + w] = max(beauties[j + w], beauties[j] + b)
maxBeauty = max(beauties) - 1
print(maxBeauty)
``` | 3 | |
710 | A | King Moves | PROGRAMMING | 800 | [
"implementation"
] | null | null | The only king stands on the standard chess board. You are given his position in format "cd", where *c* is the column from 'a' to 'h' and *d* is the row from '1' to '8'. Find the number of moves permitted for the king.
Check the king's moves here [https://en.wikipedia.org/wiki/King_(chess)](https://en.wikipedia.org/wiki/King_(chess)). | The only line contains the king's position in the format "cd", where 'c' is the column from 'a' to 'h' and 'd' is the row from '1' to '8'. | Print the only integer *x* β the number of moves permitted for the king. | [
"e4\n"
] | [
"8\n"
] | none | 0 | [
{
"input": "e4",
"output": "8"
},
{
"input": "a1",
"output": "3"
},
{
"input": "h8",
"output": "3"
},
{
"input": "a4",
"output": "5"
},
{
"input": "g7",
"output": "8"
},
{
"input": "e1",
"output": "5"
},
{
"input": "b2",
"output": "8"
... | 1,630,347,311 | 2,147,483,647 | PyPy 3 | OK | TESTS | 24 | 109 | 20,172,800 | from sys import stdin, stdout
def read():
return stdin.readline().rstrip()
def read_int():
return int(read())
def read_ints():
return list(map(int, read().split()))
def solve():
a=read()
c=0
if a[0]=='a' or a[0]=='h':
c+=1
if a[1]=='1' or a[1]=='8':
c+=1
if c==0:
print(8)
elif c==1:
print(5)
else:
print(3)
solve()
| Title: King Moves
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The only king stands on the standard chess board. You are given his position in format "cd", where *c* is the column from 'a' to 'h' and *d* is the row from '1' to '8'. Find the number of moves permitted for the king.
Check the king's moves here [https://en.wikipedia.org/wiki/King_(chess)](https://en.wikipedia.org/wiki/King_(chess)).
Input Specification:
The only line contains the king's position in the format "cd", where 'c' is the column from 'a' to 'h' and 'd' is the row from '1' to '8'.
Output Specification:
Print the only integer *x* β the number of moves permitted for the king.
Demo Input:
['e4\n']
Demo Output:
['8\n']
Note:
none | ```python
from sys import stdin, stdout
def read():
return stdin.readline().rstrip()
def read_int():
return int(read())
def read_ints():
return list(map(int, read().split()))
def solve():
a=read()
c=0
if a[0]=='a' or a[0]=='h':
c+=1
if a[1]=='1' or a[1]=='8':
c+=1
if c==0:
print(8)
elif c==1:
print(5)
else:
print(3)
solve()
``` | 3 | |
807 | A | Is it rated? | PROGRAMMING | 900 | [
"implementation",
"sortings"
] | null | null | Is it rated?
Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.
Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.
It's known that if at least one participant's rating has changed, then the round was rated for sure.
It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.
In this problem, you should not make any other assumptions about the rating system.
Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not. | The first line contains a single integer *n* (2<=β€<=*n*<=β€<=1000)Β β the number of round participants.
Each of the next *n* lines contains two integers *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=4126)Β β the rating of the *i*-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings. | If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe". | [
"6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884\n",
"4\n1500 1500\n1300 1300\n1200 1200\n1400 1400\n",
"5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699\n"
] | [
"rated\n",
"unrated\n",
"maybe\n"
] | In the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.
In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.
In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not. | 500 | [
{
"input": "6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884",
"output": "rated"
},
{
"input": "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400",
"output": "unrated"
},
{
"input": "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699",
"output": "maybe"
},
{
... | 1,593,217,124 | 2,147,483,647 | PyPy 3 | OK | TESTS | 150 | 187 | 21,606,400 | t = int(input())
left = []
right = []
for i in range(t):
x , y = input().split()
x , y = int(x) , int(y)
left.append(x)
right.append(y)
if left != right :print('rated')
elif left == right and sorted(left , reverse=True) != left and sorted(right , reverse=True) != right:print('unrated')
else:print('maybe') | Title: Is it rated?
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Is it rated?
Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.
Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.
It's known that if at least one participant's rating has changed, then the round was rated for sure.
It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.
In this problem, you should not make any other assumptions about the rating system.
Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
Input Specification:
The first line contains a single integer *n* (2<=β€<=*n*<=β€<=1000)Β β the number of round participants.
Each of the next *n* lines contains two integers *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=4126)Β β the rating of the *i*-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
Output Specification:
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
Demo Input:
['6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884\n', '4\n1500 1500\n1300 1300\n1200 1200\n1400 1400\n', '5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699\n']
Demo Output:
['rated\n', 'unrated\n', 'maybe\n']
Note:
In the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.
In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.
In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not. | ```python
t = int(input())
left = []
right = []
for i in range(t):
x , y = input().split()
x , y = int(x) , int(y)
left.append(x)
right.append(y)
if left != right :print('rated')
elif left == right and sorted(left , reverse=True) != left and sorted(right , reverse=True) != right:print('unrated')
else:print('maybe')
``` | 3 | |
379 | A | New Year Candles | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has *a* candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make *b* went out candles into a new candle. As a result, this new candle can be used like any other new candle.
Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number. | The single line contains two integers, *a* and *b* (1<=β€<=*a*<=β€<=1000;Β 2<=β€<=*b*<=β€<=1000). | Print a single integer β the number of hours Vasily can light up the room for. | [
"4 2\n",
"6 3\n"
] | [
"7\n",
"8\n"
] | Consider the first sample. For the first four hours Vasily lights up new candles, then he uses four burned out candles to make two new ones and lights them up. When these candles go out (stop burning), Vasily can make another candle. Overall, Vasily can light up the room for 7 hours. | 500 | [
{
"input": "4 2",
"output": "7"
},
{
"input": "6 3",
"output": "8"
},
{
"input": "1000 1000",
"output": "1001"
},
{
"input": "123 5",
"output": "153"
},
{
"input": "1000 2",
"output": "1999"
},
{
"input": "1 2",
"output": "1"
},
{
"input": ... | 1,643,800,871 | 2,147,483,647 | Python 3 | OK | TESTS | 32 | 46 | 0 | a,b=map(int,input().split())
c=int(a-1)/(b-1)
print(int(a+c))
| Title: New Year Candles
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has *a* candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make *b* went out candles into a new candle. As a result, this new candle can be used like any other new candle.
Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number.
Input Specification:
The single line contains two integers, *a* and *b* (1<=β€<=*a*<=β€<=1000;Β 2<=β€<=*b*<=β€<=1000).
Output Specification:
Print a single integer β the number of hours Vasily can light up the room for.
Demo Input:
['4 2\n', '6 3\n']
Demo Output:
['7\n', '8\n']
Note:
Consider the first sample. For the first four hours Vasily lights up new candles, then he uses four burned out candles to make two new ones and lights them up. When these candles go out (stop burning), Vasily can make another candle. Overall, Vasily can light up the room for 7 hours. | ```python
a,b=map(int,input().split())
c=int(a-1)/(b-1)
print(int(a+c))
``` | 3 | |
339 | A | Helpful Maths | PROGRAMMING | 800 | [
"greedy",
"implementation",
"sortings",
"strings"
] | null | null | Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.
You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum. | The first line contains a non-empty string *s* β the sum Xenia needs to count. String *s* contains no spaces. It only contains digits and characters "+". Besides, string *s* is a correct sum of numbers 1, 2 and 3. String *s* is at most 100 characters long. | Print the new sum that Xenia can count. | [
"3+2+1\n",
"1+1+3+1+3\n",
"2\n"
] | [
"1+2+3\n",
"1+1+1+3+3\n",
"2\n"
] | none | 500 | [
{
"input": "3+2+1",
"output": "1+2+3"
},
{
"input": "1+1+3+1+3",
"output": "1+1+1+3+3"
},
{
"input": "2",
"output": "2"
},
{
"input": "2+2+1+1+3",
"output": "1+1+2+2+3"
},
{
"input": "2+1+2+2+2+3+1+3+1+2",
"output": "1+1+1+2+2+2+2+2+3+3"
},
{
"input": ... | 1,694,660,081 | 2,147,483,647 | Python 3 | OK | TESTS | 21 | 92 | 0 | a=input()
b=[]
for i in range(0,len(a),2):
b.append(a[i])
b.sort()
b="+".join(b)
print(b)
| Title: Helpful Maths
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.
You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
Input Specification:
The first line contains a non-empty string *s* β the sum Xenia needs to count. String *s* contains no spaces. It only contains digits and characters "+". Besides, string *s* is a correct sum of numbers 1, 2 and 3. String *s* is at most 100 characters long.
Output Specification:
Print the new sum that Xenia can count.
Demo Input:
['3+2+1\n', '1+1+3+1+3\n', '2\n']
Demo Output:
['1+2+3\n', '1+1+1+3+3\n', '2\n']
Note:
none | ```python
a=input()
b=[]
for i in range(0,len(a),2):
b.append(a[i])
b.sort()
b="+".join(b)
print(b)
``` | 3 | |
231 | A | Team | PROGRAMMING | 800 | [
"brute force",
"greedy"
] | null | null | One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.
This contest offers *n* problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution. | The first input line contains a single integer *n* (1<=β€<=*n*<=β€<=1000) β the number of problems in the contest. Then *n* lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces. | Print a single integer β the number of problems the friends will implement on the contest. | [
"3\n1 1 0\n1 1 1\n1 0 0\n",
"2\n1 0 0\n0 1 1\n"
] | [
"2\n",
"1\n"
] | In the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it.
In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution. | 500 | [
{
"input": "3\n1 1 0\n1 1 1\n1 0 0",
"output": "2"
},
{
"input": "2\n1 0 0\n0 1 1",
"output": "1"
},
{
"input": "1\n1 0 0",
"output": "0"
},
{
"input": "2\n1 0 0\n1 1 1",
"output": "1"
},
{
"input": "5\n1 0 0\n0 1 0\n1 1 1\n0 0 1\n0 0 0",
"output": "1"
},
... | 1,697,737,931 | 2,147,483,647 | Python 3 | OK | TESTS | 21 | 92 | 0 | cases_num=int(input())
res=0
for ix in range(cases_num):
inputs=input()
cases=inputs.split(' ')
score=0
for num in cases:
score+=(int(num))
if score>=2:
res+=1
print(res) | Title: Team
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.
This contest offers *n* problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.
Input Specification:
The first input line contains a single integer *n* (1<=β€<=*n*<=β€<=1000) β the number of problems in the contest. Then *n* lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.
Output Specification:
Print a single integer β the number of problems the friends will implement on the contest.
Demo Input:
['3\n1 1 0\n1 1 1\n1 0 0\n', '2\n1 0 0\n0 1 1\n']
Demo Output:
['2\n', '1\n']
Note:
In the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it.
In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution. | ```python
cases_num=int(input())
res=0
for ix in range(cases_num):
inputs=input()
cases=inputs.split(' ')
score=0
for num in cases:
score+=(int(num))
if score>=2:
res+=1
print(res)
``` | 3 | |
50 | A | Domino piling | PROGRAMMING | 800 | [
"greedy",
"math"
] | A. Domino piling | 2 | 256 | You are given a rectangular board of *M*<=Γ<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=Γ<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions. | In a single line you are given two integers *M* and *N* β board sizes in squares (1<=β€<=*M*<=β€<=*N*<=β€<=16). | Output one number β the maximal number of dominoes, which can be placed. | [
"2 4\n",
"3 3\n"
] | [
"4\n",
"4\n"
] | none | 500 | [
{
"input": "2 4",
"output": "4"
},
{
"input": "3 3",
"output": "4"
},
{
"input": "1 5",
"output": "2"
},
{
"input": "1 6",
"output": "3"
},
{
"input": "1 15",
"output": "7"
},
{
"input": "1 16",
"output": "8"
},
{
"input": "2 5",
"outpu... | 1,647,362,354 | 2,147,483,647 | Python 3 | OK | TESTS | 35 | 248 | 6,041,600 | from tkinter import N
m,n = list(map(int, input().split()))
t= m*n
c=0
if n%2==0:
c= n/2*m
elif m%2==0:
c= m/2*n
else:
c= ((m-1)/2*n)+ (n-1)/2
print(int(c)) | Title: Domino piling
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
You are given a rectangular board of *M*<=Γ<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=Γ<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
Input Specification:
In a single line you are given two integers *M* and *N* β board sizes in squares (1<=β€<=*M*<=β€<=*N*<=β€<=16).
Output Specification:
Output one number β the maximal number of dominoes, which can be placed.
Demo Input:
['2 4\n', '3 3\n']
Demo Output:
['4\n', '4\n']
Note:
none | ```python
from tkinter import N
m,n = list(map(int, input().split()))
t= m*n
c=0
if n%2==0:
c= n/2*m
elif m%2==0:
c= m/2*n
else:
c= ((m-1)/2*n)+ (n-1)/2
print(int(c))
``` | 3.926747 |
912 | B | New Year's Eve | PROGRAMMING | 1,300 | [
"bitmasks",
"constructive algorithms",
"number theory"
] | null | null | Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains *n* sweet candies from the good ol' bakery, each labeled from 1 to *n* corresponding to its tastiness. No two candies have the same tastiness.
The choice of candies has a direct effect on Grisha's happiness. One can assume that he should take the tastiest onesΒ β but no, the holiday magic turns things upside down. It is the xor-sum of tastinesses that matters, not the ordinary sum!
A xor-sum of a sequence of integers *a*1,<=*a*2,<=...,<=*a**m* is defined as the bitwise XOR of all its elements: , here denotes the bitwise XOR operation; more about bitwise XOR can be found [here.](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)
Ded Moroz warned Grisha he has more houses to visit, so Grisha can take no more than *k* candies from the bag. Help Grisha determine the largest xor-sum (largest xor-sum means maximum happiness!) he can obtain. | The sole string contains two integers *n* and *k* (1<=β€<=*k*<=β€<=*n*<=β€<=1018). | Output one numberΒ β the largest possible xor-sum. | [
"4 3\n",
"6 6\n"
] | [
"7\n",
"7\n"
] | In the first sample case, one optimal answer is 1, 2 and 4, giving the xor-sum of 7.
In the second sample case, one can, for example, take all six candies and obtain the xor-sum of 7. | 1,000 | [
{
"input": "4 3",
"output": "7"
},
{
"input": "6 6",
"output": "7"
},
{
"input": "2 2",
"output": "3"
},
{
"input": "1022 10",
"output": "1023"
},
{
"input": "415853337373441 52",
"output": "562949953421311"
},
{
"input": "75 12",
"output": "127"
... | 1,614,694,325 | 2,147,483,647 | Python 3 | OK | TESTS | 58 | 62 | 307,200 | def precompute(arr) :
arr[0] = 1
for index in range(1,60) :
arr[index] = arr[index-1]*2
def solve(n,k,power) :
if k == 1 :
return n
else :
for index in range(59,-1,-1):
if power[index] <= n :
return power[index] + (power[index] - 1)
arr = [0] * 60
n,k = list(map(int,input().split()))
precompute(arr)
print (solve(n,k,arr))
| Title: New Year's Eve
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains *n* sweet candies from the good ol' bakery, each labeled from 1 to *n* corresponding to its tastiness. No two candies have the same tastiness.
The choice of candies has a direct effect on Grisha's happiness. One can assume that he should take the tastiest onesΒ β but no, the holiday magic turns things upside down. It is the xor-sum of tastinesses that matters, not the ordinary sum!
A xor-sum of a sequence of integers *a*1,<=*a*2,<=...,<=*a**m* is defined as the bitwise XOR of all its elements: , here denotes the bitwise XOR operation; more about bitwise XOR can be found [here.](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)
Ded Moroz warned Grisha he has more houses to visit, so Grisha can take no more than *k* candies from the bag. Help Grisha determine the largest xor-sum (largest xor-sum means maximum happiness!) he can obtain.
Input Specification:
The sole string contains two integers *n* and *k* (1<=β€<=*k*<=β€<=*n*<=β€<=1018).
Output Specification:
Output one numberΒ β the largest possible xor-sum.
Demo Input:
['4 3\n', '6 6\n']
Demo Output:
['7\n', '7\n']
Note:
In the first sample case, one optimal answer is 1, 2 and 4, giving the xor-sum of 7.
In the second sample case, one can, for example, take all six candies and obtain the xor-sum of 7. | ```python
def precompute(arr) :
arr[0] = 1
for index in range(1,60) :
arr[index] = arr[index-1]*2
def solve(n,k,power) :
if k == 1 :
return n
else :
for index in range(59,-1,-1):
if power[index] <= n :
return power[index] + (power[index] - 1)
arr = [0] * 60
n,k = list(map(int,input().split()))
precompute(arr)
print (solve(n,k,arr))
``` | 3 | |
593 | B | Anton and Lines | PROGRAMMING | 1,600 | [
"geometry",
"sortings"
] | null | null | The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of *n* lines defined by the equations *y*<==<=*k**i*Β·*x*<=+<=*b**i*. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between *x*1<=<<=*x*2. In other words, is it true that there are 1<=β€<=*i*<=<<=*j*<=β€<=*n* and *x*',<=*y*', such that:
- *y*'<==<=*k**i*<=*<=*x*'<=+<=*b**i*, that is, point (*x*',<=*y*') belongs to the line number *i*; - *y*'<==<=*k**j*<=*<=*x*'<=+<=*b**j*, that is, point (*x*',<=*y*') belongs to the line number *j*; - *x*1<=<<=*x*'<=<<=*x*2, that is, point (*x*',<=*y*') lies inside the strip bounded by *x*1<=<<=*x*2.
You can't leave Anton in trouble, can you? Write a program that solves the given task. | The first line of the input contains an integer *n* (2<=β€<=*n*<=β€<=100<=000)Β β the number of lines in the task given to Anton. The second line contains integers *x*1 and *x*2 (<=-<=1<=000<=000<=β€<=*x*1<=<<=*x*2<=β€<=1<=000<=000) defining the strip inside which you need to find a point of intersection of at least two lines.
The following *n* lines contain integers *k**i*, *b**i* (<=-<=1<=000<=000<=β€<=*k**i*,<=*b**i*<=β€<=1<=000<=000)Β β the descriptions of the lines. It is guaranteed that all lines are pairwise distinct, that is, for any two *i*<=β <=*j* it is true that either *k**i*<=β <=*k**j*, or *b**i*<=β <=*b**j*. | Print "Yes" (without quotes), if there is at least one intersection of two distinct lines, located strictly inside the strip. Otherwise print "No" (without quotes). | [
"4\n1 2\n1 2\n1 0\n0 1\n0 2\n",
"2\n1 3\n1 0\n-1 3\n",
"2\n1 3\n1 0\n0 2\n",
"2\n1 3\n1 0\n0 3\n"
] | [
"NO",
"YES",
"YES",
"NO"
] | In the first sample there are intersections located on the border of the strip, but there are no intersections located strictly inside it. | 1,000 | [
{
"input": "4\n1 2\n1 2\n1 0\n0 1\n0 2",
"output": "NO"
},
{
"input": "2\n1 3\n1 0\n-1 3",
"output": "YES"
},
{
"input": "2\n1 3\n1 0\n0 2",
"output": "YES"
},
{
"input": "2\n1 3\n1 0\n0 3",
"output": "NO"
},
{
"input": "2\n0 1\n-1000000 1000000\n1000000 -1000000"... | 1,446,661,522 | 6,022 | Python 3 | OK | TESTS | 93 | 561 | 9,932,800 | n = int(input())
a = list()
x1, x2 = map(int, input().split())
for i in range(n):
k, b = map(int, input().split())
y1 = k * x1 + b
y2 = k * x2 + b
a.append((y1, y2))
a.sort()
fl = 'NO'
y1m = a[0][0]
y2m = a[0][1]
for y1, y2 in a:
if y2 < y2m:
fl = 'YES'
else:
y2m = max(y2m, y2)
print(fl)
| Title: Anton and Lines
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of *n* lines defined by the equations *y*<==<=*k**i*Β·*x*<=+<=*b**i*. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between *x*1<=<<=*x*2. In other words, is it true that there are 1<=β€<=*i*<=<<=*j*<=β€<=*n* and *x*',<=*y*', such that:
- *y*'<==<=*k**i*<=*<=*x*'<=+<=*b**i*, that is, point (*x*',<=*y*') belongs to the line number *i*; - *y*'<==<=*k**j*<=*<=*x*'<=+<=*b**j*, that is, point (*x*',<=*y*') belongs to the line number *j*; - *x*1<=<<=*x*'<=<<=*x*2, that is, point (*x*',<=*y*') lies inside the strip bounded by *x*1<=<<=*x*2.
You can't leave Anton in trouble, can you? Write a program that solves the given task.
Input Specification:
The first line of the input contains an integer *n* (2<=β€<=*n*<=β€<=100<=000)Β β the number of lines in the task given to Anton. The second line contains integers *x*1 and *x*2 (<=-<=1<=000<=000<=β€<=*x*1<=<<=*x*2<=β€<=1<=000<=000) defining the strip inside which you need to find a point of intersection of at least two lines.
The following *n* lines contain integers *k**i*, *b**i* (<=-<=1<=000<=000<=β€<=*k**i*,<=*b**i*<=β€<=1<=000<=000)Β β the descriptions of the lines. It is guaranteed that all lines are pairwise distinct, that is, for any two *i*<=β <=*j* it is true that either *k**i*<=β <=*k**j*, or *b**i*<=β <=*b**j*.
Output Specification:
Print "Yes" (without quotes), if there is at least one intersection of two distinct lines, located strictly inside the strip. Otherwise print "No" (without quotes).
Demo Input:
['4\n1 2\n1 2\n1 0\n0 1\n0 2\n', '2\n1 3\n1 0\n-1 3\n', '2\n1 3\n1 0\n0 2\n', '2\n1 3\n1 0\n0 3\n']
Demo Output:
['NO', 'YES', 'YES', 'NO']
Note:
In the first sample there are intersections located on the border of the strip, but there are no intersections located strictly inside it. | ```python
n = int(input())
a = list()
x1, x2 = map(int, input().split())
for i in range(n):
k, b = map(int, input().split())
y1 = k * x1 + b
y2 = k * x2 + b
a.append((y1, y2))
a.sort()
fl = 'NO'
y1m = a[0][0]
y2m = a[0][1]
for y1, y2 in a:
if y2 < y2m:
fl = 'YES'
else:
y2m = max(y2m, y2)
print(fl)
``` | 3 | |
628 | B | New Skateboard | PROGRAMMING | 1,300 | [
"dp"
] | null | null | Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.
You are given a string *s* consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.
A substring of a string is a nonempty sequence of consecutive characters.
For example if string *s* is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. | The only line contains string *s* (1<=β€<=|*s*|<=β€<=3Β·105). The string *s* contains only digits from 0 to 9. | Print integer *a* β the number of substrings of the string *s* that are divisible by 4.
Note that the answer can be huge, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type. | [
"124\n",
"04\n",
"5810438174\n"
] | [
"4\n",
"3\n",
"9\n"
] | none | 0 | [
{
"input": "124",
"output": "4"
},
{
"input": "04",
"output": "3"
},
{
"input": "5810438174",
"output": "9"
},
{
"input": "1",
"output": "0"
},
{
"input": "039",
"output": "1"
},
{
"input": "97247",
"output": "6"
},
{
"input": "5810438174",... | 1,590,996,538 | 2,147,483,647 | Python 3 | OK | TESTS | 22 | 280 | 1,024,000 | s = input()
res = 0
for i in range(1, len(s)) :
if int(s[i-1 : i+1]) % 4 == 0 :
res += i
res += s.count('0') + s.count('4') + s.count('8')
print(res) | Title: New Skateboard
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.
You are given a string *s* consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.
A substring of a string is a nonempty sequence of consecutive characters.
For example if string *s* is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
Input Specification:
The only line contains string *s* (1<=β€<=|*s*|<=β€<=3Β·105). The string *s* contains only digits from 0 to 9.
Output Specification:
Print integer *a* β the number of substrings of the string *s* that are divisible by 4.
Note that the answer can be huge, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.
Demo Input:
['124\n', '04\n', '5810438174\n']
Demo Output:
['4\n', '3\n', '9\n']
Note:
none | ```python
s = input()
res = 0
for i in range(1, len(s)) :
if int(s[i-1 : i+1]) % 4 == 0 :
res += i
res += s.count('0') + s.count('4') + s.count('8')
print(res)
``` | 3 | |
59 | A | Word | PROGRAMMING | 800 | [
"implementation",
"strings"
] | A. Word | 2 | 256 | Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP β with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word. | The first line contains a word *s* β it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100. | Print the corrected word *s*. If the given word *s* has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one. | [
"HoUse\n",
"ViP\n",
"maTRIx\n"
] | [
"house\n",
"VIP\n",
"matrix\n"
] | none | 500 | [
{
"input": "HoUse",
"output": "house"
},
{
"input": "ViP",
"output": "VIP"
},
{
"input": "maTRIx",
"output": "matrix"
},
{
"input": "BNHWpnpawg",
"output": "bnhwpnpawg"
},
{
"input": "VTYGP",
"output": "VTYGP"
},
{
"input": "CHNenu",
"output": "chn... | 1,687,675,062 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 30 | 124 | 0 | k=input()
count=0
for i in k:
if(i.isupper()):
count+=1
if(count>(len(k)//2)):
print(k.upper())
else:
print(k.lower())
| Title: Word
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP β with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
Input Specification:
The first line contains a word *s* β it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100.
Output Specification:
Print the corrected word *s*. If the given word *s* has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one.
Demo Input:
['HoUse\n', 'ViP\n', 'maTRIx\n']
Demo Output:
['house\n', 'VIP\n', 'matrix\n']
Note:
none | ```python
k=input()
count=0
for i in k:
if(i.isupper()):
count+=1
if(count>(len(k)//2)):
print(k.upper())
else:
print(k.lower())
``` | 3.969 |
702 | A | Maximum Increase | PROGRAMMING | 800 | [
"dp",
"greedy",
"implementation"
] | null | null | You are given array consisting of *n* integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous. | The first line contains single positive integer *n* (1<=β€<=*n*<=β€<=105) β the number of integers.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=109). | Print the maximum length of an increasing subarray of the given array. | [
"5\n1 7 2 11 15\n",
"6\n100 100 100 100 100 100\n",
"3\n1 2 3\n"
] | [
"3\n",
"1\n",
"3\n"
] | none | 0 | [
{
"input": "5\n1 7 2 11 15",
"output": "3"
},
{
"input": "6\n100 100 100 100 100 100",
"output": "1"
},
{
"input": "3\n1 2 3",
"output": "3"
},
{
"input": "1\n1000000000",
"output": "1"
},
{
"input": "10\n802030518 598196518 640274071 983359971 71550121 96204862 7... | 1,679,084,381 | 2,147,483,647 | Python 3 | OK | TESTS | 32 | 93 | 7,884,800 | n = int (input())
current = 1
max = 1
x = list(map(int,input().split()))
for i in range(n-1): # 0 1 2 3 4
if x[i+1] > x[i]: # 1 7 2 11 15
current = current +1
else:
current=1
if max<current:max=current
print (max) | Title: Maximum Increase
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given array consisting of *n* integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input Specification:
The first line contains single positive integer *n* (1<=β€<=*n*<=β€<=105) β the number of integers.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=109).
Output Specification:
Print the maximum length of an increasing subarray of the given array.
Demo Input:
['5\n1 7 2 11 15\n', '6\n100 100 100 100 100 100\n', '3\n1 2 3\n']
Demo Output:
['3\n', '1\n', '3\n']
Note:
none | ```python
n = int (input())
current = 1
max = 1
x = list(map(int,input().split()))
for i in range(n-1): # 0 1 2 3 4
if x[i+1] > x[i]: # 1 7 2 11 15
current = current +1
else:
current=1
if max<current:max=current
print (max)
``` | 3 | |
152 | C | Pocket Book | PROGRAMMING | 1,400 | [
"combinatorics"
] | null | null | One day little Vasya found mom's pocket book. The book had *n* names of her friends and unusually enough, each name was exactly *m* letters long. Let's number the names from 1 to *n* in the order in which they are written.
As mom wasn't home, Vasya decided to play with names: he chose three integers *i*, *j*, *k* (1<=β€<=*i*<=<<=*j*<=β€<=*n*, 1<=β€<=*k*<=β€<=*m*), then he took names number *i* and *j* and swapped their prefixes of length *k*. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".
You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers *i*, *j*, *k* independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109<=+<=7). | The first input line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=100) β the number of names and the length of each name, correspondingly. Then *n* lines contain names, each name consists of exactly *m* uppercase Latin letters. | Print the single number β the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109<=+<=7). | [
"2 3\nAAB\nBAA\n",
"4 5\nABABA\nBCGDG\nAAAAA\nYABSA\n"
] | [
"4\n",
"216\n"
] | In the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB". | 1,500 | [
{
"input": "2 3\nAAB\nBAA",
"output": "4"
},
{
"input": "4 5\nABABA\nBCGDG\nAAAAA\nYABSA",
"output": "216"
},
{
"input": "1 1\nE",
"output": "1"
},
{
"input": "2 2\nNS\nPD",
"output": "4"
},
{
"input": "3 4\nPJKD\nNFJX\nFGFK",
"output": "81"
},
{
"inpu... | 1,663,609,937 | 2,147,483,647 | Python 3 | OK | TESTS | 60 | 92 | 0 | if __name__ == "__main__":
modulo=10**9+7
n,m=map(int,input().split())
names=[]
for i in range(n):
names.append(input().strip())
res=1
for j in range(m):
unique_col_char_count=0
tmp_arr=[]
for i in range(n):
if names[i][j] not in tmp_arr:
unique_col_char_count+=1
tmp_arr.append(names[i][j])
res*=unique_col_char_count
res=res%(modulo)
print(res) | Title: Pocket Book
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day little Vasya found mom's pocket book. The book had *n* names of her friends and unusually enough, each name was exactly *m* letters long. Let's number the names from 1 to *n* in the order in which they are written.
As mom wasn't home, Vasya decided to play with names: he chose three integers *i*, *j*, *k* (1<=β€<=*i*<=<<=*j*<=β€<=*n*, 1<=β€<=*k*<=β€<=*m*), then he took names number *i* and *j* and swapped their prefixes of length *k*. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".
You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers *i*, *j*, *k* independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109<=+<=7).
Input Specification:
The first input line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=100) β the number of names and the length of each name, correspondingly. Then *n* lines contain names, each name consists of exactly *m* uppercase Latin letters.
Output Specification:
Print the single number β the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109<=+<=7).
Demo Input:
['2 3\nAAB\nBAA\n', '4 5\nABABA\nBCGDG\nAAAAA\nYABSA\n']
Demo Output:
['4\n', '216\n']
Note:
In the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB". | ```python
if __name__ == "__main__":
modulo=10**9+7
n,m=map(int,input().split())
names=[]
for i in range(n):
names.append(input().strip())
res=1
for j in range(m):
unique_col_char_count=0
tmp_arr=[]
for i in range(n):
if names[i][j] not in tmp_arr:
unique_col_char_count+=1
tmp_arr.append(names[i][j])
res*=unique_col_char_count
res=res%(modulo)
print(res)
``` | 3 | |
749 | A | Bachgold Problem | PROGRAMMING | 800 | [
"greedy",
"implementation",
"math",
"number theory"
] | null | null | Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisorsΒ β 1 and *k*. | The only line of the input contains a single integer *n* (2<=β€<=*n*<=β€<=100<=000). | The first line of the output contains a single integer *k*Β β maximum possible number of primes in representation.
The second line should contain *k* primes with their sum equal to *n*. You can print them in any order. If there are several optimal solution, print any of them. | [
"5\n",
"6\n"
] | [
"2\n2 3\n",
"3\n2 2 2\n"
] | none | 500 | [
{
"input": "5",
"output": "2\n2 3"
},
{
"input": "6",
"output": "3\n2 2 2"
},
{
"input": "2",
"output": "1\n2"
},
{
"input": "3",
"output": "1\n3"
},
{
"input": "99999",
"output": "49999\n2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ... | 1,676,308,146 | 2,147,483,647 | Python 3 | OK | TESTS | 41 | 108 | 0 | n = int(input())
if n % 2 == 0:
print(n//2)
for x in range(n//2):
print(2,end=" ")
else:
print(n//2)
for x in range((n//2) - 1):
print(2,end=" ")
print(3)
| Title: Bachgold Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisorsΒ β 1 and *k*.
Input Specification:
The only line of the input contains a single integer *n* (2<=β€<=*n*<=β€<=100<=000).
Output Specification:
The first line of the output contains a single integer *k*Β β maximum possible number of primes in representation.
The second line should contain *k* primes with their sum equal to *n*. You can print them in any order. If there are several optimal solution, print any of them.
Demo Input:
['5\n', '6\n']
Demo Output:
['2\n2 3\n', '3\n2 2 2\n']
Note:
none | ```python
n = int(input())
if n % 2 == 0:
print(n//2)
for x in range(n//2):
print(2,end=" ")
else:
print(n//2)
for x in range((n//2) - 1):
print(2,end=" ")
print(3)
``` | 3 | |
928 | A | Login Verification | PROGRAMMING | 1,200 | [
"*special",
"strings"
] | null | null | When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.
Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols (Β«_Β»). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins *s* and *t* are considered similar if we can transform *s* to *t* via a sequence of operations of the following types:
- transform lowercase letters to uppercase and vice versa; - change letter Β«OΒ» (uppercase latin letter) to digit Β«0Β» and vice versa; - change digit Β«1Β» (one) to any letter among Β«lΒ» (lowercase latin Β«LΒ»), Β«IΒ» (uppercase latin Β«iΒ») and vice versa, or change one of these letters to other.
For example, logins Β«CodeforcesΒ» and Β«codef0rcesΒ» as well as Β«OO0OOO00O0OOO0O00OOO0OO_lolΒ» and Β«OO0OOO0O00OOO0O00OO0OOO_1oIΒ» are considered similar whereas Β«CodeforcesΒ» and Β«Code_forcesΒ» are not.
You're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones. | The first line contains a non-empty string *s* consisting of lower and uppercase latin letters, digits and underline symbols (Β«_Β») with length not exceeding 50 Β β the login itself.
The second line contains a single integer *n* (1<=β€<=*n*<=β€<=1<=000)Β β the number of existing logins.
The next *n* lines describe the existing logins, following the same constraints as the user login (refer to the first line of the input). It's guaranteed that no two existing logins are similar. | Print Β«YesΒ» (without quotes), if user can register via this login, i.e. none of the existing logins is similar with it.
Otherwise print Β«NoΒ» (without quotes). | [
"1_wat\n2\n2_wat\nwat_1\n",
"000\n3\n00\nooA\noOo\n",
"_i_\n3\n__i_\n_1_\nI\n",
"La0\n3\n2a0\nLa1\n1a0\n",
"abc\n1\naBc\n",
"0Lil\n2\nLIL0\n0Ril\n"
] | [
"Yes\n",
"No\n",
"No\n",
"No\n",
"No\n",
"Yes\n"
] | In the second sample case the user wants to create a login consisting of three zeros. It's impossible due to collision with the third among the existing.
In the third sample case the new login is similar with the second one. | 500 | [
{
"input": "1_wat\n2\n2_wat\nwat_1",
"output": "Yes"
},
{
"input": "000\n3\n00\nooA\noOo",
"output": "No"
},
{
"input": "_i_\n3\n__i_\n_1_\nI",
"output": "No"
},
{
"input": "La0\n3\n2a0\nLa1\n1a0",
"output": "No"
},
{
"input": "abc\n1\naBc",
"output": "No"
}... | 1,673,892,058 | 2,147,483,647 | Python 3 | OK | TESTS | 73 | 46 | 0 | s=input()
s=s.upper()
s=s.replace('O','0')
s=s.replace('L','1')
s=s.replace('I','1')
f=1
for i in range(int(input())):
s1=input()
s1=s1.upper()
s1=s1.replace('O','0')
s1=s1.replace('L','1')
s1=s1.replace('I','1')
if(s==s1):
f=0
if(f):
print("Yes")
else:
print("No") | Title: Login Verification
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.
Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols (Β«_Β»). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins *s* and *t* are considered similar if we can transform *s* to *t* via a sequence of operations of the following types:
- transform lowercase letters to uppercase and vice versa; - change letter Β«OΒ» (uppercase latin letter) to digit Β«0Β» and vice versa; - change digit Β«1Β» (one) to any letter among Β«lΒ» (lowercase latin Β«LΒ»), Β«IΒ» (uppercase latin Β«iΒ») and vice versa, or change one of these letters to other.
For example, logins Β«CodeforcesΒ» and Β«codef0rcesΒ» as well as Β«OO0OOO00O0OOO0O00OOO0OO_lolΒ» and Β«OO0OOO0O00OOO0O00OO0OOO_1oIΒ» are considered similar whereas Β«CodeforcesΒ» and Β«Code_forcesΒ» are not.
You're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones.
Input Specification:
The first line contains a non-empty string *s* consisting of lower and uppercase latin letters, digits and underline symbols (Β«_Β») with length not exceeding 50 Β β the login itself.
The second line contains a single integer *n* (1<=β€<=*n*<=β€<=1<=000)Β β the number of existing logins.
The next *n* lines describe the existing logins, following the same constraints as the user login (refer to the first line of the input). It's guaranteed that no two existing logins are similar.
Output Specification:
Print Β«YesΒ» (without quotes), if user can register via this login, i.e. none of the existing logins is similar with it.
Otherwise print Β«NoΒ» (without quotes).
Demo Input:
['1_wat\n2\n2_wat\nwat_1\n', '000\n3\n00\nooA\noOo\n', '_i_\n3\n__i_\n_1_\nI\n', 'La0\n3\n2a0\nLa1\n1a0\n', 'abc\n1\naBc\n', '0Lil\n2\nLIL0\n0Ril\n']
Demo Output:
['Yes\n', 'No\n', 'No\n', 'No\n', 'No\n', 'Yes\n']
Note:
In the second sample case the user wants to create a login consisting of three zeros. It's impossible due to collision with the third among the existing.
In the third sample case the new login is similar with the second one. | ```python
s=input()
s=s.upper()
s=s.replace('O','0')
s=s.replace('L','1')
s=s.replace('I','1')
f=1
for i in range(int(input())):
s1=input()
s1=s1.upper()
s1=s1.replace('O','0')
s1=s1.replace('L','1')
s1=s1.replace('I','1')
if(s==s1):
f=0
if(f):
print("Yes")
else:
print("No")
``` | 3 | |
799 | A | Carrot Cakes | PROGRAMMING | 1,100 | [
"brute force",
"implementation"
] | null | null | In some game by Playrix it takes *t* minutes for an oven to bake *k* carrot cakes, all cakes are ready at the same moment *t* minutes after they started baking. Arkady needs at least *n* cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take *d* minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven.
Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get *n* cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable. | The only line contains four integers *n*, *t*, *k*, *d* (1<=β€<=*n*,<=*t*,<=*k*,<=*d*<=β€<=1<=000)Β β the number of cakes needed, the time needed for one oven to bake *k* cakes, the number of cakes baked at the same time, the time needed to build the second oven. | If it is reasonable to build the second oven, print "YES". Otherwise print "NO". | [
"8 6 4 5\n",
"8 6 4 6\n",
"10 3 11 4\n",
"4 2 1 4\n"
] | [
"YES\n",
"NO\n",
"NO\n",
"YES\n"
] | In the first example it is possible to get 8 cakes in 12 minutes using one oven. The second oven can be built in 5 minutes, so after 6 minutes the first oven bakes 4 cakes, the second oven bakes 4 more ovens after 11 minutes. Thus, it is reasonable to build the second oven.
In the second example it doesn't matter whether we build the second oven or not, thus it takes 12 minutes to bake 8 cakes in both cases. Thus, it is unreasonable to build the second oven.
In the third example the first oven bakes 11 cakes in 3 minutes, that is more than needed 10. It is unreasonable to build the second oven, because its building takes more time that baking the needed number of cakes using the only oven. | 500 | [
{
"input": "8 6 4 5",
"output": "YES"
},
{
"input": "8 6 4 6",
"output": "NO"
},
{
"input": "10 3 11 4",
"output": "NO"
},
{
"input": "4 2 1 4",
"output": "YES"
},
{
"input": "28 17 16 26",
"output": "NO"
},
{
"input": "60 69 9 438",
"output": "NO"... | 1,597,672,221 | 2,147,483,647 | PyPy 3 | OK | TESTS | 93 | 140 | 0 | n, t, k, d = map(int, input().split())
g = int((n + k - 1) / k)
o1, o2 = 0, d
i = 0
while i < g:
if o1 <= o2:
o1 += t
else:
o2 += t
i += 1
if max(o1, o2) < g * t:
print("YES")
else:
print("NO") | Title: Carrot Cakes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In some game by Playrix it takes *t* minutes for an oven to bake *k* carrot cakes, all cakes are ready at the same moment *t* minutes after they started baking. Arkady needs at least *n* cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take *d* minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven.
Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get *n* cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.
Input Specification:
The only line contains four integers *n*, *t*, *k*, *d* (1<=β€<=*n*,<=*t*,<=*k*,<=*d*<=β€<=1<=000)Β β the number of cakes needed, the time needed for one oven to bake *k* cakes, the number of cakes baked at the same time, the time needed to build the second oven.
Output Specification:
If it is reasonable to build the second oven, print "YES". Otherwise print "NO".
Demo Input:
['8 6 4 5\n', '8 6 4 6\n', '10 3 11 4\n', '4 2 1 4\n']
Demo Output:
['YES\n', 'NO\n', 'NO\n', 'YES\n']
Note:
In the first example it is possible to get 8 cakes in 12 minutes using one oven. The second oven can be built in 5 minutes, so after 6 minutes the first oven bakes 4 cakes, the second oven bakes 4 more ovens after 11 minutes. Thus, it is reasonable to build the second oven.
In the second example it doesn't matter whether we build the second oven or not, thus it takes 12 minutes to bake 8 cakes in both cases. Thus, it is unreasonable to build the second oven.
In the third example the first oven bakes 11 cakes in 3 minutes, that is more than needed 10. It is unreasonable to build the second oven, because its building takes more time that baking the needed number of cakes using the only oven. | ```python
n, t, k, d = map(int, input().split())
g = int((n + k - 1) / k)
o1, o2 = 0, d
i = 0
while i < g:
if o1 <= o2:
o1 += t
else:
o2 += t
i += 1
if max(o1, o2) < g * t:
print("YES")
else:
print("NO")
``` | 3 | |
749 | A | Bachgold Problem | PROGRAMMING | 800 | [
"greedy",
"implementation",
"math",
"number theory"
] | null | null | Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisorsΒ β 1 and *k*. | The only line of the input contains a single integer *n* (2<=β€<=*n*<=β€<=100<=000). | The first line of the output contains a single integer *k*Β β maximum possible number of primes in representation.
The second line should contain *k* primes with their sum equal to *n*. You can print them in any order. If there are several optimal solution, print any of them. | [
"5\n",
"6\n"
] | [
"2\n2 3\n",
"3\n2 2 2\n"
] | none | 500 | [
{
"input": "5",
"output": "2\n2 3"
},
{
"input": "6",
"output": "3\n2 2 2"
},
{
"input": "2",
"output": "1\n2"
},
{
"input": "3",
"output": "1\n3"
},
{
"input": "99999",
"output": "49999\n2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ... | 1,693,061,281 | 2,147,483,647 | Python 3 | OK | TESTS | 41 | 77 | 1,024,000 | n = int(input())
primes_sum = [2] * (n // 2)
if n % 2 == 1:
primes_sum[-1] = 3
print(len(primes_sum))
print(*primes_sum)
| Title: Bachgold Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisorsΒ β 1 and *k*.
Input Specification:
The only line of the input contains a single integer *n* (2<=β€<=*n*<=β€<=100<=000).
Output Specification:
The first line of the output contains a single integer *k*Β β maximum possible number of primes in representation.
The second line should contain *k* primes with their sum equal to *n*. You can print them in any order. If there are several optimal solution, print any of them.
Demo Input:
['5\n', '6\n']
Demo Output:
['2\n2 3\n', '3\n2 2 2\n']
Note:
none | ```python
n = int(input())
primes_sum = [2] * (n // 2)
if n % 2 == 1:
primes_sum[-1] = 3
print(len(primes_sum))
print(*primes_sum)
``` | 3 | |
909 | A | Generate Login | PROGRAMMING | 1,000 | [
"brute force",
"greedy",
"sortings"
] | null | null | The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string *s* is its substring which occurs at the beginning of *s*: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string *a* is alphabetically earlier than a string *b*, if *a* is a prefix of *b*, or *a* and *b* coincide up to some position, and then *a* has a letter that is alphabetically earlier than the corresponding letter in *b*: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac". | The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive. | Output a single stringΒ β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well. | [
"harry potter\n",
"tom riddle\n"
] | [
"hap\n",
"tomr\n"
] | none | 500 | [
{
"input": "harry potter",
"output": "hap"
},
{
"input": "tom riddle",
"output": "tomr"
},
{
"input": "a qdpinbmcrf",
"output": "aq"
},
{
"input": "wixjzniiub ssdfodfgap",
"output": "wis"
},
{
"input": "z z",
"output": "zz"
},
{
"input": "ertuyivhfg v"... | 1,514,395,082 | 2,582 | Python 3 | OK | TESTS | 64 | 78 | 5,529,600 | def getprfx(s):
tab = [s[0]]
for i in range(1, len(s)):
x = tab[i-1] + s[i]
tab.append(x)
return tab
n, m = input().split()
a, b = getprfx(n), getprfx(m)
mn = a[0] + b[0]
for i in a:
for j in b:
if i+j < mn:
mn = i+j
print(mn) | Title: Generate Login
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string *s* is its substring which occurs at the beginning of *s*: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string *a* is alphabetically earlier than a string *b*, if *a* is a prefix of *b*, or *a* and *b* coincide up to some position, and then *a* has a letter that is alphabetically earlier than the corresponding letter in *b*: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input Specification:
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output Specification:
Output a single stringΒ β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Demo Input:
['harry potter\n', 'tom riddle\n']
Demo Output:
['hap\n', 'tomr\n']
Note:
none | ```python
def getprfx(s):
tab = [s[0]]
for i in range(1, len(s)):
x = tab[i-1] + s[i]
tab.append(x)
return tab
n, m = input().split()
a, b = getprfx(n), getprfx(m)
mn = a[0] + b[0]
for i in a:
for j in b:
if i+j < mn:
mn = i+j
print(mn)
``` | 3 | |
507 | B | Amr and Pins | PROGRAMMING | 1,400 | [
"geometry",
"math"
] | null | null | Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius *r* and center in point (*x*,<=*y*). He wants the circle center to be in new position (*x*',<=*y*').
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin.
Help Amr to achieve his goal in minimum number of steps. | Input consists of 5 space-separated integers *r*, *x*, *y*, *x*' *y*' (1<=β€<=*r*<=β€<=105, <=-<=105<=β€<=*x*,<=*y*,<=*x*',<=*y*'<=β€<=105), circle radius, coordinates of original center of the circle and coordinates of destination center of the circle respectively. | Output a single integer β minimum number of steps required to move the center of the circle to the destination point. | [
"2 0 0 0 4\n",
"1 1 1 4 4\n",
"4 5 6 5 6\n"
] | [
"1\n",
"3\n",
"0\n"
] | In the first sample test the optimal way is to put a pin at point (0,β2) and rotate the circle by 180 degrees counter-clockwise (or clockwise, no matter).
<img class="tex-graphics" src="https://espresso.codeforces.com/4e40fd4cc24a2050a0488aa131e6244369328039.png" style="max-width: 100.0%;max-height: 100.0%;"/> | 1,000 | [
{
"input": "2 0 0 0 4",
"output": "1"
},
{
"input": "1 1 1 4 4",
"output": "3"
},
{
"input": "4 5 6 5 6",
"output": "0"
},
{
"input": "10 20 0 40 0",
"output": "1"
},
{
"input": "9 20 0 40 0",
"output": "2"
},
{
"input": "5 -1 -6 -5 1",
"output": "... | 1,645,220,418 | 2,147,483,647 | PyPy 3 | OK | TESTS | 37 | 93 | 0 | from math import *
r,x,y,a,b=map(int,input().split())
print(ceil((((x-a)**2+(y-b)**2)**0.5)/(r*2)))
| Title: Amr and Pins
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius *r* and center in point (*x*,<=*y*). He wants the circle center to be in new position (*x*',<=*y*').
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin.
Help Amr to achieve his goal in minimum number of steps.
Input Specification:
Input consists of 5 space-separated integers *r*, *x*, *y*, *x*' *y*' (1<=β€<=*r*<=β€<=105, <=-<=105<=β€<=*x*,<=*y*,<=*x*',<=*y*'<=β€<=105), circle radius, coordinates of original center of the circle and coordinates of destination center of the circle respectively.
Output Specification:
Output a single integer β minimum number of steps required to move the center of the circle to the destination point.
Demo Input:
['2 0 0 0 4\n', '1 1 1 4 4\n', '4 5 6 5 6\n']
Demo Output:
['1\n', '3\n', '0\n']
Note:
In the first sample test the optimal way is to put a pin at point (0,β2) and rotate the circle by 180 degrees counter-clockwise (or clockwise, no matter).
<img class="tex-graphics" src="https://espresso.codeforces.com/4e40fd4cc24a2050a0488aa131e6244369328039.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
from math import *
r,x,y,a,b=map(int,input().split())
print(ceil((((x-a)**2+(y-b)**2)**0.5)/(r*2)))
``` | 3 | |
112 | A | Petya and Strings | PROGRAMMING | 800 | [
"implementation",
"strings"
] | A. Petya and Strings | 2 | 256 | Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison. | Each of the first two lines contains a bought string. The strings' lengths range from 1 to 100 inclusive. It is guaranteed that the strings are of the same length and also consist of uppercase and lowercase Latin letters. | If the first string is less than the second one, print "-1". If the second string is less than the first one, print "1". If the strings are equal, print "0". Note that the letters' case is not taken into consideration when the strings are compared. | [
"aaaa\naaaA\n",
"abs\nAbz\n",
"abcdefg\nAbCdEfF\n"
] | [
"0\n",
"-1\n",
"1\n"
] | If you want more formal information about the lexicographical order (also known as the "dictionary order" or "alphabetical order"), you can visit the following site:
- http://en.wikipedia.org/wiki/Lexicographical_order | 500 | [
{
"input": "aaaa\naaaA",
"output": "0"
},
{
"input": "abs\nAbz",
"output": "-1"
},
{
"input": "abcdefg\nAbCdEfF",
"output": "1"
},
{
"input": "asadasdasd\nasdwasdawd",
"output": "-1"
},
{
"input": "aslkjlkasdd\nasdlkjdajwi",
"output": "1"
},
{
"input":... | 1,695,295,819 | 2,147,483,647 | Python 3 | OK | TESTS | 53 | 92 | 0 | s1 = input().lower()
s2 = input().lower()
if s1==s2:
print(0)
if s1<s2:
print(-1)
if s1>s2:
print(1)
| Title: Petya and Strings
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.
Input Specification:
Each of the first two lines contains a bought string. The strings' lengths range from 1 to 100 inclusive. It is guaranteed that the strings are of the same length and also consist of uppercase and lowercase Latin letters.
Output Specification:
If the first string is less than the second one, print "-1". If the second string is less than the first one, print "1". If the strings are equal, print "0". Note that the letters' case is not taken into consideration when the strings are compared.
Demo Input:
['aaaa\naaaA\n', 'abs\nAbz\n', 'abcdefg\nAbCdEfF\n']
Demo Output:
['0\n', '-1\n', '1\n']
Note:
If you want more formal information about the lexicographical order (also known as the "dictionary order" or "alphabetical order"), you can visit the following site:
- http://en.wikipedia.org/wiki/Lexicographical_order | ```python
s1 = input().lower()
s2 = input().lower()
if s1==s2:
print(0)
if s1<s2:
print(-1)
if s1>s2:
print(1)
``` | 3.977 |
499 | B | Lecture | PROGRAMMING | 1,000 | [
"implementation",
"strings"
] | null | null | You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes. | The first line contains two integers, *n* and *m* (1<=β€<=*n*<=β€<=3000, 1<=β€<=*m*<=β€<=3000) β the number of words in the professor's lecture and the number of words in each of these languages.
The following *m* lines contain the words. The *i*-th line contains two strings *a**i*, *b**i* meaning that the word *a**i* belongs to the first language, the word *b**i* belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once.
The next line contains *n* space-separated strings *c*1,<=*c*2,<=...,<=*c**n* β the text of the lecture. It is guaranteed that each of the strings *c**i* belongs to the set of strings {*a*1,<=*a*2,<=... *a**m*}.
All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters. | Output exactly *n* words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input. | [
"4 3\ncodeforces codesecrof\ncontest round\nletter message\ncodeforces contest letter contest\n",
"5 3\njoll wuqrd\neuzf un\nhbnyiyc rsoqqveh\nhbnyiyc joll joll euzf joll\n"
] | [
"codeforces round letter round\n",
"hbnyiyc joll joll un joll\n"
] | none | 500 | [
{
"input": "4 3\ncodeforces codesecrof\ncontest round\nletter message\ncodeforces contest letter contest",
"output": "codeforces round letter round"
},
{
"input": "5 3\njoll wuqrd\neuzf un\nhbnyiyc rsoqqveh\nhbnyiyc joll joll euzf joll",
"output": "hbnyiyc joll joll un joll"
},
{
"input"... | 1,639,733,904 | 2,147,483,647 | Python 3 | OK | TESTS | 37 | 62 | 409,600 | n , m = map(int, input().split(" "))
notes = {}
final = []
for i in range(m):
a,b = map(str, input().split())
notes[a]=b
c = list(map(str, input().split(" ")[:n]))
for i in c:
if len(notes[i])>=len(i):
final.append(i)
else:
final.append(notes[i])
print(" ".join(final)) | Title: Lecture
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
Input Specification:
The first line contains two integers, *n* and *m* (1<=β€<=*n*<=β€<=3000, 1<=β€<=*m*<=β€<=3000) β the number of words in the professor's lecture and the number of words in each of these languages.
The following *m* lines contain the words. The *i*-th line contains two strings *a**i*, *b**i* meaning that the word *a**i* belongs to the first language, the word *b**i* belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once.
The next line contains *n* space-separated strings *c*1,<=*c*2,<=...,<=*c**n* β the text of the lecture. It is guaranteed that each of the strings *c**i* belongs to the set of strings {*a*1,<=*a*2,<=... *a**m*}.
All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.
Output Specification:
Output exactly *n* words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.
Demo Input:
['4 3\ncodeforces codesecrof\ncontest round\nletter message\ncodeforces contest letter contest\n', '5 3\njoll wuqrd\neuzf un\nhbnyiyc rsoqqveh\nhbnyiyc joll joll euzf joll\n']
Demo Output:
['codeforces round letter round\n', 'hbnyiyc joll joll un joll\n']
Note:
none | ```python
n , m = map(int, input().split(" "))
notes = {}
final = []
for i in range(m):
a,b = map(str, input().split())
notes[a]=b
c = list(map(str, input().split(" ")[:n]))
for i in c:
if len(notes[i])>=len(i):
final.append(i)
else:
final.append(notes[i])
print(" ".join(final))
``` | 3 | |
1 | A | Theatre Square | PROGRAMMING | 1,000 | [
"math"
] | A. Theatre Square | 1 | 256 | Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=Γ<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=Γ<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square. | The input contains three positive integer numbers in the first line: *n*,<=<=*m* and *a* (1<=β€<=<=*n*,<=*m*,<=*a*<=β€<=109). | Write the needed number of flagstones. | [
"6 6 4\n"
] | [
"4\n"
] | none | 0 | [
{
"input": "6 6 4",
"output": "4"
},
{
"input": "1 1 1",
"output": "1"
},
{
"input": "2 1 1",
"output": "2"
},
{
"input": "1 2 1",
"output": "2"
},
{
"input": "2 2 1",
"output": "4"
},
{
"input": "2 1 2",
"output": "1"
},
{
"input": "1 1 3"... | 1,648,553,592 | 2,147,483,647 | Python 3 | OK | TESTS | 20 | 31 | 0 | n, m, a = input().split()
n, m, a = int(n), int(m), int(a)
x = (n + a - 1) / a
y = (m + a - 1) / a
print(int(x)*int(y))
| Title: Theatre Square
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=Γ<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=Γ<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
Input Specification:
The input contains three positive integer numbers in the first line: *n*,<=<=*m* and *a* (1<=β€<=<=*n*,<=*m*,<=*a*<=β€<=109).
Output Specification:
Write the needed number of flagstones.
Demo Input:
['6 6 4\n']
Demo Output:
['4\n']
Note:
none | ```python
n, m, a = input().split()
n, m, a = int(n), int(m), int(a)
x = (n + a - 1) / a
y = (m + a - 1) / a
print(int(x)*int(y))
``` | 3.9845 |
535 | B | Tavas and SaDDas | PROGRAMMING | 1,100 | [
"bitmasks",
"brute force",
"combinatorics",
"implementation"
] | null | null | Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
The problem is:
You are given a lucky number *n*. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
If we sort all lucky numbers in increasing order, what's the 1-based index of *n*?
Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back. | The first and only line of input contains a lucky number *n* (1<=β€<=*n*<=β€<=109). | Print the index of *n* among all lucky numbers. | [
"4\n",
"7\n",
"77\n"
] | [
"1\n",
"2\n",
"6\n"
] | none | 1,000 | [
{
"input": "4",
"output": "1"
},
{
"input": "7",
"output": "2"
},
{
"input": "77",
"output": "6"
},
{
"input": "4",
"output": "1"
},
{
"input": "474744",
"output": "83"
},
{
"input": "777774",
"output": "125"
},
{
"input": "447",
"outpu... | 1,592,690,410 | 2,147,483,647 | PyPy 3 | OK | TESTS | 33 | 155 | 0 | import math
def fact(n):
ans = 1
for i in range(2, n+1):
ans*= i
return ans
def comb(n, c):
return fact(n)//(fact(n-c)*c)
n= int(input())
if(n==4):
print(1)
elif(n==7):
print(2)
else:
add = 2
ans = 0
n = str(n)
for i in range(len(n)):
ans+=(2**i)
pos = (2**len(n))
left = 1
right = pos
i = 0
while(left < right and i < len(n)):
mid = (left+right)//2
if(n[i]=='4'):
right = mid
else:
left = mid+1
i+=1
ans+=left-1
print(ans) | Title: Tavas and SaDDas
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
The problem is:
You are given a lucky number *n*. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
If we sort all lucky numbers in increasing order, what's the 1-based index of *n*?
Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.
Input Specification:
The first and only line of input contains a lucky number *n* (1<=β€<=*n*<=β€<=109).
Output Specification:
Print the index of *n* among all lucky numbers.
Demo Input:
['4\n', '7\n', '77\n']
Demo Output:
['1\n', '2\n', '6\n']
Note:
none | ```python
import math
def fact(n):
ans = 1
for i in range(2, n+1):
ans*= i
return ans
def comb(n, c):
return fact(n)//(fact(n-c)*c)
n= int(input())
if(n==4):
print(1)
elif(n==7):
print(2)
else:
add = 2
ans = 0
n = str(n)
for i in range(len(n)):
ans+=(2**i)
pos = (2**len(n))
left = 1
right = pos
i = 0
while(left < right and i < len(n)):
mid = (left+right)//2
if(n[i]=='4'):
right = mid
else:
left = mid+1
i+=1
ans+=left-1
print(ans)
``` | 3 | |
620 | A | Professor GukiZ's Robot | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | Professor GukiZ makes a new robot. The robot are in the point with coordinates (*x*1,<=*y*1) and should go to the point (*x*2,<=*y*2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps the robot should make to get the finish position. | The first line contains two integers *x*1,<=*y*1 (<=-<=109<=β€<=*x*1,<=*y*1<=β€<=109) β the start position of the robot.
The second line contains two integers *x*2,<=*y*2 (<=-<=109<=β€<=*x*2,<=*y*2<=β€<=109) β the finish position of the robot. | Print the only integer *d* β the minimal number of steps to get the finish position. | [
"0 0\n4 5\n",
"3 4\n6 1\n"
] | [
"5\n",
"3\n"
] | In the first example robot should increase both of its coordinates by one four times, so it will be in position (4,β4). After that robot should simply increase its *y* coordinate and get the finish position.
In the second example robot should simultaneously increase *x* coordinate and decrease *y* coordinate by one three times. | 0 | [
{
"input": "0 0\n4 5",
"output": "5"
},
{
"input": "3 4\n6 1",
"output": "3"
},
{
"input": "0 0\n4 6",
"output": "6"
},
{
"input": "1 1\n-3 -5",
"output": "6"
},
{
"input": "-1 -1\n-10 100",
"output": "101"
},
{
"input": "1 -1\n100 -100",
"output":... | 1,453,615,685 | 2,147,483,647 | Python 3 | OK | TESTS | 75 | 62 | 0 | x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
print(max(abs(x1-x2), abs(y1-y2))) | Title: Professor GukiZ's Robot
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Professor GukiZ makes a new robot. The robot are in the point with coordinates (*x*1,<=*y*1) and should go to the point (*x*2,<=*y*2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps the robot should make to get the finish position.
Input Specification:
The first line contains two integers *x*1,<=*y*1 (<=-<=109<=β€<=*x*1,<=*y*1<=β€<=109) β the start position of the robot.
The second line contains two integers *x*2,<=*y*2 (<=-<=109<=β€<=*x*2,<=*y*2<=β€<=109) β the finish position of the robot.
Output Specification:
Print the only integer *d* β the minimal number of steps to get the finish position.
Demo Input:
['0 0\n4 5\n', '3 4\n6 1\n']
Demo Output:
['5\n', '3\n']
Note:
In the first example robot should increase both of its coordinates by one four times, so it will be in position (4,β4). After that robot should simply increase its *y* coordinate and get the finish position.
In the second example robot should simultaneously increase *x* coordinate and decrease *y* coordinate by one three times. | ```python
x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
print(max(abs(x1-x2), abs(y1-y2)))
``` | 3 | |
894 | A | QAQ | PROGRAMMING | 800 | [
"brute force",
"dp"
] | null | null | "QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact. | The only line contains a string of length *n* (1<=β€<=*n*<=β€<=100). It's guaranteed that the string only contains uppercase English letters. | Print a single integerΒ β the number of subsequences "QAQ" in the string. | [
"QAQAQYSYIOIWIN\n",
"QAQQQZZYNOIWIN\n"
] | [
"4\n",
"3\n"
] | In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | 500 | [
{
"input": "QAQAQYSYIOIWIN",
"output": "4"
},
{
"input": "QAQQQZZYNOIWIN",
"output": "3"
},
{
"input": "QA",
"output": "0"
},
{
"input": "IAQVAQZLQBQVQFTQQQADAQJA",
"output": "24"
},
{
"input": "QQAAQASGAYAAAAKAKAQIQEAQAIAAIAQQQQQ",
"output": "378"
},
{
... | 1,594,393,783 | 2,147,483,647 | Python 3 | OK | TESTS | 43 | 109 | 6,963,200 | inputStr = input()
comb = [0,0,0]
count = 0
for i in range(len(inputStr)):
if inputStr[i] == 'Q':
comb[0] == 1
for j in range(i, len(inputStr)):
if inputStr[j] == 'A':
comb[1] == 1
for k in range(j, len(inputStr)):
if inputStr[k] == 'Q':
comb[2] += 1
count += 1
print(count) | Title: QAQ
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
Input Specification:
The only line contains a string of length *n* (1<=β€<=*n*<=β€<=100). It's guaranteed that the string only contains uppercase English letters.
Output Specification:
Print a single integerΒ β the number of subsequences "QAQ" in the string.
Demo Input:
['QAQAQYSYIOIWIN\n', 'QAQQQZZYNOIWIN\n']
Demo Output:
['4\n', '3\n']
Note:
In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | ```python
inputStr = input()
comb = [0,0,0]
count = 0
for i in range(len(inputStr)):
if inputStr[i] == 'Q':
comb[0] == 1
for j in range(i, len(inputStr)):
if inputStr[j] == 'A':
comb[1] == 1
for k in range(j, len(inputStr)):
if inputStr[k] == 'Q':
comb[2] += 1
count += 1
print(count)
``` | 3 | |
436 | B | Om Nom and Spiders | PROGRAMMING | 1,400 | [
"implementation",
"math"
] | null | null | Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all.
The park can be represented as a rectangular *n*<=Γ<=*m* field. The park has *k* spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.
Om Nom isn't yet sure where to start his walk from but he definitely wants:
- to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders); - to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park).
We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.
Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell. | The first line contains three integers *n*,<=*m*,<=*k* (2<=β€<=*n*,<=*m*<=β€<=2000;Β 0<=β€<=*k*<=β€<=*m*(*n*<=-<=1)).
Each of the next *n* lines contains *m* characters β the description of the park. The characters in the *i*-th line describe the *i*-th row of the park field. If the character in the line equals ".", that means that the corresponding cell of the field is empty; otherwise, the character in the line will equal one of the four characters: "L" (meaning that this cell has a spider at time 0, moving left), "R" (a spider moving right), "U" (a spider moving up), "D" (a spider moving down).
It is guaranteed that the first row doesn't contain any spiders. It is guaranteed that the description of the field contains no extra characters. It is guaranteed that at time 0 the field contains exactly *k* spiders. | Print *m* integers: the *j*-th integer must show the number of spiders Om Nom will see if he starts his walk from the *j*-th cell of the first row. The cells in any row of the field are numbered from left to right. | [
"3 3 4\n...\nR.L\nR.U\n",
"2 2 2\n..\nRL\n",
"2 2 2\n..\nLR\n",
"3 4 8\n....\nRRLL\nUUUU\n",
"2 2 2\n..\nUU\n"
] | [
"0 2 2 ",
"1 1 ",
"0 0 ",
"1 3 3 1 ",
"0 0 "
] | Consider the first sample. The notes below show how the spider arrangement changes on the field over time:
Character "*" represents a cell that contains two spiders at the same time.
- If Om Nom starts from the first cell of the first row, he won't see any spiders. - If he starts from the second cell, he will see two spiders at time 1. - If he starts from the third cell, he will see two spiders: one at time 1, the other one at time 2. | 1,000 | [
{
"input": "3 3 4\n...\nR.L\nR.U",
"output": "0 2 2 "
},
{
"input": "2 2 2\n..\nRL",
"output": "1 1 "
},
{
"input": "2 2 2\n..\nLR",
"output": "0 0 "
},
{
"input": "3 4 8\n....\nRRLL\nUUUU",
"output": "1 3 3 1 "
},
{
"input": "2 2 2\n..\nUU",
"output": "0 0 "
... | 1,660,110,056 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 36 | 170 | 8,704,000 | import sys
input = sys.stdin.readline
n, m, k = map(int, input().split())
g = [input()[:-1] for _ in range(n)]
d = [0]*m
for i in range(1, n):
for j in range(m):
if g[i][j] == 'R':
if j + i < m:
d[j+i] += 1
elif g[i][j] == 'L':
if j - i >= 0:
d[j-i] += 1
elif g[i][j] == 'U':
if i % 2 == 0:
d[j] += 1
print(' '.join(map(str, d)))
| Title: Om Nom and Spiders
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all.
The park can be represented as a rectangular *n*<=Γ<=*m* field. The park has *k* spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.
Om Nom isn't yet sure where to start his walk from but he definitely wants:
- to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders); - to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park).
We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.
Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.
Input Specification:
The first line contains three integers *n*,<=*m*,<=*k* (2<=β€<=*n*,<=*m*<=β€<=2000;Β 0<=β€<=*k*<=β€<=*m*(*n*<=-<=1)).
Each of the next *n* lines contains *m* characters β the description of the park. The characters in the *i*-th line describe the *i*-th row of the park field. If the character in the line equals ".", that means that the corresponding cell of the field is empty; otherwise, the character in the line will equal one of the four characters: "L" (meaning that this cell has a spider at time 0, moving left), "R" (a spider moving right), "U" (a spider moving up), "D" (a spider moving down).
It is guaranteed that the first row doesn't contain any spiders. It is guaranteed that the description of the field contains no extra characters. It is guaranteed that at time 0 the field contains exactly *k* spiders.
Output Specification:
Print *m* integers: the *j*-th integer must show the number of spiders Om Nom will see if he starts his walk from the *j*-th cell of the first row. The cells in any row of the field are numbered from left to right.
Demo Input:
['3 3 4\n...\nR.L\nR.U\n', '2 2 2\n..\nRL\n', '2 2 2\n..\nLR\n', '3 4 8\n....\nRRLL\nUUUU\n', '2 2 2\n..\nUU\n']
Demo Output:
['0 2 2 ', '1 1 ', '0 0 ', '1 3 3 1 ', '0 0 ']
Note:
Consider the first sample. The notes below show how the spider arrangement changes on the field over time:
Character "*" represents a cell that contains two spiders at the same time.
- If Om Nom starts from the first cell of the first row, he won't see any spiders. - If he starts from the second cell, he will see two spiders at time 1. - If he starts from the third cell, he will see two spiders: one at time 1, the other one at time 2. | ```python
import sys
input = sys.stdin.readline
n, m, k = map(int, input().split())
g = [input()[:-1] for _ in range(n)]
d = [0]*m
for i in range(1, n):
for j in range(m):
if g[i][j] == 'R':
if j + i < m:
d[j+i] += 1
elif g[i][j] == 'L':
if j - i >= 0:
d[j-i] += 1
elif g[i][j] == 'U':
if i % 2 == 0:
d[j] += 1
print(' '.join(map(str, d)))
``` | 3 | |
26 | A | Almost Prime | PROGRAMMING | 900 | [
"number theory"
] | A. Almost Prime | 2 | 256 | A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and *n*, inclusive. | Input contains one integer number *n* (1<=β€<=*n*<=β€<=3000). | Output the amount of almost prime numbers between 1 and *n*, inclusive. | [
"10\n",
"21\n"
] | [
"2\n",
"8\n"
] | none | 500 | [
{
"input": "10",
"output": "2"
},
{
"input": "21",
"output": "8"
},
{
"input": "1",
"output": "0"
},
{
"input": "2",
"output": "0"
},
{
"input": "4",
"output": "0"
},
{
"input": "3",
"output": "0"
},
{
"input": "8",
"output": "1"
},
... | 1,680,276,075 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 23 | 186 | 3,174,400 |
def count_primes(num):
#does not consider num as a prime number
count = 0
for divisor in range(2, int(num**0.5)+1):
if num % divisor == 0: count += 1
while num % divisor == 0:
num /= divisor
if num > 1: count += 1 #num itself is prime
return count
def count_almost_primes(num):
count = 0
for num in range(1, num+1):
if count_primes(num) == 2: count += 1
return count
def main():
num = int(input())
print(count_almost_primes(num))
main()
| Title: Almost Prime
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and *n*, inclusive.
Input Specification:
Input contains one integer number *n* (1<=β€<=*n*<=β€<=3000).
Output Specification:
Output the amount of almost prime numbers between 1 and *n*, inclusive.
Demo Input:
['10\n', '21\n']
Demo Output:
['2\n', '8\n']
Note:
none | ```python
def count_primes(num):
#does not consider num as a prime number
count = 0
for divisor in range(2, int(num**0.5)+1):
if num % divisor == 0: count += 1
while num % divisor == 0:
num /= divisor
if num > 1: count += 1 #num itself is prime
return count
def count_almost_primes(num):
count = 0
for num in range(1, num+1):
if count_primes(num) == 2: count += 1
return count
def main():
num = int(input())
print(count_almost_primes(num))
main()
``` | 3.947587 |
492 | C | Vanya and Exams | PROGRAMMING | 1,400 | [
"greedy",
"sortings"
] | null | null | Vanya wants to pass *n* exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least *avg*. The exam grade cannot exceed *r*. Vanya has passed the exams and got grade *a**i* for the *i*-th exam. To increase the grade for the *i*-th exam by 1 point, Vanya must write *b**i* essays. He can raise the exam grade multiple times.
What is the minimum number of essays that Vanya needs to write to get scholarship? | The first line contains three integers *n*, *r*, *avg* (1<=β€<=*n*<=β€<=105, 1<=β€<=*r*<=β€<=109, 1<=β€<=*avg*<=β€<=*min*(*r*,<=106))Β β the number of exams, the maximum grade and the required grade point average, respectively.
Each of the following *n* lines contains space-separated integers *a**i* and *b**i* (1<=β€<=*a**i*<=β€<=*r*, 1<=β€<=*b**i*<=β€<=106). | In the first line print the minimum number of essays. | [
"5 5 4\n5 2\n4 7\n3 1\n3 2\n2 5\n",
"2 5 4\n5 2\n5 2\n"
] | [
"4\n",
"0\n"
] | In the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.
In the second sample, Vanya doesn't need to write any essays as his general point average already is above average. | 1,500 | [
{
"input": "5 5 4\n5 2\n4 7\n3 1\n3 2\n2 5",
"output": "4"
},
{
"input": "2 5 4\n5 2\n5 2",
"output": "0"
},
{
"input": "6 5 5\n1 7\n2 4\n3 5\n4 6\n5 6\n4 7",
"output": "63"
},
{
"input": "1 1000000000 1000000\n1 1000000",
"output": "999999000000"
},
{
"input": "1... | 1,694,713,457 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 39 | 702 | 14,643,200 | def solve(a, b, r, avg):
diff = max(0, len(a) * avg - sum(a))
sorted_indices = sorted(range(len(a)), key=lambda i: b[i])
result = 0
index = 0
while diff != 0:
raise_num = min(diff, r - a[sorted_indices[index]])
result += raise_num * b[sorted_indices[index]]
diff -= raise_num
index += 1
return result
def main():
n, r, avg = map(int, input().split())
a = []
b = []
for i in range(n):
ai, bi = map(int, input().split())
a.append(ai)
b.append(bi)
print(solve(a, b, r, avg))
if __name__ == "__main__":
main() | Title: Vanya and Exams
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya wants to pass *n* exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least *avg*. The exam grade cannot exceed *r*. Vanya has passed the exams and got grade *a**i* for the *i*-th exam. To increase the grade for the *i*-th exam by 1 point, Vanya must write *b**i* essays. He can raise the exam grade multiple times.
What is the minimum number of essays that Vanya needs to write to get scholarship?
Input Specification:
The first line contains three integers *n*, *r*, *avg* (1<=β€<=*n*<=β€<=105, 1<=β€<=*r*<=β€<=109, 1<=β€<=*avg*<=β€<=*min*(*r*,<=106))Β β the number of exams, the maximum grade and the required grade point average, respectively.
Each of the following *n* lines contains space-separated integers *a**i* and *b**i* (1<=β€<=*a**i*<=β€<=*r*, 1<=β€<=*b**i*<=β€<=106).
Output Specification:
In the first line print the minimum number of essays.
Demo Input:
['5 5 4\n5 2\n4 7\n3 1\n3 2\n2 5\n', '2 5 4\n5 2\n5 2\n']
Demo Output:
['4\n', '0\n']
Note:
In the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.
In the second sample, Vanya doesn't need to write any essays as his general point average already is above average. | ```python
def solve(a, b, r, avg):
diff = max(0, len(a) * avg - sum(a))
sorted_indices = sorted(range(len(a)), key=lambda i: b[i])
result = 0
index = 0
while diff != 0:
raise_num = min(diff, r - a[sorted_indices[index]])
result += raise_num * b[sorted_indices[index]]
diff -= raise_num
index += 1
return result
def main():
n, r, avg = map(int, input().split())
a = []
b = []
for i in range(n):
ai, bi = map(int, input().split())
a.append(ai)
b.append(bi)
print(solve(a, b, r, avg))
if __name__ == "__main__":
main()
``` | 3 | |
43 | A | Football | PROGRAMMING | 1,000 | [
"strings"
] | A. Football | 2 | 256 | One day Vasya decided to have a look at the results of Berland 1910 Football Championshipβs finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie. | The first line contains an integer *n* (1<=β€<=*n*<=β€<=100) β the number of lines in the description. Then follow *n* lines β for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams. | Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner. | [
"1\nABC\n",
"5\nA\nABA\nABA\nA\nA\n"
] | [
"ABC\n",
"A\n"
] | none | 500 | [
{
"input": "1\nABC",
"output": "ABC"
},
{
"input": "5\nA\nABA\nABA\nA\nA",
"output": "A"
},
{
"input": "2\nXTSJEP\nXTSJEP",
"output": "XTSJEP"
},
{
"input": "3\nXZYDJAEDZ\nXZYDJAEDZ\nXZYDJAEDZ",
"output": "XZYDJAEDZ"
},
{
"input": "3\nQCCYXL\nQCCYXL\nAXGLFQDD",
... | 1,610,574,421 | 2,147,483,647 | PyPy 3 | OK | TESTS | 34 | 218 | 0 | n = int(input())
freq = {}
for _ in range(n):
s = input()
freq[s] = freq.get(s, 0) + 1
keys = list(freq.keys())
if len(keys) == 1:
print(keys[0])
else:
if freq[keys[0]] < freq[keys[1]]:
print(keys[1])
else:
print(keys[0]) | Title: Football
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One day Vasya decided to have a look at the results of Berland 1910 Football Championshipβs finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.
Input Specification:
The first line contains an integer *n* (1<=β€<=*n*<=β€<=100) β the number of lines in the description. Then follow *n* lines β for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.
Output Specification:
Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.
Demo Input:
['1\nABC\n', '5\nA\nABA\nABA\nA\nA\n']
Demo Output:
['ABC\n', 'A\n']
Note:
none | ```python
n = int(input())
freq = {}
for _ in range(n):
s = input()
freq[s] = freq.get(s, 0) + 1
keys = list(freq.keys())
if len(keys) == 1:
print(keys[0])
else:
if freq[keys[0]] < freq[keys[1]]:
print(keys[1])
else:
print(keys[0])
``` | 3.9455 |
740 | A | Alyona and copybooks | PROGRAMMING | 1,300 | [
"brute force",
"implementation"
] | null | null | Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for *a* rubles, a pack of two copybooks for *b* rubles, and a pack of three copybooks for *c* rubles. Alyona already has *n* copybooks.
What is the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase. | The only line contains 4 integers *n*, *a*, *b*, *c* (1<=β€<=*n*,<=*a*,<=*b*,<=*c*<=β€<=109). | Print the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4. | [
"1 1 3 4\n",
"6 2 1 1\n",
"4 4 4 4\n",
"999999999 1000000000 1000000000 1000000000\n"
] | [
"3\n",
"1\n",
"0\n",
"1000000000\n"
] | In the first example Alyona can buy 3 packs of 1 copybook for 3*a*β=β3 rubles in total. After that she will have 4 copybooks which she can split between the subjects equally.
In the second example Alyuna can buy a pack of 2 copybooks for *b*β=β1 ruble. She will have 8 copybooks in total.
In the third example Alyona can split the copybooks she already has between the 4 subject equally, so she doesn't need to buy anything.
In the fourth example Alyona should buy one pack of one copybook. | 500 | [
{
"input": "1 1 3 4",
"output": "3"
},
{
"input": "6 2 1 1",
"output": "1"
},
{
"input": "4 4 4 4",
"output": "0"
},
{
"input": "999999999 1000000000 1000000000 1000000000",
"output": "1000000000"
},
{
"input": "1016 3 2 1",
"output": "0"
},
{
"input":... | 1,480,249,146 | 2,147,483,647 | Python 3 | OK | TESTS | 89 | 77 | 0 | n, a, b, c = map(int, input().split())
to_buy = (4 - (n % 4)) % 4
b = min(a * 2, b)
c = min(a * 3, a + b, c)
# possibilities:
if to_buy == 3:
print(min(3*a, a+b, c))
elif to_buy == 2:
print(min(2*a, b, 2*c))
elif to_buy == 1:
print(min(a, b+c, 3*c))
else:
print(0)
| Title: Alyona and copybooks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for *a* rubles, a pack of two copybooks for *b* rubles, and a pack of three copybooks for *c* rubles. Alyona already has *n* copybooks.
What is the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase.
Input Specification:
The only line contains 4 integers *n*, *a*, *b*, *c* (1<=β€<=*n*,<=*a*,<=*b*,<=*c*<=β€<=109).
Output Specification:
Print the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4.
Demo Input:
['1 1 3 4\n', '6 2 1 1\n', '4 4 4 4\n', '999999999 1000000000 1000000000 1000000000\n']
Demo Output:
['3\n', '1\n', '0\n', '1000000000\n']
Note:
In the first example Alyona can buy 3 packs of 1 copybook for 3*a*β=β3 rubles in total. After that she will have 4 copybooks which she can split between the subjects equally.
In the second example Alyuna can buy a pack of 2 copybooks for *b*β=β1 ruble. She will have 8 copybooks in total.
In the third example Alyona can split the copybooks she already has between the 4 subject equally, so she doesn't need to buy anything.
In the fourth example Alyona should buy one pack of one copybook. | ```python
n, a, b, c = map(int, input().split())
to_buy = (4 - (n % 4)) % 4
b = min(a * 2, b)
c = min(a * 3, a + b, c)
# possibilities:
if to_buy == 3:
print(min(3*a, a+b, c))
elif to_buy == 2:
print(min(2*a, b, 2*c))
elif to_buy == 1:
print(min(a, b+c, 3*c))
else:
print(0)
``` | 3 | |
673 | A | Bear and Game | PROGRAMMING | 800 | [
"implementation"
] | null | null | Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be *n* interesting minutes *t*1,<=*t*2,<=...,<=*t**n*. Your task is to calculate for how many minutes Limak will watch the game. | The first line of the input contains one integer *n* (1<=β€<=*n*<=β€<=90)Β β the number of interesting minutes.
The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=β€<=*t*1<=<<=*t*2<=<<=... *t**n*<=β€<=90), given in the increasing order. | Print the number of minutes Limak will watch the game. | [
"3\n7 20 88\n",
"9\n16 20 30 40 50 60 70 80 90\n",
"9\n15 20 30 40 50 60 70 80 90\n"
] | [
"35\n",
"15\n",
"90\n"
] | In the first sample, minutes 21,β22,β...,β35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game. | 500 | [
{
"input": "3\n7 20 88",
"output": "35"
},
{
"input": "9\n16 20 30 40 50 60 70 80 90",
"output": "15"
},
{
"input": "9\n15 20 30 40 50 60 70 80 90",
"output": "90"
},
{
"input": "30\n6 11 12 15 22 24 30 31 32 33 34 35 40 42 44 45 47 50 53 54 57 58 63 67 75 77 79 81 83 88",
... | 1,472,091,580 | 2,147,483,647 | Python 3 | OK | TESTS | 34 | 62 | 4,608,000 | n=int(input())
tl = list(map(int, input().split()))
time=cnt=0
while cnt <15 and time<90:
time+=1
if tl.count(time)>0:
cnt=0
else:
cnt+=1
print(time) | Title: Bear and Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be *n* interesting minutes *t*1,<=*t*2,<=...,<=*t**n*. Your task is to calculate for how many minutes Limak will watch the game.
Input Specification:
The first line of the input contains one integer *n* (1<=β€<=*n*<=β€<=90)Β β the number of interesting minutes.
The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=β€<=*t*1<=<<=*t*2<=<<=... *t**n*<=β€<=90), given in the increasing order.
Output Specification:
Print the number of minutes Limak will watch the game.
Demo Input:
['3\n7 20 88\n', '9\n16 20 30 40 50 60 70 80 90\n', '9\n15 20 30 40 50 60 70 80 90\n']
Demo Output:
['35\n', '15\n', '90\n']
Note:
In the first sample, minutes 21,β22,β...,β35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game. | ```python
n=int(input())
tl = list(map(int, input().split()))
time=cnt=0
while cnt <15 and time<90:
time+=1
if tl.count(time)>0:
cnt=0
else:
cnt+=1
print(time)
``` | 3 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once. | The input consists of only two strings *s* and *t* denoting the favorite Santa's patter and the resulting string. *s* and *t* are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters. | If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print Β«-1Β» (without quotes).
Otherwise, the first line of output should contain the only integer *k* (*k*<=β₯<=0)Β β the number of pairs of keys that should be swapped. The following *k* lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes. | [
"helloworld\nehoolwlroz\n",
"hastalavistababy\nhastalavistababy\n",
"merrychristmas\nchristmasmerry\n"
] | [
"3\nh e\nl o\nd z\n",
"0\n",
"-1\n"
] | none | 0 | [
{
"input": "helloworld\nehoolwlroz",
"output": "3\nh e\nl o\nd z"
},
{
"input": "hastalavistababy\nhastalavistababy",
"output": "0"
},
{
"input": "merrychristmas\nchristmasmerry",
"output": "-1"
},
{
"input": "kusyvdgccw\nkusyvdgccw",
"output": "0"
},
{
"input": "... | 1,557,816,320 | 2,147,483,647 | Python 3 | OK | TESTS | 86 | 124 | 0 | s = input()
t = input()
d, u = set(), set()
for i in range(len(s)):
mn, mx = min(s[i], t[i]), max(s[i], t[i])
if (s[i] in u or t[i] in u) and (mn, mx) not in d:
print(-1)
exit()
u.add(s[i])
u.add(t[i])
d.add((mn, mx))
res = [x for x in d if x[0] != x[1]]
print(len(res))
for i in res:
print(*i)
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input Specification:
The input consists of only two strings *s* and *t* denoting the favorite Santa's patter and the resulting string. *s* and *t* are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output Specification:
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print Β«-1Β» (without quotes).
Otherwise, the first line of output should contain the only integer *k* (*k*<=β₯<=0)Β β the number of pairs of keys that should be swapped. The following *k* lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Demo Input:
['helloworld\nehoolwlroz\n', 'hastalavistababy\nhastalavistababy\n', 'merrychristmas\nchristmasmerry\n']
Demo Output:
['3\nh e\nl o\nd z\n', '0\n', '-1\n']
Note:
none | ```python
s = input()
t = input()
d, u = set(), set()
for i in range(len(s)):
mn, mx = min(s[i], t[i]), max(s[i], t[i])
if (s[i] in u or t[i] in u) and (mn, mx) not in d:
print(-1)
exit()
u.add(s[i])
u.add(t[i])
d.add((mn, mx))
res = [x for x in d if x[0] != x[1]]
print(len(res))
for i in res:
print(*i)
``` | 3 | |
25 | A | IQ test | PROGRAMMING | 1,300 | [
"brute force"
] | A. IQ test | 2 | 256 | Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness. | The first line contains integer *n* (3<=β€<=*n*<=β€<=100) β amount of numbers in the task. The second line contains *n* space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness. | Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order. | [
"5\n2 4 7 8 10\n",
"4\n1 2 1 1\n"
] | [
"3\n",
"2\n"
] | none | 0 | [
{
"input": "5\n2 4 7 8 10",
"output": "3"
},
{
"input": "4\n1 2 1 1",
"output": "2"
},
{
"input": "3\n1 2 2",
"output": "1"
},
{
"input": "3\n100 99 100",
"output": "2"
},
{
"input": "3\n5 3 2",
"output": "3"
},
{
"input": "4\n43 28 1 91",
"output"... | 1,481,699,666 | 2,147,483,647 | Python 3 | OK | TESTS | 32 | 124 | 0 | a=int(input())
b=input().split()
s=0
t=0
for i in range(a):
b[i]=int(b[i])%2
for i in range(a):
if b[i]==0:
s=s+1
else:
t=t+1
if s>t:
for i in range(a):
if b[i]==1:
print(i+1)
else:
for i in range(a):
if b[i]==0:
print(i+1) | Title: IQ test
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
Input Specification:
The first line contains integer *n* (3<=β€<=*n*<=β€<=100) β amount of numbers in the task. The second line contains *n* space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.
Output Specification:
Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.
Demo Input:
['5\n2 4 7 8 10\n', '4\n1 2 1 1\n']
Demo Output:
['3\n', '2\n']
Note:
none | ```python
a=int(input())
b=input().split()
s=0
t=0
for i in range(a):
b[i]=int(b[i])%2
for i in range(a):
if b[i]==0:
s=s+1
else:
t=t+1
if s>t:
for i in range(a):
if b[i]==1:
print(i+1)
else:
for i in range(a):
if b[i]==0:
print(i+1)
``` | 3.969 |
822 | A | I'm bored with life | PROGRAMMING | 800 | [
"implementation",
"math",
"number theory"
] | null | null | Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave ViΔkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town ViΔkopolis. He almost even fell into a depression from boredom!
Leha came up with a task for himself to relax a little. He chooses two integers *A* and *B* and then calculates the greatest common divisor of integers "*A* factorial" and "*B* factorial". Formally the hacker wants to find out GCD(*A*!,<=*B*!). It's well known that the factorial of an integer *x* is a product of all positive integers less than or equal to *x*. Thus *x*!<==<=1Β·2Β·3Β·...Β·(*x*<=-<=1)Β·*x*. For example 4!<==<=1Β·2Β·3Β·4<==<=24. Recall that GCD(*x*,<=*y*) is the largest positive integer *q* that divides (without a remainder) both *x* and *y*.
Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you? | The first and single line contains two integers *A* and *B* (1<=β€<=*A*,<=*B*<=β€<=109,<=*min*(*A*,<=*B*)<=β€<=12). | Print a single integer denoting the greatest common divisor of integers *A*! and *B*!. | [
"4 3\n"
] | [
"6\n"
] | Consider the sample.
4!β=β1Β·2Β·3Β·4β=β24. 3!β=β1Β·2Β·3β=β6. The greatest common divisor of integers 24 and 6 is exactly 6. | 500 | [
{
"input": "4 3",
"output": "6"
},
{
"input": "10 399603090",
"output": "3628800"
},
{
"input": "6 973151934",
"output": "720"
},
{
"input": "2 841668075",
"output": "2"
},
{
"input": "7 415216919",
"output": "5040"
},
{
"input": "3 283733059",
"ou... | 1,632,994,508 | 2,147,483,647 | Python 3 | OK | TESTS | 59 | 62 | 6,758,400 | import math
a,b=map(int,input().split())
c=min(a,b)
print(math.factorial(c))
| Title: I'm bored with life
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave ViΔkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town ViΔkopolis. He almost even fell into a depression from boredom!
Leha came up with a task for himself to relax a little. He chooses two integers *A* and *B* and then calculates the greatest common divisor of integers "*A* factorial" and "*B* factorial". Formally the hacker wants to find out GCD(*A*!,<=*B*!). It's well known that the factorial of an integer *x* is a product of all positive integers less than or equal to *x*. Thus *x*!<==<=1Β·2Β·3Β·...Β·(*x*<=-<=1)Β·*x*. For example 4!<==<=1Β·2Β·3Β·4<==<=24. Recall that GCD(*x*,<=*y*) is the largest positive integer *q* that divides (without a remainder) both *x* and *y*.
Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
Input Specification:
The first and single line contains two integers *A* and *B* (1<=β€<=*A*,<=*B*<=β€<=109,<=*min*(*A*,<=*B*)<=β€<=12).
Output Specification:
Print a single integer denoting the greatest common divisor of integers *A*! and *B*!.
Demo Input:
['4 3\n']
Demo Output:
['6\n']
Note:
Consider the sample.
4!β=β1Β·2Β·3Β·4β=β24. 3!β=β1Β·2Β·3β=β6. The greatest common divisor of integers 24 and 6 is exactly 6. | ```python
import math
a,b=map(int,input().split())
c=min(a,b)
print(math.factorial(c))
``` | 3 | |
305 | B | Continued Fractions | PROGRAMMING | 1,700 | [
"brute force",
"implementation",
"math"
] | null | null | A continued fraction of height *n* is a fraction of form . You are given two rational numbers, one is represented as and the other one is represented as a finite fraction of height *n*. Check if they are equal. | The first line contains two space-separated integers *p*,<=*q* (1<=β€<=*q*<=β€<=*p*<=β€<=1018) β the numerator and the denominator of the first fraction.
The second line contains integer *n* (1<=β€<=*n*<=β€<=90) β the height of the second fraction. The third line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=1018) β the continued fraction.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | Print "YES" if these fractions are equal and "NO" otherwise. | [
"9 4\n2\n2 4\n",
"9 4\n3\n2 3 1\n",
"9 4\n3\n1 2 4\n"
] | [
"YES\n",
"YES\n",
"NO\n"
] | In the first sample <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5ff92f27aebea2560d99ad61202d20bab5ee5390.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the second sample <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/221368c79c05fc0ecad4e5f7a64f30b832fd99f5.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the third sample <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4fb4b411afc0fbad27a1c8fdd08ba88ec3830ef5.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | 1,000 | [
{
"input": "9 4\n2\n2 4",
"output": "YES"
},
{
"input": "9 4\n3\n2 3 1",
"output": "YES"
},
{
"input": "9 4\n3\n1 2 4",
"output": "NO"
},
{
"input": "39088169 24157817\n36\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2",
"output": "YES"
},
{
... | 1,515,788,728 | 2,147,483,647 | Python 3 | OK | TESTS | 49 | 216 | 6,860,800 | from fractions import gcd
p,q=map(int,input().split())
gc=gcd(p,q)
p//=gc
q//=gc
n=int(input())
a=list(map(int,input().split()))
def add(a,b):
res=[]
a[0]*=b[1]
b[0]*=a[1]
temp=b[1]*a[1]
top=a[0]+b[0]
gc=gcd(top,temp)
temp//=gc
top//=gc;
res.append(top)
res.append(temp)
return res
def go(i):
res=[]
if i==n-1:
res.append(a[i])
res.append(1)
return res;
temp=list(go(i+1))
temp=temp[::-1]
ta=[]
ta.append(a[i])
ta.append(1)
temp=add(ta,temp)
return temp
res=go(0)
if(res[0]==p and res[1]==q): print("YES")
else:
print("NO") | Title: Continued Fractions
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A continued fraction of height *n* is a fraction of form . You are given two rational numbers, one is represented as and the other one is represented as a finite fraction of height *n*. Check if they are equal.
Input Specification:
The first line contains two space-separated integers *p*,<=*q* (1<=β€<=*q*<=β€<=*p*<=β€<=1018) β the numerator and the denominator of the first fraction.
The second line contains integer *n* (1<=β€<=*n*<=β€<=90) β the height of the second fraction. The third line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=1018) β the continued fraction.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output Specification:
Print "YES" if these fractions are equal and "NO" otherwise.
Demo Input:
['9 4\n2\n2 4\n', '9 4\n3\n2 3 1\n', '9 4\n3\n1 2 4\n']
Demo Output:
['YES\n', 'YES\n', 'NO\n']
Note:
In the first sample <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5ff92f27aebea2560d99ad61202d20bab5ee5390.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the second sample <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/221368c79c05fc0ecad4e5f7a64f30b832fd99f5.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the third sample <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4fb4b411afc0fbad27a1c8fdd08ba88ec3830ef5.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | ```python
from fractions import gcd
p,q=map(int,input().split())
gc=gcd(p,q)
p//=gc
q//=gc
n=int(input())
a=list(map(int,input().split()))
def add(a,b):
res=[]
a[0]*=b[1]
b[0]*=a[1]
temp=b[1]*a[1]
top=a[0]+b[0]
gc=gcd(top,temp)
temp//=gc
top//=gc;
res.append(top)
res.append(temp)
return res
def go(i):
res=[]
if i==n-1:
res.append(a[i])
res.append(1)
return res;
temp=list(go(i+1))
temp=temp[::-1]
ta=[]
ta.append(a[i])
ta.append(1)
temp=add(ta,temp)
return temp
res=go(0)
if(res[0]==p and res[1]==q): print("YES")
else:
print("NO")
``` | 3 | |
665 | C | Simple Strings | PROGRAMMING | 1,300 | [
"dp",
"greedy",
"strings"
] | null | null | zscoder loves simple strings! A string *t* is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.
zscoder is given a string *s*. He wants to change a minimum number of characters so that the string *s* becomes simple. Help him with this task! | The only line contains the string *s* (1<=β€<=|*s*|<=β€<=2Β·105) β the string given to zscoder. The string *s* consists of only lowercase English letters. | Print the simple string *s*' β the string *s* after the minimal number of changes. If there are multiple solutions, you may output any of them.
Note that the string *s*' should also consist of only lowercase English letters. | [
"aab\n",
"caaab\n",
"zscoder\n"
] | [
"bab\n",
"cabab\n",
"zscoder\n"
] | none | 0 | [
{
"input": "aab",
"output": "bab"
},
{
"input": "caaab",
"output": "cabab"
},
{
"input": "zscoder",
"output": "zscoder"
},
{
"input": "u",
"output": "u"
},
{
"input": "h",
"output": "h"
},
{
"input": "dtottttotd",
"output": "dtotataotd"
},
{
... | 1,652,869,198 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 27 | 139 | 43,520,000 | s=list(input()+'a')
for i in range(len(s)-2):
if s[i]==s[i+1]:
s[i+1]=list({'a', 'b', 'c'}-{s[i]}-{s[i+2]})[0]
print(''.join(s[:-1]))
| Title: Simple Strings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
zscoder loves simple strings! A string *t* is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.
zscoder is given a string *s*. He wants to change a minimum number of characters so that the string *s* becomes simple. Help him with this task!
Input Specification:
The only line contains the string *s* (1<=β€<=|*s*|<=β€<=2Β·105) β the string given to zscoder. The string *s* consists of only lowercase English letters.
Output Specification:
Print the simple string *s*' β the string *s* after the minimal number of changes. If there are multiple solutions, you may output any of them.
Note that the string *s*' should also consist of only lowercase English letters.
Demo Input:
['aab\n', 'caaab\n', 'zscoder\n']
Demo Output:
['bab\n', 'cabab\n', 'zscoder\n']
Note:
none | ```python
s=list(input()+'a')
for i in range(len(s)-2):
if s[i]==s[i+1]:
s[i+1]=list({'a', 'b', 'c'}-{s[i]}-{s[i+2]})[0]
print(''.join(s[:-1]))
``` | 3 | |
689 | A | Mike and Cellphone | PROGRAMMING | 1,400 | [
"brute force",
"constructive algorithms",
"implementation"
] | null | null | While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way:
Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253":
Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements? | The first line of the input contains the only integer *n* (1<=β€<=*n*<=β€<=9)Β β the number of digits in the phone number that Mike put in.
The second line contains the string consisting of *n* digits (characters from '0' to '9') representing the number that Mike put in. | If there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print "YES" (without quotes) in the only line.
Otherwise print "NO" (without quotes) in the first line. | [
"3\n586\n",
"2\n09\n",
"9\n123456789\n",
"3\n911\n"
] | [
"NO\n",
"NO\n",
"YES\n",
"YES\n"
] | You can find the picture clarifying the first sample case in the statement above. | 500 | [
{
"input": "3\n586",
"output": "NO"
},
{
"input": "2\n09",
"output": "NO"
},
{
"input": "9\n123456789",
"output": "YES"
},
{
"input": "3\n911",
"output": "YES"
},
{
"input": "3\n089",
"output": "NO"
},
{
"input": "3\n159",
"output": "YES"
},
{
... | 1,468,074,376 | 2,147,483,647 | PyPy 3 | OK | TESTS | 94 | 140 | 0 | n = input()
s = set(map(int,input()))
if all(map(lambda x: x&s!=set(),({1,4,7,0},{3,6,9,0},{7,0,9},{1,2,3}))):
print("YES")
else:
print("NO") | Title: Mike and Cellphone
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way:
Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253":
Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?
Input Specification:
The first line of the input contains the only integer *n* (1<=β€<=*n*<=β€<=9)Β β the number of digits in the phone number that Mike put in.
The second line contains the string consisting of *n* digits (characters from '0' to '9') representing the number that Mike put in.
Output Specification:
If there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print "YES" (without quotes) in the only line.
Otherwise print "NO" (without quotes) in the first line.
Demo Input:
['3\n586\n', '2\n09\n', '9\n123456789\n', '3\n911\n']
Demo Output:
['NO\n', 'NO\n', 'YES\n', 'YES\n']
Note:
You can find the picture clarifying the first sample case in the statement above. | ```python
n = input()
s = set(map(int,input()))
if all(map(lambda x: x&s!=set(),({1,4,7,0},{3,6,9,0},{7,0,9},{1,2,3}))):
print("YES")
else:
print("NO")
``` | 3 | |
255 | A | Greg's Workout | PROGRAMMING | 800 | [
"implementation"
] | null | null | Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was *n* integers *a*1,<=*a*2,<=...,<=*a**n*. These numbers mean that Greg needs to do exactly *n* exercises today. Besides, Greg should repeat the *i*-th in order exercise *a**i* times.
Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the *n*-th exercise.
Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training. | The first line contains integer *n* (1<=β€<=*n*<=β€<=20). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=25) β the number of times Greg repeats the exercises. | Print word "chest" (without the quotes), if the chest gets the most exercise, "biceps" (without the quotes), if the biceps gets the most exercise and print "back" (without the quotes) if the back gets the most exercise.
It is guaranteed that the input is such that the answer to the problem is unambiguous. | [
"2\n2 8\n",
"3\n5 1 10\n",
"7\n3 3 2 7 9 6 8\n"
] | [
"biceps\n",
"back\n",
"chest\n"
] | In the first sample Greg does 2 chest, 8 biceps and zero back exercises, so the biceps gets the most exercises.
In the second sample Greg does 5 chest, 1 biceps and 10 back exercises, so the back gets the most exercises.
In the third sample Greg does 18 chest, 12 biceps and 8 back exercises, so the chest gets the most exercise. | 500 | [
{
"input": "2\n2 8",
"output": "biceps"
},
{
"input": "3\n5 1 10",
"output": "back"
},
{
"input": "7\n3 3 2 7 9 6 8",
"output": "chest"
},
{
"input": "4\n5 6 6 2",
"output": "chest"
},
{
"input": "5\n8 2 2 6 3",
"output": "chest"
},
{
"input": "6\n8 7 ... | 1,650,824,920 | 2,147,483,647 | Python 3 | OK | TESTS | 61 | 92 | 0 | n=int(input())
a=list(map(int,input().split(" ")))
chest=0
biceps=0
back=0
for i in range(n):
if(i%3==0):
chest+=a[i]
elif(i%3==1):
biceps+=a[i]
elif(i%3==2):
back+=a[i]
if(chest>biceps and chest>back):
print("chest")
elif(biceps>chest and biceps>back):
print("biceps")
else:
if(back>chest and back>biceps):
print("back") | Title: Greg's Workout
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was *n* integers *a*1,<=*a*2,<=...,<=*a**n*. These numbers mean that Greg needs to do exactly *n* exercises today. Besides, Greg should repeat the *i*-th in order exercise *a**i* times.
Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the *n*-th exercise.
Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=20). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=25) β the number of times Greg repeats the exercises.
Output Specification:
Print word "chest" (without the quotes), if the chest gets the most exercise, "biceps" (without the quotes), if the biceps gets the most exercise and print "back" (without the quotes) if the back gets the most exercise.
It is guaranteed that the input is such that the answer to the problem is unambiguous.
Demo Input:
['2\n2 8\n', '3\n5 1 10\n', '7\n3 3 2 7 9 6 8\n']
Demo Output:
['biceps\n', 'back\n', 'chest\n']
Note:
In the first sample Greg does 2 chest, 8 biceps and zero back exercises, so the biceps gets the most exercises.
In the second sample Greg does 5 chest, 1 biceps and 10 back exercises, so the back gets the most exercises.
In the third sample Greg does 18 chest, 12 biceps and 8 back exercises, so the chest gets the most exercise. | ```python
n=int(input())
a=list(map(int,input().split(" ")))
chest=0
biceps=0
back=0
for i in range(n):
if(i%3==0):
chest+=a[i]
elif(i%3==1):
biceps+=a[i]
elif(i%3==2):
back+=a[i]
if(chest>biceps and chest>back):
print("chest")
elif(biceps>chest and biceps>back):
print("biceps")
else:
if(back>chest and back>biceps):
print("back")
``` | 3 | |
39 | F | Pacifist frogs | PROGRAMMING | 1,300 | [
"implementation"
] | F. Pacifist frogs | 2 | 64 | Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much.
One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to *n* and the number of a hill is equal to the distance in meters between it and the island. The distance between the *n*-th hill and the shore is also 1 meter.
Thumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is *d*, the frog will jump from the island on the hill *d*, then β on the hill 2*d*, then 3*d* and so on until they get to the shore (i.e. find itself beyond the hill *n*).
However, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible. | The first line contains three integers *n*, *m* and *k* (1<=β€<=*n*<=β€<=109, 1<=β€<=*m*,<=*k*<=β€<=100) β the number of hills, frogs and mosquitoes respectively. The second line contains *m* integers *d**i* (1<=β€<=*d**i*<=β€<=109) β the lengths of the frogsβ jumps. The third line contains *k* integers β the numbers of the hills on which each mosquito is sleeping. No more than one mosquito can sleep on each hill. The numbers in the lines are separated by single spaces. | In the first line output the number of frogs that smash the minimal number of mosquitoes, in the second line β their numbers in increasing order separated by spaces. The frogs are numbered from 1 to *m* in the order of the jump length given in the input data. | [
"5 3 5\n2 3 4\n1 2 3 4 5\n",
"1000000000 2 3\n2 5\n999999995 999999998 999999996\n"
] | [
"2\n2 3\n",
"1\n2\n"
] | none | 0 | [
{
"input": "5 3 5\n2 3 4\n1 2 3 4 5",
"output": "2\n2 3"
},
{
"input": "1000000000 2 3\n2 5\n999999995 999999998 999999996",
"output": "1\n2"
},
{
"input": "1 1 1\n1\n1",
"output": "1\n1"
},
{
"input": "2 2 1\n2 1\n1",
"output": "1\n1"
},
{
"input": "3 2 2\n2 4\n3... | 1,578,281,796 | 2,147,483,647 | Python 3 | OK | TESTS | 35 | 218 | 307,200 | n, m, k = map(int, input().split())
x, y = n, []
a = map(int, input().split())
b = list(map(int, input().split()))
for i, d in enumerate(a):
c = 0
for t in b:
if 0 == t % d:
c += 1
if c < x:
x = c
y = [i + 1]
elif c == x:
y += i + 1,
print(len(y))
print(' '.join(map(str, y)))
| Title: Pacifist frogs
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much.
One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to *n* and the number of a hill is equal to the distance in meters between it and the island. The distance between the *n*-th hill and the shore is also 1 meter.
Thumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is *d*, the frog will jump from the island on the hill *d*, then β on the hill 2*d*, then 3*d* and so on until they get to the shore (i.e. find itself beyond the hill *n*).
However, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible.
Input Specification:
The first line contains three integers *n*, *m* and *k* (1<=β€<=*n*<=β€<=109, 1<=β€<=*m*,<=*k*<=β€<=100) β the number of hills, frogs and mosquitoes respectively. The second line contains *m* integers *d**i* (1<=β€<=*d**i*<=β€<=109) β the lengths of the frogsβ jumps. The third line contains *k* integers β the numbers of the hills on which each mosquito is sleeping. No more than one mosquito can sleep on each hill. The numbers in the lines are separated by single spaces.
Output Specification:
In the first line output the number of frogs that smash the minimal number of mosquitoes, in the second line β their numbers in increasing order separated by spaces. The frogs are numbered from 1 to *m* in the order of the jump length given in the input data.
Demo Input:
['5 3 5\n2 3 4\n1 2 3 4 5\n', '1000000000 2 3\n2 5\n999999995 999999998 999999996\n']
Demo Output:
['2\n2 3\n', '1\n2\n']
Note:
none | ```python
n, m, k = map(int, input().split())
x, y = n, []
a = map(int, input().split())
b = list(map(int, input().split()))
for i, d in enumerate(a):
c = 0
for t in b:
if 0 == t % d:
c += 1
if c < x:
x = c
y = [i + 1]
elif c == x:
y += i + 1,
print(len(y))
print(' '.join(map(str, y)))
``` | 3.943211 |
612 | A | The Text Splitting | PROGRAMMING | 1,300 | [
"brute force",
"implementation",
"strings"
] | null | null | You are given the string *s* of length *n* and the numbers *p*,<=*q*. Split the string *s* to pieces of length *p* and *q*.
For example, the string "Hello" for *p*<==<=2, *q*<==<=3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".
Note it is allowed to split the string *s* to the strings only of length *p* or to the strings only of length *q* (see the second sample test). | The first line contains three positive integers *n*,<=*p*,<=*q* (1<=β€<=*p*,<=*q*<=β€<=*n*<=β€<=100).
The second line contains the string *s* consists of lowercase and uppercase latin letters and digits. | If it's impossible to split the string *s* to the strings of length *p* and *q* print the only number "-1".
Otherwise in the first line print integer *k* β the number of strings in partition of *s*.
Each of the next *k* lines should contain the strings in partition. Each string should be of the length *p* or *q*. The string should be in order of their appearing in string *s* β from left to right.
If there are several solutions print any of them. | [
"5 2 3\nHello\n",
"10 9 5\nCodeforces\n",
"6 4 5\nPrivet\n",
"8 1 1\nabacabac\n"
] | [
"2\nHe\nllo\n",
"2\nCodef\norces\n",
"-1\n",
"8\na\nb\na\nc\na\nb\na\nc\n"
] | none | 0 | [
{
"input": "5 2 3\nHello",
"output": "2\nHe\nllo"
},
{
"input": "10 9 5\nCodeforces",
"output": "2\nCodef\norces"
},
{
"input": "6 4 5\nPrivet",
"output": "-1"
},
{
"input": "8 1 1\nabacabac",
"output": "8\na\nb\na\nc\na\nb\na\nc"
},
{
"input": "1 1 1\n1",
"ou... | 1,588,871,796 | 2,147,483,647 | Python 3 | OK | TESTS | 72 | 124 | 6,963,200 | n, p, q = map(int, input().split())
s = input()
if p > q:
p, q = q, p
for i in range(0, n + 1, q):
if (n - i) % p == 0:
print(i // q + (n - i) // p)
for j in range(0, i, q):
print(s[j:j + q])
for j in range(i, n, p):
print(s[j:j + p])
exit(0)
print(-1)
| Title: The Text Splitting
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given the string *s* of length *n* and the numbers *p*,<=*q*. Split the string *s* to pieces of length *p* and *q*.
For example, the string "Hello" for *p*<==<=2, *q*<==<=3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".
Note it is allowed to split the string *s* to the strings only of length *p* or to the strings only of length *q* (see the second sample test).
Input Specification:
The first line contains three positive integers *n*,<=*p*,<=*q* (1<=β€<=*p*,<=*q*<=β€<=*n*<=β€<=100).
The second line contains the string *s* consists of lowercase and uppercase latin letters and digits.
Output Specification:
If it's impossible to split the string *s* to the strings of length *p* and *q* print the only number "-1".
Otherwise in the first line print integer *k* β the number of strings in partition of *s*.
Each of the next *k* lines should contain the strings in partition. Each string should be of the length *p* or *q*. The string should be in order of their appearing in string *s* β from left to right.
If there are several solutions print any of them.
Demo Input:
['5 2 3\nHello\n', '10 9 5\nCodeforces\n', '6 4 5\nPrivet\n', '8 1 1\nabacabac\n']
Demo Output:
['2\nHe\nllo\n', '2\nCodef\norces\n', '-1\n', '8\na\nb\na\nc\na\nb\na\nc\n']
Note:
none | ```python
n, p, q = map(int, input().split())
s = input()
if p > q:
p, q = q, p
for i in range(0, n + 1, q):
if (n - i) % p == 0:
print(i // q + (n - i) // p)
for j in range(0, i, q):
print(s[j:j + q])
for j in range(i, n, p):
print(s[j:j + p])
exit(0)
print(-1)
``` | 3 | |
542 | C | Idempotent functions | PROGRAMMING | 2,000 | [
"constructive algorithms",
"graphs",
"math"
] | null | null | Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1,<=2,<=...,<=*n*} is such function , that for any the formula *g*(*g*(*x*))<==<=*g*(*x*) holds.
Let's denote as *f*(*k*)(*x*) the function *f* applied *k* times to the value *x*. More formally, *f*(1)(*x*)<==<=*f*(*x*), *f*(*k*)(*x*)<==<=*f*(*f*(*k*<=-<=1)(*x*)) for each *k*<=><=1.
You are given some function . Your task is to find minimum positive integer *k* such that function *f*(*k*)(*x*) is idempotent. | In the first line of the input there is a single integer *n* (1<=β€<=*n*<=β€<=200) β the size of function *f* domain.
In the second line follow *f*(1),<=*f*(2),<=...,<=*f*(*n*) (1<=β€<=*f*(*i*)<=β€<=*n* for each 1<=β€<=*i*<=β€<=*n*), the values of a function. | Output minimum *k* such that function *f*(*k*)(*x*) is idempotent. | [
"4\n1 2 2 4\n",
"3\n2 3 3\n",
"3\n2 3 1\n"
] | [
"1\n",
"2\n",
"3\n"
] | In the first sample test function *f*(*x*)β=β*f*<sup class="upper-index">(1)</sup>(*x*) is already idempotent since *f*(*f*(1))β=β*f*(1)β=β1, *f*(*f*(2))β=β*f*(2)β=β2, *f*(*f*(3))β=β*f*(3)β=β2, *f*(*f*(4))β=β*f*(4)β=β4.
In the second sample test:
- function *f*(*x*)β=β*f*<sup class="upper-index">(1)</sup>(*x*) isn't idempotent because *f*(*f*(1))β=β3 but *f*(1)β=β2; - function *f*(*x*)β=β*f*<sup class="upper-index">(2)</sup>(*x*) is idempotent since for any *x* it is true that *f*<sup class="upper-index">(2)</sup>(*x*)β=β3, so it is also true that *f*<sup class="upper-index">(2)</sup>(*f*<sup class="upper-index">(2)</sup>(*x*))β=β3.
In the third sample test:
- function *f*(*x*)β=β*f*<sup class="upper-index">(1)</sup>(*x*) isn't idempotent because *f*(*f*(1))β=β3 but *f*(1)β=β2; - function *f*(*f*(*x*))β=β*f*<sup class="upper-index">(2)</sup>(*x*) isn't idempotent because *f*<sup class="upper-index">(2)</sup>(*f*<sup class="upper-index">(2)</sup>(1))β=β2 but *f*<sup class="upper-index">(2)</sup>(1)β=β3; - function *f*(*f*(*f*(*x*)))β=β*f*<sup class="upper-index">(3)</sup>(*x*) is idempotent since it is identity function: *f*<sup class="upper-index">(3)</sup>(*x*)β=β*x* for any <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/46a8c73444c646004dfde04451775e7af924d108.png" style="max-width: 100.0%;max-height: 100.0%;"/> meaning that the formula *f*<sup class="upper-index">(3)</sup>(*f*<sup class="upper-index">(3)</sup>(*x*))β=β*f*<sup class="upper-index">(3)</sup>(*x*) also holds. | 750 | [
{
"input": "4\n1 2 2 4",
"output": "1"
},
{
"input": "3\n2 3 3",
"output": "2"
},
{
"input": "3\n2 3 1",
"output": "3"
},
{
"input": "1\n1",
"output": "1"
},
{
"input": "16\n1 4 13 9 11 16 14 6 5 12 7 8 15 2 3 10",
"output": "105"
},
{
"input": "20\n1 ... | 1,430,670,997 | 2,197 | Python 3 | OK | TESTS | 65 | 93 | 0 | N =int(input())
inp =input().split()
F =[0 for i in range(N)]
for i in range(N): F[i] =int(inp[i])-1
ans_small =[0 for i in range(N+1)]
for i in range(N):
x =i
y =i
for j in range(N):
x =F[x]
y =F[F[y]]
if x == y:
ans_small[j+1] +=1
ans =-1
for i in range(1,N+1):
if ans == -1:
if ans_small[i] == N:
ans =i
#dlhe
pw =[0 for i in range(500)]
for i in range(N):
vis =[False for j in range(N)]
vis[i] =True
x =F[i]
while vis[x] == False:
vis[x] =True
x =F[x]
vis2 =[False for j in range(N)]
vis2[x] =True
x =F[x]
while vis2[x] == False:
vis2[x] =True
x =F[x]
c =0
for j in range(N):
if vis2[j]: c +=1
j =2
while j <= c:
p =0
while c%j == 0:
c //=j
p +=1
pw[j] =max(pw[j],p)
j +=1
if ans == -1:
ans =1
for i in range(1,500):
for j in range(pw[i]):
ans *=i
ans0 =ans
while ans <= N:
ans +=ans0
print(ans) | Title: Idempotent functions
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1,<=2,<=...,<=*n*} is such function , that for any the formula *g*(*g*(*x*))<==<=*g*(*x*) holds.
Let's denote as *f*(*k*)(*x*) the function *f* applied *k* times to the value *x*. More formally, *f*(1)(*x*)<==<=*f*(*x*), *f*(*k*)(*x*)<==<=*f*(*f*(*k*<=-<=1)(*x*)) for each *k*<=><=1.
You are given some function . Your task is to find minimum positive integer *k* such that function *f*(*k*)(*x*) is idempotent.
Input Specification:
In the first line of the input there is a single integer *n* (1<=β€<=*n*<=β€<=200) β the size of function *f* domain.
In the second line follow *f*(1),<=*f*(2),<=...,<=*f*(*n*) (1<=β€<=*f*(*i*)<=β€<=*n* for each 1<=β€<=*i*<=β€<=*n*), the values of a function.
Output Specification:
Output minimum *k* such that function *f*(*k*)(*x*) is idempotent.
Demo Input:
['4\n1 2 2 4\n', '3\n2 3 3\n', '3\n2 3 1\n']
Demo Output:
['1\n', '2\n', '3\n']
Note:
In the first sample test function *f*(*x*)β=β*f*<sup class="upper-index">(1)</sup>(*x*) is already idempotent since *f*(*f*(1))β=β*f*(1)β=β1, *f*(*f*(2))β=β*f*(2)β=β2, *f*(*f*(3))β=β*f*(3)β=β2, *f*(*f*(4))β=β*f*(4)β=β4.
In the second sample test:
- function *f*(*x*)β=β*f*<sup class="upper-index">(1)</sup>(*x*) isn't idempotent because *f*(*f*(1))β=β3 but *f*(1)β=β2; - function *f*(*x*)β=β*f*<sup class="upper-index">(2)</sup>(*x*) is idempotent since for any *x* it is true that *f*<sup class="upper-index">(2)</sup>(*x*)β=β3, so it is also true that *f*<sup class="upper-index">(2)</sup>(*f*<sup class="upper-index">(2)</sup>(*x*))β=β3.
In the third sample test:
- function *f*(*x*)β=β*f*<sup class="upper-index">(1)</sup>(*x*) isn't idempotent because *f*(*f*(1))β=β3 but *f*(1)β=β2; - function *f*(*f*(*x*))β=β*f*<sup class="upper-index">(2)</sup>(*x*) isn't idempotent because *f*<sup class="upper-index">(2)</sup>(*f*<sup class="upper-index">(2)</sup>(1))β=β2 but *f*<sup class="upper-index">(2)</sup>(1)β=β3; - function *f*(*f*(*f*(*x*)))β=β*f*<sup class="upper-index">(3)</sup>(*x*) is idempotent since it is identity function: *f*<sup class="upper-index">(3)</sup>(*x*)β=β*x* for any <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/46a8c73444c646004dfde04451775e7af924d108.png" style="max-width: 100.0%;max-height: 100.0%;"/> meaning that the formula *f*<sup class="upper-index">(3)</sup>(*f*<sup class="upper-index">(3)</sup>(*x*))β=β*f*<sup class="upper-index">(3)</sup>(*x*) also holds. | ```python
N =int(input())
inp =input().split()
F =[0 for i in range(N)]
for i in range(N): F[i] =int(inp[i])-1
ans_small =[0 for i in range(N+1)]
for i in range(N):
x =i
y =i
for j in range(N):
x =F[x]
y =F[F[y]]
if x == y:
ans_small[j+1] +=1
ans =-1
for i in range(1,N+1):
if ans == -1:
if ans_small[i] == N:
ans =i
#dlhe
pw =[0 for i in range(500)]
for i in range(N):
vis =[False for j in range(N)]
vis[i] =True
x =F[i]
while vis[x] == False:
vis[x] =True
x =F[x]
vis2 =[False for j in range(N)]
vis2[x] =True
x =F[x]
while vis2[x] == False:
vis2[x] =True
x =F[x]
c =0
for j in range(N):
if vis2[j]: c +=1
j =2
while j <= c:
p =0
while c%j == 0:
c //=j
p +=1
pw[j] =max(pw[j],p)
j +=1
if ans == -1:
ans =1
for i in range(1,500):
for j in range(pw[i]):
ans *=i
ans0 =ans
while ans <= N:
ans +=ans0
print(ans)
``` | 3 | |
723 | A | The New Year: Meeting Friends | PROGRAMMING | 800 | [
"implementation",
"math",
"sortings"
] | null | null | There are three friend living on the straight line *Ox* in Lineland. The first friend lives at the point *x*1, the second friend lives at the point *x*2, and the third friend lives at the point *x*3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?
It's guaranteed that the optimal answer is always integer. | The first line of the input contains three distinct integers *x*1, *x*2 and *x*3 (1<=β€<=*x*1,<=*x*2,<=*x*3<=β€<=100)Β β the coordinates of the houses of the first, the second and the third friends respectively. | Print one integerΒ β the minimum total distance the friends need to travel in order to meet together. | [
"7 1 4\n",
"30 20 10\n"
] | [
"6\n",
"20\n"
] | In the first sample, friends should meet at the point 4. Thus, the first friend has to travel the distance of 3 (from the point 7 to the point 4), the second friend also has to travel the distance of 3 (from the point 1 to the point 4), while the third friend should not go anywhere because he lives at the point 4. | 500 | [
{
"input": "7 1 4",
"output": "6"
},
{
"input": "30 20 10",
"output": "20"
},
{
"input": "1 4 100",
"output": "99"
},
{
"input": "100 1 91",
"output": "99"
},
{
"input": "1 45 100",
"output": "99"
},
{
"input": "1 2 3",
"output": "2"
},
{
"... | 1,673,244,117 | 2,147,483,647 | Python 3 | OK | TESTS | 48 | 46 | 0 | a = list(map(int, input().split()))
print(max(a)-min(a))
| Title: The New Year: Meeting Friends
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are three friend living on the straight line *Ox* in Lineland. The first friend lives at the point *x*1, the second friend lives at the point *x*2, and the third friend lives at the point *x*3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?
It's guaranteed that the optimal answer is always integer.
Input Specification:
The first line of the input contains three distinct integers *x*1, *x*2 and *x*3 (1<=β€<=*x*1,<=*x*2,<=*x*3<=β€<=100)Β β the coordinates of the houses of the first, the second and the third friends respectively.
Output Specification:
Print one integerΒ β the minimum total distance the friends need to travel in order to meet together.
Demo Input:
['7 1 4\n', '30 20 10\n']
Demo Output:
['6\n', '20\n']
Note:
In the first sample, friends should meet at the point 4. Thus, the first friend has to travel the distance of 3 (from the point 7 to the point 4), the second friend also has to travel the distance of 3 (from the point 1 to the point 4), while the third friend should not go anywhere because he lives at the point 4. | ```python
a = list(map(int, input().split()))
print(max(a)-min(a))
``` | 3 | |
59 | A | Word | PROGRAMMING | 800 | [
"implementation",
"strings"
] | A. Word | 2 | 256 | Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP β with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word. | The first line contains a word *s* β it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100. | Print the corrected word *s*. If the given word *s* has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one. | [
"HoUse\n",
"ViP\n",
"maTRIx\n"
] | [
"house\n",
"VIP\n",
"matrix\n"
] | none | 500 | [
{
"input": "HoUse",
"output": "house"
},
{
"input": "ViP",
"output": "VIP"
},
{
"input": "maTRIx",
"output": "matrix"
},
{
"input": "BNHWpnpawg",
"output": "bnhwpnpawg"
},
{
"input": "VTYGP",
"output": "VTYGP"
},
{
"input": "CHNenu",
"output": "chn... | 1,592,142,233 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 218 | 0 | s = input()
n = len(s)
lower = 0
upper = 0
for i in s:
if i.islower():
lower+=1
elif i.isupper():
upper+=1
if lower >= upper:
s = s.lower()
else:
s= s.upper()
print(s) | Title: Word
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP β with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
Input Specification:
The first line contains a word *s* β it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100.
Output Specification:
Print the corrected word *s*. If the given word *s* has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one.
Demo Input:
['HoUse\n', 'ViP\n', 'maTRIx\n']
Demo Output:
['house\n', 'VIP\n', 'matrix\n']
Note:
none | ```python
s = input()
n = len(s)
lower = 0
upper = 0
for i in s:
if i.islower():
lower+=1
elif i.isupper():
upper+=1
if lower >= upper:
s = s.lower()
else:
s= s.upper()
print(s)
``` | 3.9455 |
455 | A | Boredom | PROGRAMMING | 1,500 | [
"dp"
] | null | null | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him. | The first line contains integer *n* (1<=β€<=*n*<=β€<=105) that shows how many numbers are in Alex's sequence.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=β€<=*a**i*<=β€<=105). | Print a single integer β the maximum number of points that Alex can earn. | [
"2\n1 2\n",
"3\n1 2 3\n",
"9\n1 2 1 3 2 2 2 2 3\n"
] | [
"2\n",
"4\n",
"10\n"
] | Consider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | 500 | [
{
"input": "2\n1 2",
"output": "2"
},
{
"input": "3\n1 2 3",
"output": "4"
},
{
"input": "9\n1 2 1 3 2 2 2 2 3",
"output": "10"
},
{
"input": "5\n3 3 4 5 4",
"output": "11"
},
{
"input": "5\n5 3 5 3 4",
"output": "16"
},
{
"input": "5\n4 2 3 2 5",
... | 1,669,053,157 | 2,147,483,647 | Python 3 | OK | TESTS | 47 | 140 | 7,065,600 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 22 01:12:17 2022
@author: thinkpad
"""
n = int(input())
a = [int(i) for i in input().split()]
s = [0]*100002
for i in a:
s[i]+=i
res,b=0,0
for d in s:
res,b = max(res,b),res+d
print(res) | Title: Boredom
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=105) that shows how many numbers are in Alex's sequence.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=β€<=*a**i*<=β€<=105).
Output Specification:
Print a single integer β the maximum number of points that Alex can earn.
Demo Input:
['2\n1 2\n', '3\n1 2 3\n', '9\n1 2 1 3 2 2 2 2 3\n']
Demo Output:
['2\n', '4\n', '10\n']
Note:
Consider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | ```python
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 22 01:12:17 2022
@author: thinkpad
"""
n = int(input())
a = [int(i) for i in input().split()]
s = [0]*100002
for i in a:
s[i]+=i
res,b=0,0
for d in s:
res,b = max(res,b),res+d
print(res)
``` | 3 | |
637 | A | Voting for Photos | PROGRAMMING | 1,000 | [
"*special",
"constructive algorithms",
"implementation"
] | null | null | After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.
Help guys determine the winner photo by the records of likes. | The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=1000) β the total likes to the published photoes.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=1<=000<=000), where *a**i* is the identifier of the photo which got the *i*-th like. | Print the identifier of the photo which won the elections. | [
"5\n1 3 2 2 1\n",
"9\n100 200 300 200 100 300 300 100 200\n"
] | [
"2\n",
"300\n"
] | In the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second).
Thus, the winner is the photo with identifier 2, as it got:
- more likes than the photo with id 3; - as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier. | 500 | [
{
"input": "5\n1 3 2 2 1",
"output": "2"
},
{
"input": "9\n100 200 300 200 100 300 300 100 200",
"output": "300"
},
{
"input": "1\n5",
"output": "5"
},
{
"input": "1\n1000000",
"output": "1000000"
},
{
"input": "5\n1 3 4 2 2",
"output": "2"
},
{
"input... | 1,457,897,193 | 26,793 | Python 3 | OK | TESTS | 65 | 77 | 819,200 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 19:40:03 2016
@author: Kostya S.
"""
from functools import cmp_to_key
n = int(input())
d = {}
a = [int(i) for i in input().split()]
for i,e in enumerate(a):
d[e] = (i+1,1,e) if d.get(e) == None else (i+1,d[e][1] + 1,e)
t1 = sorted(list(d.values()),key = lambda x: x[1])
t2 = list(filter(lambda x: x[1] == t1[-1][1],t1))
t2 = sorted(t2,key = lambda x: x[0])
print(t2[0][-1]) | Title: Voting for Photos
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.
Help guys determine the winner photo by the records of likes.
Input Specification:
The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=1000) β the total likes to the published photoes.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=1<=000<=000), where *a**i* is the identifier of the photo which got the *i*-th like.
Output Specification:
Print the identifier of the photo which won the elections.
Demo Input:
['5\n1 3 2 2 1\n', '9\n100 200 300 200 100 300 300 100 200\n']
Demo Output:
['2\n', '300\n']
Note:
In the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second).
Thus, the winner is the photo with identifier 2, as it got:
- more likes than the photo with id 3; - as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier. | ```python
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 19:40:03 2016
@author: Kostya S.
"""
from functools import cmp_to_key
n = int(input())
d = {}
a = [int(i) for i in input().split()]
for i,e in enumerate(a):
d[e] = (i+1,1,e) if d.get(e) == None else (i+1,d[e][1] + 1,e)
t1 = sorted(list(d.values()),key = lambda x: x[1])
t2 = list(filter(lambda x: x[1] == t1[-1][1],t1))
t2 = sorted(t2,key = lambda x: x[0])
print(t2[0][-1])
``` | 3 | |
908 | A | New Year and Counting Cards | PROGRAMMING | 800 | [
"brute force",
"implementation"
] | null | null | Your friend has *n* cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.
For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.
To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. | The first and only line of input will contain a string *s* (1<=β€<=|*s*|<=β€<=50), denoting the sides of the cards that you can see on the table currently. Each character of *s* is either a lowercase English letter or a digit. | Print a single integer, the minimum number of cards you must turn over to verify your claim. | [
"ee\n",
"z\n",
"0ay1\n"
] | [
"2\n",
"0\n",
"2\n"
] | In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side.
In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them.
In the third sample, we need to flip the second and fourth cards. | 500 | [
{
"input": "ee",
"output": "2"
},
{
"input": "z",
"output": "0"
},
{
"input": "0ay1",
"output": "2"
},
{
"input": "0abcdefghijklmnopqrstuvwxyz1234567896",
"output": "10"
},
{
"input": "0a0a9e9e2i2i9o9o6u6u9z9z4x4x9b9b",
"output": "18"
},
{
"input": "01... | 1,599,229,810 | 2,147,483,647 | Python 3 | OK | TESTS | 38 | 109 | 0 | from sys import stdin, stdout
def need_to_check(card, vowels=['a','e','i','o','u']):
return (ord(card) >= ord('0') and ord(card) <= ord('9') and int(card) % 2 == 1) or (card in vowels)
def number_of_reveals(cards):
count = 0
for card in cards:
count = count+1 if need_to_check(card) else count
return count
stdout.write( str(number_of_reveals(stdin.readline())) +'\n')
| Title: New Year and Counting Cards
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Your friend has *n* cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.
For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.
To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.
Input Specification:
The first and only line of input will contain a string *s* (1<=β€<=|*s*|<=β€<=50), denoting the sides of the cards that you can see on the table currently. Each character of *s* is either a lowercase English letter or a digit.
Output Specification:
Print a single integer, the minimum number of cards you must turn over to verify your claim.
Demo Input:
['ee\n', 'z\n', '0ay1\n']
Demo Output:
['2\n', '0\n', '2\n']
Note:
In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side.
In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them.
In the third sample, we need to flip the second and fourth cards. | ```python
from sys import stdin, stdout
def need_to_check(card, vowels=['a','e','i','o','u']):
return (ord(card) >= ord('0') and ord(card) <= ord('9') and int(card) % 2 == 1) or (card in vowels)
def number_of_reveals(cards):
count = 0
for card in cards:
count = count+1 if need_to_check(card) else count
return count
stdout.write( str(number_of_reveals(stdin.readline())) +'\n')
``` | 3 | |
25 | A | IQ test | PROGRAMMING | 1,300 | [
"brute force"
] | A. IQ test | 2 | 256 | Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness. | The first line contains integer *n* (3<=β€<=*n*<=β€<=100) β amount of numbers in the task. The second line contains *n* space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness. | Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order. | [
"5\n2 4 7 8 10\n",
"4\n1 2 1 1\n"
] | [
"3\n",
"2\n"
] | none | 0 | [
{
"input": "5\n2 4 7 8 10",
"output": "3"
},
{
"input": "4\n1 2 1 1",
"output": "2"
},
{
"input": "3\n1 2 2",
"output": "1"
},
{
"input": "3\n100 99 100",
"output": "2"
},
{
"input": "3\n5 3 2",
"output": "3"
},
{
"input": "4\n43 28 1 91",
"output"... | 1,602,371,164 | 2,147,483,647 | Python 3 | OK | TESTS | 32 | 218 | 0 | n=int(input())
a=[int(x) for x in input().split()]
b=[]
for i in range(n):
b.append(a[i]%2)
if b.count(1)>b.count(0):
c=[1]*n
else:
c=[0]*n
for i in range(n):
if b[i]-c[i]!=0:
print(i+1) | Title: IQ test
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
Input Specification:
The first line contains integer *n* (3<=β€<=*n*<=β€<=100) β amount of numbers in the task. The second line contains *n* space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.
Output Specification:
Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.
Demo Input:
['5\n2 4 7 8 10\n', '4\n1 2 1 1\n']
Demo Output:
['3\n', '2\n']
Note:
none | ```python
n=int(input())
a=[int(x) for x in input().split()]
b=[]
for i in range(n):
b.append(a[i]%2)
if b.count(1)>b.count(0):
c=[1]*n
else:
c=[0]*n
for i in range(n):
if b[i]-c[i]!=0:
print(i+1)
``` | 3.9455 |
625 | B | War of the Corporations | PROGRAMMING | 1,200 | [
"constructive algorithms",
"greedy",
"strings"
] | null | null | A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string. | The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100<=000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters. | Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring. | [
"intellect\ntell\n",
"google\napple\n",
"sirisiri\nsir\n"
] | [
"1",
"0",
"2"
] | In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | 750 | [
{
"input": "intellect\ntell",
"output": "1"
},
{
"input": "google\napple",
"output": "0"
},
{
"input": "sirisiri\nsir",
"output": "2"
},
{
"input": "sirisiri\nsiri",
"output": "2"
},
{
"input": "aaaaaaa\naaaa",
"output": "1"
},
{
"input": "bbbbbb\nbb",... | 1,498,085,255 | 2,147,483,647 | Python 3 | OK | TESTS | 56 | 140 | 5,632,000 | # Description of the problem can be found at http://codeforces.com/problemset/problem/625/B
x = input()
s = input()
print(x.count(s)) | Title: War of the Corporations
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
Input Specification:
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100<=000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
Output Specification:
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
Demo Input:
['intellect\ntell\n', 'google\napple\n', 'sirisiri\nsir\n']
Demo Output:
['1', '0', '2']
Note:
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | ```python
# Description of the problem can be found at http://codeforces.com/problemset/problem/625/B
x = input()
s = input()
print(x.count(s))
``` | 3 | |
776 | A | A Serial Killer | PROGRAMMING | 900 | [
"brute force",
"implementation",
"strings"
] | null | null | Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.
The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.
You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern. | First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer *n* (1<=β€<=*n*<=β€<=1000), the number of days.
Next *n* lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person.
The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters. | Output *n*<=+<=1 lines, the *i*-th line should contain the two persons from which the killer selects for the *i*-th murder. The (*n*<=+<=1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order. | [
"ross rachel\n4\nross joey\nrachel phoebe\nphoebe monica\nmonica chandler\n",
"icm codeforces\n1\ncodeforces technex\n"
] | [
"ross rachel\njoey rachel\njoey phoebe\njoey monica\njoey chandler\n",
"icm codeforces\nicm technex\n"
] | In first example, the killer starts with ross and rachel.
- After day 1, ross is killed and joey appears. - After day 2, rachel is killed and phoebe appears. - After day 3, phoebe is killed and monica appears. - After day 4, monica is killed and chandler appears. | 500 | [
{
"input": "ross rachel\n4\nross joey\nrachel phoebe\nphoebe monica\nmonica chandler",
"output": "ross rachel\njoey rachel\njoey phoebe\njoey monica\njoey chandler"
},
{
"input": "icm codeforces\n1\ncodeforces technex",
"output": "icm codeforces\nicm technex"
},
{
"input": "a b\n3\na c\n... | 1,593,521,808 | 2,147,483,647 | PyPy 3 | OK | TESTS | 57 | 202 | 3,276,800 | n,m= input().split()
print(n,m)
num = int(input())
for i in range(num):
a,b=input().split()
if(a==n):
print(b,m)
n=b
else:
print(b,n)
m=b
| Title: A Serial Killer
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.
The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.
You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.
Input Specification:
First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer *n* (1<=β€<=*n*<=β€<=1000), the number of days.
Next *n* lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person.
The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters.
Output Specification:
Output *n*<=+<=1 lines, the *i*-th line should contain the two persons from which the killer selects for the *i*-th murder. The (*n*<=+<=1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order.
Demo Input:
['ross rachel\n4\nross joey\nrachel phoebe\nphoebe monica\nmonica chandler\n', 'icm codeforces\n1\ncodeforces technex\n']
Demo Output:
['ross rachel\njoey rachel\njoey phoebe\njoey monica\njoey chandler\n', 'icm codeforces\nicm technex\n']
Note:
In first example, the killer starts with ross and rachel.
- After day 1, ross is killed and joey appears. - After day 2, rachel is killed and phoebe appears. - After day 3, phoebe is killed and monica appears. - After day 4, monica is killed and chandler appears. | ```python
n,m= input().split()
print(n,m)
num = int(input())
for i in range(num):
a,b=input().split()
if(a==n):
print(b,m)
n=b
else:
print(b,n)
m=b
``` | 3 | |
785 | A | Anton and Polyhedrons | PROGRAMMING | 800 | [
"implementation",
"strings"
] | null | null | Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
- Tetrahedron. Tetrahedron has 4 triangular faces. - Cube. Cube has 6 square faces. - Octahedron. Octahedron has 8 triangular faces. - Dodecahedron. Dodecahedron has 12 pentagonal faces. - Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
Anton has a collection of *n* polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number! | The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=200<=000)Β β the number of polyhedrons in Anton's collection.
Each of the following *n* lines of the input contains a string *s**i*Β β the name of the *i*-th polyhedron in Anton's collection. The string can look like this:
- "Tetrahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is a tetrahedron. - "Cube" (without quotes), if the *i*-th polyhedron in Anton's collection is a cube. - "Octahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is an octahedron. - "Dodecahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is a dodecahedron. - "Icosahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is an icosahedron. | Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection. | [
"4\nIcosahedron\nCube\nTetrahedron\nDodecahedron\n",
"3\nDodecahedron\nOctahedron\nOctahedron\n"
] | [
"42\n",
"28\n"
] | In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces. | 500 | [
{
"input": "4\nIcosahedron\nCube\nTetrahedron\nDodecahedron",
"output": "42"
},
{
"input": "3\nDodecahedron\nOctahedron\nOctahedron",
"output": "28"
},
{
"input": "25\nIcosahedron\nOctahedron\nTetrahedron\nDodecahedron\nCube\nIcosahedron\nOctahedron\nCube\nTetrahedron\nIcosahedron\nIcosa... | 1,679,367,714 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 265 | 0 | s = {"Tetrahedron": 4,
"Cube": 6,
"Octahedron": 8,
"Dodecahedron": 12,
"Icosahedron": 20}
t = int(input())
add = 0
for i in range(t):
add += s[input()]
print(add)
| Title: Anton and Polyhedrons
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
- Tetrahedron. Tetrahedron has 4 triangular faces. - Cube. Cube has 6 square faces. - Octahedron. Octahedron has 8 triangular faces. - Dodecahedron. Dodecahedron has 12 pentagonal faces. - Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
Anton has a collection of *n* polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input Specification:
The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=200<=000)Β β the number of polyhedrons in Anton's collection.
Each of the following *n* lines of the input contains a string *s**i*Β β the name of the *i*-th polyhedron in Anton's collection. The string can look like this:
- "Tetrahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is a tetrahedron. - "Cube" (without quotes), if the *i*-th polyhedron in Anton's collection is a cube. - "Octahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is an octahedron. - "Dodecahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is a dodecahedron. - "Icosahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is an icosahedron.
Output Specification:
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
Demo Input:
['4\nIcosahedron\nCube\nTetrahedron\nDodecahedron\n', '3\nDodecahedron\nOctahedron\nOctahedron\n']
Demo Output:
['42\n', '28\n']
Note:
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces. | ```python
s = {"Tetrahedron": 4,
"Cube": 6,
"Octahedron": 8,
"Dodecahedron": 12,
"Icosahedron": 20}
t = int(input())
add = 0
for i in range(t):
add += s[input()]
print(add)
``` | 3 | |
227 | A | Where do I Turn? | PROGRAMMING | 1,300 | [
"geometry"
] | null | null | Trouble came from the overseas lands: a three-headed dragon Gorynych arrived. The dragon settled at point *C* and began to terrorize the residents of the surrounding villages.
A brave hero decided to put an end to the dragon. He moved from point *A* to fight with Gorynych. The hero rode from point *A* along a straight road and met point *B* on his way. The hero knows that in this land for every pair of roads it is true that they are either parallel to each other, or lie on a straight line, or are perpendicular to each other. He also knows well that points *B* and *C* are connected by a road. So the hero must either turn 90 degrees to the left or continue riding straight ahead or turn 90 degrees to the right. But he forgot where the point *C* is located.
Fortunately, a Brave Falcon flew right by. It can see all three points from the sky. The hero asked him what way to go to get to the dragon's lair.
If you have not got it, you are the falcon. Help the hero and tell him how to get him to point *C*: turn left, go straight or turn right.
At this moment the hero is believed to stand at point *B*, turning his back to point *A*. | The first input line contains two space-separated integers *x**a*,<=*y**a* (|*x**a*|,<=|*y**a*|<=β€<=109) β the coordinates of point *A*. The second line contains the coordinates of point *B* in the same form, the third line contains the coordinates of point *C*.
It is guaranteed that all points are pairwise different. It is also guaranteed that either point *B* lies on segment *AC*, or angle *ABC* is right. | Print a single line. If a hero must turn left, print "LEFT" (without the quotes); If he must go straight ahead, print "TOWARDS" (without the quotes); if he should turn right, print "RIGHT" (without the quotes). | [
"0 0\n0 1\n1 1\n",
"-1 -1\n-3 -3\n-4 -4\n",
"-4 -6\n-3 -7\n-2 -6\n"
] | [
"RIGHT\n",
"TOWARDS\n",
"LEFT\n"
] | The picture to the first sample:
The red color shows points A, B and C. The blue arrow shows the hero's direction. The green color shows the hero's trajectory.
The picture to the second sample: | 500 | [
{
"input": "0 0\n0 1\n1 1",
"output": "RIGHT"
},
{
"input": "-1 -1\n-3 -3\n-4 -4",
"output": "TOWARDS"
},
{
"input": "-4 -6\n-3 -7\n-2 -6",
"output": "LEFT"
},
{
"input": "-44 57\n-118 -41\n-216 33",
"output": "RIGHT"
},
{
"input": "39 100\n90 85\n105 136",
"o... | 1,630,951,047 | 2,147,483,647 | Python 3 | OK | TESTS | 48 | 124 | 6,963,200 | xa,ya = input().split()
xa = int(xa)
ya = int(ya)
xb,yb = input().split()
xb = int(xb)
yb = int(yb)
xc,yc = input().split()
xc = int(xc)
yc = int(yc)
vab_x = xb-xa
vab_y = yb-ya
vbc_x = xc - xb
vbc_y = yc - yb
produto_vetorial = (vab_x * vbc_y) - (vab_y * vbc_x)
if(produto_vetorial == 0):
print("TOWARDS")
elif(produto_vetorial < 0):
print("RIGHT")
else:
print("LEFT")
| Title: Where do I Turn?
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Trouble came from the overseas lands: a three-headed dragon Gorynych arrived. The dragon settled at point *C* and began to terrorize the residents of the surrounding villages.
A brave hero decided to put an end to the dragon. He moved from point *A* to fight with Gorynych. The hero rode from point *A* along a straight road and met point *B* on his way. The hero knows that in this land for every pair of roads it is true that they are either parallel to each other, or lie on a straight line, or are perpendicular to each other. He also knows well that points *B* and *C* are connected by a road. So the hero must either turn 90 degrees to the left or continue riding straight ahead or turn 90 degrees to the right. But he forgot where the point *C* is located.
Fortunately, a Brave Falcon flew right by. It can see all three points from the sky. The hero asked him what way to go to get to the dragon's lair.
If you have not got it, you are the falcon. Help the hero and tell him how to get him to point *C*: turn left, go straight or turn right.
At this moment the hero is believed to stand at point *B*, turning his back to point *A*.
Input Specification:
The first input line contains two space-separated integers *x**a*,<=*y**a* (|*x**a*|,<=|*y**a*|<=β€<=109) β the coordinates of point *A*. The second line contains the coordinates of point *B* in the same form, the third line contains the coordinates of point *C*.
It is guaranteed that all points are pairwise different. It is also guaranteed that either point *B* lies on segment *AC*, or angle *ABC* is right.
Output Specification:
Print a single line. If a hero must turn left, print "LEFT" (without the quotes); If he must go straight ahead, print "TOWARDS" (without the quotes); if he should turn right, print "RIGHT" (without the quotes).
Demo Input:
['0 0\n0 1\n1 1\n', '-1 -1\n-3 -3\n-4 -4\n', '-4 -6\n-3 -7\n-2 -6\n']
Demo Output:
['RIGHT\n', 'TOWARDS\n', 'LEFT\n']
Note:
The picture to the first sample:
The red color shows points A, B and C. The blue arrow shows the hero's direction. The green color shows the hero's trajectory.
The picture to the second sample: | ```python
xa,ya = input().split()
xa = int(xa)
ya = int(ya)
xb,yb = input().split()
xb = int(xb)
yb = int(yb)
xc,yc = input().split()
xc = int(xc)
yc = int(yc)
vab_x = xb-xa
vab_y = yb-ya
vbc_x = xc - xb
vbc_y = yc - yb
produto_vetorial = (vab_x * vbc_y) - (vab_y * vbc_x)
if(produto_vetorial == 0):
print("TOWARDS")
elif(produto_vetorial < 0):
print("RIGHT")
else:
print("LEFT")
``` | 3 | |
884 | A | Book Reading | PROGRAMMING | 800 | [
"implementation"
] | null | null | Recently Luba bought a very interesting book. She knows that it will take *t* seconds to read the book. Luba wants to finish reading as fast as she can.
But she has some work to do in each of *n* next days. The number of seconds that Luba has to spend working during *i*-th day is *a**i*. If some free time remains, she can spend it on reading.
Help Luba to determine the minimum number of day when she finishes reading.
It is guaranteed that the answer doesn't exceed *n*.
Remember that there are 86400 seconds in a day. | The first line contains two integers *n* and *t* (1<=β€<=*n*<=β€<=100, 1<=β€<=*t*<=β€<=106) β the number of days and the time required to read the book.
The second line contains *n* integers *a**i* (0<=β€<=*a**i*<=β€<=86400) β the time Luba has to spend on her work during *i*-th day. | Print the minimum day Luba can finish reading the book.
It is guaranteed that answer doesn't exceed *n*. | [
"2 2\n86400 86398\n",
"2 86400\n0 86400\n"
] | [
"2\n",
"1\n"
] | none | 0 | [
{
"input": "2 2\n86400 86398",
"output": "2"
},
{
"input": "2 86400\n0 86400",
"output": "1"
},
{
"input": "2 86400\n1 86399",
"output": "2"
},
{
"input": "100 1000000\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0... | 1,509,113,739 | 639 | Python 3 | OK | TESTS | 16 | 61 | 0 | a=input().split(' ')
n=int(a[0])
t=int(a[1])
a=input().split(' ')
a=[int(i) for i in a]
for i in range(n):
if t<=0:
print(i)
break
t=t-(86400-a[i])
else:
print(n)
| Title: Book Reading
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recently Luba bought a very interesting book. She knows that it will take *t* seconds to read the book. Luba wants to finish reading as fast as she can.
But she has some work to do in each of *n* next days. The number of seconds that Luba has to spend working during *i*-th day is *a**i*. If some free time remains, she can spend it on reading.
Help Luba to determine the minimum number of day when she finishes reading.
It is guaranteed that the answer doesn't exceed *n*.
Remember that there are 86400 seconds in a day.
Input Specification:
The first line contains two integers *n* and *t* (1<=β€<=*n*<=β€<=100, 1<=β€<=*t*<=β€<=106) β the number of days and the time required to read the book.
The second line contains *n* integers *a**i* (0<=β€<=*a**i*<=β€<=86400) β the time Luba has to spend on her work during *i*-th day.
Output Specification:
Print the minimum day Luba can finish reading the book.
It is guaranteed that answer doesn't exceed *n*.
Demo Input:
['2 2\n86400 86398\n', '2 86400\n0 86400\n']
Demo Output:
['2\n', '1\n']
Note:
none | ```python
a=input().split(' ')
n=int(a[0])
t=int(a[1])
a=input().split(' ')
a=[int(i) for i in a]
for i in range(n):
if t<=0:
print(i)
break
t=t-(86400-a[i])
else:
print(n)
``` | 3 | |
855 | A | Tom Riddle's Diary | PROGRAMMING | 800 | [
"brute force",
"implementation",
"strings"
] | null | null | Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.
He has names of *n* people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.
Formally, for a name *s**i* in the *i*-th line, output "YES" (without quotes) if there exists an index *j* such that *s**i*<==<=*s**j* and *j*<=<<=*i*, otherwise, output "NO" (without quotes). | First line of input contains an integer *n* (1<=β€<=*n*<=β€<=100)Β β the number of names in the list.
Next *n* lines each contain a string *s**i*, consisting of lowercase English letters. The length of each string is between 1 and 100. | Output *n* lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not.
You can print each letter in any case (upper or lower). | [
"6\ntom\nlucius\nginny\nharry\nginny\nharry\n",
"3\na\na\na\n"
] | [
"NO\nNO\nNO\nNO\nYES\nYES\n",
"NO\nYES\nYES\n"
] | In test case 1, for *i*β=β5 there exists *j*β=β3 such that *s*<sub class="lower-index">*i*</sub>β=β*s*<sub class="lower-index">*j*</sub> and *j*β<β*i*, which means that answer for *i*β=β5 is "YES". | 500 | [
{
"input": "6\ntom\nlucius\nginny\nharry\nginny\nharry",
"output": "NO\nNO\nNO\nNO\nYES\nYES"
},
{
"input": "3\na\na\na",
"output": "NO\nYES\nYES"
},
{
"input": "1\nzn",
"output": "NO"
},
{
"input": "9\nliyzmbjwnzryjokufuxcqtzwworjeoxkbaqrujrhdidqdvwdfzilwszgnzglnnbogaclckfnb... | 1,692,610,152 | 2,147,483,647 | Python 3 | OK | TESTS | 55 | 46 | 0 | #all those moments will be lost in time , like tears in rain "D
a=[]
n=int(input())
for _ in range(n):
b=input()
if b in a:
print('YES')
else:
print('NO')
a.append(b); | Title: Tom Riddle's Diary
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.
He has names of *n* people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.
Formally, for a name *s**i* in the *i*-th line, output "YES" (without quotes) if there exists an index *j* such that *s**i*<==<=*s**j* and *j*<=<<=*i*, otherwise, output "NO" (without quotes).
Input Specification:
First line of input contains an integer *n* (1<=β€<=*n*<=β€<=100)Β β the number of names in the list.
Next *n* lines each contain a string *s**i*, consisting of lowercase English letters. The length of each string is between 1 and 100.
Output Specification:
Output *n* lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not.
You can print each letter in any case (upper or lower).
Demo Input:
['6\ntom\nlucius\nginny\nharry\nginny\nharry\n', '3\na\na\na\n']
Demo Output:
['NO\nNO\nNO\nNO\nYES\nYES\n', 'NO\nYES\nYES\n']
Note:
In test case 1, for *i*β=β5 there exists *j*β=β3 such that *s*<sub class="lower-index">*i*</sub>β=β*s*<sub class="lower-index">*j*</sub> and *j*β<β*i*, which means that answer for *i*β=β5 is "YES". | ```python
#all those moments will be lost in time , like tears in rain "D
a=[]
n=int(input())
for _ in range(n):
b=input()
if b in a:
print('YES')
else:
print('NO')
a.append(b);
``` | 3 | |
0 | none | none | none | 0 | [
"none"
] | null | null | On the way to school, Karen became fixated on the puzzle game on her phone!
The game is played as follows. In each level, you have a grid with *n* rows and *m* columns. Each cell originally contains the number 0.
One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.
To win the level, after all the moves, the number in the cell at the *i*-th row and *j*-th column should be equal to *g**i*,<=*j*.
Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | The first line of input contains two integers, *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=100), the number of rows and the number of columns in the grid, respectively.
The next *n* lines each contain *m* integers. In particular, the *j*-th integer in the *i*-th of these rows contains *g**i*,<=*j* (0<=β€<=*g**i*,<=*j*<=β€<=500). | If there is an error and it is actually not possible to beat the level, output a single integer -1.
Otherwise, on the first line, output a single integer *k*, the minimum number of moves necessary to beat the level.
The next *k* lines should each contain one of the following, describing the moves in the order they must be done:
- row *x*, (1<=β€<=*x*<=β€<=*n*) describing a move of the form "choose the *x*-th row". - col *x*, (1<=β€<=*x*<=β€<=*m*) describing a move of the form "choose the *x*-th column".
If there are multiple optimal solutions, output any one of them. | [
"3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1\n",
"3 3\n0 0 0\n0 1 0\n0 0 0\n",
"3 3\n1 1 1\n1 1 1\n1 1 1\n"
] | [
"4\nrow 1\nrow 1\ncol 4\nrow 3\n",
"-1\n",
"3\nrow 1\nrow 2\nrow 3\n"
] | In the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level:
In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.
In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level:
Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | 0 | [
{
"input": "3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1",
"output": "4\nrow 1\nrow 1\ncol 4\nrow 3"
},
{
"input": "3 3\n0 0 0\n0 1 0\n0 0 0",
"output": "-1"
},
{
"input": "3 3\n1 1 1\n1 1 1\n1 1 1",
"output": "3\nrow 1\nrow 2\nrow 3"
},
{
"input": "3 5\n2 4 2 2 3\n0 2 0 0 1\n1 3 1 1... | 1,530,962,458 | 2,147,483,647 | Python 3 | OK | TESTS | 177 | 374 | 819,200 | n,m=map(int,input().split())
a=[];row=[];col=[]
for i in range(n):
a.append(list(map(int,input().split())))
if m>n:
for i in range(n):
row.append(min(a[i]))
for i in range(m):
col.append(a[0][i]-row[0])
else:
for i in range(m):
r=1000
for j in range(n):
r=min(r,a[j][i])
col.append(r)
for i in range(n):
row.append(a[i][0]-col[0])
for i in range(n):
for j in range(m):
if a[i][j]!=row[i]+col[j]:
exit(print(-1))
print(sum(row)+sum(col))
for i in range(n):
for j in range(row[i]):
print('row',i+1)
for i in range(m):
for j in range(col[i]):
print('col',i+1) | Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
On the way to school, Karen became fixated on the puzzle game on her phone!
The game is played as follows. In each level, you have a grid with *n* rows and *m* columns. Each cell originally contains the number 0.
One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.
To win the level, after all the moves, the number in the cell at the *i*-th row and *j*-th column should be equal to *g**i*,<=*j*.
Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!
Input Specification:
The first line of input contains two integers, *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=100), the number of rows and the number of columns in the grid, respectively.
The next *n* lines each contain *m* integers. In particular, the *j*-th integer in the *i*-th of these rows contains *g**i*,<=*j* (0<=β€<=*g**i*,<=*j*<=β€<=500).
Output Specification:
If there is an error and it is actually not possible to beat the level, output a single integer -1.
Otherwise, on the first line, output a single integer *k*, the minimum number of moves necessary to beat the level.
The next *k* lines should each contain one of the following, describing the moves in the order they must be done:
- row *x*, (1<=β€<=*x*<=β€<=*n*) describing a move of the form "choose the *x*-th row". - col *x*, (1<=β€<=*x*<=β€<=*m*) describing a move of the form "choose the *x*-th column".
If there are multiple optimal solutions, output any one of them.
Demo Input:
['3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1\n', '3 3\n0 0 0\n0 1 0\n0 0 0\n', '3 3\n1 1 1\n1 1 1\n1 1 1\n']
Demo Output:
['4\nrow 1\nrow 1\ncol 4\nrow 3\n', '-1\n', '3\nrow 1\nrow 2\nrow 3\n']
Note:
In the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level:
In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.
In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level:
Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | ```python
n,m=map(int,input().split())
a=[];row=[];col=[]
for i in range(n):
a.append(list(map(int,input().split())))
if m>n:
for i in range(n):
row.append(min(a[i]))
for i in range(m):
col.append(a[0][i]-row[0])
else:
for i in range(m):
r=1000
for j in range(n):
r=min(r,a[j][i])
col.append(r)
for i in range(n):
row.append(a[i][0]-col[0])
for i in range(n):
for j in range(m):
if a[i][j]!=row[i]+col[j]:
exit(print(-1))
print(sum(row)+sum(col))
for i in range(n):
for j in range(row[i]):
print('row',i+1)
for i in range(m):
for j in range(col[i]):
print('col',i+1)
``` | 3 | |
1,008 | A | Romaji | PROGRAMMING | 900 | [
"implementation",
"strings"
] | null | null | Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not.
Help Vitya find out if a word $s$ is Berlanese. | The first line of the input contains the string $s$ consisting of $|s|$ ($1\leq |s|\leq 100$) lowercase Latin letters. | Print "YES" (without quotes) if there is a vowel after every consonant except "n", otherwise print "NO".
You can print each letter in any case (upper or lower). | [
"sumimasen\n",
"ninja\n",
"codeforces\n"
] | [
"YES\n",
"YES\n",
"NO\n"
] | In the first and second samples, a vowel goes after each consonant except "n", so the word is Berlanese.
In the third sample, the consonant "c" goes after the consonant "r", and the consonant "s" stands on the end, so the word is not Berlanese. | 500 | [
{
"input": "sumimasen",
"output": "YES"
},
{
"input": "ninja",
"output": "YES"
},
{
"input": "codeforces",
"output": "NO"
},
{
"input": "auuaoonntanonnuewannnnpuuinniwoonennyolonnnvienonpoujinndinunnenannmuveoiuuhikucuziuhunnnmunzancenen",
"output": "YES"
},
{
"in... | 1,638,315,578 | 2,147,483,647 | Python 3 | OK | TESTS | 57 | 62 | 0 | string=input().lower()
consonants=['b','c','d','f','g','h','j','k','l','m','p','q','r','s','t','v','w','x','y','z']
vowels=['a','e','i','o','u']
ber='YES'
for n in range(len(string)-1):
if string[n] in consonants:
if string[n+1] not in vowels:
ber='NO'
if string[-1] in consonants:
ber='NO'
print(ber) | Title: Romaji
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not.
Help Vitya find out if a word $s$ is Berlanese.
Input Specification:
The first line of the input contains the string $s$ consisting of $|s|$ ($1\leq |s|\leq 100$) lowercase Latin letters.
Output Specification:
Print "YES" (without quotes) if there is a vowel after every consonant except "n", otherwise print "NO".
You can print each letter in any case (upper or lower).
Demo Input:
['sumimasen\n', 'ninja\n', 'codeforces\n']
Demo Output:
['YES\n', 'YES\n', 'NO\n']
Note:
In the first and second samples, a vowel goes after each consonant except "n", so the word is Berlanese.
In the third sample, the consonant "c" goes after the consonant "r", and the consonant "s" stands on the end, so the word is not Berlanese. | ```python
string=input().lower()
consonants=['b','c','d','f','g','h','j','k','l','m','p','q','r','s','t','v','w','x','y','z']
vowels=['a','e','i','o','u']
ber='YES'
for n in range(len(string)-1):
if string[n] in consonants:
if string[n+1] not in vowels:
ber='NO'
if string[-1] in consonants:
ber='NO'
print(ber)
``` | 3 | |
282 | A | Bit++ | PROGRAMMING | 800 | [
"implementation"
] | null | null | The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called *x*. Also, there are two operations:
- Operation ++ increases the value of variable *x* by 1. - Operation -- decreases the value of variable *x* by 1.
A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable *x*. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.
A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.
You're given a programme in language Bit++. The initial value of *x* is 0. Execute the programme and find its final value (the value of the variable when this programme is executed). | The first line contains a single integer *n* (1<=β€<=*n*<=β€<=150) β the number of statements in the programme.
Next *n* lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable *x* (denoted as letter Β«XΒ»). Thus, there are no empty statements. The operation and the variable can be written in any order. | Print a single integer β the final value of *x*. | [
"1\n++X\n",
"2\nX++\n--X\n"
] | [
"1\n",
"0\n"
] | none | 500 | [
{
"input": "1\n++X",
"output": "1"
},
{
"input": "2\nX++\n--X",
"output": "0"
},
{
"input": "3\n++X\n++X\n++X",
"output": "3"
},
{
"input": "2\n--X\n--X",
"output": "-2"
},
{
"input": "5\n++X\n--X\n++X\n--X\n--X",
"output": "-1"
},
{
"input": "28\nX--\... | 1,699,879,770 | 2,147,483,647 | Python 3 | OK | TESTS | 36 | 46 | 0 | #n is number of statement in the program
x=0
n=int(input())
for i in range(n):
stmt=input().lower()
if stmt=='++x' or stmt=='x++':
x+=1
elif stmt=='--x' or stmt=='x--':
x+=-1
print(x) | Title: Bit++
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called *x*. Also, there are two operations:
- Operation ++ increases the value of variable *x* by 1. - Operation -- decreases the value of variable *x* by 1.
A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable *x*. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.
A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.
You're given a programme in language Bit++. The initial value of *x* is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=150) β the number of statements in the programme.
Next *n* lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable *x* (denoted as letter Β«XΒ»). Thus, there are no empty statements. The operation and the variable can be written in any order.
Output Specification:
Print a single integer β the final value of *x*.
Demo Input:
['1\n++X\n', '2\nX++\n--X\n']
Demo Output:
['1\n', '0\n']
Note:
none | ```python
#n is number of statement in the program
x=0
n=int(input())
for i in range(n):
stmt=input().lower()
if stmt=='++x' or stmt=='x++':
x+=1
elif stmt=='--x' or stmt=='x--':
x+=-1
print(x)
``` | 3 | |
340 | C | Tourist Problem | PROGRAMMING | 1,600 | [
"combinatorics",
"implementation",
"math"
] | null | null | Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are *n* destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The *n* destinations are described by a non-negative integers sequence *a*1, *a*2, ..., *a**n*. The number *a**k* represents that the *k*th destination is at distance *a**k* kilometers from the starting point. No two destinations are located in the same place.
Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination.
The distance between destination located at kilometer *x* and next destination, located at kilometer *y*, is |*x*<=-<=*y*| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all *n* destinations and he doesn't visit a destination more than once.
Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. | The first line contains integer *n* (2<=β€<=*n*<=β€<=105). Next line contains *n* distinct integers *a*1, *a*2, ..., *a**n* (1<=β€<=*a**i*<=β€<=107). | Output two integers β the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. | [
"3\n2 3 5\n"
] | [
"22 3"
] | Consider 6 possible routes:
- [2, 3, 5]: total distance traveled: |2 β 0| + |3 β 2| + |5 β 3| = 5; - [2, 5, 3]: |2 β 0| + |5 β 2| + |3 β 5| = 7; - [3, 2, 5]: |3 β 0| + |2 β 3| + |5 β 2| = 7; - [3, 5, 2]: |3 β 0| + |5 β 3| + |2 β 5| = 8; - [5, 2, 3]: |5 β 0| + |2 β 5| + |3 β 2| = 9; - [5, 3, 2]: |5 β 0| + |3 β 5| + |2 β 3| = 8.
The average travel distance is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/29119d3733c79f70eb2d77186ac1606bf938508a.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ee9d5516ed2ca1d2b65ed21f8a64f58f94954c30.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ed5cc8cb7dd43cfb27f2459586062538e44de7bd.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | 2,000 | [
{
"input": "3\n2 3 5",
"output": "22 3"
},
{
"input": "4\n1 5 77 2",
"output": "547 4"
},
{
"input": "5\n3 3842 288 199 334",
"output": "35918 5"
},
{
"input": "7\n1 2 3 40 52 33 86",
"output": "255 1"
},
{
"input": "7\n1 10 100 1000 10000 1000000 10000000",
"... | 1,591,173,432 | 2,147,483,647 | Python 3 | OK | TESTS | 43 | 528 | 7,577,600 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 3 11:57:46 2020
@author: shailesh
"""
from math import gcd
def reduce_fraction(x,y):
d = gcd(x,y)
x = x//d
y = y//d
return x,y
N = int(input())
A = [int(i) for i in input().split()]
A.sort()
d0 = A[0]
sum_val = 0
for i in range(N-1):
m_bf = i+2
m_af = N - i - 1
d = A[i+1]-A[i]
# d = 1
sum_val +=m_af*(2*m_bf - 1)*d
# print(A[i],A[i+1],sum_val)
numerator = N*d0 + sum_val
denominator = N
numerator,denominator = reduce_fraction(numerator,denominator)
print(numerator,denominator)
#from itertools import permutations
#perms = list(permutations([2,3,5]))
#
#perms = [(0,) + perm for perm in perms]
#
#d = {}
#d['02'] = 0
#d['23'] = 0
#d['35'] = 0
#for perm in perms:
# for i in range(len(perm)-1):
#
# start_end = [perm[i],perm[i+1]]
# start_end.sort()
# rng = range(start_end[0],start_end[1]+1)
# if 0 in rng and 2 in rng:
# d['02'] +=1
# if 2 in rng and 3 in rng:
# d['23'] += 1
# if 3 in rng and 5 in rng:
# d['35'] +=1
| Title: Tourist Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are *n* destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The *n* destinations are described by a non-negative integers sequence *a*1, *a*2, ..., *a**n*. The number *a**k* represents that the *k*th destination is at distance *a**k* kilometers from the starting point. No two destinations are located in the same place.
Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination.
The distance between destination located at kilometer *x* and next destination, located at kilometer *y*, is |*x*<=-<=*y*| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all *n* destinations and he doesn't visit a destination more than once.
Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.
Input Specification:
The first line contains integer *n* (2<=β€<=*n*<=β€<=105). Next line contains *n* distinct integers *a*1, *a*2, ..., *a**n* (1<=β€<=*a**i*<=β€<=107).
Output Specification:
Output two integers β the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible.
Demo Input:
['3\n2 3 5\n']
Demo Output:
['22 3']
Note:
Consider 6 possible routes:
- [2, 3, 5]: total distance traveled: |2 β 0| + |3 β 2| + |5 β 3| = 5; - [2, 5, 3]: |2 β 0| + |5 β 2| + |3 β 5| = 7; - [3, 2, 5]: |3 β 0| + |2 β 3| + |5 β 2| = 7; - [3, 5, 2]: |3 β 0| + |5 β 3| + |2 β 5| = 8; - [5, 2, 3]: |5 β 0| + |2 β 5| + |3 β 2| = 9; - [5, 3, 2]: |5 β 0| + |3 β 5| + |2 β 3| = 8.
The average travel distance is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/29119d3733c79f70eb2d77186ac1606bf938508a.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ee9d5516ed2ca1d2b65ed21f8a64f58f94954c30.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ed5cc8cb7dd43cfb27f2459586062538e44de7bd.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | ```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 3 11:57:46 2020
@author: shailesh
"""
from math import gcd
def reduce_fraction(x,y):
d = gcd(x,y)
x = x//d
y = y//d
return x,y
N = int(input())
A = [int(i) for i in input().split()]
A.sort()
d0 = A[0]
sum_val = 0
for i in range(N-1):
m_bf = i+2
m_af = N - i - 1
d = A[i+1]-A[i]
# d = 1
sum_val +=m_af*(2*m_bf - 1)*d
# print(A[i],A[i+1],sum_val)
numerator = N*d0 + sum_val
denominator = N
numerator,denominator = reduce_fraction(numerator,denominator)
print(numerator,denominator)
#from itertools import permutations
#perms = list(permutations([2,3,5]))
#
#perms = [(0,) + perm for perm in perms]
#
#d = {}
#d['02'] = 0
#d['23'] = 0
#d['35'] = 0
#for perm in perms:
# for i in range(len(perm)-1):
#
# start_end = [perm[i],perm[i+1]]
# start_end.sort()
# rng = range(start_end[0],start_end[1]+1)
# if 0 in rng and 2 in rng:
# d['02'] +=1
# if 2 in rng and 3 in rng:
# d['23'] += 1
# if 3 in rng and 5 in rng:
# d['35'] +=1
``` | 3 | |
894 | A | QAQ | PROGRAMMING | 800 | [
"brute force",
"dp"
] | null | null | "QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact. | The only line contains a string of length *n* (1<=β€<=*n*<=β€<=100). It's guaranteed that the string only contains uppercase English letters. | Print a single integerΒ β the number of subsequences "QAQ" in the string. | [
"QAQAQYSYIOIWIN\n",
"QAQQQZZYNOIWIN\n"
] | [
"4\n",
"3\n"
] | In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | 500 | [
{
"input": "QAQAQYSYIOIWIN",
"output": "4"
},
{
"input": "QAQQQZZYNOIWIN",
"output": "3"
},
{
"input": "QA",
"output": "0"
},
{
"input": "IAQVAQZLQBQVQFTQQQADAQJA",
"output": "24"
},
{
"input": "QQAAQASGAYAAAAKAKAQIQEAQAIAAIAQQQQQ",
"output": "378"
},
{
... | 1,671,476,320 | 2,147,483,647 | PyPy 3 | OK | TESTS | 43 | 93 | 1,536,000 | a = input()
n = len(a)
c = 0
for i in range(n):
if a[i] == 'Q':
for j in range(i + 1, n):
if a[j] == 'A':
for k in range(j + 1, n):
if a[k] == 'Q':
c += 1
print(c) | Title: QAQ
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
Input Specification:
The only line contains a string of length *n* (1<=β€<=*n*<=β€<=100). It's guaranteed that the string only contains uppercase English letters.
Output Specification:
Print a single integerΒ β the number of subsequences "QAQ" in the string.
Demo Input:
['QAQAQYSYIOIWIN\n', 'QAQQQZZYNOIWIN\n']
Demo Output:
['4\n', '3\n']
Note:
In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | ```python
a = input()
n = len(a)
c = 0
for i in range(n):
if a[i] == 'Q':
for j in range(i + 1, n):
if a[j] == 'A':
for k in range(j + 1, n):
if a[k] == 'Q':
c += 1
print(c)
``` | 3 | |
625 | C | K-special Tables | PROGRAMMING | 1,300 | [
"constructive algorithms",
"implementation"
] | null | null | People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of *k*-special tables. In case you forget, the table *n*<=Γ<=*n* is called *k*-special if the following three conditions are satisfied:
- every integer from 1 to *n*2 appears in the table exactly once; - in each row numbers are situated in increasing order; - the sum of numbers in the *k*-th column is maximum possible.
Your goal is to help Alice and find at least one *k*-special table of size *n*<=Γ<=*n*. Both rows and columns are numbered from 1 to *n*, with rows numbered from top to bottom and columns numbered from left to right. | The first line of the input contains two integers *n* and *k* (1<=β€<=*n*<=β€<=500,<=1<=β€<=*k*<=β€<=*n*)Β β the size of the table Alice is looking for and the column that should have maximum possible sum. | First print the sum of the integers in the *k*-th column of the required table.
Next *n* lines should contain the description of the table itself: first line should contains *n* elements of the first row, second line should contain *n* elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any. | [
"4 1\n",
"5 3\n"
] | [
"28\n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n",
"85\n5 6 17 18 19\n9 10 23 24 25\n7 8 20 21 22\n3 4 14 15 16\n1 2 11 12 13\n\n"
] | none | 1,000 | [
{
"input": "4 1",
"output": "28\n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16"
},
{
"input": "5 3",
"output": "85\n1 2 11 12 13\n3 4 14 15 16\n5 6 17 18 19\n7 8 20 21 22\n9 10 23 24 25"
},
{
"input": "1 1",
"output": "1\n1"
},
{
"input": "2 1",
"output": "4\n1 2\n3 4"
},
... | 1,657,818,548 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 52 | 93 | 4,608,000 | import sys
input = sys.stdin.readline
n, k = map(int, input().split())
d = [[0]*n for _ in range(n)]
x = (k-1)*n + 1
c = 1
if k > 1:
for i in range(n):
for j in range(k-1):
d[i][j] = c
c += 1
for i in range(n):
for j in range(k-1, n):
d[i][j] = c
c += 1
print(sum(d[i][k-1] for i in range(n)))
for i in d:
print(' '.join(map(str, i))) | Title: K-special Tables
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of *k*-special tables. In case you forget, the table *n*<=Γ<=*n* is called *k*-special if the following three conditions are satisfied:
- every integer from 1 to *n*2 appears in the table exactly once; - in each row numbers are situated in increasing order; - the sum of numbers in the *k*-th column is maximum possible.
Your goal is to help Alice and find at least one *k*-special table of size *n*<=Γ<=*n*. Both rows and columns are numbered from 1 to *n*, with rows numbered from top to bottom and columns numbered from left to right.
Input Specification:
The first line of the input contains two integers *n* and *k* (1<=β€<=*n*<=β€<=500,<=1<=β€<=*k*<=β€<=*n*)Β β the size of the table Alice is looking for and the column that should have maximum possible sum.
Output Specification:
First print the sum of the integers in the *k*-th column of the required table.
Next *n* lines should contain the description of the table itself: first line should contains *n* elements of the first row, second line should contain *n* elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Demo Input:
['4 1\n', '5 3\n']
Demo Output:
['28\n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n', '85\n5 6 17 18 19\n9 10 23 24 25\n7 8 20 21 22\n3 4 14 15 16\n1 2 11 12 13\n\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
d = [[0]*n for _ in range(n)]
x = (k-1)*n + 1
c = 1
if k > 1:
for i in range(n):
for j in range(k-1):
d[i][j] = c
c += 1
for i in range(n):
for j in range(k-1, n):
d[i][j] = c
c += 1
print(sum(d[i][k-1] for i in range(n)))
for i in d:
print(' '.join(map(str, i)))
``` | 3 | |
1,006 | A | Adjacent Replacements | PROGRAMMING | 800 | [
"implementation"
] | null | null | Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
- Replace each occurrence of $1$ in the array $a$ with $2$; - Replace each occurrence of $2$ in the array $a$ with $1$; - Replace each occurrence of $3$ in the array $a$ with $4$; - Replace each occurrence of $4$ in the array $a$ with $3$; - Replace each occurrence of $5$ in the array $a$ with $6$; - Replace each occurrence of $6$ in the array $a$ with $5$; - $\dots$ - Replace each occurrence of $10^9 - 1$ in the array $a$ with $10^9$; - Replace each occurrence of $10^9$ in the array $a$ with $10^9 - 1$.
Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($2i - 1, 2i$) for each $i \in\{1, 2, \ldots, 5 \cdot 10^8\}$ as described above.
For example, for the array $a = [1, 2, 4, 5, 10]$, the following sequence of arrays represents the algorithm:
$[1, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $1$ with $2$) $\rightarrow$ $[2, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $2$ with $1$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $3$ with $4$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $4$ with $3$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $5$ with $6$) $\rightarrow$ $[1, 1, 3, 6, 10]$ $\rightarrow$ (replace all occurrences of $6$ with $5$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ $\dots$ $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $10$ with $9$) $\rightarrow$ $[1, 1, 3, 5, 9]$. The later steps of the algorithm do not change the array.
Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it. | The first line of the input contains one integer number $n$ ($1 \le n \le 1000$) β the number of elements in Mishka's birthday present (surprisingly, an array).
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) β the elements of the array. | Print $n$ integers β $b_1, b_2, \dots, b_n$, where $b_i$ is the final value of the $i$-th element of the array after applying "Mishka's Adjacent Replacements Algorithm" to the array $a$. Note that you cannot change the order of elements in the array. | [
"5\n1 2 4 5 10\n",
"10\n10000 10 50605065 1 5 89 5 999999999 60506056 1000000000\n"
] | [
"1 1 3 5 9\n",
"9999 9 50605065 1 5 89 5 999999999 60506055 999999999\n"
] | The first example is described in the problem statement. | 0 | [
{
"input": "5\n1 2 4 5 10",
"output": "1 1 3 5 9"
},
{
"input": "10\n10000 10 50605065 1 5 89 5 999999999 60506056 1000000000",
"output": "9999 9 50605065 1 5 89 5 999999999 60506055 999999999"
},
{
"input": "1\n999999999",
"output": "999999999"
},
{
"input": "1\n1000000000",... | 1,598,864,624 | 2,147,483,647 | Python 3 | OK | TESTS | 18 | 93 | 6,963,200 | n = int(input())
a = [int(s) for s in input().split(' ')]
b = [str(c - ((c + 1) % 2)) for c in a]
print(' '.join(b))
| Title: Adjacent Replacements
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
- Replace each occurrence of $1$ in the array $a$ with $2$; - Replace each occurrence of $2$ in the array $a$ with $1$; - Replace each occurrence of $3$ in the array $a$ with $4$; - Replace each occurrence of $4$ in the array $a$ with $3$; - Replace each occurrence of $5$ in the array $a$ with $6$; - Replace each occurrence of $6$ in the array $a$ with $5$; - $\dots$ - Replace each occurrence of $10^9 - 1$ in the array $a$ with $10^9$; - Replace each occurrence of $10^9$ in the array $a$ with $10^9 - 1$.
Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($2i - 1, 2i$) for each $i \in\{1, 2, \ldots, 5 \cdot 10^8\}$ as described above.
For example, for the array $a = [1, 2, 4, 5, 10]$, the following sequence of arrays represents the algorithm:
$[1, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $1$ with $2$) $\rightarrow$ $[2, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $2$ with $1$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $3$ with $4$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $4$ with $3$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $5$ with $6$) $\rightarrow$ $[1, 1, 3, 6, 10]$ $\rightarrow$ (replace all occurrences of $6$ with $5$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ $\dots$ $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $10$ with $9$) $\rightarrow$ $[1, 1, 3, 5, 9]$. The later steps of the algorithm do not change the array.
Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.
Input Specification:
The first line of the input contains one integer number $n$ ($1 \le n \le 1000$) β the number of elements in Mishka's birthday present (surprisingly, an array).
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) β the elements of the array.
Output Specification:
Print $n$ integers β $b_1, b_2, \dots, b_n$, where $b_i$ is the final value of the $i$-th element of the array after applying "Mishka's Adjacent Replacements Algorithm" to the array $a$. Note that you cannot change the order of elements in the array.
Demo Input:
['5\n1 2 4 5 10\n', '10\n10000 10 50605065 1 5 89 5 999999999 60506056 1000000000\n']
Demo Output:
['1 1 3 5 9\n', '9999 9 50605065 1 5 89 5 999999999 60506055 999999999\n']
Note:
The first example is described in the problem statement. | ```python
n = int(input())
a = [int(s) for s in input().split(' ')]
b = [str(c - ((c + 1) % 2)) for c in a]
print(' '.join(b))
``` | 3 | |
443 | A | Anton and Letters | PROGRAMMING | 800 | [
"constructive algorithms",
"implementation"
] | null | null | Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set. | The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space. | Print a single number β the number of distinct letters in Anton's set. | [
"{a, b, c}\n",
"{b, a, b, a}\n",
"{}\n"
] | [
"3\n",
"2\n",
"0\n"
] | none | 500 | [
{
"input": "{a, b, c}",
"output": "3"
},
{
"input": "{b, a, b, a}",
"output": "2"
},
{
"input": "{}",
"output": "0"
},
{
"input": "{a, a, c, b, b, b, c, c, c, c}",
"output": "3"
},
{
"input": "{a, c, b, b}",
"output": "3"
},
{
"input": "{a, b}",
"o... | 1,692,772,851 | 2,147,483,647 | PyPy 3 | OK | TESTS | 27 | 93 | 0 | a = input()
p=[]
for i in a:
if(i.isalpha()==True):
p.append(i)
s=list(set(p))
print(len(s)) | Title: Anton and Letters
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.
Input Specification:
The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.
Output Specification:
Print a single number β the number of distinct letters in Anton's set.
Demo Input:
['{a, b, c}\n', '{b, a, b, a}\n', '{}\n']
Demo Output:
['3\n', '2\n', '0\n']
Note:
none | ```python
a = input()
p=[]
for i in a:
if(i.isalpha()==True):
p.append(i)
s=list(set(p))
print(len(s))
``` | 3 | |
805 | B | 3-palindrome | PROGRAMMING | 1,000 | [
"constructive algorithms"
] | null | null | In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given *n* he wants to obtain a string of *n* characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible. | The first line contains single integer *n* (1<=β€<=*n*<=β€<=2Β·105)Β β the length of the string. | Print the string that satisfies all the constraints.
If there are multiple answers, print any of them. | [
"2\n",
"3\n"
] | [
"aa\n",
"bba\n"
] | A palindrome is a sequence of characters which reads the same backward and forward. | 1,000 | [
{
"input": "2",
"output": "aa"
},
{
"input": "3",
"output": "aab"
},
{
"input": "38",
"output": "aabbaabbaabbaabbaabbaabbaabbaabbaabbaa"
},
{
"input": "47",
"output": "aabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaab"
},
{
"input": "59",
"output": "aabbaabbaabb... | 1,602,629,518 | 418 | Python 3 | OK | TESTS | 42 | 108 | 409,600 | n = int(input())
s = 'bbaa' * (n // 4 + 1)
s = s[:n]
print(s) | Title: 3-palindrome
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given *n* he wants to obtain a string of *n* characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.
Input Specification:
The first line contains single integer *n* (1<=β€<=*n*<=β€<=2Β·105)Β β the length of the string.
Output Specification:
Print the string that satisfies all the constraints.
If there are multiple answers, print any of them.
Demo Input:
['2\n', '3\n']
Demo Output:
['aa\n', 'bba\n']
Note:
A palindrome is a sequence of characters which reads the same backward and forward. | ```python
n = int(input())
s = 'bbaa' * (n // 4 + 1)
s = s[:n]
print(s)
``` | 3 | |
242 | B | Big Segment | PROGRAMMING | 1,100 | [
"implementation",
"sortings"
] | null | null | A coordinate line has *n* segments, the *i*-th segment starts at the position *l**i* and ends at the position *r**i*. We will denote such a segment as [*l**i*,<=*r**i*].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.
Formally we will assume that segment [*a*,<=*b*] covers segment [*c*,<=*d*], if they meet this condition *a*<=β€<=*c*<=β€<=*d*<=β€<=*b*. | The first line contains integer *n* (1<=β€<=*n*<=β€<=105) β the number of segments. Next *n* lines contain the descriptions of the segments. The *i*-th line contains two space-separated integers *l**i*,<=*r**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=109) β the borders of the *i*-th segment.
It is guaranteed that no two segments coincide. | Print a single integer β the number of the segment that covers all other segments in the set. If there's no solution, print -1.
The segments are numbered starting from 1 in the order in which they appear in the input. | [
"3\n1 1\n2 2\n3 3\n",
"6\n1 5\n2 3\n1 10\n7 10\n7 7\n10 10\n"
] | [
"-1\n",
"3\n"
] | none | 1,000 | [
{
"input": "3\n1 1\n2 2\n3 3",
"output": "-1"
},
{
"input": "6\n1 5\n2 3\n1 10\n7 10\n7 7\n10 10",
"output": "3"
},
{
"input": "4\n1 5\n2 2\n2 4\n2 5",
"output": "1"
},
{
"input": "5\n3 3\n1 3\n2 2\n2 3\n1 2",
"output": "2"
},
{
"input": "7\n7 7\n8 8\n3 7\n1 6\n1 ... | 1,585,860,422 | 2,147,483,647 | PyPy 3 | OK | TESTS | 45 | 1,902 | 16,076,800 | n=int(input())
L=[]
aG=0;
mini = 1000000000
maxi = -1000000000;
for i in range(0,n):
a=input().rstrip().split(' ')
L.append(a)
if int(a[0])<=mini and int(a[1])>=maxi:
G=int(a[0]);
H=int(a[1]);
S=i;
mini = int(a[0])
maxi = int(a[1])
#print(S,mini,maxi)
for i in range(0,len(L)):
A=L[i];
# print(A)
if int(A[0])>=mini and int(A[0])<=maxi and int(A[1])>=mini and int(A[1]) <= maxi:
continue;
else:
aG=1;
break;
# print(i)
if aG==1:
print(-1)
else:
print(S+1); | Title: Big Segment
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A coordinate line has *n* segments, the *i*-th segment starts at the position *l**i* and ends at the position *r**i*. We will denote such a segment as [*l**i*,<=*r**i*].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.
Formally we will assume that segment [*a*,<=*b*] covers segment [*c*,<=*d*], if they meet this condition *a*<=β€<=*c*<=β€<=*d*<=β€<=*b*.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=105) β the number of segments. Next *n* lines contain the descriptions of the segments. The *i*-th line contains two space-separated integers *l**i*,<=*r**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=109) β the borders of the *i*-th segment.
It is guaranteed that no two segments coincide.
Output Specification:
Print a single integer β the number of the segment that covers all other segments in the set. If there's no solution, print -1.
The segments are numbered starting from 1 in the order in which they appear in the input.
Demo Input:
['3\n1 1\n2 2\n3 3\n', '6\n1 5\n2 3\n1 10\n7 10\n7 7\n10 10\n']
Demo Output:
['-1\n', '3\n']
Note:
none | ```python
n=int(input())
L=[]
aG=0;
mini = 1000000000
maxi = -1000000000;
for i in range(0,n):
a=input().rstrip().split(' ')
L.append(a)
if int(a[0])<=mini and int(a[1])>=maxi:
G=int(a[0]);
H=int(a[1]);
S=i;
mini = int(a[0])
maxi = int(a[1])
#print(S,mini,maxi)
for i in range(0,len(L)):
A=L[i];
# print(A)
if int(A[0])>=mini and int(A[0])<=maxi and int(A[1])>=mini and int(A[1]) <= maxi:
continue;
else:
aG=1;
break;
# print(i)
if aG==1:
print(-1)
else:
print(S+1);
``` | 3 | |
946 | A | Partition | PROGRAMMING | 800 | [
"greedy"
] | null | null | You are given a sequence *a* consisting of *n* integers. You may partition this sequence into two sequences *b* and *c* in such a way that every element belongs exactly to one of these sequences.
Let *B* be the sum of elements belonging to *b*, and *C* be the sum of elements belonging to *c* (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of *B*<=-<=*C*? | The first line contains one integer *n* (1<=β€<=*n*<=β€<=100) β the number of elements in *a*.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (<=-<=100<=β€<=*a**i*<=β€<=100) β the elements of sequence *a*. | Print the maximum possible value of *B*<=-<=*C*, where *B* is the sum of elements of sequence *b*, and *C* is the sum of elements of sequence *c*. | [
"3\n1 -2 0\n",
"6\n16 23 16 15 42 8\n"
] | [
"3\n",
"120\n"
] | In the first example we may choose *b*β=β{1,β0}, *c*β=β{β-β2}. Then *B*β=β1, *C*β=ββ-β2, *B*β-β*C*β=β3.
In the second example we choose *b*β=β{16,β23,β16,β15,β42,β8}, *c*β=β{} (an empty sequence). Then *B*β=β120, *C*β=β0, *B*β-β*C*β=β120. | 0 | [
{
"input": "3\n1 -2 0",
"output": "3"
},
{
"input": "6\n16 23 16 15 42 8",
"output": "120"
},
{
"input": "1\n-1",
"output": "1"
},
{
"input": "100\n-100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -100 -10... | 1,580,799,944 | 2,147,483,647 | Python 3 | OK | TESTS | 72 | 109 | 0 | n = int(input())
b, c = 0, 0
for i in map(int, input().split()):
if i < 0:
c += i
else:
b += i
print(b - c)
| Title: Partition
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a sequence *a* consisting of *n* integers. You may partition this sequence into two sequences *b* and *c* in such a way that every element belongs exactly to one of these sequences.
Let *B* be the sum of elements belonging to *b*, and *C* be the sum of elements belonging to *c* (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of *B*<=-<=*C*?
Input Specification:
The first line contains one integer *n* (1<=β€<=*n*<=β€<=100) β the number of elements in *a*.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (<=-<=100<=β€<=*a**i*<=β€<=100) β the elements of sequence *a*.
Output Specification:
Print the maximum possible value of *B*<=-<=*C*, where *B* is the sum of elements of sequence *b*, and *C* is the sum of elements of sequence *c*.
Demo Input:
['3\n1 -2 0\n', '6\n16 23 16 15 42 8\n']
Demo Output:
['3\n', '120\n']
Note:
In the first example we may choose *b*β=β{1,β0}, *c*β=β{β-β2}. Then *B*β=β1, *C*β=ββ-β2, *B*β-β*C*β=β3.
In the second example we choose *b*β=β{16,β23,β16,β15,β42,β8}, *c*β=β{} (an empty sequence). Then *B*β=β120, *C*β=β0, *B*β-β*C*β=β120. | ```python
n = int(input())
b, c = 0, 0
for i in map(int, input().split()):
if i < 0:
c += i
else:
b += i
print(b - c)
``` | 3 | |
802 | G | Fake News (easy) | PROGRAMMING | 800 | [
"implementation",
"strings"
] | null | null | As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it... | The first and only line of input contains a single nonempty string *s* of length at most 1000 composed of lowercase letters (a-z). | Output YES if the string *s* contains heidi as a subsequence and NO otherwise. | [
"abcheaibcdi\n",
"hiedi\n"
] | [
"YES",
"NO"
] | A string *s* contains another string *p* as a subsequence if it is possible to delete some characters from *s* and obtain *p*. | 0 | [
{
"input": "abcheaibcdi",
"output": "YES"
},
{
"input": "hiedi",
"output": "NO"
},
{
"input": "ihied",
"output": "NO"
},
{
"input": "diehi",
"output": "NO"
},
{
"input": "deiih",
"output": "NO"
},
{
"input": "iheid",
"output": "NO"
},
{
"in... | 1,633,725,431 | 2,147,483,647 | Python 3 | OK | TESTS | 58 | 62 | 6,758,400 | def main():
s = input()
heidi = "heidi"
j = 0
hasHeidi = 0
for i in s:
if(i == heidi[j]):
if(j < 4):
j += 1
else:
hasHeidi = 1
if(hasHeidi == 0):
print("NO")
else:
print("YES")
if __name__ == '__main__':
main()
| Title: Fake News (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...
Input Specification:
The first and only line of input contains a single nonempty string *s* of length at most 1000 composed of lowercase letters (a-z).
Output Specification:
Output YES if the string *s* contains heidi as a subsequence and NO otherwise.
Demo Input:
['abcheaibcdi\n', 'hiedi\n']
Demo Output:
['YES', 'NO']
Note:
A string *s* contains another string *p* as a subsequence if it is possible to delete some characters from *s* and obtain *p*. | ```python
def main():
s = input()
heidi = "heidi"
j = 0
hasHeidi = 0
for i in s:
if(i == heidi[j]):
if(j < 4):
j += 1
else:
hasHeidi = 1
if(hasHeidi == 0):
print("NO")
else:
print("YES")
if __name__ == '__main__':
main()
``` | 3 | |
278 | B | New Problem | PROGRAMMING | 1,500 | [
"brute force",
"strings"
] | null | null | Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems.
You've got the titles of *n* last problems β the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.
A substring *s*[*l*... *r*] (1<=β€<=*l*<=β€<=*r*<=β€<=|*s*|) of string *s*<==<=*s*1*s*2... *s*|*s*| (where |*s*| is the length of string *s*) is string *s**l**s**l*<=+<=1... *s**r*.
String *x*<==<=*x*1*x*2... *x**p* is lexicographically smaller than string *y*<==<=*y*1*y*2... *y**q*, if either *p*<=<<=*q* and *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**p*<==<=*y**p*, or there exists such number *r* (*r*<=<<=*p*,<=*r*<=<<=*q*), that *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**r*<==<=*y**r* and *x**r*<=+<=1<=<<=*y**r*<=+<=1. The string characters are compared by their ASCII codes. | The first line contains integer *n* (1<=β€<=*n*<=β€<=30) β the number of titles you've got to consider. Then follow *n* problem titles, one per line. Each title only consists of lowercase English letters (specifically, it doesn't contain any spaces) and has the length from 1 to 20, inclusive. | Print a string, consisting of lowercase English letters β the lexicographically minimum shortest original title. | [
"5\nthreehorses\ngoodsubstrings\nsecret\nprimematrix\nbeautifulyear\n",
"4\naa\nbdefghijklmn\nopqrstuvwxyz\nc\n"
] | [
"j\n",
"ab\n"
] | In the first sample the first 9 letters of the English alphabet (a, b, c, d, e, f, g, h, i) occur in the problem titles, so the answer is letter j.
In the second sample the titles contain 26 English letters, so the shortest original title cannot have length 1. Title aa occurs as a substring in the first title. | 1,000 | [
{
"input": "5\nthreehorses\ngoodsubstrings\nsecret\nprimematrix\nbeautifulyear",
"output": "j"
},
{
"input": "4\naa\nbdefghijklmn\nopqrstuvwxyz\nc",
"output": "ab"
},
{
"input": "1\na",
"output": "b"
},
{
"input": "1\nb",
"output": "a"
},
{
"input": "1\nz",
"o... | 1,571,597,995 | 2,147,483,647 | Python 3 | OK | TESTS | 33 | 248 | 0 | # from dust i have come, dust i will be
n = int(input())
a = []
for i in range(n):
x = input()
a.append(x)
arr = []
for i in range(26):
arr.append(chr(i + ord('a')))
for i in range(26):
for j in range(26):
arr.append(arr[i] + chr(j + ord('a')))
for i in range(len(arr)):
cnt = 0
for j in range(n):
if arr[i] not in a[j]:
cnt += 1
if cnt == n:
print(arr[i])
exit(0)
| Title: New Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems.
You've got the titles of *n* last problems β the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.
A substring *s*[*l*... *r*] (1<=β€<=*l*<=β€<=*r*<=β€<=|*s*|) of string *s*<==<=*s*1*s*2... *s*|*s*| (where |*s*| is the length of string *s*) is string *s**l**s**l*<=+<=1... *s**r*.
String *x*<==<=*x*1*x*2... *x**p* is lexicographically smaller than string *y*<==<=*y*1*y*2... *y**q*, if either *p*<=<<=*q* and *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**p*<==<=*y**p*, or there exists such number *r* (*r*<=<<=*p*,<=*r*<=<<=*q*), that *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**r*<==<=*y**r* and *x**r*<=+<=1<=<<=*y**r*<=+<=1. The string characters are compared by their ASCII codes.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=30) β the number of titles you've got to consider. Then follow *n* problem titles, one per line. Each title only consists of lowercase English letters (specifically, it doesn't contain any spaces) and has the length from 1 to 20, inclusive.
Output Specification:
Print a string, consisting of lowercase English letters β the lexicographically minimum shortest original title.
Demo Input:
['5\nthreehorses\ngoodsubstrings\nsecret\nprimematrix\nbeautifulyear\n', '4\naa\nbdefghijklmn\nopqrstuvwxyz\nc\n']
Demo Output:
['j\n', 'ab\n']
Note:
In the first sample the first 9 letters of the English alphabet (a, b, c, d, e, f, g, h, i) occur in the problem titles, so the answer is letter j.
In the second sample the titles contain 26 English letters, so the shortest original title cannot have length 1. Title aa occurs as a substring in the first title. | ```python
# from dust i have come, dust i will be
n = int(input())
a = []
for i in range(n):
x = input()
a.append(x)
arr = []
for i in range(26):
arr.append(chr(i + ord('a')))
for i in range(26):
for j in range(26):
arr.append(arr[i] + chr(j + ord('a')))
for i in range(len(arr)):
cnt = 0
for j in range(n):
if arr[i] not in a[j]:
cnt += 1
if cnt == n:
print(arr[i])
exit(0)
``` | 3 | |
805 | B | 3-palindrome | PROGRAMMING | 1,000 | [
"constructive algorithms"
] | null | null | In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given *n* he wants to obtain a string of *n* characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible. | The first line contains single integer *n* (1<=β€<=*n*<=β€<=2Β·105)Β β the length of the string. | Print the string that satisfies all the constraints.
If there are multiple answers, print any of them. | [
"2\n",
"3\n"
] | [
"aa\n",
"bba\n"
] | A palindrome is a sequence of characters which reads the same backward and forward. | 1,000 | [
{
"input": "2",
"output": "aa"
},
{
"input": "3",
"output": "aab"
},
{
"input": "38",
"output": "aabbaabbaabbaabbaabbaabbaabbaabbaabbaa"
},
{
"input": "47",
"output": "aabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaab"
},
{
"input": "59",
"output": "aabbaabbaabb... | 1,596,355,058 | 2,147,483,647 | PyPy 3 | OK | TESTS | 42 | 155 | 21,196,800 | n = int(input())
thingo=["a","a","b","b"]
print(int(n/4)*"aabb" + "".join(thingo[:n%4])) | Title: 3-palindrome
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given *n* he wants to obtain a string of *n* characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.
Input Specification:
The first line contains single integer *n* (1<=β€<=*n*<=β€<=2Β·105)Β β the length of the string.
Output Specification:
Print the string that satisfies all the constraints.
If there are multiple answers, print any of them.
Demo Input:
['2\n', '3\n']
Demo Output:
['aa\n', 'bba\n']
Note:
A palindrome is a sequence of characters which reads the same backward and forward. | ```python
n = int(input())
thingo=["a","a","b","b"]
print(int(n/4)*"aabb" + "".join(thingo[:n%4]))
``` | 3 | |
129 | A | Cookies | PROGRAMMING | 900 | [
"implementation"
] | null | null | Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even? | The first line contains the only integer *n* (1<=β€<=*n*<=β€<=100) β the number of cookie bags Anna and Maria have. The second line contains *n* integers *a**i* (1<=β€<=*a**i*<=β€<=100) β the number of cookies in the *i*-th bag. | Print in the only line the only number β the sought number of ways. If there are no such ways print 0. | [
"1\n1\n",
"10\n1 2 2 3 4 4 4 2 2 2\n",
"11\n2 2 2 2 2 2 2 2 2 2 99\n"
] | [
"1\n",
"8\n",
"1\n"
] | In the first sample Olga should take the only bag so that the twins ended up with the even number of cookies.
In the second sample Olga can take any of five bags with two cookies or any of three bags with four cookies β 5β+β3β=β8 ways in total.
In the third sample, no matter which bag with two cookies Olga chooses, the twins are left with 2β*β9β+β99β=β117 cookies. Thus, Olga has only one option: to take the bag with 99 cookies. | 500 | [
{
"input": "1\n1",
"output": "1"
},
{
"input": "10\n1 2 2 3 4 4 4 2 2 2",
"output": "8"
},
{
"input": "11\n2 2 2 2 2 2 2 2 2 2 99",
"output": "1"
},
{
"input": "2\n1 1",
"output": "0"
},
{
"input": "2\n2 2",
"output": "2"
},
{
"input": "2\n1 2",
"o... | 1,656,272,331 | 2,147,483,647 | Python 3 | OK | TESTS | 52 | 92 | 4,505,600 | n = int(input())
a = [int(i) for i in input().split()]
x = sum(a)
counter = 0
for i in range(len(a)):
difference = x - a[i]
if difference % 2 == 0:
counter = counter + 1
print(counter) | Title: Cookies
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?
Input Specification:
The first line contains the only integer *n* (1<=β€<=*n*<=β€<=100) β the number of cookie bags Anna and Maria have. The second line contains *n* integers *a**i* (1<=β€<=*a**i*<=β€<=100) β the number of cookies in the *i*-th bag.
Output Specification:
Print in the only line the only number β the sought number of ways. If there are no such ways print 0.
Demo Input:
['1\n1\n', '10\n1 2 2 3 4 4 4 2 2 2\n', '11\n2 2 2 2 2 2 2 2 2 2 99\n']
Demo Output:
['1\n', '8\n', '1\n']
Note:
In the first sample Olga should take the only bag so that the twins ended up with the even number of cookies.
In the second sample Olga can take any of five bags with two cookies or any of three bags with four cookies β 5β+β3β=β8 ways in total.
In the third sample, no matter which bag with two cookies Olga chooses, the twins are left with 2β*β9β+β99β=β117 cookies. Thus, Olga has only one option: to take the bag with 99 cookies. | ```python
n = int(input())
a = [int(i) for i in input().split()]
x = sum(a)
counter = 0
for i in range(len(a)):
difference = x - a[i]
if difference % 2 == 0:
counter = counter + 1
print(counter)
``` | 3 | |
750 | A | New Year and Hurry | PROGRAMMING | 800 | [
"binary search",
"brute force",
"implementation",
"math"
] | null | null | Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5Β·*i* minutes to solve the *i*-th problem.
Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs *k* minutes to get there from his house, where he will participate in the contest first.
How many problems can Limak solve if he wants to make it to the party? | The only line of the input contains two integers *n* and *k* (1<=β€<=*n*<=β€<=10, 1<=β€<=*k*<=β€<=240)Β β the number of the problems in the contest and the number of minutes Limak needs to get to the party from his house. | Print one integer, denoting the maximum possible number of problems Limak can solve so that he could get to the party at midnight or earlier. | [
"3 222\n",
"4 190\n",
"7 1\n"
] | [
"2\n",
"4\n",
"7\n"
] | In the first sample, there are 3 problems and Limak needs 222 minutes to get to the party. The three problems require 5, 10 and 15 minutes respectively. Limak can spend 5β+β10β=β15 minutes to solve first two problems. Then, at 20:15 he can leave his house to get to the party at 23:57 (after 222 minutes). In this scenario Limak would solve 2 problems. He doesn't have enough time to solve 3 problems so the answer is 2.
In the second sample, Limak can solve all 4 problems in 5β+β10β+β15β+β20β=β50 minutes. At 20:50 he will leave the house and go to the party. He will get there exactly at midnight.
In the third sample, Limak needs only 1 minute to get to the party. He has enough time to solve all 7 problems. | 500 | [
{
"input": "3 222",
"output": "2"
},
{
"input": "4 190",
"output": "4"
},
{
"input": "7 1",
"output": "7"
},
{
"input": "10 135",
"output": "6"
},
{
"input": "10 136",
"output": "5"
},
{
"input": "1 1",
"output": "1"
},
{
"input": "1 240",
... | 1,700,313,373 | 2,147,483,647 | Python 3 | OK | TESTS | 52 | 46 | 0 | Q, min = input().split()
QsolvinTime = 0
count = 0
qmin = 5
for i in range(int(Q)):
QsolvinTime += qmin
if 240 - int(min) >= QsolvinTime:
qmin += 5
count += 1
else:
break
print(count) | Title: New Year and Hurry
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5Β·*i* minutes to solve the *i*-th problem.
Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs *k* minutes to get there from his house, where he will participate in the contest first.
How many problems can Limak solve if he wants to make it to the party?
Input Specification:
The only line of the input contains two integers *n* and *k* (1<=β€<=*n*<=β€<=10, 1<=β€<=*k*<=β€<=240)Β β the number of the problems in the contest and the number of minutes Limak needs to get to the party from his house.
Output Specification:
Print one integer, denoting the maximum possible number of problems Limak can solve so that he could get to the party at midnight or earlier.
Demo Input:
['3 222\n', '4 190\n', '7 1\n']
Demo Output:
['2\n', '4\n', '7\n']
Note:
In the first sample, there are 3 problems and Limak needs 222 minutes to get to the party. The three problems require 5, 10 and 15 minutes respectively. Limak can spend 5β+β10β=β15 minutes to solve first two problems. Then, at 20:15 he can leave his house to get to the party at 23:57 (after 222 minutes). In this scenario Limak would solve 2 problems. He doesn't have enough time to solve 3 problems so the answer is 2.
In the second sample, Limak can solve all 4 problems in 5β+β10β+β15β+β20β=β50 minutes. At 20:50 he will leave the house and go to the party. He will get there exactly at midnight.
In the third sample, Limak needs only 1 minute to get to the party. He has enough time to solve all 7 problems. | ```python
Q, min = input().split()
QsolvinTime = 0
count = 0
qmin = 5
for i in range(int(Q)):
QsolvinTime += qmin
if 240 - int(min) >= QsolvinTime:
qmin += 5
count += 1
else:
break
print(count)
``` | 3 | |
988 | A | Diverse Team | PROGRAMMING | 800 | [
"brute force",
"implementation"
] | null | null | There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \le k \le n$) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print $k$ distinct numbers which should be the indices of students in the team you form. If there are multiple answers, print any of them. | The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 100$) β the number of students and the size of the team you have to form.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$), where $a_i$ is the rating of $i$-th student. | If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print $k$ distinct integers from $1$ to $n$ which should be the indices of students in the team you form. All the ratings of the students in the team should be distinct. You may print the indices in any order. If there are multiple answers, print any of them.
Assume that the students are numbered from $1$ to $n$. | [
"5 3\n15 13 15 15 12\n",
"5 4\n15 13 15 15 12\n",
"4 4\n20 10 40 30\n"
] | [
"YES\n1 2 5 \n",
"NO\n",
"YES\n1 2 3 4 \n"
] | All possible answers for the first example:
- {1 2 5} - {2 3 5} - {2 4 5}
Note that the order does not matter. | 0 | [
{
"input": "5 3\n15 13 15 15 12",
"output": "YES\n1 2 5 "
},
{
"input": "5 4\n15 13 15 15 12",
"output": "NO"
},
{
"input": "4 4\n20 10 40 30",
"output": "YES\n1 2 3 4 "
},
{
"input": "1 1\n1",
"output": "YES\n1 "
},
{
"input": "100 53\n16 17 1 2 27 5 9 9 53 24 17... | 1,625,758,791 | 2,147,483,647 | Python 3 | OK | TESTS | 10 | 62 | 0 | n,k=map(int,input().split())
l=list(map(int,input().split()))
s=set()
for i in range(len(l)):
s.add(l[i])
l1=[i for i in s]
l2=[]
if len(s)>=k:
print("YES")
for i in range(k):
if(l1[i] in l):
l2.append(l.index(l1[i])+1)
l2.sort()
for i in range(len(l2)):
print(l2[i],end=' ')
else:
print("NO")
| Title: Diverse Team
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \le k \le n$) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print $k$ distinct numbers which should be the indices of students in the team you form. If there are multiple answers, print any of them.
Input Specification:
The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 100$) β the number of students and the size of the team you have to form.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$), where $a_i$ is the rating of $i$-th student.
Output Specification:
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print $k$ distinct integers from $1$ to $n$ which should be the indices of students in the team you form. All the ratings of the students in the team should be distinct. You may print the indices in any order. If there are multiple answers, print any of them.
Assume that the students are numbered from $1$ to $n$.
Demo Input:
['5 3\n15 13 15 15 12\n', '5 4\n15 13 15 15 12\n', '4 4\n20 10 40 30\n']
Demo Output:
['YES\n1 2 5 \n', 'NO\n', 'YES\n1 2 3 4 \n']
Note:
All possible answers for the first example:
- {1 2 5} - {2 3 5} - {2 4 5}
Note that the order does not matter. | ```python
n,k=map(int,input().split())
l=list(map(int,input().split()))
s=set()
for i in range(len(l)):
s.add(l[i])
l1=[i for i in s]
l2=[]
if len(s)>=k:
print("YES")
for i in range(k):
if(l1[i] in l):
l2.append(l.index(l1[i])+1)
l2.sort()
for i in range(len(l2)):
print(l2[i],end=' ')
else:
print("NO")
``` | 3 | |
246 | A | Buggy Sorting | PROGRAMMING | 900 | [
"constructive algorithms",
"greedy",
"sortings"
] | null | null | Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of *n* integers *a*1,<=*a*2,<=...,<=*a**n* in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number *n* and array *a*.
But Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of *n* doesn't exist, print -1. | You've got a single integer *n* (1<=β€<=*n*<=β€<=50) β the size of the sorted array. | Print *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=100) β the counter-example, for which Valera's algorithm won't work correctly. If the counter-example that meets the described conditions is impossible to give, print -1.
If there are several counter-examples, consisting of *n* numbers, you are allowed to print any of them. | [
"1\n"
] | [
"-1\n"
] | none | 500 | [
{
"input": "1",
"output": "-1"
},
{
"input": "2",
"output": "-1"
},
{
"input": "3",
"output": "3 2 1 "
},
{
"input": "4",
"output": "4 3 2 1 "
},
{
"input": "5",
"output": "5 4 3 2 1 "
},
{
"input": "6",
"output": "6 5 4 3 2 1 "
},
{
"input... | 1,676,717,806 | 2,147,483,647 | Python 3 | OK | TESTS | 21 | 46 | 0 | # LUOGU_RID: 102443681
n = int(input())
if n < 3:
print(-1)
else:
print(*range(n, 0, -1)) | Title: Buggy Sorting
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of *n* integers *a*1,<=*a*2,<=...,<=*a**n* in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number *n* and array *a*.
But Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of *n* doesn't exist, print -1.
Input Specification:
You've got a single integer *n* (1<=β€<=*n*<=β€<=50) β the size of the sorted array.
Output Specification:
Print *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=100) β the counter-example, for which Valera's algorithm won't work correctly. If the counter-example that meets the described conditions is impossible to give, print -1.
If there are several counter-examples, consisting of *n* numbers, you are allowed to print any of them.
Demo Input:
['1\n']
Demo Output:
['-1\n']
Note:
none | ```python
# LUOGU_RID: 102443681
n = int(input())
if n < 3:
print(-1)
else:
print(*range(n, 0, -1))
``` | 3 | |
544 | B | Sea and Islands | PROGRAMMING | 1,400 | [
"constructive algorithms",
"implementation"
] | null | null | A map of some object is a rectangular field consisting of *n* rows and *n* columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly *k* islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).
Find a way to cover some cells with sand so that exactly *k* islands appear on the *n*<=Γ<=*n* map, or determine that no such way exists. | The single line contains two positive integers *n*, *k* (1<=β€<=*n*<=β€<=100, 0<=β€<=*k*<=β€<=*n*2) β the size of the map and the number of islands you should form. | If the answer doesn't exist, print "NO" (without the quotes) in a single line.
Otherwise, print "YES" in the first line. In the next *n* lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal *n*.
If there are multiple answers, you may print any of them.
You should not maximize the sizes of islands. | [
"5 2\n",
"5 25\n"
] | [
"YES\nSSSSS\nLLLLL\nSSSSS\nLLLLL\nSSSSS\n",
"NO\n"
] | none | 1,000 | [
{
"input": "5 2",
"output": "YES\nSSSSS\nLLLLL\nSSSSS\nLLLLL\nSSSSS"
},
{
"input": "5 25",
"output": "NO"
},
{
"input": "82 6047",
"output": "NO"
},
{
"input": "6 5",
"output": "YES\nLSLSLS\nSLSLSS\nSSSSSS\nSSSSSS\nSSSSSS\nSSSSSS"
},
{
"input": "10 80",
"outpu... | 1,574,799,916 | 2,147,483,647 | Python 3 | OK | TESTS | 42 | 124 | 307,200 | import sys
input = sys.stdin.readline
read_tuple = lambda _type: map(_type, input().split(' '))
def solve():
n, k = read_tuple(int)
grid = [['S' for _ in range(n)] for _ in range(n)]
flag = True
for i in range(n):
for j in range(n):
if k and flag:
grid[i][j] = 'L'
k -= 1
flag ^= True
if n % 2 == 0:
flag ^= True
if k == 0:
print("YES")
else:
print("NO")
if k == 0:
for row in grid:
print(''.join(row))
if __name__ == '__main__':
solve()
| Title: Sea and Islands
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A map of some object is a rectangular field consisting of *n* rows and *n* columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly *k* islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).
Find a way to cover some cells with sand so that exactly *k* islands appear on the *n*<=Γ<=*n* map, or determine that no such way exists.
Input Specification:
The single line contains two positive integers *n*, *k* (1<=β€<=*n*<=β€<=100, 0<=β€<=*k*<=β€<=*n*2) β the size of the map and the number of islands you should form.
Output Specification:
If the answer doesn't exist, print "NO" (without the quotes) in a single line.
Otherwise, print "YES" in the first line. In the next *n* lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal *n*.
If there are multiple answers, you may print any of them.
You should not maximize the sizes of islands.
Demo Input:
['5 2\n', '5 25\n']
Demo Output:
['YES\nSSSSS\nLLLLL\nSSSSS\nLLLLL\nSSSSS\n', 'NO\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
read_tuple = lambda _type: map(_type, input().split(' '))
def solve():
n, k = read_tuple(int)
grid = [['S' for _ in range(n)] for _ in range(n)]
flag = True
for i in range(n):
for j in range(n):
if k and flag:
grid[i][j] = 'L'
k -= 1
flag ^= True
if n % 2 == 0:
flag ^= True
if k == 0:
print("YES")
else:
print("NO")
if k == 0:
for row in grid:
print(''.join(row))
if __name__ == '__main__':
solve()
``` | 3 | |
690 | F1 | Tree of Life (easy) | PROGRAMMING | 1,300 | [] | null | null | Heidi has finally found the mythical Tree of Life β a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies.
On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of *n* points (called vertices), some of which are connected using *n*<=-<=1 line segments (edges) so that each pair of vertices is connected by a path (a sequence of one or more edges).
To decipher the prophecy, Heidi needs to perform a number of steps. The first is counting the number of lifelines in the tree β these are paths of length 2, i.e., consisting of two edges. Help her! | The first line of the input contains a single integer *n* β the number of vertices in the tree (1<=β€<=*n*<=β€<=10000). The vertices are labeled with the numbers from 1 to *n*. Then *n*<=-<=1 lines follow, each describing one edge using two space-separated numbers *a*β*b* β the labels of the vertices connected by the edge (1<=β€<=*a*<=<<=*b*<=β€<=*n*). It is guaranteed that the input represents a tree. | Print one integer β the number of lifelines in the tree. | [
"4\n1 2\n1 3\n1 4\n",
"5\n1 2\n2 3\n3 4\n3 5\n"
] | [
"3",
"4"
] | In the second sample, there are four lifelines: paths between vertices 1 and 3, 2 and 4, 2 and 5, and 4 and 5. | 0 | [
{
"input": "4\n1 2\n1 3\n1 4",
"output": "3"
},
{
"input": "5\n1 2\n2 3\n3 4\n3 5",
"output": "4"
},
{
"input": "2\n1 2",
"output": "0"
},
{
"input": "3\n2 1\n3 2",
"output": "1"
},
{
"input": "10\n5 1\n1 2\n9 3\n10 5\n6 3\n8 5\n2 7\n2 3\n9 4",
"output": "11"
... | 1,490,269,770 | 2,147,483,647 | Python 3 | OK | TESTS | 19 | 93 | 4,812,800 | n = int(input())
t = [0] * n
out = 0
for _ in range(n-1):
a, b = input().split(' ')
a, b = [int(a), int(b)]
t[a-1] += 1
t[b-1] += 1
for x in t:
out += x * (x-1) / 2
print(int(out))
| Title: Tree of Life (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Heidi has finally found the mythical Tree of Life β a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies.
On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of *n* points (called vertices), some of which are connected using *n*<=-<=1 line segments (edges) so that each pair of vertices is connected by a path (a sequence of one or more edges).
To decipher the prophecy, Heidi needs to perform a number of steps. The first is counting the number of lifelines in the tree β these are paths of length 2, i.e., consisting of two edges. Help her!
Input Specification:
The first line of the input contains a single integer *n* β the number of vertices in the tree (1<=β€<=*n*<=β€<=10000). The vertices are labeled with the numbers from 1 to *n*. Then *n*<=-<=1 lines follow, each describing one edge using two space-separated numbers *a*β*b* β the labels of the vertices connected by the edge (1<=β€<=*a*<=<<=*b*<=β€<=*n*). It is guaranteed that the input represents a tree.
Output Specification:
Print one integer β the number of lifelines in the tree.
Demo Input:
['4\n1 2\n1 3\n1 4\n', '5\n1 2\n2 3\n3 4\n3 5\n']
Demo Output:
['3', '4']
Note:
In the second sample, there are four lifelines: paths between vertices 1 and 3, 2 and 4, 2 and 5, and 4 and 5. | ```python
n = int(input())
t = [0] * n
out = 0
for _ in range(n-1):
a, b = input().split(' ')
a, b = [int(a), int(b)]
t[a-1] += 1
t[b-1] += 1
for x in t:
out += x * (x-1) / 2
print(int(out))
``` | 3 | |
381 | A | Sereja and Dima | PROGRAMMING | 800 | [
"greedy",
"implementation",
"two pointers"
] | null | null | Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.
Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.
Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her. | The first line contains integer *n* (1<=β€<=*n*<=β€<=1000) β the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000. | On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game. | [
"4\n4 1 2 10\n",
"7\n1 2 3 4 5 6 7\n"
] | [
"12 5\n",
"16 12\n"
] | In the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5. | 500 | [
{
"input": "4\n4 1 2 10",
"output": "12 5"
},
{
"input": "7\n1 2 3 4 5 6 7",
"output": "16 12"
},
{
"input": "42\n15 29 37 22 16 5 26 31 6 32 19 3 45 36 33 14 25 20 48 7 42 11 24 28 9 18 8 21 47 17 38 40 44 4 35 1 43 39 41 27 12 13",
"output": "613 418"
},
{
"input": "43\n32 ... | 1,676,105,198 | 2,147,483,647 | Python 3 | OK | TESTS | 34 | 46 | 102,400 | from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
def main():
t = 1
# t = int(input())
for _ in range(t):
run_test_case()
def run_test_case():
n = int(input())
l = list(map(int, input().split()))
sereja = dima = 0
left, right = 0, n - 1
i = 0
while left <= right:
curMax = max(l[left], l[right])
if i % 2 == 0:
sereja += curMax
else:
dima += curMax
if l[left] > l[right]:
left += 1
else:
right -= 1
i += 1
print(sereja, dima)
if __name__ == "__main__":
main()
"""
/* stuff you should look for
* int overflow, array bounds
* special cases (n=1?)
* do smth instead of nothing and stay organized
* WRITE STUFF DOWN
* DON'T GET STUCK ON ONE APPROACH
*/
"""
| Title: Sereja and Dima
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.
Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.
Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=1000) β the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.
Output Specification:
On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.
Demo Input:
['4\n4 1 2 10\n', '7\n1 2 3 4 5 6 7\n']
Demo Output:
['12 5\n', '16 12\n']
Note:
In the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5. | ```python
from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
def main():
t = 1
# t = int(input())
for _ in range(t):
run_test_case()
def run_test_case():
n = int(input())
l = list(map(int, input().split()))
sereja = dima = 0
left, right = 0, n - 1
i = 0
while left <= right:
curMax = max(l[left], l[right])
if i % 2 == 0:
sereja += curMax
else:
dima += curMax
if l[left] > l[right]:
left += 1
else:
right -= 1
i += 1
print(sereja, dima)
if __name__ == "__main__":
main()
"""
/* stuff you should look for
* int overflow, array bounds
* special cases (n=1?)
* do smth instead of nothing and stay organized
* WRITE STUFF DOWN
* DON'T GET STUCK ON ONE APPROACH
*/
"""
``` | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.