contestId int64 0 1.01k | index stringclasses 57 values | name stringlengths 2 58 | type stringclasses 2 values | rating int64 0 3.5k | tags listlengths 0 11 | title stringclasses 522 values | time-limit stringclasses 8 values | memory-limit stringclasses 8 values | problem-description stringlengths 0 7.15k | input-specification stringlengths 0 2.05k | output-specification stringlengths 0 1.5k | demo-input listlengths 0 7 | demo-output listlengths 0 7 | note stringlengths 0 5.24k | points float64 0 425k | test_cases listlengths 0 402 | creationTimeSeconds int64 1.37B 1.7B | relativeTimeSeconds int64 8 2.15B | programmingLanguage stringclasses 3 values | verdict stringclasses 14 values | testset stringclasses 12 values | passedTestCount int64 0 1k | timeConsumedMillis int64 0 15k | memoryConsumedBytes int64 0 805M | code stringlengths 3 65.5k | prompt stringlengths 262 8.2k | response stringlengths 17 65.5k | score float64 -1 3.99 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
526 | C | Om Nom and Candies | PROGRAMMING | 2,000 | [
"brute force",
"greedy",
"math"
] | null | null | A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place?
One day, when he came to his friend Evan, Om Nom didn't find him at home but he found two bags with candies. The first was full of blue candies and the second bag was full of red candies. Om Nom knows that each red candy weighs *W**r* grams and each blue candy weighs *W**b* grams. Eating a single red candy gives Om Nom *H**r* joy units and eating a single blue candy gives Om Nom *H**b* joy units.
Candies are the most important thing in the world, but on the other hand overeating is not good. Om Nom knows if he eats more than *C* grams of candies, he will get sick. Om Nom thinks that it isn't proper to leave candy leftovers, so he can only eat a whole candy. Om Nom is a great mathematician and he quickly determined how many candies of what type he should eat in order to get the maximum number of joy units. Can you repeat his achievement? You can assume that each bag contains more candies that Om Nom can eat. | The single line contains five integers *C*,<=*H**r*,<=*H**b*,<=*W**r*,<=*W**b* (1<=≤<=*C*,<=*H**r*,<=*H**b*,<=*W**r*,<=*W**b*<=≤<=109). | Print a single integer — the maximum number of joy units that Om Nom can get. | [
"10 3 5 2 3\n"
] | [
"16\n"
] | In the sample test Om Nom can eat two candies of each type and thus get 16 joy units. | 1,250 | [
{
"input": "10 3 5 2 3",
"output": "16"
},
{
"input": "5 3 1 6 7",
"output": "0"
},
{
"input": "982068341 55 57 106 109",
"output": "513558662"
},
{
"input": "930064129 32726326 25428197 83013449 64501049",
"output": "363523396"
},
{
"input": "927155987 21197 1599... | 1,689,167,495 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 46 | 0 | print("_RANDOM_GUESS_1689167495.5827782")# 1689167495.582819 | Title: Om Nom and Candies
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place?
One day, when he came to his friend Evan, Om Nom didn't find him at home but he found two bags with candies. The first was full of blue candies and the second bag was full of red candies. Om Nom knows that each red candy weighs *W**r* grams and each blue candy weighs *W**b* grams. Eating a single red candy gives Om Nom *H**r* joy units and eating a single blue candy gives Om Nom *H**b* joy units.
Candies are the most important thing in the world, but on the other hand overeating is not good. Om Nom knows if he eats more than *C* grams of candies, he will get sick. Om Nom thinks that it isn't proper to leave candy leftovers, so he can only eat a whole candy. Om Nom is a great mathematician and he quickly determined how many candies of what type he should eat in order to get the maximum number of joy units. Can you repeat his achievement? You can assume that each bag contains more candies that Om Nom can eat.
Input Specification:
The single line contains five integers *C*,<=*H**r*,<=*H**b*,<=*W**r*,<=*W**b* (1<=≤<=*C*,<=*H**r*,<=*H**b*,<=*W**r*,<=*W**b*<=≤<=109).
Output Specification:
Print a single integer — the maximum number of joy units that Om Nom can get.
Demo Input:
['10 3 5 2 3\n']
Demo Output:
['16\n']
Note:
In the sample test Om Nom can eat two candies of each type and thus get 16 joy units. | ```python
print("_RANDOM_GUESS_1689167495.5827782")# 1689167495.582819
``` | 0 | |
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,632,507,312 | 2,147,483,647 | Python 3 | OK | TESTS | 43 | 77 | 6,758,400 | count = 0
string = input()
for i, char in enumerate(string):
if char == 'A':
count += string[:i].count('Q') * string[i:].count('Q')
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
count = 0
string = input()
for i, char in enumerate(string):
if char == 'A':
count += string[:i].count('Q') * string[i:].count('Q')
print(count)
``` | 3 | |
342 | C | Cupboard and Balloons | PROGRAMMING | 1,900 | [
"geometry"
] | null | null | A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius *r* (the cupboard's top) and two walls of height *h* (the cupboard's sides). The cupboard's depth is *r*, that is, it looks like a rectangle with base *r* and height *h*<=+<=*r* from the sides. The figure below shows what the cupboard looks like (the front view is on the left, the side view is on the right).
Xenia got lots of balloons for her birthday. The girl hates the mess, so she wants to store the balloons in the cupboard. Luckily, each balloon is a sphere with radius . Help Xenia calculate the maximum number of balloons she can put in her cupboard.
You can say that a balloon is in the cupboard if you can't see any part of the balloon on the left or right view. The balloons in the cupboard can touch each other. It is not allowed to squeeze the balloons or deform them in any way. You can assume that the cupboard's walls are negligibly thin. | The single line contains two integers *r*,<=*h* (1<=≤<=*r*,<=*h*<=≤<=107). | Print a single integer — the maximum number of balloons Xenia can put in the cupboard. | [
"1 1\n",
"1 2\n",
"2 1\n"
] | [
"3\n",
"5\n",
"2\n"
] | none | 1,500 | [
{
"input": "1 1",
"output": "3"
},
{
"input": "1 2",
"output": "5"
},
{
"input": "2 1",
"output": "2"
},
{
"input": "2 2",
"output": "3"
},
{
"input": "2 3",
"output": "4"
},
{
"input": "4 1",
"output": "1"
},
{
"input": "5 1",
"output"... | 1,553,083,001 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 4 | 248 | 0 | r, h=map(int,input().split())
if h// r :
print((h//r)*2 +1)
else:
print(2)
| Title: Cupboard and Balloons
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius *r* (the cupboard's top) and two walls of height *h* (the cupboard's sides). The cupboard's depth is *r*, that is, it looks like a rectangle with base *r* and height *h*<=+<=*r* from the sides. The figure below shows what the cupboard looks like (the front view is on the left, the side view is on the right).
Xenia got lots of balloons for her birthday. The girl hates the mess, so she wants to store the balloons in the cupboard. Luckily, each balloon is a sphere with radius . Help Xenia calculate the maximum number of balloons she can put in her cupboard.
You can say that a balloon is in the cupboard if you can't see any part of the balloon on the left or right view. The balloons in the cupboard can touch each other. It is not allowed to squeeze the balloons or deform them in any way. You can assume that the cupboard's walls are negligibly thin.
Input Specification:
The single line contains two integers *r*,<=*h* (1<=≤<=*r*,<=*h*<=≤<=107).
Output Specification:
Print a single integer — the maximum number of balloons Xenia can put in the cupboard.
Demo Input:
['1 1\n', '1 2\n', '2 1\n']
Demo Output:
['3\n', '5\n', '2\n']
Note:
none | ```python
r, h=map(int,input().split())
if h// r :
print((h//r)*2 +1)
else:
print(2)
``` | 0 | |
262 | A | Roma and Lucky Numbers | PROGRAMMING | 800 | [
"implementation"
] | null | null | Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.
Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Roma's got *n* positive integers. He wonders, how many of those integers have not more than *k* lucky digits? Help him, write the program that solves the problem. | The first line contains two integers *n*, *k* (1<=≤<=*n*,<=*k*<=≤<=100). The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=109) — the numbers that Roma has.
The numbers in the lines are separated by single spaces. | In a single line print a single integer — the answer to the problem. | [
"3 4\n1 2 4\n",
"3 2\n447 44 77\n"
] | [
"3\n",
"2\n"
] | In the first sample all numbers contain at most four lucky digits, so the answer is 3.
In the second sample number 447 doesn't fit in, as it contains more than two lucky digits. All other numbers are fine, so the answer is 2. | 500 | [
{
"input": "3 4\n1 2 4",
"output": "3"
},
{
"input": "3 2\n447 44 77",
"output": "2"
},
{
"input": "2 2\n507978501 180480073",
"output": "2"
},
{
"input": "9 6\n655243746 167613748 1470546 57644035 176077477 56984809 44677 215706823 369042089",
"output": "9"
},
{
... | 1,659,220,033 | 2,147,483,647 | Python 3 | OK | TESTS | 34 | 92 | 0 | n = [int(x) for x in input().split()]
s = input().split()
count = 0
for i in range(0, n[0]):
count2 = 0
for j in range(0, len(s[i])):
if s[i][j] == "4" or s[i][j] == "7":
count2 += 1
if count2 <= n[1]:
count += 1
print(count) | Title: Roma and Lucky Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.
Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Roma's got *n* positive integers. He wonders, how many of those integers have not more than *k* lucky digits? Help him, write the program that solves the problem.
Input Specification:
The first line contains two integers *n*, *k* (1<=≤<=*n*,<=*k*<=≤<=100). The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=109) — the numbers that Roma has.
The numbers in the lines are separated by single spaces.
Output Specification:
In a single line print a single integer — the answer to the problem.
Demo Input:
['3 4\n1 2 4\n', '3 2\n447 44 77\n']
Demo Output:
['3\n', '2\n']
Note:
In the first sample all numbers contain at most four lucky digits, so the answer is 3.
In the second sample number 447 doesn't fit in, as it contains more than two lucky digits. All other numbers are fine, so the answer is 2. | ```python
n = [int(x) for x in input().split()]
s = input().split()
count = 0
for i in range(0, n[0]):
count2 = 0
for j in range(0, len(s[i])):
if s[i][j] == "4" or s[i][j] == "7":
count2 += 1
if count2 <= n[1]:
count += 1
print(count)
``` | 3 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.
Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=5·105) — the number of lines.
Next *n* lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant *x**i* 0<=≤<=*x**i*<=≤<=1023. | Output an integer *k* (0<=≤<=*k*<=≤<=5) — the length of your program.
Next *k* lines must contain commands in the same format as in the input. | [
"3\n| 3\n^ 2\n| 1\n",
"3\n& 1\n& 3\n& 5\n",
"3\n^ 1\n^ 2\n^ 3\n"
] | [
"2\n| 3\n^ 2\n",
"1\n& 1\n",
"0\n"
] | You can read about bitwise operations in [https://en.wikipedia.org/wiki/Bitwise_operation](https://en.wikipedia.org/wiki/Bitwise_operation).
Second sample:
Let *x* be an input of the Petya's program. It's output is ((*x*&1)&3)&5 = *x*&(1&3&5) = *x*&1. So these two programs always give the same outputs. | 0 | [
{
"input": "3\n| 3\n^ 2\n| 1",
"output": "2\n| 3\n^ 2"
},
{
"input": "3\n& 1\n& 3\n& 5",
"output": "1\n& 1"
},
{
"input": "3\n^ 1\n^ 2\n^ 3",
"output": "0"
},
{
"input": "2\n| 999\n^ 689",
"output": "2\n| 999\n^ 689"
},
{
"input": "3\n& 242\n^ 506\n^ 522",
"ou... | 1,522,688,212 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 77 | 7,065,600 | n = int(input())
zero = 0
ones = 1023
for _ in range(n):
op, num = input().split()
num = int(num)
if op == '&':
zero &= num
ones &= num
elif op == '|':
zero |= num
ones |= num
else:
zero ^= num
ones ^= num
and_bits = 0
or_bits = 0
xor_bits = 0
for i in range(10):
z = (zero >> i) & 1
o = (ones >> i) & 1
if z == 0 and o == 0:
and_bits |= 0 << i
or_bits |= 0 << i
xor_bits |= 0 << i
elif z == 0 and o == 1:
and_bits |= 1 << i
or_bits |= 0 << i
xor_bits |= 0 << i
elif z == 1 and o == 0:
and_bits |= 0 << i
or_bits |= 0 << i
xor_bits |= 1 << i
else:
and_bits |= 0 << i
or_bits |= 1 << i
xor_bits |= 0 << i
print(3)
print('& {}'.format(and_bits))
print('| {}'.format(or_bits))
print('^ {}'.format(xor_bits)) | Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.
Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=5·105) — the number of lines.
Next *n* lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant *x**i* 0<=≤<=*x**i*<=≤<=1023.
Output Specification:
Output an integer *k* (0<=≤<=*k*<=≤<=5) — the length of your program.
Next *k* lines must contain commands in the same format as in the input.
Demo Input:
['3\n| 3\n^ 2\n| 1\n', '3\n& 1\n& 3\n& 5\n', '3\n^ 1\n^ 2\n^ 3\n']
Demo Output:
['2\n| 3\n^ 2\n', '1\n& 1\n', '0\n']
Note:
You can read about bitwise operations in [https://en.wikipedia.org/wiki/Bitwise_operation](https://en.wikipedia.org/wiki/Bitwise_operation).
Second sample:
Let *x* be an input of the Petya's program. It's output is ((*x*&1)&3)&5 = *x*&(1&3&5) = *x*&1. So these two programs always give the same outputs. | ```python
n = int(input())
zero = 0
ones = 1023
for _ in range(n):
op, num = input().split()
num = int(num)
if op == '&':
zero &= num
ones &= num
elif op == '|':
zero |= num
ones |= num
else:
zero ^= num
ones ^= num
and_bits = 0
or_bits = 0
xor_bits = 0
for i in range(10):
z = (zero >> i) & 1
o = (ones >> i) & 1
if z == 0 and o == 0:
and_bits |= 0 << i
or_bits |= 0 << i
xor_bits |= 0 << i
elif z == 0 and o == 1:
and_bits |= 1 << i
or_bits |= 0 << i
xor_bits |= 0 << i
elif z == 1 and o == 0:
and_bits |= 0 << i
or_bits |= 0 << i
xor_bits |= 1 << i
else:
and_bits |= 0 << i
or_bits |= 1 << i
xor_bits |= 0 << i
print(3)
print('& {}'.format(and_bits))
print('| {}'.format(or_bits))
print('^ {}'.format(xor_bits))
``` | 0 | |
363 | B | Fence | PROGRAMMING | 1,100 | [
"brute force",
"dp"
] | null | null | There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights.
Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly *k* consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such *k* consecutive planks that the sum of their heights is minimal possible.
Write the program that finds the indexes of *k* consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic). | The first line of the input contains integers *n* and *k* (1<=≤<=*n*<=≤<=1.5·105,<=1<=≤<=*k*<=≤<=*n*) — the number of planks in the fence and the width of the hole for the piano. The second line contains the sequence of integers *h*1,<=*h*2,<=...,<=*h**n* (1<=≤<=*h**i*<=≤<=100), where *h**i* is the height of the *i*-th plank of the fence. | Print such integer *j* that the sum of the heights of planks *j*, *j*<=+<=1, ..., *j*<=+<=*k*<=-<=1 is the minimum possible. If there are multiple such *j*'s, print any of them. | [
"7 3\n1 2 6 1 1 7 1\n"
] | [
"3\n"
] | In the sample, your task is to find three consecutive planks with the minimum sum of heights. In the given case three planks with indexes 3, 4 and 5 have the required attribute, their total height is 8. | 1,000 | [
{
"input": "7 3\n1 2 6 1 1 7 1",
"output": "3"
},
{
"input": "1 1\n100",
"output": "1"
},
{
"input": "2 1\n10 20",
"output": "1"
},
{
"input": "10 5\n1 2 3 1 2 2 3 1 4 5",
"output": "1"
},
{
"input": "10 2\n3 1 4 1 4 6 2 1 4 6",
"output": "7"
},
{
"inp... | 1,693,270,148 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 30 | 0 | x = input()
p = []
y = x.split(" ")
for i in y:
p.append(int(i))
x = input()
L = []
y = x.split(" ")
for i in y:
L.append(int(i))
L = [1,2,6,1,1,7,1]
n = p[0]
k = p[1]
if n == k:
print(sum(L))
else:
s = 0
for i in range(k):
s = s+L[i]
ind = 1
minc = s
for i in range(1,len(L)-k+1):
s = s - L[i-1]+L[i+k-1]
if minc > s:
minc = s
ind = i+1
print(ind) | Title: Fence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights.
Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly *k* consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such *k* consecutive planks that the sum of their heights is minimal possible.
Write the program that finds the indexes of *k* consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).
Input Specification:
The first line of the input contains integers *n* and *k* (1<=≤<=*n*<=≤<=1.5·105,<=1<=≤<=*k*<=≤<=*n*) — the number of planks in the fence and the width of the hole for the piano. The second line contains the sequence of integers *h*1,<=*h*2,<=...,<=*h**n* (1<=≤<=*h**i*<=≤<=100), where *h**i* is the height of the *i*-th plank of the fence.
Output Specification:
Print such integer *j* that the sum of the heights of planks *j*, *j*<=+<=1, ..., *j*<=+<=*k*<=-<=1 is the minimum possible. If there are multiple such *j*'s, print any of them.
Demo Input:
['7 3\n1 2 6 1 1 7 1\n']
Demo Output:
['3\n']
Note:
In the sample, your task is to find three consecutive planks with the minimum sum of heights. In the given case three planks with indexes 3, 4 and 5 have the required attribute, their total height is 8. | ```python
x = input()
p = []
y = x.split(" ")
for i in y:
p.append(int(i))
x = input()
L = []
y = x.split(" ")
for i in y:
L.append(int(i))
L = [1,2,6,1,1,7,1]
n = p[0]
k = p[1]
if n == k:
print(sum(L))
else:
s = 0
for i in range(k):
s = s+L[i]
ind = 1
minc = s
for i in range(1,len(L)-k+1):
s = s - L[i-1]+L[i+k-1]
if minc > s:
minc = s
ind = i+1
print(ind)
``` | 0 | |
999 | E | Reachability from the Capital | PROGRAMMING | 2,000 | [
"dfs and similar",
"graphs",
"greedy"
] | null | null | There are $n$ cities and $m$ roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.
What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?
New roads will also be one-way. | The first line of input consists of three integers $n$, $m$ and $s$ ($1 \le n \le 5000, 0 \le m \le 5000, 1 \le s \le n$) — the number of cities, the number of roads and the index of the capital. Cities are indexed from $1$ to $n$.
The following $m$ lines contain roads: road $i$ is given as a pair of cities $u_i$, $v_i$ ($1 \le u_i, v_i \le n$, $u_i \ne v_i$). For each pair of cities $(u, v)$, there can be at most one road from $u$ to $v$. Roads in opposite directions between a pair of cities are allowed (i.e. from $u$ to $v$ and from $v$ to $u$). | Print one integer — the minimum number of extra roads needed to make all the cities reachable from city $s$. If all the cities are already reachable from $s$, print 0. | [
"9 9 1\n1 2\n1 3\n2 3\n1 5\n5 6\n6 1\n1 8\n9 8\n7 1\n",
"5 4 5\n1 2\n2 3\n3 4\n4 1\n"
] | [
"3\n",
"1\n"
] | The first example is illustrated by the following:
For example, you can add roads ($6, 4$), ($7, 9$), ($1, 7$) to make all the cities reachable from $s = 1$.
The second example is illustrated by the following:
In this example, you can add any one of the roads ($5, 1$), ($5, 2$), ($5, 3$), ($5, 4$) to make all the cities reachable from $s = 5$. | 0 | [
{
"input": "9 9 1\n1 2\n1 3\n2 3\n1 5\n5 6\n6 1\n1 8\n9 8\n7 1",
"output": "3"
},
{
"input": "5 4 5\n1 2\n2 3\n3 4\n4 1",
"output": "1"
},
{
"input": "5000 0 2956",
"output": "4999"
},
{
"input": "2 0 2",
"output": "1"
},
{
"input": "2 1 1\n1 2",
"output": "0"... | 1,643,256,519 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 3 | 1,060 | 9,625,600 | """
-*- coding: utf-8 -*-
Created on Wed Jan 26 14:30:20 2022
@author: Tausif Khan Arnob
"""
R = lambda:map(int, input().split())
n, m, s = R()
graph = [[] for _ in range(n)]
for _ in range(m):
x, y = R()
graph[x - 1].append(y - 1)
# print('Graph:')
# print(*graph, sep = '\n')
reachable = [False for _ in range(n)]
def dfs_reachable(x):
reachable[x] = True
for y in graph[x]:
if not reachable[y]:
dfs_reachable(y)
dfs_reachable(s - 1)
# print('Reachable: ', reachable)
unreachable = []
def dfs_unreachable(x):
unreachable[x] = True
for y in graph[x]:
if not unreachable[x] and not reachable[x]:
dfs_unreachable(x)
unreachable_cities = []
for i in range(n):
unreachable = [False for _ in range(n)]
dfs_unreachable(i)
unreachable_cities.append([unreachable.count(True), i])
unreachable_cities.sort(reverse = True)
# print(unreachable_cities)
ans = 0
for cnt, i in unreachable_cities:
if reachable[i] == False:
ans += 1
dfs_reachable(i)
print(ans) | Title: Reachability from the Capital
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are $n$ cities and $m$ roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.
What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?
New roads will also be one-way.
Input Specification:
The first line of input consists of three integers $n$, $m$ and $s$ ($1 \le n \le 5000, 0 \le m \le 5000, 1 \le s \le n$) — the number of cities, the number of roads and the index of the capital. Cities are indexed from $1$ to $n$.
The following $m$ lines contain roads: road $i$ is given as a pair of cities $u_i$, $v_i$ ($1 \le u_i, v_i \le n$, $u_i \ne v_i$). For each pair of cities $(u, v)$, there can be at most one road from $u$ to $v$. Roads in opposite directions between a pair of cities are allowed (i.e. from $u$ to $v$ and from $v$ to $u$).
Output Specification:
Print one integer — the minimum number of extra roads needed to make all the cities reachable from city $s$. If all the cities are already reachable from $s$, print 0.
Demo Input:
['9 9 1\n1 2\n1 3\n2 3\n1 5\n5 6\n6 1\n1 8\n9 8\n7 1\n', '5 4 5\n1 2\n2 3\n3 4\n4 1\n']
Demo Output:
['3\n', '1\n']
Note:
The first example is illustrated by the following:
For example, you can add roads ($6, 4$), ($7, 9$), ($1, 7$) to make all the cities reachable from $s = 1$.
The second example is illustrated by the following:
In this example, you can add any one of the roads ($5, 1$), ($5, 2$), ($5, 3$), ($5, 4$) to make all the cities reachable from $s = 5$. | ```python
"""
-*- coding: utf-8 -*-
Created on Wed Jan 26 14:30:20 2022
@author: Tausif Khan Arnob
"""
R = lambda:map(int, input().split())
n, m, s = R()
graph = [[] for _ in range(n)]
for _ in range(m):
x, y = R()
graph[x - 1].append(y - 1)
# print('Graph:')
# print(*graph, sep = '\n')
reachable = [False for _ in range(n)]
def dfs_reachable(x):
reachable[x] = True
for y in graph[x]:
if not reachable[y]:
dfs_reachable(y)
dfs_reachable(s - 1)
# print('Reachable: ', reachable)
unreachable = []
def dfs_unreachable(x):
unreachable[x] = True
for y in graph[x]:
if not unreachable[x] and not reachable[x]:
dfs_unreachable(x)
unreachable_cities = []
for i in range(n):
unreachable = [False for _ in range(n)]
dfs_unreachable(i)
unreachable_cities.append([unreachable.count(True), i])
unreachable_cities.sort(reverse = True)
# print(unreachable_cities)
ans = 0
for cnt, i in unreachable_cities:
if reachable[i] == False:
ans += 1
dfs_reachable(i)
print(ans)
``` | 0 | |
711 | A | Bus to Udayland | PROGRAMMING | 800 | [
"brute force",
"implementation"
] | null | null | ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has *n* rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit? | The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of rows of seats in the bus.
Then, *n* lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.
Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details. | If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next *n* lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output).
If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line.
If there are multiple solutions, you may print any of them. | [
"6\nOO|OX\nXO|XX\nOX|OO\nXX|OX\nOO|OO\nOO|XX\n",
"4\nXO|OX\nXO|XX\nOX|OX\nXX|OX\n",
"5\nXX|XX\nXX|XX\nXO|OX\nXO|OO\nOX|XO\n"
] | [
"YES\n++|OX\nXO|XX\nOX|OO\nXX|OX\nOO|OO\nOO|XX\n",
"NO\n",
"YES\nXX|XX\nXX|XX\nXO|OX\nXO|++\nOX|XO\n"
] | Note that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.
O+|+X
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX | 500 | [
{
"input": "6\nOO|OX\nXO|XX\nOX|OO\nXX|OX\nOO|OO\nOO|XX",
"output": "YES\n++|OX\nXO|XX\nOX|OO\nXX|OX\nOO|OO\nOO|XX"
},
{
"input": "4\nXO|OX\nXO|XX\nOX|OX\nXX|OX",
"output": "NO"
},
{
"input": "5\nXX|XX\nXX|XX\nXO|OX\nXO|OO\nOX|XO",
"output": "YES\nXX|XX\nXX|XX\nXO|OX\nXO|++\nOX|XO"
... | 1,668,841,535 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 71 | 109 | 3,481,600 | f = 1
ans = []
for i in range(int(input())):
a = input()
if 'OO' in a and f:
ans.append(a.replace('OO','++',1))
f = 0
else:
ans.append(a)
if f:
print('NO')
else:
print('YES')
print(*ans,sep='\n') | Title: Bus to Udayland
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has *n* rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?
Input Specification:
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of rows of seats in the bus.
Then, *n* lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.
Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details.
Output Specification:
If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next *n* lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output).
If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line.
If there are multiple solutions, you may print any of them.
Demo Input:
['6\nOO|OX\nXO|XX\nOX|OO\nXX|OX\nOO|OO\nOO|XX\n', '4\nXO|OX\nXO|XX\nOX|OX\nXX|OX\n', '5\nXX|XX\nXX|XX\nXO|OX\nXO|OO\nOX|XO\n']
Demo Output:
['YES\n++|OX\nXO|XX\nOX|OO\nXX|OX\nOO|OO\nOO|XX\n', 'NO\n', 'YES\nXX|XX\nXX|XX\nXO|OX\nXO|++\nOX|XO\n']
Note:
Note that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.
O+|+X
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX | ```python
f = 1
ans = []
for i in range(int(input())):
a = input()
if 'OO' in a and f:
ans.append(a.replace('OO','++',1))
f = 0
else:
ans.append(a)
if f:
print('NO')
else:
print('YES')
print(*ans,sep='\n')
``` | 3 | |
994 | B | Knights of a Polygonal Table | PROGRAMMING | 1,400 | [
"greedy",
"implementation",
"sortings"
] | null | null | Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than $k$ other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins.
Now each knight ponders: how many coins he can have if only he kills other knights?
You should answer this question for each knight. | The first line contains two integers $n$ and $k$ $(1 \le n \le 10^5, 0 \le k \le \min(n-1,10))$ — the number of knights and the number $k$ from the statement.
The second line contains $n$ integers $p_1, p_2 ,\ldots,p_n$ $(1 \le p_i \le 10^9)$ — powers of the knights. All $p_i$ are distinct.
The third line contains $n$ integers $c_1, c_2 ,\ldots,c_n$ $(0 \le c_i \le 10^9)$ — the number of coins each knight has. | Print $n$ integers — the maximum number of coins each knight can have it only he kills other knights. | [
"4 2\n4 5 9 7\n1 2 11 33\n",
"5 1\n1 2 3 4 5\n1 2 3 4 5\n",
"1 0\n2\n3\n"
] | [
"1 3 46 36 ",
"1 3 5 7 9 ",
"3 "
] | Consider the first example.
- The first knight is the weakest, so he can't kill anyone. That leaves him with the only coin he initially has. - The second knight can kill the first knight and add his coin to his own two. - The third knight is the strongest, but he can't kill more than $k = 2$ other knights. It is optimal to kill the second and the fourth knights: $2+11+33 = 46$. - The fourth knight should kill the first and the second knights: $33+1+2 = 36$.
In the second example the first knight can't kill anyone, while all the others should kill the one with the index less by one than their own.
In the third example there is only one knight, so he can't kill anyone. | 1,000 | [
{
"input": "4 2\n4 5 9 7\n1 2 11 33",
"output": "1 3 46 36 "
},
{
"input": "5 1\n1 2 3 4 5\n1 2 3 4 5",
"output": "1 3 5 7 9 "
},
{
"input": "1 0\n2\n3",
"output": "3 "
},
{
"input": "7 1\n2 3 4 5 7 8 9\n0 3 7 9 5 8 9",
"output": "0 3 10 16 14 17 18 "
},
{
"input"... | 1,673,933,367 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 46 | 102,400 | from functools import reduce
n , k = [*map(int,input().split())]
arr = [*map(int,input().split())]
crr = [*map(int,input().split())]
brr = sorted([[arr [i], crr [i] , i] for i in range (n)], key = lambda p: p [0])
pref = 0
ans = [0] * n
for i in range(n):
pref += brr[i][1]
if i > k:
pref -= brr [i - k - 1][1]
ans [brr [i][2]] = pref
print (*ans) | Title: Knights of a Polygonal Table
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than $k$ other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins.
Now each knight ponders: how many coins he can have if only he kills other knights?
You should answer this question for each knight.
Input Specification:
The first line contains two integers $n$ and $k$ $(1 \le n \le 10^5, 0 \le k \le \min(n-1,10))$ — the number of knights and the number $k$ from the statement.
The second line contains $n$ integers $p_1, p_2 ,\ldots,p_n$ $(1 \le p_i \le 10^9)$ — powers of the knights. All $p_i$ are distinct.
The third line contains $n$ integers $c_1, c_2 ,\ldots,c_n$ $(0 \le c_i \le 10^9)$ — the number of coins each knight has.
Output Specification:
Print $n$ integers — the maximum number of coins each knight can have it only he kills other knights.
Demo Input:
['4 2\n4 5 9 7\n1 2 11 33\n', '5 1\n1 2 3 4 5\n1 2 3 4 5\n', '1 0\n2\n3\n']
Demo Output:
['1 3 46 36 ', '1 3 5 7 9 ', '3 ']
Note:
Consider the first example.
- The first knight is the weakest, so he can't kill anyone. That leaves him with the only coin he initially has. - The second knight can kill the first knight and add his coin to his own two. - The third knight is the strongest, but he can't kill more than $k = 2$ other knights. It is optimal to kill the second and the fourth knights: $2+11+33 = 46$. - The fourth knight should kill the first and the second knights: $33+1+2 = 36$.
In the second example the first knight can't kill anyone, while all the others should kill the one with the index less by one than their own.
In the third example there is only one knight, so he can't kill anyone. | ```python
from functools import reduce
n , k = [*map(int,input().split())]
arr = [*map(int,input().split())]
crr = [*map(int,input().split())]
brr = sorted([[arr [i], crr [i] , i] for i in range (n)], key = lambda p: p [0])
pref = 0
ans = [0] * n
for i in range(n):
pref += brr[i][1]
if i > k:
pref -= brr [i - k - 1][1]
ans [brr [i][2]] = pref
print (*ans)
``` | 0 | |
358 | B | Dima and Text Messages | PROGRAMMING | 1,500 | [
"brute force",
"strings"
] | null | null | Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.
Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3*word*1<3*word*2<3 ... *word**n*<3.
Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.
Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above. | The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of words in Dima's message. Next *n* lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105.
The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less. | In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise. | [
"3\ni\nlove\nyou\n<3i<3love<23you<3\n",
"7\ni\nam\nnot\nmain\nin\nthe\nfamily\n<3i<>3am<3the<3<main<3in<3the<3><3family<3\n"
] | [
"yes\n",
"no\n"
] | Please note that Dima got a good old kick in the pants for the second sample from the statement. | 1,000 | [
{
"input": "3\ni\nlove\nyou\n<3i<3love<23you<3",
"output": "yes"
},
{
"input": "7\ni\nam\nnot\nmain\nin\nthe\nfamily\n<3i<>3am<3the<3<main<3in<3the<3><3family<3",
"output": "no"
},
{
"input": "3\ni\nlove\nyou\n<3i<3lo<3ve<3y<<<<<<<ou3<3",
"output": "yes"
},
{
"input": "4\na\n... | 1,668,112,351 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 31 | 0 | """
https://codeforces.com/problemset/problem/358/B
"""
tests = int(input())
texts = []
for _ in range(tests + 1):
texts.append(input())
def trouve_i3(text):
if (v:=text.find('<'))>-1 and text.find('3')>v:
return True
return False
a = texts[-1]
res = []
i = 0
possible = True
#trouve les mots
for c in texts[:-1]:
if (z := a.find(c, i)) > 0:
i =z+ len(c)
res.append((z, i))
else:
possible = False
break
# trouve les <3
if possible:
if not trouve_i3(a[0:res[0][0]]):
possible=False
if possible:
for i,(v,w) in enumerate(res[:-1]):
if not trouve_i3(a[res[i][1]:res[i+1][0]]):
possible=False
break
if possible:
if not trouve_i3(a[res[-1][1]:]):
possible=False
if possible:
print("yes")
else:
print("no")
| Title: Dima and Text Messages
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.
Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3*word*1<3*word*2<3 ... *word**n*<3.
Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.
Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of words in Dima's message. Next *n* lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105.
The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.
Output Specification:
In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.
Demo Input:
['3\ni\nlove\nyou\n<3i<3love<23you<3\n', '7\ni\nam\nnot\nmain\nin\nthe\nfamily\n<3i<>3am<3the<3<main<3in<3the<3><3family<3\n']
Demo Output:
['yes\n', 'no\n']
Note:
Please note that Dima got a good old kick in the pants for the second sample from the statement. | ```python
"""
https://codeforces.com/problemset/problem/358/B
"""
tests = int(input())
texts = []
for _ in range(tests + 1):
texts.append(input())
def trouve_i3(text):
if (v:=text.find('<'))>-1 and text.find('3')>v:
return True
return False
a = texts[-1]
res = []
i = 0
possible = True
#trouve les mots
for c in texts[:-1]:
if (z := a.find(c, i)) > 0:
i =z+ len(c)
res.append((z, i))
else:
possible = False
break
# trouve les <3
if possible:
if not trouve_i3(a[0:res[0][0]]):
possible=False
if possible:
for i,(v,w) in enumerate(res[:-1]):
if not trouve_i3(a[res[i][1]:res[i+1][0]]):
possible=False
break
if possible:
if not trouve_i3(a[res[-1][1]:]):
possible=False
if possible:
print("yes")
else:
print("no")
``` | 0 | |
990 | G | GCD Counting | PROGRAMMING | 2,400 | [
"divide and conquer",
"dp",
"dsu",
"number theory",
"trees"
] | null | null | You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$.
Let's denote the function $g(x, y)$ as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex $x$ to vertex $y$ (including these two vertices).
For every integer from $1$ to $2 \cdot 10^5$ you have to count the number of pairs $(x, y)$ $(1 \le x \le y \le n)$ such that $g(x, y)$ is equal to this number. | The first line contains one integer $n$ — the number of vertices $(1 \le n \le 2 \cdot 10^5)$.
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ $(1 \le a_i \le 2 \cdot 10^5)$ — the numbers written on vertices.
Then $n - 1$ lines follow, each containing two integers $x$ and $y$ $(1 \le x, y \le n, x \ne y)$ denoting an edge connecting vertex $x$ with vertex $y$. It is guaranteed that these edges form a tree. | For every integer $i$ from $1$ to $2 \cdot 10^5$ do the following: if there is no pair $(x, y)$ such that $x \le y$ and $g(x, y) = i$, don't output anything. Otherwise output two integers: $i$ and the number of aforementioned pairs. You have to consider the values of $i$ in ascending order.
See the examples for better understanding. | [
"3\n1 2 3\n1 2\n2 3\n",
"6\n1 2 4 8 16 32\n1 6\n6 3\n3 4\n4 2\n6 5\n",
"4\n9 16 144 6\n1 3\n2 3\n4 3\n"
] | [
"1 4\n2 1\n3 1\n",
"1 6\n2 5\n4 6\n8 1\n16 2\n32 1\n",
"1 1\n2 1\n3 1\n6 2\n9 2\n16 2\n144 1\n"
] | none | 0 | [
{
"input": "3\n1 2 3\n1 2\n2 3",
"output": "1 4\n2 1\n3 1"
},
{
"input": "6\n1 2 4 8 16 32\n1 6\n6 3\n3 4\n4 2\n6 5",
"output": "1 6\n2 5\n4 6\n8 1\n16 2\n32 1"
},
{
"input": "4\n9 16 144 6\n1 3\n2 3\n4 3",
"output": "1 1\n2 1\n3 1\n6 2\n9 2\n16 2\n144 1"
},
{
"input": "3\n1 ... | 1,634,928,884 | 2,147,483,647 | PyPy 3 | TIME_LIMIT_EXCEEDED | TESTS | 4 | 4,500 | 72,908,800 | from collections import deque
import sys
input = sys.stdin.buffer.readline
def divisor(i):
s = []
for j in range(1, int(i ** (1 / 2)) + 1):
if i % j == 0:
s.append(i // j)
s.append(j)
return sorted(set(s), reverse = True)
def bfs(s, d, y):
q = deque()
q.append(s)
visit[s] = y
cnt = 0
while q:
i = q.popleft()
if not a[i] ^ d:
ok[i] = 1
cnt += 1
for j in G[i]:
if visit[j] ^ y and not a[j] % d:
visit[j] = y
q.append(j)
return cnt
n = int(input())
a = [0] + list(map(int, input().split()))
G = [[] for _ in range(n + 1)]
for _ in range(n - 1):
x, y = map(int, input().split())
G[x].append(y)
G[y].append(x)
l = 2 * pow(10, 5)
b = []
for i in range(1, n + 1):
b.append((a[i], i))
b.sort(reverse = True)
visit = [0] * (n + 1)
ok = [0] * (n + 1)
dp = [0] * (l + 1)
x = l + 1
y = 1
for ai, i in b:
if ok[i]:
continue
if x ^ ai:
d = divisor(ai)
x = ai
c = []
for j in G[i]:
if ok[j]:
c.append(j)
for d0 in d:
f = 1
for j in c:
if not a[j] % d0:
f = 0
break
if f:
cnt = bfs(i, d0, y)
y += 1
dp[d0] += cnt * (cnt + 1) // 2
for i in range(l // 2, 0, -1):
ng = 0
for j in range(2 * i, l + 1, i):
ng += dp[j]
dp[i] -= ng
ans = []
for i in range(1, l + 1):
if dp[i]:
ans.append(str(i) + " " + str(dp[i]))
sys.stdout.write("\n".join(ans)) | Title: GCD Counting
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$.
Let's denote the function $g(x, y)$ as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex $x$ to vertex $y$ (including these two vertices).
For every integer from $1$ to $2 \cdot 10^5$ you have to count the number of pairs $(x, y)$ $(1 \le x \le y \le n)$ such that $g(x, y)$ is equal to this number.
Input Specification:
The first line contains one integer $n$ — the number of vertices $(1 \le n \le 2 \cdot 10^5)$.
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ $(1 \le a_i \le 2 \cdot 10^5)$ — the numbers written on vertices.
Then $n - 1$ lines follow, each containing two integers $x$ and $y$ $(1 \le x, y \le n, x \ne y)$ denoting an edge connecting vertex $x$ with vertex $y$. It is guaranteed that these edges form a tree.
Output Specification:
For every integer $i$ from $1$ to $2 \cdot 10^5$ do the following: if there is no pair $(x, y)$ such that $x \le y$ and $g(x, y) = i$, don't output anything. Otherwise output two integers: $i$ and the number of aforementioned pairs. You have to consider the values of $i$ in ascending order.
See the examples for better understanding.
Demo Input:
['3\n1 2 3\n1 2\n2 3\n', '6\n1 2 4 8 16 32\n1 6\n6 3\n3 4\n4 2\n6 5\n', '4\n9 16 144 6\n1 3\n2 3\n4 3\n']
Demo Output:
['1 4\n2 1\n3 1\n', '1 6\n2 5\n4 6\n8 1\n16 2\n32 1\n', '1 1\n2 1\n3 1\n6 2\n9 2\n16 2\n144 1\n']
Note:
none | ```python
from collections import deque
import sys
input = sys.stdin.buffer.readline
def divisor(i):
s = []
for j in range(1, int(i ** (1 / 2)) + 1):
if i % j == 0:
s.append(i // j)
s.append(j)
return sorted(set(s), reverse = True)
def bfs(s, d, y):
q = deque()
q.append(s)
visit[s] = y
cnt = 0
while q:
i = q.popleft()
if not a[i] ^ d:
ok[i] = 1
cnt += 1
for j in G[i]:
if visit[j] ^ y and not a[j] % d:
visit[j] = y
q.append(j)
return cnt
n = int(input())
a = [0] + list(map(int, input().split()))
G = [[] for _ in range(n + 1)]
for _ in range(n - 1):
x, y = map(int, input().split())
G[x].append(y)
G[y].append(x)
l = 2 * pow(10, 5)
b = []
for i in range(1, n + 1):
b.append((a[i], i))
b.sort(reverse = True)
visit = [0] * (n + 1)
ok = [0] * (n + 1)
dp = [0] * (l + 1)
x = l + 1
y = 1
for ai, i in b:
if ok[i]:
continue
if x ^ ai:
d = divisor(ai)
x = ai
c = []
for j in G[i]:
if ok[j]:
c.append(j)
for d0 in d:
f = 1
for j in c:
if not a[j] % d0:
f = 0
break
if f:
cnt = bfs(i, d0, y)
y += 1
dp[d0] += cnt * (cnt + 1) // 2
for i in range(l // 2, 0, -1):
ng = 0
for j in range(2 * i, l + 1, i):
ng += dp[j]
dp[i] -= ng
ans = []
for i in range(1, l + 1):
if dp[i]:
ans.append(str(i) + " " + str(dp[i]))
sys.stdout.write("\n".join(ans))
``` | 0 | |
746 | A | Compote | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | Nikolay has *a* lemons, *b* apples and *c* pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1:<=2:<=4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits.
Your task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print 0. | The first line contains the positive integer *a* (1<=≤<=*a*<=≤<=1000) — the number of lemons Nikolay has.
The second line contains the positive integer *b* (1<=≤<=*b*<=≤<=1000) — the number of apples Nikolay has.
The third line contains the positive integer *c* (1<=≤<=*c*<=≤<=1000) — the number of pears Nikolay has. | Print the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. | [
"2\n5\n7\n",
"4\n7\n13\n",
"2\n3\n2\n"
] | [
"7\n",
"21\n",
"0\n"
] | In the first example Nikolay can use 1 lemon, 2 apples and 4 pears, so the answer is 1 + 2 + 4 = 7.
In the second example Nikolay can use 3 lemons, 6 apples and 12 pears, so the answer is 3 + 6 + 12 = 21.
In the third example Nikolay don't have enough pears to cook any compote, so the answer is 0. | 500 | [
{
"input": "2\n5\n7",
"output": "7"
},
{
"input": "4\n7\n13",
"output": "21"
},
{
"input": "2\n3\n2",
"output": "0"
},
{
"input": "1\n1\n1",
"output": "0"
},
{
"input": "1\n2\n4",
"output": "7"
},
{
"input": "1000\n1000\n1000",
"output": "1750"
}... | 1,655,917,511 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 46 | 0 | a,b,c = map(int, input().split())
a //= 1
b //= 2
c //= 4
m = min(a,b,c)
print(m * 7) | Title: Compote
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Nikolay has *a* lemons, *b* apples and *c* pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1:<=2:<=4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits.
Your task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print 0.
Input Specification:
The first line contains the positive integer *a* (1<=≤<=*a*<=≤<=1000) — the number of lemons Nikolay has.
The second line contains the positive integer *b* (1<=≤<=*b*<=≤<=1000) — the number of apples Nikolay has.
The third line contains the positive integer *c* (1<=≤<=*c*<=≤<=1000) — the number of pears Nikolay has.
Output Specification:
Print the maximum total number of lemons, apples and pears from which Nikolay can cook the compote.
Demo Input:
['2\n5\n7\n', '4\n7\n13\n', '2\n3\n2\n']
Demo Output:
['7\n', '21\n', '0\n']
Note:
In the first example Nikolay can use 1 lemon, 2 apples and 4 pears, so the answer is 1 + 2 + 4 = 7.
In the second example Nikolay can use 3 lemons, 6 apples and 12 pears, so the answer is 3 + 6 + 12 = 21.
In the third example Nikolay don't have enough pears to cook any compote, so the answer is 0. | ```python
a,b,c = map(int, input().split())
a //= 1
b //= 2
c //= 4
m = min(a,b,c)
print(m * 7)
``` | -1 | |
479 | C | Exams | PROGRAMMING | 1,400 | [
"greedy",
"sortings"
] | null | null | Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly *n* exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a student can take the exam for the *i*-th subject on the day number *a**i*. However, Valera has made an arrangement with each teacher and the teacher of the *i*-th subject allowed him to take an exam before the schedule time on day *b**i* (*b**i*<=<<=*a**i*). Thus, Valera can take an exam for the *i*-th subject either on day *a**i*, or on day *b**i*. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number *a**i*.
Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date. | The first line contains a single positive integer *n* (1<=≤<=*n*<=≤<=5000) — the number of exams Valera will take.
Each of the next *n* lines contains two positive space-separated integers *a**i* and *b**i* (1<=≤<=*b**i*<=<<=*a**i*<=≤<=109) — the date of the exam in the schedule and the early date of passing the *i*-th exam, correspondingly. | Print a single integer — the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date. | [
"3\n5 2\n3 1\n4 2\n",
"3\n6 1\n5 2\n4 3\n"
] | [
"2\n",
"6\n"
] | In the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5.
In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject. | 1,500 | [
{
"input": "3\n5 2\n3 1\n4 2",
"output": "2"
},
{
"input": "3\n6 1\n5 2\n4 3",
"output": "6"
},
{
"input": "1\n1000000000 999999999",
"output": "999999999"
},
{
"input": "1\n2 1",
"output": "1"
},
{
"input": "2\n3 2\n3 2",
"output": "2"
},
{
"input": "... | 1,696,859,162 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 53 | 155 | 5,734,400 | n = int(input())
exams = []
for i in range(n):
exams.append(list(map(int, input().split())))
# print(exams)
exams.sort()
start = exams[0][1]
# print(exams)
for s,e in exams:
# print(vals)
if e >= start:
start = e
else:
start = s
# print(vals)
print(start)
| Title: Exams
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly *n* exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a student can take the exam for the *i*-th subject on the day number *a**i*. However, Valera has made an arrangement with each teacher and the teacher of the *i*-th subject allowed him to take an exam before the schedule time on day *b**i* (*b**i*<=<<=*a**i*). Thus, Valera can take an exam for the *i*-th subject either on day *a**i*, or on day *b**i*. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number *a**i*.
Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.
Input Specification:
The first line contains a single positive integer *n* (1<=≤<=*n*<=≤<=5000) — the number of exams Valera will take.
Each of the next *n* lines contains two positive space-separated integers *a**i* and *b**i* (1<=≤<=*b**i*<=<<=*a**i*<=≤<=109) — the date of the exam in the schedule and the early date of passing the *i*-th exam, correspondingly.
Output Specification:
Print a single integer — the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date.
Demo Input:
['3\n5 2\n3 1\n4 2\n', '3\n6 1\n5 2\n4 3\n']
Demo Output:
['2\n', '6\n']
Note:
In the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5.
In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject. | ```python
n = int(input())
exams = []
for i in range(n):
exams.append(list(map(int, input().split())))
# print(exams)
exams.sort()
start = exams[0][1]
# print(exams)
for s,e in exams:
# print(vals)
if e >= start:
start = e
else:
start = s
# print(vals)
print(start)
``` | 3 | |
47 | B | Coins | PROGRAMMING | 1,200 | [
"implementation"
] | B. Coins | 2 | 256 | One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal. | The input data contains the results of all the weighting, one result on each line. It is guaranteed that every coin pair was weighted exactly once. Vasya labelled the coins with letters «A», «B» and «C». Each result is a line that appears as (letter)(> or < sign)(letter). For example, if coin "A" proved lighter than coin "B", the result of the weighting is A<B. | It the results are contradictory, print Impossible. Otherwise, print without spaces the rearrangement of letters «A», «B» and «C» which represent the coins in the increasing order of their weights. | [
"A>B\nC<B\nA>C\n",
"A<B\nB>C\nC>A\n"
] | [
"CBA",
"ACB"
] | none | 1,000 | [
{
"input": "A>B\nC<B\nA>C",
"output": "CBA"
},
{
"input": "A<B\nB>C\nC>A",
"output": "ACB"
},
{
"input": "A<C\nB<A\nB>C",
"output": "Impossible"
},
{
"input": "A<B\nA<C\nB>C",
"output": "ACB"
},
{
"input": "B>A\nC<B\nC>A",
"output": "ACB"
},
{
"input":... | 1,659,997,452 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 60 | 0 | x=input()
y=input()
z=input()
theList=['','','','','']
error=1
Xsplit=list(x)
if Xsplit[1] == '>':
theList[1]=Xsplit[0]
theList[3] = Xsplit[2]
elif Xsplit[1] == '<':
theList[1]=Xsplit[2]
theList[3] = Xsplit[0]
Ysplit=list(y)
if Ysplit[1] == '<':
if Ysplit[2] in Xsplit:
location=theList.index(Ysplit[2])
theList[location+1]=Ysplit[0]
elif Ysplit[0] in Xsplit:
location = theList.index(Ysplit[0])
theList[location - 1] = Ysplit[2]
elif Ysplit[1] == '>':
if Ysplit[2] in Xsplit:
location=theList.index(Ysplit[2])
theList[location-1]=Ysplit[0]
elif Ysplit[0] in Xsplit:
location = theList.index(Ysplit[0])
theList[location +1] = Ysplit[2]
Zsplit=list(z)
if Zsplit[1] == '<':
if Zsplit[2] in Ysplit:
location=theList.index(Zsplit[2])
location2 = theList.index(Zsplit[2], default=None)
if location2 != location:
error = 0
elif location == None:
theList[location + 1] = Zsplit[0]
elif Zsplit[0] in Ysplit:
location = theList.index(Zsplit[0])
location2 = theList.index(Zsplit[2], default=None)
if location2 != location:
error = 0
elif location == None:
theList[location - 1] = Zsplit[2]
elif Zsplit[1] == '>':
if Zsplit[2] in Ysplit:
location=theList.index(Zsplit[2])
location2 = theList.index(Zsplit[0], default=None)
if location2 != location:
error = 0
elif location == None:
theList[location - 1] = Zsplit[0]
elif Zsplit[0] in Ysplit:
location = theList.index(Zsplit[0])
location2 =theList.index(Zsplit[2],default=None)
if location2 != location:
error=0
elif location == None:
theList[location + 1] = Zsplit[2]
if error==1:
theList.reverse()
print("".join(map(str, theList)))
else:
print("error")
| Title: Coins
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal.
Input Specification:
The input data contains the results of all the weighting, one result on each line. It is guaranteed that every coin pair was weighted exactly once. Vasya labelled the coins with letters «A», «B» and «C». Each result is a line that appears as (letter)(> or < sign)(letter). For example, if coin "A" proved lighter than coin "B", the result of the weighting is A<B.
Output Specification:
It the results are contradictory, print Impossible. Otherwise, print without spaces the rearrangement of letters «A», «B» and «C» which represent the coins in the increasing order of their weights.
Demo Input:
['A>B\nC<B\nA>C\n', 'A<B\nB>C\nC>A\n']
Demo Output:
['CBA', 'ACB']
Note:
none | ```python
x=input()
y=input()
z=input()
theList=['','','','','']
error=1
Xsplit=list(x)
if Xsplit[1] == '>':
theList[1]=Xsplit[0]
theList[3] = Xsplit[2]
elif Xsplit[1] == '<':
theList[1]=Xsplit[2]
theList[3] = Xsplit[0]
Ysplit=list(y)
if Ysplit[1] == '<':
if Ysplit[2] in Xsplit:
location=theList.index(Ysplit[2])
theList[location+1]=Ysplit[0]
elif Ysplit[0] in Xsplit:
location = theList.index(Ysplit[0])
theList[location - 1] = Ysplit[2]
elif Ysplit[1] == '>':
if Ysplit[2] in Xsplit:
location=theList.index(Ysplit[2])
theList[location-1]=Ysplit[0]
elif Ysplit[0] in Xsplit:
location = theList.index(Ysplit[0])
theList[location +1] = Ysplit[2]
Zsplit=list(z)
if Zsplit[1] == '<':
if Zsplit[2] in Ysplit:
location=theList.index(Zsplit[2])
location2 = theList.index(Zsplit[2], default=None)
if location2 != location:
error = 0
elif location == None:
theList[location + 1] = Zsplit[0]
elif Zsplit[0] in Ysplit:
location = theList.index(Zsplit[0])
location2 = theList.index(Zsplit[2], default=None)
if location2 != location:
error = 0
elif location == None:
theList[location - 1] = Zsplit[2]
elif Zsplit[1] == '>':
if Zsplit[2] in Ysplit:
location=theList.index(Zsplit[2])
location2 = theList.index(Zsplit[0], default=None)
if location2 != location:
error = 0
elif location == None:
theList[location - 1] = Zsplit[0]
elif Zsplit[0] in Ysplit:
location = theList.index(Zsplit[0])
location2 =theList.index(Zsplit[2],default=None)
if location2 != location:
error=0
elif location == None:
theList[location + 1] = Zsplit[2]
if error==1:
theList.reverse()
print("".join(map(str, theList)))
else:
print("error")
``` | -1 |
761 | A | Dasha and Stairs | PROGRAMMING | 1,000 | [
"brute force",
"constructive algorithms",
"implementation",
"math"
] | null | null | On her way to programming school tiger Dasha faced her first test — a huge staircase!
The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — the number of steps with even and odd numbers.
You need to check whether there is an interval of steps from the *l*-th to the *r*-th (1<=≤<=*l*<=≤<=*r*), for which values that Dasha has found are correct. | In the only line you are given two integers *a*, *b* (0<=≤<=*a*,<=*b*<=≤<=100) — the number of even and odd steps, accordingly. | In the only line print "YES", if the interval of steps described above exists, and "NO" otherwise. | [
"2 3\n",
"3 1\n"
] | [
"YES\n",
"NO\n"
] | In the first example one of suitable intervals is from 1 to 5. The interval contains two even steps — 2 and 4, and three odd: 1, 3 and 5. | 500 | [
{
"input": "2 3",
"output": "YES"
},
{
"input": "3 1",
"output": "NO"
},
{
"input": "5 4",
"output": "YES"
},
{
"input": "9 9",
"output": "YES"
},
{
"input": "85 95",
"output": "NO"
},
{
"input": "0 1",
"output": "YES"
},
{
"input": "89 25"... | 1,486,239,522 | 2,147,483,647 | Python 3 | OK | TESTS | 21 | 62 | 4,608,000 | n,m=map(int, input().split())
if n==0 and m==0:
print('NO')
elif abs(n-m)<=1:
print('YES')
else:
print('NO')
| Title: Dasha and Stairs
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
On her way to programming school tiger Dasha faced her first test — a huge staircase!
The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — the number of steps with even and odd numbers.
You need to check whether there is an interval of steps from the *l*-th to the *r*-th (1<=≤<=*l*<=≤<=*r*), for which values that Dasha has found are correct.
Input Specification:
In the only line you are given two integers *a*, *b* (0<=≤<=*a*,<=*b*<=≤<=100) — the number of even and odd steps, accordingly.
Output Specification:
In the only line print "YES", if the interval of steps described above exists, and "NO" otherwise.
Demo Input:
['2 3\n', '3 1\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first example one of suitable intervals is from 1 to 5. The interval contains two even steps — 2 and 4, and three odd: 1, 3 and 5. | ```python
n,m=map(int, input().split())
if n==0 and m==0:
print('NO')
elif abs(n-m)<=1:
print('YES')
else:
print('NO')
``` | 3 | |
766 | B | Mahmoud and a Triangle | PROGRAMMING | 1,000 | [
"constructive algorithms",
"geometry",
"greedy",
"math",
"number theory",
"sortings"
] | null | null | Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle.
Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area. | The first line contains single integer *n* (3<=≤<=*n*<=≤<=105) — the number of line segments Mahmoud has.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — the lengths of line segments Mahmoud has. | In the only line print "YES" if he can choose exactly three line segments and form a non-degenerate triangle with them, and "NO" otherwise. | [
"5\n1 5 3 2 4\n",
"3\n4 1 2\n"
] | [
"YES\n",
"NO\n"
] | For the first example, he can use line segments with lengths 2, 4 and 5 to form a non-degenerate triangle. | 1,000 | [
{
"input": "5\n1 5 3 2 4",
"output": "YES"
},
{
"input": "3\n4 1 2",
"output": "NO"
},
{
"input": "30\n197 75 517 39724 7906061 1153471 3 15166 168284 3019844 272293 316 16 24548 42 118 5792 5 9373 1866366 4886214 24 2206 712886 104005 1363 836 64273 440585 3576",
"output": "NO"
},... | 1,699,153,433 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 0 | 77 | 0 | n = int(input())
a = list(map(int, input().split()))
a.sort()
l = a[0]
r = a[1]
flag = True
for c in range(2, n):
m = a[c]
if l + r > m and l + m > r and m + r > l:
print("YES")
flag = False
break
if flag:
print("NO") | Title: Mahmoud and a Triangle
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle.
Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.
Input Specification:
The first line contains single integer *n* (3<=≤<=*n*<=≤<=105) — the number of line segments Mahmoud has.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — the lengths of line segments Mahmoud has.
Output Specification:
In the only line print "YES" if he can choose exactly three line segments and form a non-degenerate triangle with them, and "NO" otherwise.
Demo Input:
['5\n1 5 3 2 4\n', '3\n4 1 2\n']
Demo Output:
['YES\n', 'NO\n']
Note:
For the first example, he can use line segments with lengths 2, 4 and 5 to form a non-degenerate triangle. | ```python
n = int(input())
a = list(map(int, input().split()))
a.sort()
l = a[0]
r = a[1]
flag = True
for c in range(2, n):
m = a[c]
if l + r > m and l + m > r and m + r > l:
print("YES")
flag = False
break
if flag:
print("NO")
``` | 0 | |
962 | D | Merge Equals | PROGRAMMING | 1,600 | [
"data structures",
"implementation"
] | null | null | You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value $x$ that occurs in the array $2$ or more times. Take the first two occurrences of $x$ in this array (the two leftmost occurrences). Remove the left of these two occurrences, and the right one is replaced by the sum of this two values (that is, $2 \cdot x$).
Determine how the array will look after described operations are performed.
For example, consider the given array looks like $[3, 4, 1, 2, 2, 1, 1]$. It will be changed in the following way: $[3, 4, 1, 2, 2, 1, 1]~\rightarrow~[3, 4, 2, 2, 2, 1]~\rightarrow~[3, 4, 4, 2, 1]~\rightarrow~[3, 8, 2, 1]$.
If the given array is look like $[1, 1, 3, 1, 1]$ it will be changed in the following way: $[1, 1, 3, 1, 1]~\rightarrow~[2, 3, 1, 1]~\rightarrow~[2, 3, 2]~\rightarrow~[3, 4]$. | The first line contains a single integer $n$ ($2 \le n \le 150\,000$) — the number of elements in the array.
The second line contains a sequence from $n$ elements $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{9}$) — the elements of the array. | In the first line print an integer $k$ — the number of elements in the array after all the performed operations. In the second line print $k$ integers — the elements of the array after all the performed operations. | [
"7\n3 4 1 2 2 1 1\n",
"5\n1 1 3 1 1\n",
"5\n10 40 20 50 30\n"
] | [
"4\n3 8 2 1 \n",
"2\n3 4 \n",
"5\n10 40 20 50 30 \n"
] | The first two examples were considered in the statement.
In the third example all integers in the given array are distinct, so it will not change. | 0 | [
{
"input": "7\n3 4 1 2 2 1 1",
"output": "4\n3 8 2 1 "
},
{
"input": "5\n1 1 3 1 1",
"output": "2\n3 4 "
},
{
"input": "5\n10 40 20 50 30",
"output": "5\n10 40 20 50 30 "
},
{
"input": "100\n10 10 15 12 15 13 15 12 10 10 15 11 13 14 13 14 10 13 12 10 14 12 13 11 14 15 12 11 1... | 1,567,155,559 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 6 | 264 | 11,571,200 | n = int(input())
A = list(map(int, input().split()))
inds = {}
counter = {}
topop = set()
i = 0
c = 0
for __ in range(10 ** 6):
if i not in topop:
if A[i] in inds and inds[A[i]] not in topop:
topop.add(inds[A[i]])
A[i] *= 2
c += 1
inds[A[i]] = i
i += 1
if i == n:
inds.clear()
i = 0
ans = []
for i in range(n):
if i not in topop:
ans.append(A[i])
print(len(ans))
print(*ans) | Title: Merge Equals
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value $x$ that occurs in the array $2$ or more times. Take the first two occurrences of $x$ in this array (the two leftmost occurrences). Remove the left of these two occurrences, and the right one is replaced by the sum of this two values (that is, $2 \cdot x$).
Determine how the array will look after described operations are performed.
For example, consider the given array looks like $[3, 4, 1, 2, 2, 1, 1]$. It will be changed in the following way: $[3, 4, 1, 2, 2, 1, 1]~\rightarrow~[3, 4, 2, 2, 2, 1]~\rightarrow~[3, 4, 4, 2, 1]~\rightarrow~[3, 8, 2, 1]$.
If the given array is look like $[1, 1, 3, 1, 1]$ it will be changed in the following way: $[1, 1, 3, 1, 1]~\rightarrow~[2, 3, 1, 1]~\rightarrow~[2, 3, 2]~\rightarrow~[3, 4]$.
Input Specification:
The first line contains a single integer $n$ ($2 \le n \le 150\,000$) — the number of elements in the array.
The second line contains a sequence from $n$ elements $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{9}$) — the elements of the array.
Output Specification:
In the first line print an integer $k$ — the number of elements in the array after all the performed operations. In the second line print $k$ integers — the elements of the array after all the performed operations.
Demo Input:
['7\n3 4 1 2 2 1 1\n', '5\n1 1 3 1 1\n', '5\n10 40 20 50 30\n']
Demo Output:
['4\n3 8 2 1 \n', '2\n3 4 \n', '5\n10 40 20 50 30 \n']
Note:
The first two examples were considered in the statement.
In the third example all integers in the given array are distinct, so it will not change. | ```python
n = int(input())
A = list(map(int, input().split()))
inds = {}
counter = {}
topop = set()
i = 0
c = 0
for __ in range(10 ** 6):
if i not in topop:
if A[i] in inds and inds[A[i]] not in topop:
topop.add(inds[A[i]])
A[i] *= 2
c += 1
inds[A[i]] = i
i += 1
if i == n:
inds.clear()
i = 0
ans = []
for i in range(n):
if i not in topop:
ans.append(A[i])
print(len(ans))
print(*ans)
``` | 0 | |
1,000 | B | Light It Up | PROGRAMMING | 1,500 | [
"greedy"
] | null | null | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.
The lamp allows only good programs. Good program can be represented as a non-empty array $a$, where $0 < a_1 < a_2 < \dots < a_{|a|} < M$. All $a_i$ must be integers. Of course, preinstalled program is a good program.
The lamp follows program $a$ in next manner: at moment $0$ turns power and light on. Then at moment $a_i$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $1$ and then do nothing, the total time when the lamp is lit will be $1$. Finally, at moment $M$ the lamp is turning its power off regardless of its state.
Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $a$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $a$, or even at the begining or at the end of $a$.
Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $x$ till moment $y$, then its lit for $y - x$ units of time. Segments of time when the lamp is lit are summed up. | First line contains two space separated integers $n$ and $M$ ($1 \le n \le 10^5$, $2 \le M \le 10^9$) — the length of program $a$ and the moment when power turns off.
Second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($0 < a_1 < a_2 < \dots < a_n < M$) — initially installed program $a$. | Print the only integer — maximum possible total time when the lamp is lit. | [
"3 10\n4 6 7\n",
"2 12\n1 10\n",
"2 7\n3 4\n"
] | [
"8\n",
"9\n",
"6\n"
] | In the first example, one of possible optimal solutions is to insert value $x = 3$ before $a_1$, so program will be $[3, 4, 6, 7]$ and time of lamp being lit equals $(3 - 0) + (6 - 4) + (10 - 7) = 8$. Other possible solution is to insert $x = 5$ in appropriate place.
In the second example, there is only one optimal solution: to insert $x = 2$ between $a_1$ and $a_2$. Program will become $[1, 2, 10]$, and answer will be $(1 - 0) + (10 - 2) = 9$.
In the third example, optimal answer is to leave program untouched, so answer will be $(3 - 0) + (7 - 4) = 6$. | 0 | [
{
"input": "3 10\n4 6 7",
"output": "8"
},
{
"input": "2 12\n1 10",
"output": "9"
},
{
"input": "2 7\n3 4",
"output": "6"
},
{
"input": "1 2\n1",
"output": "1"
},
{
"input": "5 10\n1 3 5 6 8",
"output": "6"
},
{
"input": "7 1000000000\n1 10001 10011 20... | 1,635,214,742 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 9 | 186 | 13,004,800 | n,M = map(int,input().split())
k = list(map(int,input().split()))
k.append(0)
k.append(M)
k.sort()
r = []
l_odd = []
l_even = []
for i in range(1,len(k),2):
s = k[i] - k[i-1]
l_odd.append(s)
for i in range(2,len(k),2):
s = k[i] - k[i-1]
l_even.append(s)
l1 = sum(l_odd)
l2 = sum(l_even)
r.append(l1)
leftlo = 0
rightle = l2
for i in range(0,len(l_odd)):
s = l_odd[i]
if i > 0:
leftlo += l_odd[i-1]
rightle -= l_even[i-1]
l0 = leftlo + rightle + s-1
r.append(l0)
for i in range(0,len(l_even)):
s = l_even[i]
if i > 0:
leftlo += l_odd[i-1]
rightle -= l_even[i]
l0 = leftlo + rightle + s-1
r.append(l0)
print(max(r))
| Title: Light It Up
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.
The lamp allows only good programs. Good program can be represented as a non-empty array $a$, where $0 < a_1 < a_2 < \dots < a_{|a|} < M$. All $a_i$ must be integers. Of course, preinstalled program is a good program.
The lamp follows program $a$ in next manner: at moment $0$ turns power and light on. Then at moment $a_i$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $1$ and then do nothing, the total time when the lamp is lit will be $1$. Finally, at moment $M$ the lamp is turning its power off regardless of its state.
Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $a$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $a$, or even at the begining or at the end of $a$.
Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $x$ till moment $y$, then its lit for $y - x$ units of time. Segments of time when the lamp is lit are summed up.
Input Specification:
First line contains two space separated integers $n$ and $M$ ($1 \le n \le 10^5$, $2 \le M \le 10^9$) — the length of program $a$ and the moment when power turns off.
Second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($0 < a_1 < a_2 < \dots < a_n < M$) — initially installed program $a$.
Output Specification:
Print the only integer — maximum possible total time when the lamp is lit.
Demo Input:
['3 10\n4 6 7\n', '2 12\n1 10\n', '2 7\n3 4\n']
Demo Output:
['8\n', '9\n', '6\n']
Note:
In the first example, one of possible optimal solutions is to insert value $x = 3$ before $a_1$, so program will be $[3, 4, 6, 7]$ and time of lamp being lit equals $(3 - 0) + (6 - 4) + (10 - 7) = 8$. Other possible solution is to insert $x = 5$ in appropriate place.
In the second example, there is only one optimal solution: to insert $x = 2$ between $a_1$ and $a_2$. Program will become $[1, 2, 10]$, and answer will be $(1 - 0) + (10 - 2) = 9$.
In the third example, optimal answer is to leave program untouched, so answer will be $(3 - 0) + (7 - 4) = 6$. | ```python
n,M = map(int,input().split())
k = list(map(int,input().split()))
k.append(0)
k.append(M)
k.sort()
r = []
l_odd = []
l_even = []
for i in range(1,len(k),2):
s = k[i] - k[i-1]
l_odd.append(s)
for i in range(2,len(k),2):
s = k[i] - k[i-1]
l_even.append(s)
l1 = sum(l_odd)
l2 = sum(l_even)
r.append(l1)
leftlo = 0
rightle = l2
for i in range(0,len(l_odd)):
s = l_odd[i]
if i > 0:
leftlo += l_odd[i-1]
rightle -= l_even[i-1]
l0 = leftlo + rightle + s-1
r.append(l0)
for i in range(0,len(l_even)):
s = l_even[i]
if i > 0:
leftlo += l_odd[i-1]
rightle -= l_even[i]
l0 = leftlo + rightle + s-1
r.append(l0)
print(max(r))
``` | 0 | |
228 | A | Is your horseshoe on the other hoof? | PROGRAMMING | 800 | [
"implementation"
] | null | null | Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.
Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. | The first line contains four space-separated integers *s*1,<=*s*2,<=*s*3,<=*s*4 (1<=≤<=*s*1,<=*s*2,<=*s*3,<=*s*4<=≤<=109) — the colors of horseshoes Valera has.
Consider all possible colors indexed with integers. | Print a single integer — the minimum number of horseshoes Valera needs to buy. | [
"1 7 3 3\n",
"7 7 7 7\n"
] | [
"1\n",
"3\n"
] | none | 500 | [
{
"input": "1 7 3 3",
"output": "1"
},
{
"input": "7 7 7 7",
"output": "3"
},
{
"input": "81170865 673572653 756938629 995577259",
"output": "0"
},
{
"input": "3491663 217797045 522540872 715355328",
"output": "0"
},
{
"input": "251590420 586975278 916631563 58697... | 1,697,276,531 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 2 | 92 | 0 | s1,s2,s3,s4=map(int,input().split())
s=str(s1)+str(s2)+str(s3)+str(s4)
s=set(s)
l=len(s)
print(4-l) | Title: Is your horseshoe on the other hoof?
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.
Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
Input Specification:
The first line contains four space-separated integers *s*1,<=*s*2,<=*s*3,<=*s*4 (1<=≤<=*s*1,<=*s*2,<=*s*3,<=*s*4<=≤<=109) — the colors of horseshoes Valera has.
Consider all possible colors indexed with integers.
Output Specification:
Print a single integer — the minimum number of horseshoes Valera needs to buy.
Demo Input:
['1 7 3 3\n', '7 7 7 7\n']
Demo Output:
['1\n', '3\n']
Note:
none | ```python
s1,s2,s3,s4=map(int,input().split())
s=str(s1)+str(s2)+str(s3)+str(s4)
s=set(s)
l=len(s)
print(4-l)
``` | 0 | |
90 | A | Cableway | PROGRAMMING | 1,000 | [
"greedy",
"math"
] | A. Cableway | 2 | 256 | A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.
A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well.
The number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, after each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, the cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly 30 minutes for a cablecar to get to the top.
All students are divided into three groups: *r* of them like to ascend only in the red cablecars, *g* of them prefer only the green ones and *b* of them prefer only the blue ones. A student never gets on a cablecar painted a color that he doesn't like,
The first cablecar to arrive (at the moment of time 0) is painted red. Determine the least time it will take all students to ascend to the mountain top. | The first line contains three integers *r*, *g* and *b* (0<=≤<=*r*,<=*g*,<=*b*<=≤<=100). It is guaranteed that *r*<=+<=*g*<=+<=*b*<=><=0, it means that the group consists of at least one student. | Print a single number — the minimal time the students need for the whole group to ascend to the top of the mountain. | [
"1 3 2\n",
"3 2 1\n"
] | [
"34",
"33"
] | Let's analyze the first sample.
At the moment of time 0 a red cablecar comes and one student from the *r* group get on it and ascends to the top at the moment of time 30.
At the moment of time 1 a green cablecar arrives and two students from the *g* group get on it; they get to the top at the moment of time 31.
At the moment of time 2 comes the blue cablecar and two students from the *b* group get on it. They ascend to the top at the moment of time 32.
At the moment of time 3 a red cablecar arrives but the only student who is left doesn't like red and the cablecar leaves empty.
At the moment of time 4 a green cablecar arrives and one student from the *g* group gets on it. He ascends to top at the moment of time 34.
Thus, all the students are on the top, overall the ascension took exactly 34 minutes. | 500 | [
{
"input": "1 3 2",
"output": "34"
},
{
"input": "3 2 1",
"output": "33"
},
{
"input": "3 5 2",
"output": "37"
},
{
"input": "10 10 10",
"output": "44"
},
{
"input": "29 7 24",
"output": "72"
},
{
"input": "28 94 13",
"output": "169"
},
{
"... | 1,583,955,751 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 216 | 307,200 | r, g, b = map(int, input().split())
print(30 + max(r, g + 1, b + 2))
| Title: Cableway
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.
A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well.
The number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, after each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, the cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly 30 minutes for a cablecar to get to the top.
All students are divided into three groups: *r* of them like to ascend only in the red cablecars, *g* of them prefer only the green ones and *b* of them prefer only the blue ones. A student never gets on a cablecar painted a color that he doesn't like,
The first cablecar to arrive (at the moment of time 0) is painted red. Determine the least time it will take all students to ascend to the mountain top.
Input Specification:
The first line contains three integers *r*, *g* and *b* (0<=≤<=*r*,<=*g*,<=*b*<=≤<=100). It is guaranteed that *r*<=+<=*g*<=+<=*b*<=><=0, it means that the group consists of at least one student.
Output Specification:
Print a single number — the minimal time the students need for the whole group to ascend to the top of the mountain.
Demo Input:
['1 3 2\n', '3 2 1\n']
Demo Output:
['34', '33']
Note:
Let's analyze the first sample.
At the moment of time 0 a red cablecar comes and one student from the *r* group get on it and ascends to the top at the moment of time 30.
At the moment of time 1 a green cablecar arrives and two students from the *g* group get on it; they get to the top at the moment of time 31.
At the moment of time 2 comes the blue cablecar and two students from the *b* group get on it. They ascend to the top at the moment of time 32.
At the moment of time 3 a red cablecar arrives but the only student who is left doesn't like red and the cablecar leaves empty.
At the moment of time 4 a green cablecar arrives and one student from the *g* group gets on it. He ascends to top at the moment of time 34.
Thus, all the students are on the top, overall the ascension took exactly 34 minutes. | ```python
r, g, b = map(int, input().split())
print(30 + max(r, g + 1, b + 2))
``` | 0 |
12 | A | Super Agent | PROGRAMMING | 800 | [
"implementation"
] | A. Super Agent | 2 | 256 | There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage, he penetrated into the Potatoland territory and reached the secret base.
Now he is standing at the entrance, but to get inside he need to pass combination lock. Minute ago one of the workers entered the password on the terminal and opened the door. The terminal is a square digital keyboard 3<=×<=3 with digits from 1 to 9.
Pearlo knows that the password consists from distinct digits and is probably symmetric with respect to the central button of the terminal. He has heat sensor which allowed him to detect the digits which the worker pressed. Now he wants to check whether the password entered by the worker is symmetric with respect to the central button of the terminal. This fact can Help Pearlo to reduce the number of different possible password combinations. | Input contains the matrix of three rows of three symbols each. Symbol «X» means that the corresponding button was pressed, and «.» means that is was not pressed. The matrix may contain no «X», also it may contain no «.». | Print YES if the password is symmetric with respect to the central button of the terminal and NO otherwise. | [
"XX.\n...\n.XX\n",
"X.X\nX..\n...\n"
] | [
"YES\n",
"NO\n"
] | If you are not familiar with the term «central symmetry», you may look into http://en.wikipedia.org/wiki/Central_symmetry | 0 | [
{
"input": "XX.\n...\n.XX",
"output": "YES"
},
{
"input": ".X.\n.X.\n.X.",
"output": "YES"
},
{
"input": "XXX\nXXX\nXXX",
"output": "YES"
},
{
"input": "XXX\nX.X\nXXX",
"output": "YES"
},
{
"input": "X..\n.X.\n..X",
"output": "YES"
},
{
"input": "...\n... | 1,618,048,774 | 2,147,483,647 | Python 3 | OK | TESTS | 40 | 124 | 0 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 30 19:32:51 2021
@author: nehas
"""
r1=input()
r2=input()
r3=input()
if(r1[0]==r3[2] and r1[1]==r3[1] and r1[2]==r3[0] and r2[0]==r2[2]):
print("YES")
else:
print("NO") | Title: Super Agent
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage, he penetrated into the Potatoland territory and reached the secret base.
Now he is standing at the entrance, but to get inside he need to pass combination lock. Minute ago one of the workers entered the password on the terminal and opened the door. The terminal is a square digital keyboard 3<=×<=3 with digits from 1 to 9.
Pearlo knows that the password consists from distinct digits and is probably symmetric with respect to the central button of the terminal. He has heat sensor which allowed him to detect the digits which the worker pressed. Now he wants to check whether the password entered by the worker is symmetric with respect to the central button of the terminal. This fact can Help Pearlo to reduce the number of different possible password combinations.
Input Specification:
Input contains the matrix of three rows of three symbols each. Symbol «X» means that the corresponding button was pressed, and «.» means that is was not pressed. The matrix may contain no «X», also it may contain no «.».
Output Specification:
Print YES if the password is symmetric with respect to the central button of the terminal and NO otherwise.
Demo Input:
['XX.\n...\n.XX\n', 'X.X\nX..\n...\n']
Demo Output:
['YES\n', 'NO\n']
Note:
If you are not familiar with the term «central symmetry», you may look into http://en.wikipedia.org/wiki/Central_symmetry | ```python
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 30 19:32:51 2021
@author: nehas
"""
r1=input()
r2=input()
r3=input()
if(r1[0]==r3[2] and r1[1]==r3[1] and r1[2]==r3[0] and r2[0]==r2[2]):
print("YES")
else:
print("NO")
``` | 3.969 |
709 | A | Juicer | PROGRAMMING | 900 | [
"implementation"
] | null | null | Kolya is going to make fresh orange juice. He has *n* oranges of sizes *a*1,<=*a*2,<=...,<=*a**n*. Kolya will put them in the juicer in the fixed order, starting with orange of size *a*1, then orange of size *a*2 and so on. To be put in the juicer the orange must have size not exceeding *b*, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.
The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than *d*. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section? | The first line of the input contains three integers *n*, *b* and *d* (1<=≤<=*n*<=≤<=100<=000, 1<=≤<=*b*<=≤<=*d*<=≤<=1<=000<=000) — the number of oranges, the maximum size of the orange that fits in the juicer and the value *d*, which determines the condition when the waste section should be emptied.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1<=000<=000) — sizes of the oranges listed in the order Kolya is going to try to put them in the juicer. | Print one integer — the number of times Kolya will have to empty the waste section. | [
"2 7 10\n5 6\n",
"1 5 10\n7\n",
"3 10 10\n5 7 7\n",
"1 1 1\n1\n"
] | [
"1\n",
"0\n",
"1\n",
"0\n"
] | In the first sample, Kolya will squeeze the juice from two oranges and empty the waste section afterwards.
In the second sample, the orange won't fit in the juicer so Kolya will have no juice at all. | 500 | [
{
"input": "2 7 10\n5 6",
"output": "1"
},
{
"input": "1 5 10\n7",
"output": "0"
},
{
"input": "3 10 10\n5 7 7",
"output": "1"
},
{
"input": "1 1 1\n1",
"output": "0"
},
{
"input": "2 951637 951638\n44069 951637",
"output": "1"
},
{
"input": "50 100 12... | 1,687,613,448 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 58 | 92 | 11,673,600 | n,b,d = map(int,input().split())
ai = [int(x) for x in input().split()]
empty = section = 0
for a in ai:
if a <= b:
section += a
if section > d:
section = 0
empty += 1
print(empty) | Title: Juicer
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Kolya is going to make fresh orange juice. He has *n* oranges of sizes *a*1,<=*a*2,<=...,<=*a**n*. Kolya will put them in the juicer in the fixed order, starting with orange of size *a*1, then orange of size *a*2 and so on. To be put in the juicer the orange must have size not exceeding *b*, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.
The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than *d*. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?
Input Specification:
The first line of the input contains three integers *n*, *b* and *d* (1<=≤<=*n*<=≤<=100<=000, 1<=≤<=*b*<=≤<=*d*<=≤<=1<=000<=000) — the number of oranges, the maximum size of the orange that fits in the juicer and the value *d*, which determines the condition when the waste section should be emptied.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1<=000<=000) — sizes of the oranges listed in the order Kolya is going to try to put them in the juicer.
Output Specification:
Print one integer — the number of times Kolya will have to empty the waste section.
Demo Input:
['2 7 10\n5 6\n', '1 5 10\n7\n', '3 10 10\n5 7 7\n', '1 1 1\n1\n']
Demo Output:
['1\n', '0\n', '1\n', '0\n']
Note:
In the first sample, Kolya will squeeze the juice from two oranges and empty the waste section afterwards.
In the second sample, the orange won't fit in the juicer so Kolya will have no juice at all. | ```python
n,b,d = map(int,input().split())
ai = [int(x) for x in input().split()]
empty = section = 0
for a in ai:
if a <= b:
section += a
if section > d:
section = 0
empty += 1
print(empty)
``` | 3 | |
287 | A | IQ Test | PROGRAMMING | 1,100 | [
"brute force",
"implementation"
] | null | null | In the city of Ultima Thule job applicants are often offered an IQ test.
The test is as follows: the person gets a piece of squared paper with a 4<=×<=4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2<=×<=2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed.
Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2<=×<=2 square, consisting of cells of the same color. | Four lines contain four characters each: the *j*-th character of the *i*-th line equals "." if the cell in the *i*-th row and the *j*-th column of the square is painted white, and "#", if the cell is black. | Print "YES" (without the quotes), if the test can be passed and "NO" (without the quotes) otherwise. | [
"####\n.#..\n####\n....\n",
"####\n....\n####\n....\n"
] | [
"YES\n",
"NO\n"
] | In the first test sample it is enough to repaint the first cell in the second row. After such repainting the required 2 × 2 square is on the intersection of the 1-st and 2-nd row with the 1-st and 2-nd column. | 500 | [
{
"input": "###.\n...#\n###.\n...#",
"output": "NO"
},
{
"input": ".##.\n#..#\n.##.\n#..#",
"output": "NO"
},
{
"input": ".#.#\n#.#.\n.#.#\n#.#.",
"output": "NO"
},
{
"input": "##..\n..##\n##..\n..##",
"output": "NO"
},
{
"input": "#.#.\n#.#.\n.#.#\n.#.#",
"ou... | 1,574,534,745 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 7 | 124 | 0 | def rev(s):
s1 = ''
for i in s:
if i=="#":
s1+="."
else:
s1+="#"
return s1
l1 = []
for _ in range(4):
l1.append(input())
for i in range(1,4):
if l1[i-1]==rev(l1[i]):
pass
else:
print("YES")
break
else:
print("NO") | Title: IQ Test
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the city of Ultima Thule job applicants are often offered an IQ test.
The test is as follows: the person gets a piece of squared paper with a 4<=×<=4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2<=×<=2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed.
Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2<=×<=2 square, consisting of cells of the same color.
Input Specification:
Four lines contain four characters each: the *j*-th character of the *i*-th line equals "." if the cell in the *i*-th row and the *j*-th column of the square is painted white, and "#", if the cell is black.
Output Specification:
Print "YES" (without the quotes), if the test can be passed and "NO" (without the quotes) otherwise.
Demo Input:
['####\n.#..\n####\n....\n', '####\n....\n####\n....\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first test sample it is enough to repaint the first cell in the second row. After such repainting the required 2 × 2 square is on the intersection of the 1-st and 2-nd row with the 1-st and 2-nd column. | ```python
def rev(s):
s1 = ''
for i in s:
if i=="#":
s1+="."
else:
s1+="#"
return s1
l1 = []
for _ in range(4):
l1.append(input())
for i in range(1,4):
if l1[i-1]==rev(l1[i]):
pass
else:
print("YES")
break
else:
print("NO")
``` | 0 | |
33 | A | What is for dinner? | PROGRAMMING | 1,200 | [
"greedy",
"implementation"
] | A. What is for dinner? | 2 | 256 | In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing".
For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).
It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again.
Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative.
As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.
We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one. | The first line contains three integers *n*, *m*, *k* (1<=≤<=*m*<=≤<=*n*<=≤<=1000,<=0<=≤<=*k*<=≤<=106) — total amount of Valerie's teeth, amount of tooth rows and amount of crucians in Valerie's portion for dinner. Then follow *n* lines, each containing two integers: *r* (1<=≤<=*r*<=≤<=*m*) — index of the row, where belongs the corresponding tooth, and *c* (0<=≤<=*c*<=≤<=106) — its residual viability.
It's guaranteed that each tooth row has positive amount of teeth. | In the first line output the maximum amount of crucians that Valerie can consume for dinner. | [
"4 3 18\n2 3\n1 2\n3 6\n2 3\n",
"2 2 13\n1 13\n2 12\n"
] | [
"11\n",
"13\n"
] | none | 500 | [
{
"input": "4 3 18\n2 3\n1 2\n3 6\n2 3",
"output": "11"
},
{
"input": "2 2 13\n1 13\n2 12",
"output": "13"
},
{
"input": "5 4 8\n4 6\n4 5\n1 3\n2 0\n3 3",
"output": "8"
},
{
"input": "1 1 0\n1 3",
"output": "0"
},
{
"input": "7 1 30\n1 8\n1 15\n1 5\n1 17\n1 9\n1 1... | 1,553,374,315 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 4 | 216 | 0 | inp=input().split(" ")
n=int(inp[0])
m=inp[1]
k=int(inp[2])
blich=set()
res=0
for i in range(n):
blich.add(tuple(input().split(" ")))
for x in blich:
res += int(x[1])
print(k) if res>k else print(res) | Title: What is for dinner?
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing".
For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).
It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again.
Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative.
As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.
We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.
Input Specification:
The first line contains three integers *n*, *m*, *k* (1<=≤<=*m*<=≤<=*n*<=≤<=1000,<=0<=≤<=*k*<=≤<=106) — total amount of Valerie's teeth, amount of tooth rows and amount of crucians in Valerie's portion for dinner. Then follow *n* lines, each containing two integers: *r* (1<=≤<=*r*<=≤<=*m*) — index of the row, where belongs the corresponding tooth, and *c* (0<=≤<=*c*<=≤<=106) — its residual viability.
It's guaranteed that each tooth row has positive amount of teeth.
Output Specification:
In the first line output the maximum amount of crucians that Valerie can consume for dinner.
Demo Input:
['4 3 18\n2 3\n1 2\n3 6\n2 3\n', '2 2 13\n1 13\n2 12\n']
Demo Output:
['11\n', '13\n']
Note:
none | ```python
inp=input().split(" ")
n=int(inp[0])
m=inp[1]
k=int(inp[2])
blich=set()
res=0
for i in range(n):
blich.add(tuple(input().split(" ")))
for x in blich:
res += int(x[1])
print(k) if res>k else print(res)
``` | 0 |
116 | A | Tram | PROGRAMMING | 800 | [
"implementation"
] | null | null | Linear Kingdom has exactly one tram line. It has *n* stops, numbered from 1 to *n* in the order of tram's movement. At the *i*-th stop *a**i* passengers exit the tram, while *b**i* passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.
Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram. | The first line contains a single number *n* (2<=≤<=*n*<=≤<=1000) — the number of the tram's stops.
Then *n* lines follow, each contains two integers *a**i* and *b**i* (0<=≤<=*a**i*,<=*b**i*<=≤<=1000) — the number of passengers that exits the tram at the *i*-th stop, and the number of passengers that enter the tram at the *i*-th stop. The stops are given from the first to the last stop in the order of tram's movement.
- The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, . This particularly means that *a*1<==<=0. - At the last stop, all the passengers exit the tram and it becomes empty. More formally, . - No passenger will enter the train at the last stop. That is, *b**n*<==<=0. | Print a single integer denoting the minimum possible capacity of the tram (0 is allowed). | [
"4\n0 3\n2 5\n4 2\n4 0\n"
] | [
"6\n"
] | For the first example, a capacity of 6 is sufficient:
- At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3. - At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now. - At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now. - Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints.
Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer. | 500 | [
{
"input": "4\n0 3\n2 5\n4 2\n4 0",
"output": "6"
},
{
"input": "5\n0 4\n4 6\n6 5\n5 4\n4 0",
"output": "6"
},
{
"input": "10\n0 5\n1 7\n10 8\n5 3\n0 5\n3 3\n8 8\n0 6\n10 1\n9 0",
"output": "18"
},
{
"input": "3\n0 1\n1 1\n1 0",
"output": "1"
},
{
"input": "4\n0 1... | 1,685,978,378 | 2,147,483,647 | Python 3 | OK | TESTS | 71 | 92 | 0 | c=0
l=0
for i in range(int(input())):
q,w=map(int,input().split())
c=c-q+w
if l<c:
l=c
print(l) | Title: Tram
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Linear Kingdom has exactly one tram line. It has *n* stops, numbered from 1 to *n* in the order of tram's movement. At the *i*-th stop *a**i* passengers exit the tram, while *b**i* passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.
Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.
Input Specification:
The first line contains a single number *n* (2<=≤<=*n*<=≤<=1000) — the number of the tram's stops.
Then *n* lines follow, each contains two integers *a**i* and *b**i* (0<=≤<=*a**i*,<=*b**i*<=≤<=1000) — the number of passengers that exits the tram at the *i*-th stop, and the number of passengers that enter the tram at the *i*-th stop. The stops are given from the first to the last stop in the order of tram's movement.
- The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, . This particularly means that *a*1<==<=0. - At the last stop, all the passengers exit the tram and it becomes empty. More formally, . - No passenger will enter the train at the last stop. That is, *b**n*<==<=0.
Output Specification:
Print a single integer denoting the minimum possible capacity of the tram (0 is allowed).
Demo Input:
['4\n0 3\n2 5\n4 2\n4 0\n']
Demo Output:
['6\n']
Note:
For the first example, a capacity of 6 is sufficient:
- At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3. - At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now. - At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now. - Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints.
Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer. | ```python
c=0
l=0
for i in range(int(input())):
q,w=map(int,input().split())
c=c-q+w
if l<c:
l=c
print(l)
``` | 3 | |
707 | A | Brain's Photos | PROGRAMMING | 800 | [
"implementation"
] | null | null | Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour!
As soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white.
Photo can be represented as a matrix sized *n*<=×<=*m*, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors:
- 'C' (cyan)- 'M' (magenta)- 'Y' (yellow)- 'W' (white)- 'G' (grey)- 'B' (black)
The photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored. | The first line of the input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the number of photo pixel matrix rows and columns respectively.
Then *n* lines describing matrix rows follow. Each of them contains *m* space-separated characters describing colors of pixels in a row. Each character in the line is one of the 'C', 'M', 'Y', 'W', 'G' or 'B'. | Print the "#Black&White" (without quotes), if the photo is black-and-white and "#Color" (without quotes), if it is colored, in the only line. | [
"2 2\nC M\nY Y\n",
"3 2\nW W\nW W\nB B\n",
"1 1\nW\n"
] | [
"#Color",
"#Black&White",
"#Black&White"
] | none | 500 | [
{
"input": "2 2\nC M\nY Y",
"output": "#Color"
},
{
"input": "3 2\nW W\nW W\nB B",
"output": "#Black&White"
},
{
"input": "1 1\nW",
"output": "#Black&White"
},
{
"input": "2 3\nW W W\nB G Y",
"output": "#Color"
},
{
"input": "1 1\nW",
"output": "#Black&White"
... | 1,653,583,131 | 2,147,483,647 | Python 3 | OK | TESTS | 50 | 46 | 0 | n,m=map(int,input().split())
list1=[]
for i in range(n):
l=list(map(str,input().split()))
list1.append(l)
c=0
for i in list1:
for j in i:
if j=='C' or j=='M' or j=='Y':
c=1
break
if c==1:
break
if c==1:
print("#Color")
else:
print("#Black&White") | Title: Brain's Photos
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour!
As soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white.
Photo can be represented as a matrix sized *n*<=×<=*m*, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors:
- 'C' (cyan)- 'M' (magenta)- 'Y' (yellow)- 'W' (white)- 'G' (grey)- 'B' (black)
The photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.
Input Specification:
The first line of the input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the number of photo pixel matrix rows and columns respectively.
Then *n* lines describing matrix rows follow. Each of them contains *m* space-separated characters describing colors of pixels in a row. Each character in the line is one of the 'C', 'M', 'Y', 'W', 'G' or 'B'.
Output Specification:
Print the "#Black&White" (without quotes), if the photo is black-and-white and "#Color" (without quotes), if it is colored, in the only line.
Demo Input:
['2 2\nC M\nY Y\n', '3 2\nW W\nW W\nB B\n', '1 1\nW\n']
Demo Output:
['#Color', '#Black&White', '#Black&White']
Note:
none | ```python
n,m=map(int,input().split())
list1=[]
for i in range(n):
l=list(map(str,input().split()))
list1.append(l)
c=0
for i in list1:
for j in i:
if j=='C' or j=='M' or j=='Y':
c=1
break
if c==1:
break
if c==1:
print("#Color")
else:
print("#Black&White")
``` | 3 | |
721 | B | Passwords | PROGRAMMING | 1,100 | [
"implementation",
"math",
"sortings",
"strings"
] | null | null | Vanya is managed to enter his favourite site Codehorses. Vanya uses *n* distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.
Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrary order. Just when Vanya will have entered the correct password, he is immediately authorized on the site. Vanya will not enter any password twice.
Entering any passwords takes one second for Vanya. But if Vanya will enter wrong password *k* times, then he is able to make the next try only 5 seconds after that. Vanya makes each try immediately, that is, at each moment when Vanya is able to enter password, he is doing that.
Determine how many seconds will Vanya need to enter Codehorses in the best case for him (if he spends minimum possible number of second) and in the worst case (if he spends maximum possible amount of seconds). | The first line of the input contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=100) — the number of Vanya's passwords and the number of failed tries, after which the access to the site is blocked for 5 seconds.
The next *n* lines contains passwords, one per line — pairwise distinct non-empty strings consisting of latin letters and digits. Each password length does not exceed 100 characters.
The last line of the input contains the Vanya's Codehorses password. It is guaranteed that the Vanya's Codehorses password is equal to some of his *n* passwords. | Print two integers — time (in seconds), Vanya needs to be authorized to Codehorses in the best case for him and in the worst case respectively. | [
"5 2\ncba\nabc\nbb1\nabC\nABC\nabc\n",
"4 100\n11\n22\n1\n2\n22\n"
] | [
"1 15\n",
"3 4\n"
] | Consider the first sample case. As soon as all passwords have the same length, Vanya can enter the right password at the first try as well as at the last try. If he enters it at the first try, he spends exactly 1 second. Thus in the best case the answer is 1. If, at the other hand, he enters it at the last try, he enters another 4 passwords before. He spends 2 seconds to enter first 2 passwords, then he waits 5 seconds as soon as he made 2 wrong tries. Then he spends 2 more seconds to enter 2 wrong passwords, again waits 5 seconds and, finally, enters the correct password spending 1 more second. In summary in the worst case he is able to be authorized in 15 seconds.
Consider the second sample case. There is no way of entering passwords and get the access to the site blocked. As soon as the required password has length of 2, Vanya enters all passwords of length 1 anyway, spending 2 seconds for that. Then, in the best case, he immediately enters the correct password and the answer for the best case is 3, but in the worst case he enters wrong password of length 2 and only then the right one, spending 4 seconds at all. | 1,000 | [
{
"input": "5 2\ncba\nabc\nbb1\nabC\nABC\nabc",
"output": "1 15"
},
{
"input": "4 100\n11\n22\n1\n2\n22",
"output": "3 4"
},
{
"input": "1 1\na1\na1",
"output": "1 1"
},
{
"input": "1 100\na1\na1",
"output": "1 1"
},
{
"input": "2 1\nabc\nAbc\nAbc",
"output": ... | 1,592,862,156 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 2 | 140 | 20,172,800 | 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,k = map(int, input().split())
mini = 0
maxi = 0
pas = []
for i in range(n):
pas.append(str(input()))
pas = sorted(pas, key =lambda x:len(x))
cor = str(input())
clen = len(cor)
for i in range(n):
if(len(pas[i])==clen and mini==0):
mini = i+1+(((i+1)//k)*5)
if(len(pas[i]) > clen or i==n-1):
maxi = i+1+(((i+1)//k)*5)
break
print(mini, maxi)
| Title: Passwords
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya is managed to enter his favourite site Codehorses. Vanya uses *n* distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.
Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrary order. Just when Vanya will have entered the correct password, he is immediately authorized on the site. Vanya will not enter any password twice.
Entering any passwords takes one second for Vanya. But if Vanya will enter wrong password *k* times, then he is able to make the next try only 5 seconds after that. Vanya makes each try immediately, that is, at each moment when Vanya is able to enter password, he is doing that.
Determine how many seconds will Vanya need to enter Codehorses in the best case for him (if he spends minimum possible number of second) and in the worst case (if he spends maximum possible amount of seconds).
Input Specification:
The first line of the input contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=100) — the number of Vanya's passwords and the number of failed tries, after which the access to the site is blocked for 5 seconds.
The next *n* lines contains passwords, one per line — pairwise distinct non-empty strings consisting of latin letters and digits. Each password length does not exceed 100 characters.
The last line of the input contains the Vanya's Codehorses password. It is guaranteed that the Vanya's Codehorses password is equal to some of his *n* passwords.
Output Specification:
Print two integers — time (in seconds), Vanya needs to be authorized to Codehorses in the best case for him and in the worst case respectively.
Demo Input:
['5 2\ncba\nabc\nbb1\nabC\nABC\nabc\n', '4 100\n11\n22\n1\n2\n22\n']
Demo Output:
['1 15\n', '3 4\n']
Note:
Consider the first sample case. As soon as all passwords have the same length, Vanya can enter the right password at the first try as well as at the last try. If he enters it at the first try, he spends exactly 1 second. Thus in the best case the answer is 1. If, at the other hand, he enters it at the last try, he enters another 4 passwords before. He spends 2 seconds to enter first 2 passwords, then he waits 5 seconds as soon as he made 2 wrong tries. Then he spends 2 more seconds to enter 2 wrong passwords, again waits 5 seconds and, finally, enters the correct password spending 1 more second. In summary in the worst case he is able to be authorized in 15 seconds.
Consider the second sample case. There is no way of entering passwords and get the access to the site blocked. As soon as the required password has length of 2, Vanya enters all passwords of length 1 anyway, spending 2 seconds for that. Then, in the best case, he immediately enters the correct password and the answer for the best case is 3, but in the worst case he enters wrong password of length 2 and only then the right one, spending 4 seconds at all. | ```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,k = map(int, input().split())
mini = 0
maxi = 0
pas = []
for i in range(n):
pas.append(str(input()))
pas = sorted(pas, key =lambda x:len(x))
cor = str(input())
clen = len(cor)
for i in range(n):
if(len(pas[i])==clen and mini==0):
mini = i+1+(((i+1)//k)*5)
if(len(pas[i]) > clen or i==n-1):
maxi = i+1+(((i+1)//k)*5)
break
print(mini, maxi)
``` | 0 | |
270 | A | Fancy Fence | PROGRAMMING | 1,100 | [
"geometry",
"implementation",
"math"
] | null | null | Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle *a*.
Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to *a*? | The first line of input contains an integer *t* (0<=<<=*t*<=<<=180) — the number of tests. Each of the following *t* lines contains a single integer *a* (0<=<<=*a*<=<<=180) — the angle the robot can make corners at measured in degrees. | For each test, output on a single line "YES" (without quotes), if the robot can build a fence Emuskald wants, and "NO" (without quotes), if it is impossible. | [
"3\n30\n60\n90\n"
] | [
"NO\nYES\nYES\n"
] | In the first test case, it is impossible to build the fence, since there is no regular polygon with angle <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/df5f4b07dd5316fde165b43657b2696e2919e791.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the second test case, the fence is a regular triangle, and in the last test case — a square. | 500 | [
{
"input": "3\n30\n60\n90",
"output": "NO\nYES\nYES"
},
{
"input": "6\n1\n2\n3\n170\n179\n25",
"output": "NO\nNO\nNO\nYES\nYES\nNO"
}
] | 1,665,621,234 | 2,147,483,647 | Python 3 | OK | TESTS | 3 | 60 | 0 | t = int(input())
for i in range(t):
def angle(a):
if 360%(180-a)==0:
return'YES'
else:
return'NO'
a = int(input())
print(angle(a)) | Title: Fancy Fence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle *a*.
Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to *a*?
Input Specification:
The first line of input contains an integer *t* (0<=<<=*t*<=<<=180) — the number of tests. Each of the following *t* lines contains a single integer *a* (0<=<<=*a*<=<<=180) — the angle the robot can make corners at measured in degrees.
Output Specification:
For each test, output on a single line "YES" (without quotes), if the robot can build a fence Emuskald wants, and "NO" (without quotes), if it is impossible.
Demo Input:
['3\n30\n60\n90\n']
Demo Output:
['NO\nYES\nYES\n']
Note:
In the first test case, it is impossible to build the fence, since there is no regular polygon with angle <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/df5f4b07dd5316fde165b43657b2696e2919e791.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the second test case, the fence is a regular triangle, and in the last test case — a square. | ```python
t = int(input())
for i in range(t):
def angle(a):
if 360%(180-a)==0:
return'YES'
else:
return'NO'
a = int(input())
print(angle(a))
``` | 3 | |
916 | C | Jamie and Interesting Graph | PROGRAMMING | 1,600 | [
"constructive algorithms",
"graphs",
"shortest paths"
] | null | null | Jamie has recently found undirected weighted graphs with the following properties very interesting:
- The graph is connected and contains exactly *n* vertices and *m* edges. - All edge weights are integers and are in range [1,<=109] inclusive. - The length of shortest path from 1 to *n* is a prime number. - The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number. - The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting! | First line of input contains 2 integers *n*, *m* — the required number of vertices and edges. | In the first line output 2 integers *sp*, *mstw* (1<=≤<=*sp*,<=*mstw*<=≤<=1014) — the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next *m* lines output the edges of the graph. In each line output 3 integers *u*, *v*, *w* (1<=≤<=*u*,<=*v*<=≤<=*n*,<=1<=≤<=*w*<=≤<=109) describing the edge connecting *u* and *v* and having weight *w*. | [
"4 4\n",
"5 4\n"
] | [
"7 7\n1 2 3\n2 3 2\n3 4 2\n2 4 4\n",
"7 13\n1 2 2\n1 3 4\n1 4 3\n4 5 4\n"
] | The graph of sample 1: <img class="tex-graphics" src="https://espresso.codeforces.com/42f9750de41b0d9a6b21e8615170113cfe19b0f2.png" style="max-width: 100.0%;max-height: 100.0%;"/> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (*v*<sub class="lower-index">1</sub>, *v*<sub class="lower-index">2</sub>, ... , *v*<sub class="lower-index">*k*</sub>) such that *v*<sub class="lower-index">*i*</sub> is adjacent to *v*<sub class="lower-index">*i* + 1</sub> 1 ≤ *i* < *k* and the sum of weight <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e7f62cfd5c2c3b81dc80aaf2f512898495354f03.png" style="max-width: 100.0%;max-height: 100.0%;"/> is minimized where *w*(*i*, *j*) is the edge weight between *i* and *j*. ([https://en.wikipedia.org/wiki/Shortest_path_problem](https://en.wikipedia.org/wiki/Shortest_path_problem))
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. ([https://en.wikipedia.org/wiki/Prime_number](https://en.wikipedia.org/wiki/Prime_number))
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. ([https://en.wikipedia.org/wiki/Minimum_spanning_tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree))
[https://en.wikipedia.org/wiki/Multiple_edges](https://en.wikipedia.org/wiki/Multiple_edges) | 1,500 | [
{
"input": "4 4",
"output": "100003 100003\n1 2 100001\n2 3 1\n3 4 1\n1 3 1000000000"
},
{
"input": "5 4",
"output": "100003 100003\n1 2 100000\n2 3 1\n3 4 1\n4 5 1"
},
{
"input": "2 1",
"output": "100003 100003\n1 2 100003"
},
{
"input": "10 19",
"output": "100003 100003... | 1,518,521,050 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 0 | 46 | 19,968,000 | n, m = map(int, input().split())
p = 700001
for i in range(n - 2):
print(i + 1, i + 2, 1)
print(n - 1, n, p - n + 2)
m -= (n - 1)
for i in range(n):
for j in range(i + 2, n):
if m == 0:
exit()
m -= 1
print(i + 1, j + 1, 100000000)
| Title: Jamie and Interesting Graph
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Jamie has recently found undirected weighted graphs with the following properties very interesting:
- The graph is connected and contains exactly *n* vertices and *m* edges. - All edge weights are integers and are in range [1,<=109] inclusive. - The length of shortest path from 1 to *n* is a prime number. - The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number. - The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input Specification:
First line of input contains 2 integers *n*, *m* — the required number of vertices and edges.
Output Specification:
In the first line output 2 integers *sp*, *mstw* (1<=≤<=*sp*,<=*mstw*<=≤<=1014) — the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next *m* lines output the edges of the graph. In each line output 3 integers *u*, *v*, *w* (1<=≤<=*u*,<=*v*<=≤<=*n*,<=1<=≤<=*w*<=≤<=109) describing the edge connecting *u* and *v* and having weight *w*.
Demo Input:
['4 4\n', '5 4\n']
Demo Output:
['7 7\n1 2 3\n2 3 2\n3 4 2\n2 4 4\n', '7 13\n1 2 2\n1 3 4\n1 4 3\n4 5 4\n']
Note:
The graph of sample 1: <img class="tex-graphics" src="https://espresso.codeforces.com/42f9750de41b0d9a6b21e8615170113cfe19b0f2.png" style="max-width: 100.0%;max-height: 100.0%;"/> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (*v*<sub class="lower-index">1</sub>, *v*<sub class="lower-index">2</sub>, ... , *v*<sub class="lower-index">*k*</sub>) such that *v*<sub class="lower-index">*i*</sub> is adjacent to *v*<sub class="lower-index">*i* + 1</sub> 1 ≤ *i* < *k* and the sum of weight <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e7f62cfd5c2c3b81dc80aaf2f512898495354f03.png" style="max-width: 100.0%;max-height: 100.0%;"/> is minimized where *w*(*i*, *j*) is the edge weight between *i* and *j*. ([https://en.wikipedia.org/wiki/Shortest_path_problem](https://en.wikipedia.org/wiki/Shortest_path_problem))
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. ([https://en.wikipedia.org/wiki/Prime_number](https://en.wikipedia.org/wiki/Prime_number))
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. ([https://en.wikipedia.org/wiki/Minimum_spanning_tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree))
[https://en.wikipedia.org/wiki/Multiple_edges](https://en.wikipedia.org/wiki/Multiple_edges) | ```python
n, m = map(int, input().split())
p = 700001
for i in range(n - 2):
print(i + 1, i + 2, 1)
print(n - 1, n, p - n + 2)
m -= (n - 1)
for i in range(n):
for j in range(i + 2, n):
if m == 0:
exit()
m -= 1
print(i + 1, j + 1, 100000000)
``` | 0 | |
150 | A | Win or Freeze | PROGRAMMING | 1,400 | [
"games",
"math",
"number theory"
] | null | null | You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer *q*. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself.
The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move. | The first line contains the only integer *q* (1<=≤<=*q*<=≤<=1013).
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator. | In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer — his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them. | [
"6\n",
"30\n",
"1\n"
] | [
"2\n",
"1\n6\n",
"1\n0\n"
] | Number 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory. | 500 | [
{
"input": "6",
"output": "2"
},
{
"input": "30",
"output": "1\n6"
},
{
"input": "1",
"output": "1\n0"
},
{
"input": "2",
"output": "1\n0"
},
{
"input": "3",
"output": "1\n0"
},
{
"input": "5",
"output": "1\n0"
},
{
"input": "445538663413",... | 1,686,853,034 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 2 | 46 | 0 | n = int(input())
k = n
factors = []
i = 2
while i*i <= k :
if k%i == 0 :
factors.append(i)
while k%i == 0 :
k //= i
i += 1
if k != 1 :
factors.append(k)
if len(factors) == 1 :
print(1,0,sep='\n')
exit()
for i in factors :
if i*i < n and n%(i*i) == 0 :
print(1,i*i,sep='\n')
break
else :
if len(factors) == 1 :
print(2)
exit()
for i in range(len(factors)-1) :
for j in range(i+1,len(factors)) :
if factors[i]*factors[j] < n :
print(1,factors[i]*factors[j],sep='\n')
exit()
else :
print(2) | Title: Win or Freeze
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer *q*. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself.
The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.
Input Specification:
The first line contains the only integer *q* (1<=≤<=*q*<=≤<=1013).
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Output Specification:
In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer — his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them.
Demo Input:
['6\n', '30\n', '1\n']
Demo Output:
['2\n', '1\n6\n', '1\n0\n']
Note:
Number 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory. | ```python
n = int(input())
k = n
factors = []
i = 2
while i*i <= k :
if k%i == 0 :
factors.append(i)
while k%i == 0 :
k //= i
i += 1
if k != 1 :
factors.append(k)
if len(factors) == 1 :
print(1,0,sep='\n')
exit()
for i in factors :
if i*i < n and n%(i*i) == 0 :
print(1,i*i,sep='\n')
break
else :
if len(factors) == 1 :
print(2)
exit()
for i in range(len(factors)-1) :
for j in range(i+1,len(factors)) :
if factors[i]*factors[j] < n :
print(1,factors[i]*factors[j],sep='\n')
exit()
else :
print(2)
``` | 0 | |
412 | E | E-mail Addresses | PROGRAMMING | 1,900 | [
"implementation"
] | null | null | One of the most important products of the R1 company is a popular @r1.com mail service. The R1 mailboxes receive and send millions of emails every day.
Today, the online news thundered with terrible information. The R1 database crashed and almost no data could be saved except for one big string. The developers assume that the string contains the letters of some users of the R1 mail. Recovering letters is a tedious mostly manual work. So before you start this process, it was decided to estimate the difficulty of recovering. Namely, we need to calculate the number of different substrings of the saved string that form correct e-mail addresses.
We assume that valid addresses are only the e-mail addresses which meet the following criteria:
- the address should begin with a non-empty sequence of letters, numbers, characters '_', starting with a letter; - then must go character '@'; - then must go a non-empty sequence of letters or numbers; - then must go character '.'; - the address must end with a non-empty sequence of letters.
You got lucky again and the job was entrusted to you! Please note that the substring is several consecutive characters in a string. Two substrings, one consisting of the characters of the string with numbers *l*1,<=*l*1<=+<=1,<=*l*1<=+<=2,<=...,<=*r*1 and the other one consisting of the characters of the string with numbers *l*2,<=*l*2<=+<=1,<=*l*2<=+<=2,<=...,<=*r*2, are considered distinct if *l*1<=≠<=*l*2 or *r*1<=≠<=*r*2. | The first and the only line contains the sequence of characters *s*1*s*2... *s**n* (1<=≤<=*n*<=≤<=106) — the saved string. It is guaranteed that the given string contains only small English letters, digits and characters '.', '_', '@'. | Print in a single line the number of substrings that are valid e-mail addresses. | [
"[email protected]\n",
"[email protected]@[email protected]\n",
"[email protected]\n",
".asd123__..@\n"
] | [
"18\n",
"8\n",
"1\n",
"0\n"
] | In the first test case all the substrings that are correct e-mail addresses begin from one of the letters of the word agapov and end in one of the letters of the word com.
In the second test case note that the e-mail [[email protected]](/cdn-cgi/l/email-protection) is considered twice in the answer. Note that in this example the e-mail entries overlap inside the string. | 2,500 | [
{
"input": "gerald.agapov1991@gmail.com",
"output": "18"
},
{
"input": "x@x.x@x.x_e_@r1.com",
"output": "8"
},
{
"input": "a___@1.r",
"output": "1"
},
{
"input": ".asd123__..@",
"output": "0"
},
{
"input": "@",
"output": "0"
},
{
"input": ".",
"out... | 1,411,030,571 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 30 | 1,000 | 4,300,800 | s = input()
# находим собаку
# находим адреса слева
# умножаем на длину д.зоны
dogs = []
numbers = 0
dogp = 0
for i in range(len(s)):
if s[i] == '@':
dogs.append(i)
#print(dogs)
lastdog = 0
while dogp < len(dogs):
curgood = 0
# check leftside
for i in range(dogs[dogp]-1, -1, -1):
if s[i].isalpha():
curgood += 1
elif s[i].isdigit() or s[i] == '_':
pass
else:
break
tomult = 0
dotplace = 0
for i in range(dogs[dogp]+1, len(s)):
if dotplace == 0:
if s[i] == '_' or s[i] == '@':
tomult = 0
break
if s[i] == '.':
if i == dogs[dogp]+1:
tomult = 0
break
else:
dotplace = i
else:
if s[i].isalpha():
tomult += 1
else:
break
lastdog = dogs[dogp]
dogp += 1
numbers += curgood * tomult
print(numbers)
| Title: E-mail Addresses
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One of the most important products of the R1 company is a popular @r1.com mail service. The R1 mailboxes receive and send millions of emails every day.
Today, the online news thundered with terrible information. The R1 database crashed and almost no data could be saved except for one big string. The developers assume that the string contains the letters of some users of the R1 mail. Recovering letters is a tedious mostly manual work. So before you start this process, it was decided to estimate the difficulty of recovering. Namely, we need to calculate the number of different substrings of the saved string that form correct e-mail addresses.
We assume that valid addresses are only the e-mail addresses which meet the following criteria:
- the address should begin with a non-empty sequence of letters, numbers, characters '_', starting with a letter; - then must go character '@'; - then must go a non-empty sequence of letters or numbers; - then must go character '.'; - the address must end with a non-empty sequence of letters.
You got lucky again and the job was entrusted to you! Please note that the substring is several consecutive characters in a string. Two substrings, one consisting of the characters of the string with numbers *l*1,<=*l*1<=+<=1,<=*l*1<=+<=2,<=...,<=*r*1 and the other one consisting of the characters of the string with numbers *l*2,<=*l*2<=+<=1,<=*l*2<=+<=2,<=...,<=*r*2, are considered distinct if *l*1<=≠<=*l*2 or *r*1<=≠<=*r*2.
Input Specification:
The first and the only line contains the sequence of characters *s*1*s*2... *s**n* (1<=≤<=*n*<=≤<=106) — the saved string. It is guaranteed that the given string contains only small English letters, digits and characters '.', '_', '@'.
Output Specification:
Print in a single line the number of substrings that are valid e-mail addresses.
Demo Input:
['[email\xa0protected]\n', '[email\xa0protected]@[email\xa0protected]\n', '[email\xa0protected]\n', '.asd123__..@\n']
Demo Output:
['18\n', '8\n', '1\n', '0\n']
Note:
In the first test case all the substrings that are correct e-mail addresses begin from one of the letters of the word agapov and end in one of the letters of the word com.
In the second test case note that the e-mail [[email protected]](/cdn-cgi/l/email-protection) is considered twice in the answer. Note that in this example the e-mail entries overlap inside the string. | ```python
s = input()
# находим собаку
# находим адреса слева
# умножаем на длину д.зоны
dogs = []
numbers = 0
dogp = 0
for i in range(len(s)):
if s[i] == '@':
dogs.append(i)
#print(dogs)
lastdog = 0
while dogp < len(dogs):
curgood = 0
# check leftside
for i in range(dogs[dogp]-1, -1, -1):
if s[i].isalpha():
curgood += 1
elif s[i].isdigit() or s[i] == '_':
pass
else:
break
tomult = 0
dotplace = 0
for i in range(dogs[dogp]+1, len(s)):
if dotplace == 0:
if s[i] == '_' or s[i] == '@':
tomult = 0
break
if s[i] == '.':
if i == dogs[dogp]+1:
tomult = 0
break
else:
dotplace = i
else:
if s[i].isalpha():
tomult += 1
else:
break
lastdog = dogs[dogp]
dogp += 1
numbers += curgood * tomult
print(numbers)
``` | 0 | |
569 | A | Music | PROGRAMMING | 1,500 | [
"implementation",
"math"
] | null | null | Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is *T* seconds. Lesha downloads the first *S* seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For *q* seconds of real time the Internet allows you to download *q*<=-<=1 seconds of the track.
Tell Lesha, for how many times he will start the song, including the very first start. | The single line contains three integers *T*,<=*S*,<=*q* (2<=≤<=*q*<=≤<=104, 1<=≤<=*S*<=<<=*T*<=≤<=105). | Print a single integer — the number of times the song will be restarted. | [
"5 2 2\n",
"5 4 7\n",
"6 2 3\n"
] | [
"2\n",
"1\n",
"1\n"
] | In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.
In the second test, the song is almost downloaded, and Lesha will start it only once.
In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case. | 500 | [
{
"input": "5 2 2",
"output": "2"
},
{
"input": "5 4 7",
"output": "1"
},
{
"input": "6 2 3",
"output": "1"
},
{
"input": "2 1 2",
"output": "1"
},
{
"input": "2 1 3",
"output": "1"
},
{
"input": "2 1 10000",
"output": "1"
},
{
"input": "12... | 1,449,384,890 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 10 | 62 | 0 | # print ("Input T, S, and q on one line")
nums = input().split()
T = int(nums[0])
S = int(nums[1])
q = int(nums[2])
answer = 1
check = S * q
while (check < T):
T = T - check
answer += 1
print (answer)
| Title: Music
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is *T* seconds. Lesha downloads the first *S* seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For *q* seconds of real time the Internet allows you to download *q*<=-<=1 seconds of the track.
Tell Lesha, for how many times he will start the song, including the very first start.
Input Specification:
The single line contains three integers *T*,<=*S*,<=*q* (2<=≤<=*q*<=≤<=104, 1<=≤<=*S*<=<<=*T*<=≤<=105).
Output Specification:
Print a single integer — the number of times the song will be restarted.
Demo Input:
['5 2 2\n', '5 4 7\n', '6 2 3\n']
Demo Output:
['2\n', '1\n', '1\n']
Note:
In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.
In the second test, the song is almost downloaded, and Lesha will start it only once.
In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case. | ```python
# print ("Input T, S, and q on one line")
nums = input().split()
T = int(nums[0])
S = int(nums[1])
q = int(nums[2])
answer = 1
check = S * q
while (check < T):
T = T - check
answer += 1
print (answer)
``` | 0 | |
697 | A | Pineapple Incident | PROGRAMMING | 900 | [
"implementation",
"math"
] | null | null | Ted has a pineapple. This pineapple is able to bark like a bulldog! At time *t* (in seconds) it barks for the first time. Then every *s* seconds after it, it barks twice with 1 second interval. Thus it barks at times *t*, *t*<=+<=*s*, *t*<=+<=*s*<=+<=1, *t*<=+<=2*s*, *t*<=+<=2*s*<=+<=1, etc.
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time *x* (in seconds), so he asked you to tell him if it's gonna bark at that time. | The first and only line of input contains three integers *t*, *s* and *x* (0<=≤<=*t*,<=*x*<=≤<=109, 2<=≤<=*s*<=≤<=109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively. | Print a single "YES" (without quotes) if the pineapple will bark at time *x* or a single "NO" (without quotes) otherwise in the only line of output. | [
"3 10 4\n",
"3 10 3\n",
"3 8 51\n",
"3 8 52\n"
] | [
"NO\n",
"YES\n",
"YES\n",
"YES\n"
] | In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52. | 500 | [
{
"input": "3 10 4",
"output": "NO"
},
{
"input": "3 10 3",
"output": "YES"
},
{
"input": "3 8 51",
"output": "YES"
},
{
"input": "3 8 52",
"output": "YES"
},
{
"input": "456947336 740144 45",
"output": "NO"
},
{
"input": "33 232603 599417964",
"ou... | 1,468,687,906 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | #def f(t, s, x):
return x == t or x >= t + s and (x - t) % s <= 1
t, s, x = map(int, raw_input().split())
print "YES" if f(t, s, x) else "NO" | Title: Pineapple Incident
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time *t* (in seconds) it barks for the first time. Then every *s* seconds after it, it barks twice with 1 second interval. Thus it barks at times *t*, *t*<=+<=*s*, *t*<=+<=*s*<=+<=1, *t*<=+<=2*s*, *t*<=+<=2*s*<=+<=1, etc.
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time *x* (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input Specification:
The first and only line of input contains three integers *t*, *s* and *x* (0<=≤<=*t*,<=*x*<=≤<=109, 2<=≤<=*s*<=≤<=109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output Specification:
Print a single "YES" (without quotes) if the pineapple will bark at time *x* or a single "NO" (without quotes) otherwise in the only line of output.
Demo Input:
['3 10 4\n', '3 10 3\n', '3 8 51\n', '3 8 52\n']
Demo Output:
['NO\n', 'YES\n', 'YES\n', 'YES\n']
Note:
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52. | ```python
#def f(t, s, x):
return x == t or x >= t + s and (x - t) % s <= 1
t, s, x = map(int, raw_input().split())
print "YES" if f(t, s, x) else "NO"
``` | -1 | |
268 | A | Games | PROGRAMMING | 800 | [
"brute force"
] | null | null | Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.
There are *n* teams taking part in the national championship. The championship consists of *n*·(*n*<=-<=1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.
You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question. | The first line contains an integer *n* (2<=≤<=*n*<=≤<=30). Each of the following *n* lines contains a pair of distinct space-separated integers *h**i*, *a**i* (1<=≤<=*h**i*,<=*a**i*<=≤<=100) — the colors of the *i*-th team's home and guest uniforms, respectively. | In a single line print the number of games where the host team is going to play in the guest uniform. | [
"3\n1 2\n2 4\n3 4\n",
"4\n100 42\n42 100\n5 42\n100 5\n",
"2\n1 2\n1 2\n"
] | [
"1\n",
"5\n",
"0\n"
] | In the first test case the championship consists of 6 games. The only game with the event in question is the game between teams 2 and 1 on the stadium of team 2.
In the second test sample the host team will have to wear guest uniform in the games between teams: 1 and 2, 2 and 1, 2 and 3, 3 and 4, 4 and 2 (the host team is written first). | 500 | [
{
"input": "3\n1 2\n2 4\n3 4",
"output": "1"
},
{
"input": "4\n100 42\n42 100\n5 42\n100 5",
"output": "5"
},
{
"input": "2\n1 2\n1 2",
"output": "0"
},
{
"input": "7\n4 7\n52 55\n16 4\n55 4\n20 99\n3 4\n7 52",
"output": "6"
},
{
"input": "10\n68 42\n1 35\n25 70\n... | 1,698,439,871 | 2,147,483,647 | PyPy 3-64 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 |
#define _CRT_SECURE_NO_DEPRECATE
#define _SECURE_SCL 0
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <iostream>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <cctype>
#include <sstream>
#include <cassert>
#include <bitset>
#include <memory.h>
#include <complex>
using namespace std;
#pragma comment(linker, "/STACK:200000000")
typedef long long int64;
#define forn(i, n) for(int i = 0; i < (int)(n); i++)
#define ford(i, n) for(int i = (int)(n) - 1; i >= 0; i--)
#define fore(i, a, n) for(int i = (int)(a); i < (int)(n); i++)
#define pb push_back
#define mp make_pair
#define fs first
#define sc second
#define last(a) (int(a.size()) - 1)
#define all(a) a.begin(), a.end()
const double EPS = 1E-9;
const int INF = 1000000000;
const int64 INF64 = (int64) 1E18;
const double PI = 3.1415926535897932384626433832795;
int main() {
#ifdef RADs_project
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
#endif
int n;
cin >> n;
vector<int> a(n), b(n);
forn(i, n)
cin >> a[i] >> b[i];
int cnt = 0;
forn(i, n)
forn(j, n)
if (i != j && b[i] == a[j])
cnt++;
cout << cnt << endl;
return 0;
} | Title: Games
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.
There are *n* teams taking part in the national championship. The championship consists of *n*·(*n*<=-<=1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.
You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
Input Specification:
The first line contains an integer *n* (2<=≤<=*n*<=≤<=30). Each of the following *n* lines contains a pair of distinct space-separated integers *h**i*, *a**i* (1<=≤<=*h**i*,<=*a**i*<=≤<=100) — the colors of the *i*-th team's home and guest uniforms, respectively.
Output Specification:
In a single line print the number of games where the host team is going to play in the guest uniform.
Demo Input:
['3\n1 2\n2 4\n3 4\n', '4\n100 42\n42 100\n5 42\n100 5\n', '2\n1 2\n1 2\n']
Demo Output:
['1\n', '5\n', '0\n']
Note:
In the first test case the championship consists of 6 games. The only game with the event in question is the game between teams 2 and 1 on the stadium of team 2.
In the second test sample the host team will have to wear guest uniform in the games between teams: 1 and 2, 2 and 1, 2 and 3, 3 and 4, 4 and 2 (the host team is written first). | ```python
#define _CRT_SECURE_NO_DEPRECATE
#define _SECURE_SCL 0
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <iostream>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <cctype>
#include <sstream>
#include <cassert>
#include <bitset>
#include <memory.h>
#include <complex>
using namespace std;
#pragma comment(linker, "/STACK:200000000")
typedef long long int64;
#define forn(i, n) for(int i = 0; i < (int)(n); i++)
#define ford(i, n) for(int i = (int)(n) - 1; i >= 0; i--)
#define fore(i, a, n) for(int i = (int)(a); i < (int)(n); i++)
#define pb push_back
#define mp make_pair
#define fs first
#define sc second
#define last(a) (int(a.size()) - 1)
#define all(a) a.begin(), a.end()
const double EPS = 1E-9;
const int INF = 1000000000;
const int64 INF64 = (int64) 1E18;
const double PI = 3.1415926535897932384626433832795;
int main() {
#ifdef RADs_project
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
#endif
int n;
cin >> n;
vector<int> a(n), b(n);
forn(i, n)
cin >> a[i] >> b[i];
int cnt = 0;
forn(i, n)
forn(j, n)
if (i != j && b[i] == a[j])
cnt++;
cout << cnt << endl;
return 0;
}
``` | -1 | |
703 | A | Mishka and Game | PROGRAMMING | 800 | [
"implementation"
] | null | null | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds *n* is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.
In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.
Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | The first line of the input contains single integer *n* *n* (1<=≤<=*n*<=≤<=100) — the number of game rounds.
The next *n* lines contains rounds description. *i*-th of them contains pair of integers *m**i* and *c**i* (1<=≤<=*m**i*,<=<=*c**i*<=≤<=6) — values on dice upper face after Mishka's and Chris' throws in *i*-th round respectively. | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line.
If Chris is the winner of the game, print "Chris" (without quotes) in the only line.
If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | [
"3\n3 5\n2 1\n4 2\n",
"2\n6 1\n1 6\n",
"3\n1 5\n3 3\n2 2\n"
] | [
"Mishka",
"Friendship is magic!^^",
"Chris"
] | In the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.
In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.
In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | 500 | [
{
"input": "3\n3 5\n2 1\n4 2",
"output": "Mishka"
},
{
"input": "2\n6 1\n1 6",
"output": "Friendship is magic!^^"
},
{
"input": "3\n1 5\n3 3\n2 2",
"output": "Chris"
},
{
"input": "6\n4 1\n4 2\n5 3\n5 1\n5 3\n4 1",
"output": "Mishka"
},
{
"input": "8\n2 4\n1 4\n1 ... | 1,691,396,111 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 1 | 62 | 0 | n=int(input())
for i in range(n):
a,b=input().split()
a=int(a)
b=int(b)
if a>b:
print("Mishka")
elif b>a:
print("Chris")
else:
print("Friendship is magic!^^")
| Title: Mishka and Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds *n* is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.
In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.
Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!
Input Specification:
The first line of the input contains single integer *n* *n* (1<=≤<=*n*<=≤<=100) — the number of game rounds.
The next *n* lines contains rounds description. *i*-th of them contains pair of integers *m**i* and *c**i* (1<=≤<=*m**i*,<=<=*c**i*<=≤<=6) — values on dice upper face after Mishka's and Chris' throws in *i*-th round respectively.
Output Specification:
If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line.
If Chris is the winner of the game, print "Chris" (without quotes) in the only line.
If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line.
Demo Input:
['3\n3 5\n2 1\n4 2\n', '2\n6 1\n1 6\n', '3\n1 5\n3 3\n2 2\n']
Demo Output:
['Mishka', 'Friendship is magic!^^', 'Chris']
Note:
In the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.
In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.
In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | ```python
n=int(input())
for i in range(n):
a,b=input().split()
a=int(a)
b=int(b)
if a>b:
print("Mishka")
elif b>a:
print("Chris")
else:
print("Friendship is magic!^^")
``` | 0 | |
32 | B | Borze | PROGRAMMING | 800 | [
"expression parsing",
"implementation"
] | B. Borze | 2 | 256 | Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet. | The first line contains a number in Borze code. The length of the string is between 1 and 200 characters. It's guaranteed that the given string is a valid Borze code of some ternary number (this number can have leading zeroes). | Output the decoded ternary number. It can have leading zeroes. | [
".-.--\n",
"--.\n",
"-..-.--\n"
] | [
"012",
"20",
"1012"
] | none | 1,000 | [
{
"input": ".-.--",
"output": "012"
},
{
"input": "--.",
"output": "20"
},
{
"input": "-..-.--",
"output": "1012"
},
{
"input": "---..",
"output": "210"
},
{
"input": "..--.---..",
"output": "0020210"
},
{
"input": "-.....----.",
"output": "1000022... | 1,644,758,245 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 9 | 62 | 0 | def solve(s):
map = {}
map['.'] = '0'
map['-.'] = '1'
map['--'] = '2'
temp = ''
ans = ''
for c in s:
if len(temp) < 2:
temp += c
else:
if temp in map:
ans+= (map[temp])
temp = c
else:
ans+= (map[temp[0]])
temp = temp[1]+c
if temp in map:
ans+= map[temp]
return ans
if __name__ == '__main__':
t=1
while t:
s = input()
print(solve(s))
t-=1
| Title: Borze
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input Specification:
The first line contains a number in Borze code. The length of the string is between 1 and 200 characters. It's guaranteed that the given string is a valid Borze code of some ternary number (this number can have leading zeroes).
Output Specification:
Output the decoded ternary number. It can have leading zeroes.
Demo Input:
['.-.--\n', '--.\n', '-..-.--\n']
Demo Output:
['012', '20', '1012']
Note:
none | ```python
def solve(s):
map = {}
map['.'] = '0'
map['-.'] = '1'
map['--'] = '2'
temp = ''
ans = ''
for c in s:
if len(temp) < 2:
temp += c
else:
if temp in map:
ans+= (map[temp])
temp = c
else:
ans+= (map[temp[0]])
temp = temp[1]+c
if temp in map:
ans+= map[temp]
return ans
if __name__ == '__main__':
t=1
while t:
s = input()
print(solve(s))
t-=1
``` | 0 |
401 | A | Vanya and Cards | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed *x* in the absolute value.
Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found *n* of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?
You can assume that initially Vanya had infinitely many cards with each integer number from <=-<=*x* to *x*. | The first line contains two integers: *n* (1<=≤<=*n*<=≤<=1000) — the number of found cards and *x* (1<=≤<=*x*<=≤<=1000) — the maximum absolute value of the number on a card. The second line contains *n* space-separated integers — the numbers on found cards. It is guaranteed that the numbers do not exceed *x* in their absolute value. | Print a single number — the answer to the problem. | [
"3 2\n-1 1 2\n",
"2 3\n-2 -2\n"
] | [
"1\n",
"2\n"
] | In the first sample, Vanya needs to find a single card with number -2.
In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value. | 500 | [
{
"input": "3 2\n-1 1 2",
"output": "1"
},
{
"input": "2 3\n-2 -2",
"output": "2"
},
{
"input": "4 4\n1 2 3 4",
"output": "3"
},
{
"input": "2 2\n-1 -1",
"output": "1"
},
{
"input": "15 5\n-2 -1 2 -4 -3 4 -4 -2 -2 2 -2 -1 1 -4 -2",
"output": "4"
},
{
"... | 1,697,226,027 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 47 | 77 | 0 | n, x = [int(i) for i in input().split()]
k = [int(i) for i in input().split()]
s = sum(k)
c = 0
if s == 0:
print(0)
exit()
if s > 0:
while s > 0:
s -= x
c += 1
else:
while s < 0:
s += x
c += 1
print(c) | Title: Vanya and Cards
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed *x* in the absolute value.
Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found *n* of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?
You can assume that initially Vanya had infinitely many cards with each integer number from <=-<=*x* to *x*.
Input Specification:
The first line contains two integers: *n* (1<=≤<=*n*<=≤<=1000) — the number of found cards and *x* (1<=≤<=*x*<=≤<=1000) — the maximum absolute value of the number on a card. The second line contains *n* space-separated integers — the numbers on found cards. It is guaranteed that the numbers do not exceed *x* in their absolute value.
Output Specification:
Print a single number — the answer to the problem.
Demo Input:
['3 2\n-1 1 2\n', '2 3\n-2 -2\n']
Demo Output:
['1\n', '2\n']
Note:
In the first sample, Vanya needs to find a single card with number -2.
In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value. | ```python
n, x = [int(i) for i in input().split()]
k = [int(i) for i in input().split()]
s = sum(k)
c = 0
if s == 0:
print(0)
exit()
if s > 0:
while s > 0:
s -= x
c += 1
else:
while s < 0:
s += x
c += 1
print(c)
``` | 3 | |
688 | B | Lovely Palindromes | PROGRAMMING | 1,000 | [
"constructive algorithms",
"math"
] | null | null | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.
Now Pari asks you to write a program that gets a huge integer *n* from the input and tells what is the *n*-th even-length positive palindrome number? | The only line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=10100<=000). | Print the *n*-th even-length palindrome number. | [
"1\n",
"10\n"
] | [
"11\n",
"1001\n"
] | The first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | 1,000 | [
{
"input": "1",
"output": "11"
},
{
"input": "10",
"output": "1001"
},
{
"input": "11",
"output": "1111"
},
{
"input": "12",
"output": "1221"
},
{
"input": "100",
"output": "100001"
},
{
"input": "1321",
"output": "13211231"
},
{
"input": "... | 1,644,378,523 | 2,147,483,647 | PyPy 3-64 | TIME_LIMIT_EXCEEDED | TESTS | 7 | 1,000 | 10,035,200 | from sys import stdin, stdout
n = int(stdin.readline())
output = ""
while(n!=0):
x = n%10
output = str(x) + output + str(x)
n//=10
stdout.write(output+"\n") | Title: Lovely Palindromes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.
Now Pari asks you to write a program that gets a huge integer *n* from the input and tells what is the *n*-th even-length positive palindrome number?
Input Specification:
The only line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=10100<=000).
Output Specification:
Print the *n*-th even-length palindrome number.
Demo Input:
['1\n', '10\n']
Demo Output:
['11\n', '1001\n']
Note:
The first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | ```python
from sys import stdin, stdout
n = int(stdin.readline())
output = ""
while(n!=0):
x = n%10
output = str(x) + output + str(x)
n//=10
stdout.write(output+"\n")
``` | 0 | |
396 | C | On Changing Tree | PROGRAMMING | 0 | [
"data structures",
"graphs",
"trees"
] | null | null | You are given a rooted tree consisting of *n* vertices numbered from 1 to *n*. The root of the tree is a vertex number 1.
Initially all vertices contain number 0. Then come *q* queries, each query has one of the two types:
- The format of the query: 1 *v* *x* *k*. In response to the query, you need to add to the number at vertex *v* number *x*; to the numbers at the descendants of vertex *v* at distance 1, add *x*<=-<=*k*; and so on, to the numbers written in the descendants of vertex *v* at distance *i*, you need to add *x*<=-<=(*i*·*k*). The distance between two vertices is the number of edges in the shortest path between these vertices. - The format of the query: 2 *v*. In reply to the query you should print the number written in vertex *v* modulo 1000000007 (109<=+<=7).
Process the queries given in the input. | The first line contains integer *n* (1<=≤<=*n*<=≤<=3·105) — 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* is the number of the vertex that is the parent of vertex *i* in the tree.
The third line contains integer *q* (1<=≤<=*q*<=≤<=3·105) — the number of queries. Next *q* lines contain the queries, one per line. The first number in the line is *type*. It represents the type of the query. If *type*<==<=1, then next follow space-separated integers *v*,<=*x*,<=*k* (1<=≤<=*v*<=≤<=*n*; 0<=≤<=*x*<=<<=109<=+<=7; 0<=≤<=*k*<=<<=109<=+<=7). If *type*<==<=2, then next follows integer *v* (1<=≤<=*v*<=≤<=*n*) — the vertex where you need to find the value of the number. | For each query of the second type print on a single line the number written in the vertex from the query. Print the number modulo 1000000007 (109<=+<=7). | [
"3\n1 1\n3\n1 1 2 1\n2 1\n2 2\n"
] | [
"2\n1\n"
] | You can read about a rooted tree here: http://en.wikipedia.org/wiki/Tree_(graph_theory). | 1,500 | [
{
"input": "3\n1 1\n3\n1 1 2 1\n2 1\n2 2",
"output": "2\n1"
},
{
"input": "10\n1 2 3 4 4 3 3 6 7\n10\n1 6 13 98\n1 7 17 66\n1 5 32 39\n1 1 9 5\n1 7 27 11\n1 1 24 79\n1 5 87 86\n2 2\n1 5 9 38\n2 5",
"output": "999999956\n999999832"
},
{
"input": "1\n\n1\n2 1",
"output": "0"
}
] | 1,559,330,579 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 265 | 21,299,200 | from collections import deque
I = lambda : map(int,input().split())
n = int(input())
mod = pow(10,9)+7
parent = [ 0 for i in range (300001)]
ht = [ 0 for i in range (300001)]
gr = [ [] for i in range (300001)]
visited = [ 0 for i in range (300001)]
node = [ 0 for i in range (300001)]
li = list(I())
for i in range (2,n+1) :
gr[li[i-2]] += [i]
#print(gr)
qu = deque([1])
while qu :
t = qu.popleft()
for i in range (len(gr[t])) :
if visited[gr[t][i]] == 0 :
visited[gr[t][i]] = 1
qu.append(gr[t][i])
ht[gr[t][i]] = ht[t] + 1
#print(gr[1:4])
q = int(input())
for _ in range (q) :
li = list(I())
if li[0] == 1 :
ver , add , sub = li[1] ,li[2] ,li[3]
#print(ver,add,sub)
for i in range (1,n+1) :
visited[i] = 0
node[ver] += add
#print(node[ver])
qu = deque([ver])
visited[ver] =1
while qu :
t= qu.popleft()
for i in range (len(gr[t])) :
if visited[gr[t][i]] == 0 :
visited[gr[t][i]] = 1
qu.append(gr[t][i])
node[gr[t][i]] += add -sub*(ht[gr[t][i]] - ht[t])
#print(node[1:4])
else :
print(node [li[1] ])
| Title: On Changing Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a rooted tree consisting of *n* vertices numbered from 1 to *n*. The root of the tree is a vertex number 1.
Initially all vertices contain number 0. Then come *q* queries, each query has one of the two types:
- The format of the query: 1 *v* *x* *k*. In response to the query, you need to add to the number at vertex *v* number *x*; to the numbers at the descendants of vertex *v* at distance 1, add *x*<=-<=*k*; and so on, to the numbers written in the descendants of vertex *v* at distance *i*, you need to add *x*<=-<=(*i*·*k*). The distance between two vertices is the number of edges in the shortest path between these vertices. - The format of the query: 2 *v*. In reply to the query you should print the number written in vertex *v* modulo 1000000007 (109<=+<=7).
Process the queries given in the input.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=3·105) — 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* is the number of the vertex that is the parent of vertex *i* in the tree.
The third line contains integer *q* (1<=≤<=*q*<=≤<=3·105) — the number of queries. Next *q* lines contain the queries, one per line. The first number in the line is *type*. It represents the type of the query. If *type*<==<=1, then next follow space-separated integers *v*,<=*x*,<=*k* (1<=≤<=*v*<=≤<=*n*; 0<=≤<=*x*<=<<=109<=+<=7; 0<=≤<=*k*<=<<=109<=+<=7). If *type*<==<=2, then next follows integer *v* (1<=≤<=*v*<=≤<=*n*) — the vertex where you need to find the value of the number.
Output Specification:
For each query of the second type print on a single line the number written in the vertex from the query. Print the number modulo 1000000007 (109<=+<=7).
Demo Input:
['3\n1 1\n3\n1 1 2 1\n2 1\n2 2\n']
Demo Output:
['2\n1\n']
Note:
You can read about a rooted tree here: http://en.wikipedia.org/wiki/Tree_(graph_theory). | ```python
from collections import deque
I = lambda : map(int,input().split())
n = int(input())
mod = pow(10,9)+7
parent = [ 0 for i in range (300001)]
ht = [ 0 for i in range (300001)]
gr = [ [] for i in range (300001)]
visited = [ 0 for i in range (300001)]
node = [ 0 for i in range (300001)]
li = list(I())
for i in range (2,n+1) :
gr[li[i-2]] += [i]
#print(gr)
qu = deque([1])
while qu :
t = qu.popleft()
for i in range (len(gr[t])) :
if visited[gr[t][i]] == 0 :
visited[gr[t][i]] = 1
qu.append(gr[t][i])
ht[gr[t][i]] = ht[t] + 1
#print(gr[1:4])
q = int(input())
for _ in range (q) :
li = list(I())
if li[0] == 1 :
ver , add , sub = li[1] ,li[2] ,li[3]
#print(ver,add,sub)
for i in range (1,n+1) :
visited[i] = 0
node[ver] += add
#print(node[ver])
qu = deque([ver])
visited[ver] =1
while qu :
t= qu.popleft()
for i in range (len(gr[t])) :
if visited[gr[t][i]] == 0 :
visited[gr[t][i]] = 1
qu.append(gr[t][i])
node[gr[t][i]] += add -sub*(ht[gr[t][i]] - ht[t])
#print(node[1:4])
else :
print(node [li[1] ])
``` | 0 | |
617 | A | Elephant | PROGRAMMING | 800 | [
"math"
] | null | null | An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=><=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house. | The first line of the input contains an integer *x* (1<=≤<=*x*<=≤<=1<=000<=000) — The coordinate of the friend's house. | Print the minimum number of steps that elephant needs to make to get from point 0 to point *x*. | [
"5\n",
"12\n"
] | [
"1\n",
"3\n"
] | In the first sample the elephant needs to make one step of length 5 to reach the point *x*.
In the second sample the elephant can get to point *x* if he moves by 3, 5 and 4. There are other ways to get the optimal answer but the elephant cannot reach *x* in less than three moves. | 500 | [
{
"input": "5",
"output": "1"
},
{
"input": "12",
"output": "3"
},
{
"input": "999999",
"output": "200000"
},
{
"input": "41",
"output": "9"
},
{
"input": "1000000",
"output": "200000"
},
{
"input": "1",
"output": "1"
},
{
"input": "2",
... | 1,699,203,160 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 15 | 0 | x= int(input())
big_moves= x/5
small_moves= 1
if big_moves is 5:
print(1)
else:
print(int(big_moves)+ small_moves) | Title: Elephant
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=><=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.
Input Specification:
The first line of the input contains an integer *x* (1<=≤<=*x*<=≤<=1<=000<=000) — The coordinate of the friend's house.
Output Specification:
Print the minimum number of steps that elephant needs to make to get from point 0 to point *x*.
Demo Input:
['5\n', '12\n']
Demo Output:
['1\n', '3\n']
Note:
In the first sample the elephant needs to make one step of length 5 to reach the point *x*.
In the second sample the elephant can get to point *x* if he moves by 3, 5 and 4. There are other ways to get the optimal answer but the elephant cannot reach *x* in less than three moves. | ```python
x= int(input())
big_moves= x/5
small_moves= 1
if big_moves is 5:
print(1)
else:
print(int(big_moves)+ small_moves)
``` | 0 | |
591 | B | Rebranding | PROGRAMMING | 1,200 | [
"implementation",
"strings"
] | null | null | The name of one small but proud corporation consists of *n* lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.
For this purpose the corporation has consecutively hired *m* designers. Once a company hires the *i*-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters *x**i* by *y**i*, and all the letters *y**i* by *x**i*. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that *x**i* coincides with *y**i*. The version of the name received after the work of the last designer becomes the new name of the corporation.
Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.
Satisfy Arkady's curiosity and tell him the final version of the name. | The first line of the input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=200<=000) — the length of the initial name and the number of designers hired, respectively.
The second line consists of *n* lowercase English letters and represents the original name of the corporation.
Next *m* lines contain the descriptions of the designers' actions: the *i*-th of them contains two space-separated lowercase English letters *x**i* and *y**i*. | Print the new name of the corporation. | [
"6 1\npolice\np m\n",
"11 6\nabacabadaba\na b\nb c\na d\ne g\nf a\nb b\n"
] | [
"molice\n",
"cdcbcdcfcdc\n"
] | In the second sample the name of the corporation consecutively changes as follows:
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c7648432f7138ca53234357d7e08d1d119166055.png" style="max-width: 100.0%;max-height: 100.0%;"/>
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/de89ad7bc7f27c46ec34f5e66ce0dc23bd5bc90a.png" style="max-width: 100.0%;max-height: 100.0%;"/>
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/812e653c8d7ff496e6a0f04c676423806751531e.png" style="max-width: 100.0%;max-height: 100.0%;"/>
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/19c564fcefb8dde36256240a8b877bb6a4792bfe.png" style="max-width: 100.0%;max-height: 100.0%;"/>
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e1cafd93792430ad1a49e893e04715383bdae757.png" style="max-width: 100.0%;max-height: 100.0%;"/> | 1,000 | [
{
"input": "6 1\npolice\np m",
"output": "molice"
},
{
"input": "11 6\nabacabadaba\na b\nb c\na d\ne g\nf a\nb b",
"output": "cdcbcdcfcdc"
},
{
"input": "1 1\nf\nz h",
"output": "f"
},
{
"input": "1 1\na\na b",
"output": "b"
},
{
"input": "10 10\nlellelleel\ne l\n... | 1,662,380,930 | 2,147,483,647 | PyPy 3-64 | TIME_LIMIT_EXCEEDED | TESTS | 5 | 2,000 | 76,697,600 | # Problem Link: https://codeforces.com/problemset/problem/591/B
# Problem Status:
# --------------------------- SEPARATOR ---------------------------
def TheAmazingFunction(Title: str, Arr: list):
Table = []
Ans = ""
for T in range(97, 97+26):
Table.append(chr(T))
for U in Arr:
i1 = Table.index(U[0])
i2 = Table.index(U[1])
Temp = Table[i1]
Table[i1] = Table[i2]
Table[i2] = Temp
for L in Title:
Ans += Table[ord(L)-97]
return Ans
# --------------------------- SEPARATOR ---------------------------
N, M = list(map(int, input().split()))
Name = input()
A = []
for i in range(M):
A.append([])
A[-1] = input().split()
print(TheAmazingFunction(Name, A))
# --------------------------- SEPARATOR ---------------------------
| Title: Rebranding
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The name of one small but proud corporation consists of *n* lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.
For this purpose the corporation has consecutively hired *m* designers. Once a company hires the *i*-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters *x**i* by *y**i*, and all the letters *y**i* by *x**i*. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that *x**i* coincides with *y**i*. The version of the name received after the work of the last designer becomes the new name of the corporation.
Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.
Satisfy Arkady's curiosity and tell him the final version of the name.
Input Specification:
The first line of the input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=200<=000) — the length of the initial name and the number of designers hired, respectively.
The second line consists of *n* lowercase English letters and represents the original name of the corporation.
Next *m* lines contain the descriptions of the designers' actions: the *i*-th of them contains two space-separated lowercase English letters *x**i* and *y**i*.
Output Specification:
Print the new name of the corporation.
Demo Input:
['6 1\npolice\np m\n', '11 6\nabacabadaba\na b\nb c\na d\ne g\nf a\nb b\n']
Demo Output:
['molice\n', 'cdcbcdcfcdc\n']
Note:
In the second sample the name of the corporation consecutively changes as follows:
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c7648432f7138ca53234357d7e08d1d119166055.png" style="max-width: 100.0%;max-height: 100.0%;"/>
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/de89ad7bc7f27c46ec34f5e66ce0dc23bd5bc90a.png" style="max-width: 100.0%;max-height: 100.0%;"/>
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/812e653c8d7ff496e6a0f04c676423806751531e.png" style="max-width: 100.0%;max-height: 100.0%;"/>
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/19c564fcefb8dde36256240a8b877bb6a4792bfe.png" style="max-width: 100.0%;max-height: 100.0%;"/>
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e1cafd93792430ad1a49e893e04715383bdae757.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
# Problem Link: https://codeforces.com/problemset/problem/591/B
# Problem Status:
# --------------------------- SEPARATOR ---------------------------
def TheAmazingFunction(Title: str, Arr: list):
Table = []
Ans = ""
for T in range(97, 97+26):
Table.append(chr(T))
for U in Arr:
i1 = Table.index(U[0])
i2 = Table.index(U[1])
Temp = Table[i1]
Table[i1] = Table[i2]
Table[i2] = Temp
for L in Title:
Ans += Table[ord(L)-97]
return Ans
# --------------------------- SEPARATOR ---------------------------
N, M = list(map(int, input().split()))
Name = input()
A = []
for i in range(M):
A.append([])
A[-1] = input().split()
print(TheAmazingFunction(Name, A))
# --------------------------- SEPARATOR ---------------------------
``` | 0 | |
358 | A | Dima and Continuous Line | PROGRAMMING | 1,400 | [
"brute force",
"implementation"
] | null | null | Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework.
The teacher gave Seryozha the coordinates of *n* distinct points on the abscissa axis and asked to consecutively connect them by semi-circus in a certain order: first connect the first point with the second one, then connect the second point with the third one, then the third one with the fourth one and so on to the *n*-th point. Two points with coordinates (*x*1,<=0) and (*x*2,<=0) should be connected by a semi-circle that passes above the abscissa axis with the diameter that coincides with the segment between points. Seryozha needs to find out if the line on the picture intersects itself. For clarifications, see the picture Seryozha showed to Dima (the left picture has self-intersections, the right picture doesn't have any).
Seryozha is not a small boy, so the coordinates of the points can be rather large. Help Dima cope with the problem. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=103). The second line contains *n* distinct integers *x*1,<=*x*2,<=...,<=*x**n* (<=-<=106<=≤<=*x**i*<=≤<=106) — the *i*-th point has coordinates (*x**i*,<=0). The points are not necessarily sorted by their *x* coordinate. | In the single line print "yes" (without the quotes), if the line has self-intersections. Otherwise, print "no" (without the quotes). | [
"4\n0 10 5 15\n",
"4\n0 15 5 10\n"
] | [
"yes\n",
"no\n"
] | The first test from the statement is on the picture to the left, the second test is on the picture to the right. | 500 | [
{
"input": "4\n0 10 5 15",
"output": "yes"
},
{
"input": "4\n0 15 5 10",
"output": "no"
},
{
"input": "5\n0 1000 2000 3000 1500",
"output": "yes"
},
{
"input": "5\n-724093 710736 -383722 -359011 439613",
"output": "no"
},
{
"input": "50\n384672 661179 -775591 -989... | 1,602,149,419 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 5 | 124 | 0 | length = input()
points = [int(i) for i in input().split()]
minimum = min(points)
maximum = max(points)
minimum_indices = [i for i, x in enumerate(points) if x==minimum ]
maximum_indices = [i for i, x in enumerate(points) if x==maximum]
for max in maximum_indices:
found = False
for min in minimum_indices:
if min+1 == max:
found = True
break
if found == True:
print("no")
else:
print("yes")
| Title: Dima and Continuous Line
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework.
The teacher gave Seryozha the coordinates of *n* distinct points on the abscissa axis and asked to consecutively connect them by semi-circus in a certain order: first connect the first point with the second one, then connect the second point with the third one, then the third one with the fourth one and so on to the *n*-th point. Two points with coordinates (*x*1,<=0) and (*x*2,<=0) should be connected by a semi-circle that passes above the abscissa axis with the diameter that coincides with the segment between points. Seryozha needs to find out if the line on the picture intersects itself. For clarifications, see the picture Seryozha showed to Dima (the left picture has self-intersections, the right picture doesn't have any).
Seryozha is not a small boy, so the coordinates of the points can be rather large. Help Dima cope with the problem.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=103). The second line contains *n* distinct integers *x*1,<=*x*2,<=...,<=*x**n* (<=-<=106<=≤<=*x**i*<=≤<=106) — the *i*-th point has coordinates (*x**i*,<=0). The points are not necessarily sorted by their *x* coordinate.
Output Specification:
In the single line print "yes" (without the quotes), if the line has self-intersections. Otherwise, print "no" (without the quotes).
Demo Input:
['4\n0 10 5 15\n', '4\n0 15 5 10\n']
Demo Output:
['yes\n', 'no\n']
Note:
The first test from the statement is on the picture to the left, the second test is on the picture to the right. | ```python
length = input()
points = [int(i) for i in input().split()]
minimum = min(points)
maximum = max(points)
minimum_indices = [i for i, x in enumerate(points) if x==minimum ]
maximum_indices = [i for i, x in enumerate(points) if x==maximum]
for max in maximum_indices:
found = False
for min in minimum_indices:
if min+1 == max:
found = True
break
if found == True:
print("no")
else:
print("yes")
``` | 0 | |
525 | A | Vitaliy and Pie | PROGRAMMING | 1,100 | [
"greedy",
"hashing",
"strings"
] | null | null | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1.
The potato pie is located in the *n*-th room and Vitaly needs to go there.
Each pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key.
In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F.
Each of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.
Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*.
Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | The first line of the input contains a positive integer *n* (2<=≤<=*n*<=≤<=105) — the number of rooms in the house.
The second line of the input contains string *s* of length 2·*n*<=-<=2. Let's number the elements of the string from left to right, starting from one.
The odd positions in the given string *s* contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position *i* of the given string *s* contains a lowercase Latin letter — the type of the key that lies in room number (*i*<=+<=1)<=/<=2.
The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position *i* of the given string *s* contains an uppercase letter — the type of the door that leads from room *i*<=/<=2 to room *i*<=/<=2<=+<=1. | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room *n*. | [
"3\naAbB\n",
"4\naBaCaB\n",
"5\nxYyXzZaZ\n"
] | [
"0\n",
"3\n",
"2\n"
] | none | 250 | [
{
"input": "3\naAbB",
"output": "0"
},
{
"input": "4\naBaCaB",
"output": "3"
},
{
"input": "5\nxYyXzZaZ",
"output": "2"
},
{
"input": "26\naAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyY",
"output": "0"
},
{
"input": "26\nzAyBxCwDvEuFtGsHrIqJpKoLnMmNlOkPjQiRhSg... | 1,667,940,997 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 7 | 124 | 15,667,200 | n=int(input())
room= str(input())
kr=[]
rl=[]
buy=0
for i in room:
rl.append(i)
if len(room)==(2*n-2):
for j in range(len(room)):
if j%2==0:
if rl[j+1].lower() in kr:
pass
else:
if rl[j]==rl[j+1].lower():
pass
else:
kr.append(rl[j])
buy=buy+1
print(buy)
| Title: Vitaliy and Pie
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1.
The potato pie is located in the *n*-th room and Vitaly needs to go there.
Each pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key.
In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F.
Each of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.
Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*.
Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
Input Specification:
The first line of the input contains a positive integer *n* (2<=≤<=*n*<=≤<=105) — the number of rooms in the house.
The second line of the input contains string *s* of length 2·*n*<=-<=2. Let's number the elements of the string from left to right, starting from one.
The odd positions in the given string *s* contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position *i* of the given string *s* contains a lowercase Latin letter — the type of the key that lies in room number (*i*<=+<=1)<=/<=2.
The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position *i* of the given string *s* contains an uppercase letter — the type of the door that leads from room *i*<=/<=2 to room *i*<=/<=2<=+<=1.
Output Specification:
Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room *n*.
Demo Input:
['3\naAbB\n', '4\naBaCaB\n', '5\nxYyXzZaZ\n']
Demo Output:
['0\n', '3\n', '2\n']
Note:
none | ```python
n=int(input())
room= str(input())
kr=[]
rl=[]
buy=0
for i in room:
rl.append(i)
if len(room)==(2*n-2):
for j in range(len(room)):
if j%2==0:
if rl[j+1].lower() in kr:
pass
else:
if rl[j]==rl[j+1].lower():
pass
else:
kr.append(rl[j])
buy=buy+1
print(buy)
``` | 0 | |
337 | A | Puzzles | PROGRAMMING | 900 | [
"greedy"
] | null | null | The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her *n* students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).
The shop assistant told the teacher that there are *m* puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of *f*1 pieces, the second one consists of *f*2 pieces and so on.
Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let *A* be the number of pieces in the largest puzzle that the teacher buys and *B* be the number of pieces in the smallest such puzzle. She wants to choose such *n* puzzles that *A*<=-<=*B* is minimum possible. Help the teacher and find the least possible value of *A*<=-<=*B*. | The first line contains space-separated integers *n* and *m* (2<=≤<=*n*<=≤<=*m*<=≤<=50). The second line contains *m* space-separated integers *f*1,<=*f*2,<=...,<=*f**m* (4<=≤<=*f**i*<=≤<=1000) — the quantities of pieces in the puzzles sold in the shop. | Print a single integer — the least possible difference the teacher can obtain. | [
"4 6\n10 12 10 7 5 22\n"
] | [
"5\n"
] | Sample 1. The class has 4 students. The shop sells 6 puzzles. If Ms. Manana buys the first four puzzles consisting of 10, 12, 10 and 7 pieces correspondingly, then the difference between the sizes of the largest and the smallest puzzle will be equal to 5. It is impossible to obtain a smaller difference. Note that the teacher can also buy puzzles 1, 3, 4 and 5 to obtain the difference 5. | 500 | [
{
"input": "4 6\n10 12 10 7 5 22",
"output": "5"
},
{
"input": "2 2\n4 4",
"output": "0"
},
{
"input": "2 10\n4 5 6 7 8 9 10 11 12 12",
"output": "0"
},
{
"input": "4 5\n818 136 713 59 946",
"output": "759"
},
{
"input": "3 20\n446 852 783 313 549 965 40 88 86 617... | 1,693,884,039 | 2,147,483,647 | Python 3 | OK | TESTS | 18 | 92 | 0 | n, m = map(int, input().split(" "))
p = list(map(int, input().split(" ")))
p.sort()
d = p[len(p)-1]
for i in range((m-n)+1):
d = min(d, p[(i + n)-1] - p[i])
print(d)
| Title: Puzzles
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her *n* students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).
The shop assistant told the teacher that there are *m* puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of *f*1 pieces, the second one consists of *f*2 pieces and so on.
Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let *A* be the number of pieces in the largest puzzle that the teacher buys and *B* be the number of pieces in the smallest such puzzle. She wants to choose such *n* puzzles that *A*<=-<=*B* is minimum possible. Help the teacher and find the least possible value of *A*<=-<=*B*.
Input Specification:
The first line contains space-separated integers *n* and *m* (2<=≤<=*n*<=≤<=*m*<=≤<=50). The second line contains *m* space-separated integers *f*1,<=*f*2,<=...,<=*f**m* (4<=≤<=*f**i*<=≤<=1000) — the quantities of pieces in the puzzles sold in the shop.
Output Specification:
Print a single integer — the least possible difference the teacher can obtain.
Demo Input:
['4 6\n10 12 10 7 5 22\n']
Demo Output:
['5\n']
Note:
Sample 1. The class has 4 students. The shop sells 6 puzzles. If Ms. Manana buys the first four puzzles consisting of 10, 12, 10 and 7 pieces correspondingly, then the difference between the sizes of the largest and the smallest puzzle will be equal to 5. It is impossible to obtain a smaller difference. Note that the teacher can also buy puzzles 1, 3, 4 and 5 to obtain the difference 5. | ```python
n, m = map(int, input().split(" "))
p = list(map(int, input().split(" ")))
p.sort()
d = p[len(p)-1]
for i in range((m-n)+1):
d = min(d, p[(i + n)-1] - p[i])
print(d)
``` | 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,647,094,806 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 11 | 1,000 | 921,600 | s = input()
t = input()
if (s[-1]!=t[-1] or s=="" or t==""):
print(len(s) + len(t))
elif s==t:
print(0)
else:
i = -1
while s[i:]==t[i:]:
i -= 1
i += 1
print(len(s[:i]) + len(t[:i])) | 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
s = input()
t = input()
if (s[-1]!=t[-1] or s=="" or t==""):
print(len(s) + len(t))
elif s==t:
print(0)
else:
i = -1
while s[i:]==t[i:]:
i -= 1
i += 1
print(len(s[:i]) + len(t[:i]))
``` | 0 | |
729 | B | Spotlights | PROGRAMMING | 1,200 | [
"dp",
"implementation"
] | null | null | Theater stage is a rectangular field of size *n*<=×<=*m*. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.
A position is good if two conditions hold:
- there is no actor in the cell the spotlight is placed to; - there is at least one actor in the direction the spotlight projects.
Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ. | The first line contains two positive integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and the number of columns in the plan.
The next *n* lines contain *m* integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan. | Print one integer — the number of good positions for placing the spotlight. | [
"2 4\n0 1 0 0\n1 0 1 0\n",
"4 4\n0 0 0 0\n1 0 0 1\n0 1 1 0\n0 1 0 0\n"
] | [
"9\n",
"20\n"
] | In the first example the following positions are good:
1. the (1, 1) cell and right direction; 1. the (1, 1) cell and down direction; 1. the (1, 3) cell and left direction; 1. the (1, 3) cell and down direction; 1. the (1, 4) cell and left direction; 1. the (2, 2) cell and left direction; 1. the (2, 2) cell and up direction; 1. the (2, 2) and right direction; 1. the (2, 4) cell and left direction.
Therefore, there are 9 good positions in this example. | 1,000 | [
{
"input": "2 4\n0 1 0 0\n1 0 1 0",
"output": "9"
},
{
"input": "4 4\n0 0 0 0\n1 0 0 1\n0 1 1 0\n0 1 0 0",
"output": "20"
},
{
"input": "1 5\n1 1 0 0 0",
"output": "3"
},
{
"input": "2 10\n0 0 0 0 0 0 0 1 0 0\n1 0 0 0 0 0 0 0 0 0",
"output": "20"
},
{
"input": "3 ... | 1,673,618,108 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 72 | 374 | 74,342,400 | s = list(map(int, input().split()))
n,m = s[0],s[1]
spisok = []
for i in range(n):
p = list(map(int, input().split()))
spisok.append(p)
s1 = []
s2 = []
s3 = []
s4 = []
k1 = 0
k2 = 0
k3 = 0
k4 = 0
for i in range(n):
for j in range(m):
if spisok[i][j] == 0:
k1 += 1
if spisok[i][j] == 1:
s1.append(k1)
k1 = 0
k1 = 0
for i in range(n):
for j in range(m-1, -1, -1):
if spisok[i][j] == 0:
k2 += 1
if spisok[i][j] == 1:
s2.append(k2)
k2 = 0
k2 = 0
for i in range(m):
for j in range(n):
if spisok[j][i] == 0:
k3 += 1
if spisok[j][i] == 1:
s3.append(k3)
k3 = 0
k3 = 0
for i in range(m):
for j in range(n - 1, -1, -1):
if spisok[j][i] == 0:
k4 += 1
if spisok[j][i] == 1:
s4.append(k4)
k4 = 0
k4 = 0
print(sum(s1) + sum(s2) + sum(s3) + sum(s4))
| Title: Spotlights
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Theater stage is a rectangular field of size *n*<=×<=*m*. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.
A position is good if two conditions hold:
- there is no actor in the cell the spotlight is placed to; - there is at least one actor in the direction the spotlight projects.
Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.
Input Specification:
The first line contains two positive integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and the number of columns in the plan.
The next *n* lines contain *m* integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.
Output Specification:
Print one integer — the number of good positions for placing the spotlight.
Demo Input:
['2 4\n0 1 0 0\n1 0 1 0\n', '4 4\n0 0 0 0\n1 0 0 1\n0 1 1 0\n0 1 0 0\n']
Demo Output:
['9\n', '20\n']
Note:
In the first example the following positions are good:
1. the (1, 1) cell and right direction; 1. the (1, 1) cell and down direction; 1. the (1, 3) cell and left direction; 1. the (1, 3) cell and down direction; 1. the (1, 4) cell and left direction; 1. the (2, 2) cell and left direction; 1. the (2, 2) cell and up direction; 1. the (2, 2) and right direction; 1. the (2, 4) cell and left direction.
Therefore, there are 9 good positions in this example. | ```python
s = list(map(int, input().split()))
n,m = s[0],s[1]
spisok = []
for i in range(n):
p = list(map(int, input().split()))
spisok.append(p)
s1 = []
s2 = []
s3 = []
s4 = []
k1 = 0
k2 = 0
k3 = 0
k4 = 0
for i in range(n):
for j in range(m):
if spisok[i][j] == 0:
k1 += 1
if spisok[i][j] == 1:
s1.append(k1)
k1 = 0
k1 = 0
for i in range(n):
for j in range(m-1, -1, -1):
if spisok[i][j] == 0:
k2 += 1
if spisok[i][j] == 1:
s2.append(k2)
k2 = 0
k2 = 0
for i in range(m):
for j in range(n):
if spisok[j][i] == 0:
k3 += 1
if spisok[j][i] == 1:
s3.append(k3)
k3 = 0
k3 = 0
for i in range(m):
for j in range(n - 1, -1, -1):
if spisok[j][i] == 0:
k4 += 1
if spisok[j][i] == 1:
s4.append(k4)
k4 = 0
k4 = 0
print(sum(s1) + sum(s2) + sum(s3) + sum(s4))
``` | 3 | |
719 | A | Vitya in the Countryside | PROGRAMMING | 1,100 | [
"implementation"
] | null | null | Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for *n* consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has. | The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=92) — the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains *n* integers *a**i* (0<=≤<=*a**i*<=≤<=15) — Vitya's records.
It's guaranteed that the input data is consistent. | If Vitya can be sure that the size of visible part of the moon on day *n*<=+<=1 will be less than the size of the visible part on day *n*, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1. | [
"5\n3 4 5 6 7\n",
"7\n12 13 14 15 14 13 12\n",
"1\n8\n"
] | [
"UP\n",
"DOWN\n",
"-1\n"
] | In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1. | 500 | [
{
"input": "5\n3 4 5 6 7",
"output": "UP"
},
{
"input": "7\n12 13 14 15 14 13 12",
"output": "DOWN"
},
{
"input": "1\n8",
"output": "-1"
},
{
"input": "44\n7 8 9 10 11 12 13 14 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 14 13 12 11 10",
"out... | 1,474,927,558 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 8 | 77 | 0 |
n=int(input())
ch=input()
l=[]
l=ch.split()
if (l[n-1]=='15'):
print('DOWN')
else :
if (l[n-1]=='0'):
print('UP')
else :
if (n > 1):
if ((l[n-1] < l[n-2])):
print('DOWN')
else:
print ('UP')
else:
print('-1')
| Title: Vitya in the Countryside
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for *n* consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input Specification:
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=92) — the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains *n* integers *a**i* (0<=≤<=*a**i*<=≤<=15) — Vitya's records.
It's guaranteed that the input data is consistent.
Output Specification:
If Vitya can be sure that the size of visible part of the moon on day *n*<=+<=1 will be less than the size of the visible part on day *n*, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Demo Input:
['5\n3 4 5 6 7\n', '7\n12 13 14 15 14 13 12\n', '1\n8\n']
Demo Output:
['UP\n', 'DOWN\n', '-1\n']
Note:
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1. | ```python
n=int(input())
ch=input()
l=[]
l=ch.split()
if (l[n-1]=='15'):
print('DOWN')
else :
if (l[n-1]=='0'):
print('UP')
else :
if (n > 1):
if ((l[n-1] < l[n-2])):
print('DOWN')
else:
print ('UP')
else:
print('-1')
``` | 0 | |
96 | A | Football | PROGRAMMING | 900 | [
"implementation",
"strings"
] | A. Football | 2 | 256 | Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not. | The first input line contains a non-empty string consisting of characters "0" and "1", which represents players. The length of the string does not exceed 100 characters. There's at least one player from each team present on the field. | Print "YES" if the situation is dangerous. Otherwise, print "NO". | [
"001001\n",
"1000000001\n"
] | [
"NO\n",
"YES\n"
] | none | 500 | [
{
"input": "001001",
"output": "NO"
},
{
"input": "1000000001",
"output": "YES"
},
{
"input": "00100110111111101",
"output": "YES"
},
{
"input": "11110111111111111",
"output": "YES"
},
{
"input": "01",
"output": "NO"
},
{
"input": "10100101",
"outp... | 1,679,390,158 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 2 | 122 | 0 | n = str(input())
c = 0
for i in range(len(n)-1):
if n[i+1] == n[i]:
c += 1
if c == 7:
break
else:
c = 0
print('YES' if c == 7 else 'NO') | Title: Football
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.
Input Specification:
The first input line contains a non-empty string consisting of characters "0" and "1", which represents players. The length of the string does not exceed 100 characters. There's at least one player from each team present on the field.
Output Specification:
Print "YES" if the situation is dangerous. Otherwise, print "NO".
Demo Input:
['001001\n', '1000000001\n']
Demo Output:
['NO\n', 'YES\n']
Note:
none | ```python
n = str(input())
c = 0
for i in range(len(n)-1):
if n[i+1] == n[i]:
c += 1
if c == 7:
break
else:
c = 0
print('YES' if c == 7 else 'NO')
``` | 0 |
982 | B | Bus of Characters | PROGRAMMING | 1,300 | [
"data structures",
"greedy",
"implementation"
] | null | null | In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct.
Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers:
- an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; - an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it.
You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take. | The first line contains a single integer $n$ ($1 \le n \le 200\,000$) — the number of rows in the bus.
The second line contains the sequence of integers $w_1, w_2, \dots, w_n$ ($1 \le w_i \le 10^{9}$), where $w_i$ is the width of each of the seats in the $i$-th row. It is guaranteed that all $w_i$ are distinct.
The third line contains a string of length $2n$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $j$-th character is '0', then the passenger that enters the bus on the $j$-th stop is an introvert. If the $j$-th character is '1', the the passenger that enters the bus on the $j$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $n$), and for each extrovert there always is a suitable row. | Print $2n$ integers — the rows the passengers will take. The order of passengers should be the same as in input. | [
"2\n3 1\n0011\n",
"6\n10 8 9 11 13 5\n010010011101\n"
] | [
"2 1 1 2 \n",
"6 6 2 3 3 1 4 4 1 2 5 5 \n"
] | In the first example the first passenger (introvert) chooses the row $2$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $1$, because it is the only empty row now. The third passenger (extrovert) chooses the row $1$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $2$, because it is the only row with an empty place. | 1,000 | [
{
"input": "2\n3 1\n0011",
"output": "2 1 1 2 "
},
{
"input": "6\n10 8 9 11 13 5\n010010011101",
"output": "6 6 2 3 3 1 4 4 1 2 5 5 "
},
{
"input": "1\n1\n01",
"output": "1 1 "
},
{
"input": "1\n1000000\n01",
"output": "1 1 "
},
{
"input": "2\n1 1000000\n0011",
... | 1,664,189,607 | 2,147,483,647 | PyPy 3-64 | TIME_LIMIT_EXCEEDED | TESTS | 10 | 2,000 | 33,587,200 | def main():
n = int(input())
s = [*map(int, input().split())]
for i in range(len(s)):
s[i] = (s[i], i + 1)
s.sort(reverse=True)
x = input()
stek = []
for i in x:
if i == '0':
print(s[-1][1], end=' ')
stek += [s[-1][1]]
s = s[:-1]
if i == '1':
print(stek[-1], end=' ')
stek.pop()
main()
'''
2
3 1
0011
'''
| Title: Bus of Characters
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct.
Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers:
- an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; - an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it.
You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.
Input Specification:
The first line contains a single integer $n$ ($1 \le n \le 200\,000$) — the number of rows in the bus.
The second line contains the sequence of integers $w_1, w_2, \dots, w_n$ ($1 \le w_i \le 10^{9}$), where $w_i$ is the width of each of the seats in the $i$-th row. It is guaranteed that all $w_i$ are distinct.
The third line contains a string of length $2n$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $j$-th character is '0', then the passenger that enters the bus on the $j$-th stop is an introvert. If the $j$-th character is '1', the the passenger that enters the bus on the $j$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $n$), and for each extrovert there always is a suitable row.
Output Specification:
Print $2n$ integers — the rows the passengers will take. The order of passengers should be the same as in input.
Demo Input:
['2\n3 1\n0011\n', '6\n10 8 9 11 13 5\n010010011101\n']
Demo Output:
['2 1 1 2 \n', '6 6 2 3 3 1 4 4 1 2 5 5 \n']
Note:
In the first example the first passenger (introvert) chooses the row $2$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $1$, because it is the only empty row now. The third passenger (extrovert) chooses the row $1$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $2$, because it is the only row with an empty place. | ```python
def main():
n = int(input())
s = [*map(int, input().split())]
for i in range(len(s)):
s[i] = (s[i], i + 1)
s.sort(reverse=True)
x = input()
stek = []
for i in x:
if i == '0':
print(s[-1][1], end=' ')
stek += [s[-1][1]]
s = s[:-1]
if i == '1':
print(stek[-1], end=' ')
stek.pop()
main()
'''
2
3 1
0011
'''
``` | 0 | |
931 | A | Friends Meeting | PROGRAMMING | 800 | [
"brute force",
"greedy",
"implementation",
"math"
] | null | null | Two friends are on the coordinate axis *Ox* in points with integer coordinates. One of them is in the point *x*1<==<=*a*, another one is in the point *x*2<==<=*b*.
Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by 1, the second move increases the tiredness by 2, the third — by 3 and so on. For example, if a friend moves first to the left, then to the right (returning to the same point), and then again to the left his tiredness becomes equal to 1<=+<=2<=+<=3<==<=6.
The friends want to meet in a integer point. Determine the minimum total tiredness they should gain, if they meet in the same point. | The first line contains a single integer *a* (1<=≤<=*a*<=≤<=1000) — the initial position of the first friend.
The second line contains a single integer *b* (1<=≤<=*b*<=≤<=1000) — the initial position of the second friend.
It is guaranteed that *a*<=≠<=*b*. | Print the minimum possible total tiredness if the friends meet in the same point. | [
"3\n4\n",
"101\n99\n",
"5\n10\n"
] | [
"1\n",
"2\n",
"9\n"
] | In the first example the first friend should move by one to the right (then the meeting happens at point 4), or the second friend should move by one to the left (then the meeting happens at point 3). In both cases, the total tiredness becomes 1.
In the second example the first friend should move by one to the left, and the second friend should move by one to the right. Then they meet in the point 100, and the total tiredness becomes 1 + 1 = 2.
In the third example one of the optimal ways is the following. The first friend should move three times to the right, and the second friend — two times to the left. Thus the friends meet in the point 8, and the total tiredness becomes 1 + 2 + 3 + 1 + 2 = 9. | 500 | [
{
"input": "3\n4",
"output": "1"
},
{
"input": "101\n99",
"output": "2"
},
{
"input": "5\n10",
"output": "9"
},
{
"input": "1\n2",
"output": "1"
},
{
"input": "1\n1000",
"output": "250000"
},
{
"input": "999\n1000",
"output": "1"
},
{
"inpu... | 1,535,635,969 | 2,147,483,647 | PyPy 3 | OK | TESTS | 40 | 140 | 0 | a = int(input())
b = int(input())
acount = 0
bcount = 0
aturn = True
total = 0
if (a < b):
t = a
a = b
b = t
while (a!=b):
if (aturn):
a -= 1
acount += 1
total += acount
else:
b += 1
bcount += 1
total += bcount
aturn = not aturn
print(total) | Title: Friends Meeting
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two friends are on the coordinate axis *Ox* in points with integer coordinates. One of them is in the point *x*1<==<=*a*, another one is in the point *x*2<==<=*b*.
Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by 1, the second move increases the tiredness by 2, the third — by 3 and so on. For example, if a friend moves first to the left, then to the right (returning to the same point), and then again to the left his tiredness becomes equal to 1<=+<=2<=+<=3<==<=6.
The friends want to meet in a integer point. Determine the minimum total tiredness they should gain, if they meet in the same point.
Input Specification:
The first line contains a single integer *a* (1<=≤<=*a*<=≤<=1000) — the initial position of the first friend.
The second line contains a single integer *b* (1<=≤<=*b*<=≤<=1000) — the initial position of the second friend.
It is guaranteed that *a*<=≠<=*b*.
Output Specification:
Print the minimum possible total tiredness if the friends meet in the same point.
Demo Input:
['3\n4\n', '101\n99\n', '5\n10\n']
Demo Output:
['1\n', '2\n', '9\n']
Note:
In the first example the first friend should move by one to the right (then the meeting happens at point 4), or the second friend should move by one to the left (then the meeting happens at point 3). In both cases, the total tiredness becomes 1.
In the second example the first friend should move by one to the left, and the second friend should move by one to the right. Then they meet in the point 100, and the total tiredness becomes 1 + 1 = 2.
In the third example one of the optimal ways is the following. The first friend should move three times to the right, and the second friend — two times to the left. Thus the friends meet in the point 8, and the total tiredness becomes 1 + 2 + 3 + 1 + 2 = 9. | ```python
a = int(input())
b = int(input())
acount = 0
bcount = 0
aturn = True
total = 0
if (a < b):
t = a
a = b
b = t
while (a!=b):
if (aturn):
a -= 1
acount += 1
total += acount
else:
b += 1
bcount += 1
total += bcount
aturn = not aturn
print(total)
``` | 3 | |
518 | A | Vitaly and Strings | PROGRAMMING | 1,600 | [
"constructive algorithms",
"strings"
] | null | null | Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings *s* and *t* to Vitaly. The strings have the same length, they consist of lowercase English letters, string *s* is lexicographically smaller than string *t*. Vitaly wondered if there is such string that is lexicographically larger than string *s* and at the same is lexicographically smaller than string *t*. This string should also consist of lowercase English letters and have the length equal to the lengths of strings *s* and *t*.
Let's help Vitaly solve this easy problem! | The first line contains string *s* (1<=≤<=|*s*|<=≤<=100), consisting of lowercase English letters. Here, |*s*| denotes the length of the string.
The second line contains string *t* (|*t*|<==<=|*s*|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings *s* and *t* are the same and string *s* is lexicographically less than string *t*. | If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them. | [
"a\nc\n",
"aaa\nzzz\n",
"abcdefg\nabcdefh\n"
] | [
"b\n",
"kkk\n",
"No such string\n"
] | String *s* = *s*<sub class="lower-index">1</sub>*s*<sub class="lower-index">2</sub>... *s*<sub class="lower-index">*n*</sub> is said to be lexicographically smaller than *t* = *t*<sub class="lower-index">1</sub>*t*<sub class="lower-index">2</sub>... *t*<sub class="lower-index">*n*</sub>, if there exists such *i*, that *s*<sub class="lower-index">1</sub> = *t*<sub class="lower-index">1</sub>, *s*<sub class="lower-index">2</sub> = *t*<sub class="lower-index">2</sub>, ... *s*<sub class="lower-index">*i* - 1</sub> = *t*<sub class="lower-index">*i* - 1</sub>, *s*<sub class="lower-index">*i*</sub> < *t*<sub class="lower-index">*i*</sub>. | 500 | [
{
"input": "a\nc",
"output": "b"
},
{
"input": "aaa\nzzz",
"output": "kkk"
},
{
"input": "abcdefg\nabcdefh",
"output": "No such string"
},
{
"input": "abcdefg\nabcfefg",
"output": "abcdefh"
},
{
"input": "frt\nfru",
"output": "No such string"
},
{
"inp... | 1,543,793,383 | 2,147,483,647 | PyPy 3 | OK | TESTS | 51 | 170 | 0 | from operator import itemgetter
#int(input())
#map(int,input().split())
#[list(map(int,input().split())) for i in range(q)]
#print("YES" * ans + "NO" * (1-ans))
s = input()
s2 = input()
alth = "abcdefghijklmnopqrstuvwxyz"
n = len(s)
s3 = [0] * n
for i in range(n-1,-1,-1):
if s[i] == "z":
s3[i] = "a"
else:
s3[i] = alth[alth.find(s[i]) + 1]
for i in range(i):
s3[i] = s[i]
break
s3 = "".join(s3)
if s3 == s2:
print("No such string")
else:
print(s3)
| Title: Vitaly and Strings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings *s* and *t* to Vitaly. The strings have the same length, they consist of lowercase English letters, string *s* is lexicographically smaller than string *t*. Vitaly wondered if there is such string that is lexicographically larger than string *s* and at the same is lexicographically smaller than string *t*. This string should also consist of lowercase English letters and have the length equal to the lengths of strings *s* and *t*.
Let's help Vitaly solve this easy problem!
Input Specification:
The first line contains string *s* (1<=≤<=|*s*|<=≤<=100), consisting of lowercase English letters. Here, |*s*| denotes the length of the string.
The second line contains string *t* (|*t*|<==<=|*s*|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings *s* and *t* are the same and string *s* is lexicographically less than string *t*.
Output Specification:
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Demo Input:
['a\nc\n', 'aaa\nzzz\n', 'abcdefg\nabcdefh\n']
Demo Output:
['b\n', 'kkk\n', 'No such string\n']
Note:
String *s* = *s*<sub class="lower-index">1</sub>*s*<sub class="lower-index">2</sub>... *s*<sub class="lower-index">*n*</sub> is said to be lexicographically smaller than *t* = *t*<sub class="lower-index">1</sub>*t*<sub class="lower-index">2</sub>... *t*<sub class="lower-index">*n*</sub>, if there exists such *i*, that *s*<sub class="lower-index">1</sub> = *t*<sub class="lower-index">1</sub>, *s*<sub class="lower-index">2</sub> = *t*<sub class="lower-index">2</sub>, ... *s*<sub class="lower-index">*i* - 1</sub> = *t*<sub class="lower-index">*i* - 1</sub>, *s*<sub class="lower-index">*i*</sub> < *t*<sub class="lower-index">*i*</sub>. | ```python
from operator import itemgetter
#int(input())
#map(int,input().split())
#[list(map(int,input().split())) for i in range(q)]
#print("YES" * ans + "NO" * (1-ans))
s = input()
s2 = input()
alth = "abcdefghijklmnopqrstuvwxyz"
n = len(s)
s3 = [0] * n
for i in range(n-1,-1,-1):
if s[i] == "z":
s3[i] = "a"
else:
s3[i] = alth[alth.find(s[i]) + 1]
for i in range(i):
s3[i] = s[i]
break
s3 = "".join(s3)
if s3 == s2:
print("No such string")
else:
print(s3)
``` | 3 | |
937 | B | Vile Grasshoppers | PROGRAMMING | 1,400 | [
"brute force",
"math",
"number theory"
] | null | null | The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.
The pine's trunk includes several branches, located one above another and numbered from 2 to *y*. Some of them (more precise, from 2 to *p*) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch *x* can jump to branches .
Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking.
In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible. | The only line contains two integers *p* and *y* (2<=≤<=*p*<=≤<=*y*<=≤<=109). | Output the number of the highest suitable branch. If there are none, print -1 instead. | [
"3 6\n",
"3 4\n"
] | [
"5\n",
"-1\n"
] | In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5.
It immediately follows that there are no valid branches in second sample case. | 1,000 | [
{
"input": "3 6",
"output": "5"
},
{
"input": "3 4",
"output": "-1"
},
{
"input": "2 2",
"output": "-1"
},
{
"input": "5 50",
"output": "49"
},
{
"input": "944192806 944193066",
"output": "944192807"
},
{
"input": "1000000000 1000000000",
"output":... | 1,584,454,852 | 4,852 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 4 | 1,000 | 0 | p, y = map(int, input().split())
ans = -1
for i in range(y, 2 - 1, -1):
can = True
for j in range(2, p + 1):
can &= i % j != 0
if can:
ans = i
break
print(ans)
| Title: Vile Grasshoppers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.
The pine's trunk includes several branches, located one above another and numbered from 2 to *y*. Some of them (more precise, from 2 to *p*) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch *x* can jump to branches .
Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking.
In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible.
Input Specification:
The only line contains two integers *p* and *y* (2<=≤<=*p*<=≤<=*y*<=≤<=109).
Output Specification:
Output the number of the highest suitable branch. If there are none, print -1 instead.
Demo Input:
['3 6\n', '3 4\n']
Demo Output:
['5\n', '-1\n']
Note:
In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5.
It immediately follows that there are no valid branches in second sample case. | ```python
p, y = map(int, input().split())
ans = -1
for i in range(y, 2 - 1, -1):
can = True
for j in range(2, p + 1):
can &= i % j != 0
if can:
ans = i
break
print(ans)
``` | 0 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer *x* was given. The task was to add *x* to the sum of the digits of the number *x* written in decimal numeral system.
Since the number *n* on the board was small, Vova quickly guessed which *x* could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number *n* for all suitable values of *x* or determine that such *x* does not exist. Write such a program for Vova. | The first line contains integer *n* (1<=≤<=*n*<=≤<=109). | In the first line print one integer *k* — number of different values of *x* satisfying the condition.
In next *k* lines print these values in ascending order. | [
"21\n",
"20\n"
] | [
"1\n15\n",
"0\n"
] | In the first test case *x* = 15 there is only one variant: 15 + 1 + 5 = 21.
In the second test case there are no such *x*. | 0 | [
{
"input": "21",
"output": "1\n15"
},
{
"input": "20",
"output": "0"
},
{
"input": "1",
"output": "0"
},
{
"input": "2",
"output": "1\n1"
},
{
"input": "3",
"output": "0"
},
{
"input": "100000001",
"output": "2\n99999937\n100000000"
},
{
"i... | 1,520,961,415 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 46 | 5,632,000 | def sumDigits(x):
sumD = 0
for c in x:
sumD += int(c)
return sumD
xs = input()
xi = int(xs)
sumD = sumDigits(xs)
lst = []
for i in range(1, xi - sumD):
if i + sumDigits(str(i)) == xi:
lst.append(i)
if not lst:
print(0)
exit()
for x in lst:
print(x)
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer *x* was given. The task was to add *x* to the sum of the digits of the number *x* written in decimal numeral system.
Since the number *n* on the board was small, Vova quickly guessed which *x* could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number *n* for all suitable values of *x* or determine that such *x* does not exist. Write such a program for Vova.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=109).
Output Specification:
In the first line print one integer *k* — number of different values of *x* satisfying the condition.
In next *k* lines print these values in ascending order.
Demo Input:
['21\n', '20\n']
Demo Output:
['1\n15\n', '0\n']
Note:
In the first test case *x* = 15 there is only one variant: 15 + 1 + 5 = 21.
In the second test case there are no such *x*. | ```python
def sumDigits(x):
sumD = 0
for c in x:
sumD += int(c)
return sumD
xs = input()
xi = int(xs)
sumD = sumDigits(xs)
lst = []
for i in range(1, xi - sumD):
if i + sumDigits(str(i)) == xi:
lst.append(i)
if not lst:
print(0)
exit()
for x in lst:
print(x)
``` | 0 | |
479 | A | Expression | PROGRAMMING | 1,000 | [
"brute force",
"math"
] | null | null | Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers *a*, *b*, *c* on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting expression is as large as possible. Let's consider an example: assume that the teacher wrote numbers 1, 2 and 3 on the blackboard. Here are some ways of placing signs and brackets:
- 1+2*3=7 - 1*(2+3)=5 - 1*2*3=6 - (1+2)*3=9
Note that you can insert operation signs only between *a* and *b*, and between *b* and *c*, that is, you cannot swap integers. For instance, in the given sample you cannot get expression (1+3)*2.
It's easy to see that the maximum value that you can obtain is 9.
Your task is: given *a*, *b* and *c* print the maximum value that you can get. | The input contains three integers *a*, *b* and *c*, each on a single line (1<=≤<=*a*,<=*b*,<=*c*<=≤<=10). | Print the maximum value of the expression that you can obtain. | [
"1\n2\n3\n",
"2\n10\n3\n"
] | [
"9\n",
"60\n"
] | none | 500 | [
{
"input": "1\n2\n3",
"output": "9"
},
{
"input": "2\n10\n3",
"output": "60"
},
{
"input": "1\n1\n1",
"output": "3"
},
{
"input": "1\n2\n1",
"output": "4"
},
{
"input": "10\n10\n10",
"output": "1000"
},
{
"input": "5\n1\n3",
"output": "20"
},
{... | 1,695,573,886 | 2,147,483,647 | Python 3 | OK | TESTS | 29 | 46 | 0 | x = int(input())
y = int(input())
z = int(input())
print(max(x*y*z,max((x+y)*z,max(x+y+z,x*(y+z))))) | Title: Expression
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers *a*, *b*, *c* on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting expression is as large as possible. Let's consider an example: assume that the teacher wrote numbers 1, 2 and 3 on the blackboard. Here are some ways of placing signs and brackets:
- 1+2*3=7 - 1*(2+3)=5 - 1*2*3=6 - (1+2)*3=9
Note that you can insert operation signs only between *a* and *b*, and between *b* and *c*, that is, you cannot swap integers. For instance, in the given sample you cannot get expression (1+3)*2.
It's easy to see that the maximum value that you can obtain is 9.
Your task is: given *a*, *b* and *c* print the maximum value that you can get.
Input Specification:
The input contains three integers *a*, *b* and *c*, each on a single line (1<=≤<=*a*,<=*b*,<=*c*<=≤<=10).
Output Specification:
Print the maximum value of the expression that you can obtain.
Demo Input:
['1\n2\n3\n', '2\n10\n3\n']
Demo Output:
['9\n', '60\n']
Note:
none | ```python
x = int(input())
y = int(input())
z = int(input())
print(max(x*y*z,max((x+y)*z,max(x+y+z,x*(y+z)))))
``` | 3 | |
961 | B | Lecture Sleep | PROGRAMMING | 1,200 | [
"data structures",
"dp",
"implementation",
"two pointers"
] | null | null | Your friend Mishka and you attend a calculus lecture. Lecture lasts *n* minutes. Lecturer tells *a**i* theorems during the *i*-th minute.
Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array *t* of Mishka's behavior. If Mishka is asleep during the *i*-th minute of the lecture then *t**i* will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — *a**i* during the *i*-th minute. Otherwise he writes nothing.
You know some secret technique to keep Mishka awake for *k* minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and *n*<=-<=*k*<=+<=1. If you use it on some minute *i* then Mishka will be awake during minutes *j* such that and will write down all the theorems lecturer tells.
You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up. | The first line of the input contains two integer numbers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=105) — the duration of the lecture in minutes and the number of minutes you can keep Mishka awake.
The second line of the input contains *n* integer numbers *a*1,<=*a*2,<=... *a**n* (1<=≤<=*a**i*<=≤<=104) — the number of theorems lecturer tells during the *i*-th minute.
The third line of the input contains *n* integer numbers *t*1,<=*t*2,<=... *t**n* (0<=≤<=*t**i*<=≤<=1) — type of Mishka's behavior at the *i*-th minute of the lecture. | Print only one integer — the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up. | [
"6 3\n1 3 5 2 5 4\n1 1 0 1 0 0\n"
] | [
"16\n"
] | In the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16. | 0 | [
{
"input": "6 3\n1 3 5 2 5 4\n1 1 0 1 0 0",
"output": "16"
},
{
"input": "5 3\n1 9999 10000 10000 10000\n0 0 0 0 0",
"output": "30000"
},
{
"input": "3 3\n10 10 10\n1 1 0",
"output": "30"
},
{
"input": "1 1\n423\n0",
"output": "423"
},
{
"input": "6 6\n1 3 5 2 5 4... | 1,644,944,004 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 3 | 155 | 11,264,000 | n,k=map(int,input().split())
a=list(map(int,input().split()))
l=list(map(int,input().split()))
res=0
for i in range(len(l)):
if l[i]==1:
res+=a[i]
a[i]=0
prefixsum=[0 for i in range(n)]
for i in range(1,n):
a[i]+=a[i-1]
for i in range(k,n):
prefixsum[i]=a[i]-a[i-k]
maxsum=0
for i in range(n):
if prefixsum[i]>maxsum:
maxsum=prefixsum[i]
print(res+maxsum) | Title: Lecture Sleep
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Your friend Mishka and you attend a calculus lecture. Lecture lasts *n* minutes. Lecturer tells *a**i* theorems during the *i*-th minute.
Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array *t* of Mishka's behavior. If Mishka is asleep during the *i*-th minute of the lecture then *t**i* will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — *a**i* during the *i*-th minute. Otherwise he writes nothing.
You know some secret technique to keep Mishka awake for *k* minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and *n*<=-<=*k*<=+<=1. If you use it on some minute *i* then Mishka will be awake during minutes *j* such that and will write down all the theorems lecturer tells.
You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
Input Specification:
The first line of the input contains two integer numbers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=105) — the duration of the lecture in minutes and the number of minutes you can keep Mishka awake.
The second line of the input contains *n* integer numbers *a*1,<=*a*2,<=... *a**n* (1<=≤<=*a**i*<=≤<=104) — the number of theorems lecturer tells during the *i*-th minute.
The third line of the input contains *n* integer numbers *t*1,<=*t*2,<=... *t**n* (0<=≤<=*t**i*<=≤<=1) — type of Mishka's behavior at the *i*-th minute of the lecture.
Output Specification:
Print only one integer — the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
Demo Input:
['6 3\n1 3 5 2 5 4\n1 1 0 1 0 0\n']
Demo Output:
['16\n']
Note:
In the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16. | ```python
n,k=map(int,input().split())
a=list(map(int,input().split()))
l=list(map(int,input().split()))
res=0
for i in range(len(l)):
if l[i]==1:
res+=a[i]
a[i]=0
prefixsum=[0 for i in range(n)]
for i in range(1,n):
a[i]+=a[i-1]
for i in range(k,n):
prefixsum[i]=a[i]-a[i-k]
maxsum=0
for i in range(n):
if prefixsum[i]>maxsum:
maxsum=prefixsum[i]
print(res+maxsum)
``` | 0 | |
9 | B | Running Student | PROGRAMMING | 1,200 | [
"brute force",
"geometry",
"implementation"
] | B. Running Student | 1 | 64 | And again a misfortune fell on Poor Student. He is being late for an exam.
Having rushed to a bus stop that is in point (0,<=0), he got on a minibus and they drove along a straight line, parallel to axis *OX*, in the direction of increasing *x*.
Poor Student knows the following:
- during one run the minibus makes *n* stops, the *i*-th stop is in point (*x**i*,<=0) - coordinates of all the stops are different - the minibus drives at a constant speed, equal to *v**b* - it can be assumed the passengers get on and off the minibus at a bus stop momentarily - Student can get off the minibus only at a bus stop - Student will have to get off the minibus at a terminal stop, if he does not get off earlier - the University, where the exam will be held, is in point (*x**u*,<=*y**u*) - Student can run from a bus stop to the University at a constant speed *v**s* as long as needed - a distance between two points can be calculated according to the following formula: - Student is already on the minibus, so, he cannot get off at the first bus stop
Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University. | The first line contains three integer numbers: 2<=≤<=*n*<=≤<=100, 1<=≤<=*v**b*,<=*v**s*<=≤<=1000. The second line contains *n* non-negative integers in ascending order: coordinates *x**i* of the bus stop with index *i*. It is guaranteed that *x*1 equals to zero, and *x**n*<=≤<=105. The third line contains the coordinates of the University, integers *x**u* and *y**u*, not exceeding 105 in absolute value. | In the only line output the answer to the problem — index of the optimum bus stop. | [
"4 5 2\n0 2 4 6\n4 1\n",
"2 1 1\n0 100000\n100000 100000\n"
] | [
"3",
"2"
] | As you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus. | 0 | [
{
"input": "4 5 2\n0 2 4 6\n4 1",
"output": "3"
},
{
"input": "2 1 1\n0 100000\n100000 100000",
"output": "2"
},
{
"input": "6 5 1\n0 1 2 3 4 5\n0 0",
"output": "2"
},
{
"input": "4 100 10\n0 118 121 178\n220 220",
"output": "4"
},
{
"input": "4 3 3\n0 6 8 10\n7 -... | 1,646,064,696 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 10 | 62 | 0 | v1 = []
v2 = []
v3 = []
aux_real = 999999999999992
n, vb, vs = map(int, input().split())
x = list(map(int, input().split()))
x_uni, y_uni = map(int, input().split())
for i in range (n):
aux = x[i] / vb
v1.append(aux)
for j in range (n):
aux1 = (x_uni - x[j]) ** 2
aux2 = y_uni ** 2
aux2 = aux1 + aux2
aux3 = aux2 ** 0.5
v2.append(aux3)
for s in range (0, n):
aux = v1[s] + v2[s]
if s != 0:
if (aux_real > aux):
aux_real = aux
index = s + 1
print(index)
| Title: Running Student
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
And again a misfortune fell on Poor Student. He is being late for an exam.
Having rushed to a bus stop that is in point (0,<=0), he got on a minibus and they drove along a straight line, parallel to axis *OX*, in the direction of increasing *x*.
Poor Student knows the following:
- during one run the minibus makes *n* stops, the *i*-th stop is in point (*x**i*,<=0) - coordinates of all the stops are different - the minibus drives at a constant speed, equal to *v**b* - it can be assumed the passengers get on and off the minibus at a bus stop momentarily - Student can get off the minibus only at a bus stop - Student will have to get off the minibus at a terminal stop, if he does not get off earlier - the University, where the exam will be held, is in point (*x**u*,<=*y**u*) - Student can run from a bus stop to the University at a constant speed *v**s* as long as needed - a distance between two points can be calculated according to the following formula: - Student is already on the minibus, so, he cannot get off at the first bus stop
Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.
Input Specification:
The first line contains three integer numbers: 2<=≤<=*n*<=≤<=100, 1<=≤<=*v**b*,<=*v**s*<=≤<=1000. The second line contains *n* non-negative integers in ascending order: coordinates *x**i* of the bus stop with index *i*. It is guaranteed that *x*1 equals to zero, and *x**n*<=≤<=105. The third line contains the coordinates of the University, integers *x**u* and *y**u*, not exceeding 105 in absolute value.
Output Specification:
In the only line output the answer to the problem — index of the optimum bus stop.
Demo Input:
['4 5 2\n0 2 4 6\n4 1\n', '2 1 1\n0 100000\n100000 100000\n']
Demo Output:
['3', '2']
Note:
As you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus. | ```python
v1 = []
v2 = []
v3 = []
aux_real = 999999999999992
n, vb, vs = map(int, input().split())
x = list(map(int, input().split()))
x_uni, y_uni = map(int, input().split())
for i in range (n):
aux = x[i] / vb
v1.append(aux)
for j in range (n):
aux1 = (x_uni - x[j]) ** 2
aux2 = y_uni ** 2
aux2 = aux1 + aux2
aux3 = aux2 ** 0.5
v2.append(aux3)
for s in range (0, n):
aux = v1[s] + v2[s]
if s != 0:
if (aux_real > aux):
aux_real = aux
index = s + 1
print(index)
``` | 0 |
794 | A | Bank Robbery | PROGRAMMING | 800 | [
"brute force",
"implementation"
] | null | null | A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.
Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the *i*-th safe from the left is called safe *i*. There are *n* banknotes left in all the safes in total. The *i*-th banknote is in safe *x**i*. Oleg is now at safe *a*. There are two security guards, one of which guards the safe *b* such that *b*<=<<=*a*, i.e. the first guard is to the left of Oleg. The other guard guards the safe *c* so that *c*<=><=*a*, i.e. he is to the right of Oleg.
The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather. | The first line of input contains three space-separated integers, *a*, *b* and *c* (1<=≤<=*b*<=<<=*a*<=<<=*c*<=≤<=109), denoting the positions of Oleg, the first security guard and the second security guard, respectively.
The next line of input contains a single integer *n* (1<=≤<=*n*<=≤<=105), denoting the number of banknotes.
The next line of input contains *n* space-separated integers *x*1,<=*x*2,<=...,<=*x**n* (1<=≤<=*x**i*<=≤<=109), denoting that the *i*-th banknote is located in the *x**i*-th safe. Note that *x**i* are not guaranteed to be distinct. | Output a single integer: the maximum number of banknotes Oleg can take. | [
"5 3 7\n8\n4 7 5 5 3 6 2 8\n",
"6 5 7\n5\n1 5 7 92 3\n"
] | [
"4\n",
"0\n"
] | In the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes.
For the second sample, Oleg can't take any banknotes without bumping into any of the security guards. | 500 | [
{
"input": "5 3 7\n8\n4 7 5 5 3 6 2 8",
"output": "4"
},
{
"input": "6 5 7\n5\n1 5 7 92 3",
"output": "0"
},
{
"input": "3 2 4\n1\n3",
"output": "1"
},
{
"input": "5 3 8\n12\n8 3 4 5 7 6 8 3 5 4 7 6",
"output": "8"
},
{
"input": "7 3 10\n5\n3 3 3 3 3",
"output... | 1,666,438,629 | 2,147,483,647 | Python 3 | OK | TESTS | 46 | 109 | 7,372,800 | A = list(input().split())
for i in range(len(A)):
A[i]=int(A[i])
a=A[0]
b=A[1]
c=A[2]
n = int(input())
B = list(input().split())
for i in range(len(B)):
B[i]=int(B[i])
count = 0
for i in B:
if i>b and i<c:
count+=1
print(count)
| Title: Bank Robbery
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.
Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the *i*-th safe from the left is called safe *i*. There are *n* banknotes left in all the safes in total. The *i*-th banknote is in safe *x**i*. Oleg is now at safe *a*. There are two security guards, one of which guards the safe *b* such that *b*<=<<=*a*, i.e. the first guard is to the left of Oleg. The other guard guards the safe *c* so that *c*<=><=*a*, i.e. he is to the right of Oleg.
The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.
Input Specification:
The first line of input contains three space-separated integers, *a*, *b* and *c* (1<=≤<=*b*<=<<=*a*<=<<=*c*<=≤<=109), denoting the positions of Oleg, the first security guard and the second security guard, respectively.
The next line of input contains a single integer *n* (1<=≤<=*n*<=≤<=105), denoting the number of banknotes.
The next line of input contains *n* space-separated integers *x*1,<=*x*2,<=...,<=*x**n* (1<=≤<=*x**i*<=≤<=109), denoting that the *i*-th banknote is located in the *x**i*-th safe. Note that *x**i* are not guaranteed to be distinct.
Output Specification:
Output a single integer: the maximum number of banknotes Oleg can take.
Demo Input:
['5 3 7\n8\n4 7 5 5 3 6 2 8\n', '6 5 7\n5\n1 5 7 92 3\n']
Demo Output:
['4\n', '0\n']
Note:
In the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes.
For the second sample, Oleg can't take any banknotes without bumping into any of the security guards. | ```python
A = list(input().split())
for i in range(len(A)):
A[i]=int(A[i])
a=A[0]
b=A[1]
c=A[2]
n = int(input())
B = list(input().split())
for i in range(len(B)):
B[i]=int(B[i])
count = 0
for i in B:
if i>b and i<c:
count+=1
print(count)
``` | 3 | |
764 | A | Taymyr is calling you | PROGRAMMING | 800 | [
"brute force",
"implementation",
"math"
] | null | null | Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.
Ilia-alpinist calls every *n* minutes, i.e. in minutes *n*, 2*n*, 3*n* and so on. Artists come to the comrade every *m* minutes, i.e. in minutes *m*, 2*m*, 3*m* and so on. The day is *z* minutes long, i.e. the day consists of minutes 1,<=2,<=...,<=*z*. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute. | The only string contains three integers — *n*, *m* and *z* (1<=≤<=*n*,<=*m*,<=*z*<=≤<=104). | Print single integer — the minimum number of artists that should be killed so that there are no artists in the room when Ilia calls. | [
"1 1 10\n",
"1 2 5\n",
"2 3 9\n"
] | [
"10\n",
"2\n",
"1\n"
] | Taymyr is a place in the north of Russia.
In the first test the artists come each minute, as well as the calls, so we need to kill all of them.
In the second test we need to kill artists which come on the second and the fourth minutes.
In the third test — only the artist which comes on the sixth minute. | 500 | [
{
"input": "1 1 10",
"output": "10"
},
{
"input": "1 2 5",
"output": "2"
},
{
"input": "2 3 9",
"output": "1"
},
{
"input": "4 8 9",
"output": "1"
},
{
"input": "7 9 2",
"output": "0"
},
{
"input": "10000 10000 10000",
"output": "1"
},
{
"i... | 1,553,622,352 | 2,147,483,647 | Python 3 | OK | TESTS | 32 | 748 | 307,200 | # import sys
# sys.stdin=open("input.in",'r')
# sys.stdout=open("outp.out",'w')
n,m,z=map(int,input().split())
a=[i for i in range(n,z+1,n)]
b=[j for j in range(m,z+1,m)]
c=0
for x in a:
if x in b:
c+=1
print(c) | Title: Taymyr is calling you
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.
Ilia-alpinist calls every *n* minutes, i.e. in minutes *n*, 2*n*, 3*n* and so on. Artists come to the comrade every *m* minutes, i.e. in minutes *m*, 2*m*, 3*m* and so on. The day is *z* minutes long, i.e. the day consists of minutes 1,<=2,<=...,<=*z*. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute.
Input Specification:
The only string contains three integers — *n*, *m* and *z* (1<=≤<=*n*,<=*m*,<=*z*<=≤<=104).
Output Specification:
Print single integer — the minimum number of artists that should be killed so that there are no artists in the room when Ilia calls.
Demo Input:
['1 1 10\n', '1 2 5\n', '2 3 9\n']
Demo Output:
['10\n', '2\n', '1\n']
Note:
Taymyr is a place in the north of Russia.
In the first test the artists come each minute, as well as the calls, so we need to kill all of them.
In the second test we need to kill artists which come on the second and the fourth minutes.
In the third test — only the artist which comes on the sixth minute. | ```python
# import sys
# sys.stdin=open("input.in",'r')
# sys.stdout=open("outp.out",'w')
n,m,z=map(int,input().split())
a=[i for i in range(n,z+1,n)]
b=[j for j in range(m,z+1,m)]
c=0
for x in a:
if x in b:
c+=1
print(c)
``` | 3 | |
102 | B | Sum of Digits | PROGRAMMING | 1,000 | [
"implementation"
] | B. Sum of Digits | 2 | 265 | Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit? | The first line contains the only integer *n* (0<=≤<=*n*<=≤<=10100000). It is guaranteed that *n* doesn't contain any leading zeroes. | Print the number of times a number can be replaced by the sum of its digits until it only contains one digit. | [
"0\n",
"10\n",
"991\n"
] | [
"0\n",
"1\n",
"3\n"
] | In the first sample the number already is one-digit — Herald can't cast a spell.
The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.
The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit. | 1,000 | [
{
"input": "0",
"output": "0"
},
{
"input": "10",
"output": "1"
},
{
"input": "991",
"output": "3"
},
{
"input": "99",
"output": "2"
},
{
"input": "100",
"output": "1"
},
{
"input": "123456789",
"output": "2"
},
{
"input": "32",
"output... | 1,598,517,263 | 2,147,483,647 | PyPy 3 | OK | TESTS | 51 | 1,246 | 7,884,800 | import sys
input = sys.stdin.readline
def inp():
return int(input())
def minp():
return map(int,input().split())
def inpsl():
return list(input().split())
def write(s):
sys.stdout.write(s+" ")
def main():
n = inp()
cnt = 0
while(n>9):
n = sum([int(i) for i in str(n)])
cnt += 1
print(cnt)
main() | Title: Sum of Digits
Time Limit: 2 seconds
Memory Limit: 265 megabytes
Problem Description:
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit?
Input Specification:
The first line contains the only integer *n* (0<=≤<=*n*<=≤<=10100000). It is guaranteed that *n* doesn't contain any leading zeroes.
Output Specification:
Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.
Demo Input:
['0\n', '10\n', '991\n']
Demo Output:
['0\n', '1\n', '3\n']
Note:
In the first sample the number already is one-digit — Herald can't cast a spell.
The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.
The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit. | ```python
import sys
input = sys.stdin.readline
def inp():
return int(input())
def minp():
return map(int,input().split())
def inpsl():
return list(input().split())
def write(s):
sys.stdout.write(s+" ")
def main():
n = inp()
cnt = 0
while(n>9):
n = sum([int(i) for i in str(n)])
cnt += 1
print(cnt)
main()
``` | 3.674312 |
797 | A | k-Factorization | PROGRAMMING | 1,100 | [
"implementation",
"math",
"number theory"
] | null | null | Given a positive integer *n*, find *k* integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to *n*. | The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=100000, 1<=≤<=*k*<=≤<=20). | If it's impossible to find the representation of *n* as a product of *k* numbers, print -1.
Otherwise, print *k* integers in any order. Their product must be equal to *n*. If there are multiple answers, print any of them. | [
"100000 2\n",
"100000 20\n",
"1024 5\n"
] | [
"2 50000 \n",
"-1\n",
"2 64 2 2 2 \n"
] | none | 0 | [
{
"input": "100000 2",
"output": "2 50000 "
},
{
"input": "100000 20",
"output": "-1"
},
{
"input": "1024 5",
"output": "2 64 2 2 2 "
},
{
"input": "100000 10",
"output": "2 2 2 2 2 5 5 5 5 5 "
},
{
"input": "99999 3",
"output": "3 813 41 "
},
{
"input... | 1,654,950,297 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 10 | 31 | 0 | from math import sqrt
n, k = [int(x) for x in input().split()]
n1 = n
counter = 0
divisors = []
for i in range(2, int(sqrt(n)) + 1):
while n % i == 0:
n //= i
counter += 1
divisors.append(i)
if k > counter:
print(-1)
else:
mult = 1
for i in range(k - 1):
mult *= divisors[i]
print(*divisors[:k - 1], n1 // mult)
| Title: k-Factorization
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Given a positive integer *n*, find *k* integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to *n*.
Input Specification:
The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=100000, 1<=≤<=*k*<=≤<=20).
Output Specification:
If it's impossible to find the representation of *n* as a product of *k* numbers, print -1.
Otherwise, print *k* integers in any order. Their product must be equal to *n*. If there are multiple answers, print any of them.
Demo Input:
['100000 2\n', '100000 20\n', '1024 5\n']
Demo Output:
['2 50000 \n', '-1\n', '2 64 2 2 2 \n']
Note:
none | ```python
from math import sqrt
n, k = [int(x) for x in input().split()]
n1 = n
counter = 0
divisors = []
for i in range(2, int(sqrt(n)) + 1):
while n % i == 0:
n //= i
counter += 1
divisors.append(i)
if k > counter:
print(-1)
else:
mult = 1
for i in range(k - 1):
mult *= divisors[i]
print(*divisors[:k - 1], n1 // mult)
``` | 0 | |
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,718,194 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 31 | 0 | a,b,c = map(int,input().split())
g = 0
r = 0
while g != c:
g += 1
r += g * a
print(r - b) | 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
a,b,c = map(int,input().split())
g = 0
r = 0
while g != c:
g += 1
r += g * a
print(r - b)
``` | 0 | |
744 | B | Hongcow's Game | PROGRAMMING | 1,900 | [
"bitmasks",
"divide and conquer",
"interactive"
] | null | null | This is an interactive problem. In the interaction section below you will see the information about flushing the output.
In this problem, you will be playing a game with Hongcow. How lucky of you!
Hongcow has a hidden *n* by *n* matrix *M*. Let *M**i*,<=*j* denote the entry *i*-th row and *j*-th column of the matrix. The rows and columns are labeled from 1 to *n*.
The matrix entries are between 0 and 109. In addition, *M**i*,<=*i*<==<=0 for all valid *i*. Your task is to find the minimum value along each row, excluding diagonal elements. Formally, for each *i*, you must find .
To do this, you can ask Hongcow some questions.
A question consists of giving Hongcow a subset of distinct indices {*w*1,<=*w*2,<=...,<=*w**k*}, with 1<=≤<=*k*<=≤<=*n*. Hongcow will respond with *n* integers. The *i*-th integer will contain the minimum value of *min*1<=≤<=*j*<=≤<=*k**M**i*,<=*w**j*.
You may only ask Hongcow at most 20 questions — he thinks you only need that many questions answered.
When you are ready to answer, print out a single integer <=-<=1 on its own line, then *n* integers on the next line. The *i*-th integer should be the minimum value in the *i*-th row of the matrix, excluding the *i*-th element. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.
You will get Wrong Answer verdict if
- Your question or answers are not in the format described in this statement. - You ask strictly more than 20 questions. - Your question contains duplicate indices. - The value of *k* in your question does not lie in the range from 1 to *n*, inclusive. - Your final answer is not correct. | The first line of input will contain a single integer *n* (2<=≤<=*n*<=≤<=1,<=000). | To print the final answer, print out the string -1 on its own line. Then, the next line should contain *n* integers. The *i*-th integer should be the minimum value of the *i*-th row of the matrix, excluding elements on the diagonal. Do not forget to flush your answer! | [
"3\n0 0 0\n2 7 0\n0 0 4\n3 0 8\n0 5 4",
"2\n0 0\n0 0"
] | [
"3\n1 2 3\n1\n3\n2\n1 2\n1\n2\n1\n1\n-1\n2 5 4\n",
"1\n2\n1\n1\n-1\n0 0"
] | In the first sample, Hongcow has the hidden matrix
Here is a more readable version demonstrating the interaction. The column on the left represents Hongcow, while the column on the right represents the contestant.
For the second sample, it is possible for off-diagonal elements of the matrix to be zero. | 1,250 | [] | 1,482,673,361 | 2,147,483,647 | Python 3 | OK | TESTS | 63 | 265 | 6,451,200 | import math,sys,re,itertools,pprint,collections,copy
rs,ri,rai,raf=input,lambda:int(input()),lambda:list(map(int, input().split())),lambda:list(map(float, input().split()))
pai=lambda x: print(" ".join(map(str, x)))
n = ri()
line_min = [float("inf") for _ in range(n)]
requests = []
def init_requests():
requests.append([
[(1, n//2)], [(n//2+1, n)]
])
while True:
l, r = requests[-1]
ln, rn = [], []
for i, j in l + r:
if j - i > 0:
ln.append(
(i, (i+j)//2)
)
rn.append(
((i+j)//2+1, j)
)
if len(ln) == 0 and len(rn) == 0:
break
requests.append([ln, rn])
def make_request(a: list):
print(len(a))
print(" ".join(map(str, a)))
sys.stdout.flush()
ans = rai()
for i in range(n):
if i+1 not in a:
line_min[i] = min(line_min[i], ans[i])
init_requests()
for l, r in requests:
la = []
for lr in l:
la += list(range(lr[0], lr[1]+1))
make_request(la)
ra = []
for rr in r:
ra += list(range(rr[0], rr[1]+1))
make_request(ra)
print(-1)
pai(line_min)
| Title: Hongcow's Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
This is an interactive problem. In the interaction section below you will see the information about flushing the output.
In this problem, you will be playing a game with Hongcow. How lucky of you!
Hongcow has a hidden *n* by *n* matrix *M*. Let *M**i*,<=*j* denote the entry *i*-th row and *j*-th column of the matrix. The rows and columns are labeled from 1 to *n*.
The matrix entries are between 0 and 109. In addition, *M**i*,<=*i*<==<=0 for all valid *i*. Your task is to find the minimum value along each row, excluding diagonal elements. Formally, for each *i*, you must find .
To do this, you can ask Hongcow some questions.
A question consists of giving Hongcow a subset of distinct indices {*w*1,<=*w*2,<=...,<=*w**k*}, with 1<=≤<=*k*<=≤<=*n*. Hongcow will respond with *n* integers. The *i*-th integer will contain the minimum value of *min*1<=≤<=*j*<=≤<=*k**M**i*,<=*w**j*.
You may only ask Hongcow at most 20 questions — he thinks you only need that many questions answered.
When you are ready to answer, print out a single integer <=-<=1 on its own line, then *n* integers on the next line. The *i*-th integer should be the minimum value in the *i*-th row of the matrix, excluding the *i*-th element. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.
You will get Wrong Answer verdict if
- Your question or answers are not in the format described in this statement. - You ask strictly more than 20 questions. - Your question contains duplicate indices. - The value of *k* in your question does not lie in the range from 1 to *n*, inclusive. - Your final answer is not correct.
Input Specification:
The first line of input will contain a single integer *n* (2<=≤<=*n*<=≤<=1,<=000).
Output Specification:
To print the final answer, print out the string -1 on its own line. Then, the next line should contain *n* integers. The *i*-th integer should be the minimum value of the *i*-th row of the matrix, excluding elements on the diagonal. Do not forget to flush your answer!
Demo Input:
['3\n0 0 0\n2 7 0\n0 0 4\n3 0 8\n0 5 4', '2\n0 0\n0 0']
Demo Output:
['3\n1 2 3\n1\n3\n2\n1 2\n1\n2\n1\n1\n-1\n2 5 4\n', '1\n2\n1\n1\n-1\n0 0']
Note:
In the first sample, Hongcow has the hidden matrix
Here is a more readable version demonstrating the interaction. The column on the left represents Hongcow, while the column on the right represents the contestant.
For the second sample, it is possible for off-diagonal elements of the matrix to be zero. | ```python
import math,sys,re,itertools,pprint,collections,copy
rs,ri,rai,raf=input,lambda:int(input()),lambda:list(map(int, input().split())),lambda:list(map(float, input().split()))
pai=lambda x: print(" ".join(map(str, x)))
n = ri()
line_min = [float("inf") for _ in range(n)]
requests = []
def init_requests():
requests.append([
[(1, n//2)], [(n//2+1, n)]
])
while True:
l, r = requests[-1]
ln, rn = [], []
for i, j in l + r:
if j - i > 0:
ln.append(
(i, (i+j)//2)
)
rn.append(
((i+j)//2+1, j)
)
if len(ln) == 0 and len(rn) == 0:
break
requests.append([ln, rn])
def make_request(a: list):
print(len(a))
print(" ".join(map(str, a)))
sys.stdout.flush()
ans = rai()
for i in range(n):
if i+1 not in a:
line_min[i] = min(line_min[i], ans[i])
init_requests()
for l, r in requests:
la = []
for lr in l:
la += list(range(lr[0], lr[1]+1))
make_request(la)
ra = []
for rr in r:
ra += list(range(rr[0], rr[1]+1))
make_request(ra)
print(-1)
pai(line_min)
``` | 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,651,644,775 | 2,147,483,647 | Python 3 | OK | TESTS | 58 | 77 | 409,600 | #!/usr/bin/env python
import math
import sys
import itertools
import fractions
if __name__ == '__main__':
wtf = sys.stdin.read()
wtf = wtf.strip().split('\n')
S = wtf[0]
f = ''
FNT = 'heidi'
z = FNT
for s in S:
if len(f) == 5:
if f == FNT:
break
f = ''
z = FNT
if s == z[0]:
f += s
z = z[1:]
print('YES' if f == 'heidi' else 'NO')
| 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
#!/usr/bin/env python
import math
import sys
import itertools
import fractions
if __name__ == '__main__':
wtf = sys.stdin.read()
wtf = wtf.strip().split('\n')
S = wtf[0]
f = ''
FNT = 'heidi'
z = FNT
for s in S:
if len(f) == 5:
if f == FNT:
break
f = ''
z = FNT
if s == z[0]:
f += s
z = z[1:]
print('YES' if f == 'heidi' else 'NO')
``` | 3 | |
69 | A | Young Physicist | PROGRAMMING | 1,000 | [
"implementation",
"math"
] | A. Young Physicist | 2 | 256 | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. | The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100), then follow *n* lines containing three integers each: the *x**i* coordinate, the *y**i* coordinate and the *z**i* coordinate of the force vector, applied to the body (<=-<=100<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=100). | Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. | [
"3\n4 1 7\n-2 4 -1\n1 -5 -3\n",
"3\n3 -1 7\n-5 2 -4\n2 -1 -3\n"
] | [
"NO",
"YES"
] | none | 500 | [
{
"input": "3\n4 1 7\n-2 4 -1\n1 -5 -3",
"output": "NO"
},
{
"input": "3\n3 -1 7\n-5 2 -4\n2 -1 -3",
"output": "YES"
},
{
"input": "10\n21 32 -46\n43 -35 21\n42 2 -50\n22 40 20\n-27 -9 38\n-4 1 1\n-40 6 -31\n-13 -2 34\n-21 34 -12\n-32 -29 41",
"output": "NO"
},
{
"input": "10... | 1,584,558,927 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 156 | 0 | n=int(input())
m=[]
for i in range(n):
l=list(map(int, input().split()))
m.append(l)
sum=0
for i in range(3):
for j in range(n):
sum+=m[j][i]
print(sum)
if(sum==0):
print("YES")
else:
print("NO")
| Title: Young Physicist
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
Input Specification:
The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100), then follow *n* lines containing three integers each: the *x**i* coordinate, the *y**i* coordinate and the *z**i* coordinate of the force vector, applied to the body (<=-<=100<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=100).
Output Specification:
Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.
Demo Input:
['3\n4 1 7\n-2 4 -1\n1 -5 -3\n', '3\n3 -1 7\n-5 2 -4\n2 -1 -3\n']
Demo Output:
['NO', 'YES']
Note:
none | ```python
n=int(input())
m=[]
for i in range(n):
l=list(map(int, input().split()))
m.append(l)
sum=0
for i in range(3):
for j in range(n):
sum+=m[j][i]
print(sum)
if(sum==0):
print("YES")
else:
print("NO")
``` | 0 |
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,633,169,745 | 2,147,483,647 | Python 3 | OK | TESTS | 28 | 140 | 7,782,400 | a = input()
b = input()
n = 0
a1 = len(a)
b1 = len(b)
while a1 != 0 and b1 != 0 and a[a1-1] == b[b1-1]:
a1 -= 1
b1 -= 1
print(a1 + b1)
# Sat Oct 02 2021 13:15:45 GMT+0300 (Москва, стандартное время)
| 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
a = input()
b = input()
n = 0
a1 = len(a)
b1 = len(b)
while a1 != 0 and b1 != 0 and a[a1-1] == b[b1-1]:
a1 -= 1
b1 -= 1
print(a1 + b1)
# Sat Oct 02 2021 13:15:45 GMT+0300 (Москва, стандартное время)
``` | 3 | |
38 | H | The Great Marathon | PROGRAMMING | 2,400 | [
"dp"
] | H. The Great Marathon | 4 | 256 | On the Berland Dependence Day it was decided to organize a great marathon. Berland consists of *n* cities, some of which are linked by two-way roads. Each road has a certain length. The cities are numbered from 1 to *n*. It is known that one can get from any city to any other one by the roads.
*n* runners take part in the competition, one from each city. But Berland runners are talkative by nature and that's why the juries took measures to avoid large crowds of marathon participants. The jury decided that every runner should start the marathon from their hometown. Before the start every sportsman will get a piece of paper containing the name of the city where the sportsman's finishing line is. The finish is chosen randomly for every sportsman but it can't coincide with the sportsman's starting point. Several sportsmen are allowed to finish in one and the same city. All the sportsmen start simultaneously and everyone runs the shortest route from the starting point to the finishing one. All the sportsmen run at one speed which equals to 1.
After the competition a follow-up table of the results will be composed where the sportsmen will be sorted according to the nondecrease of time they spent to cover the distance. The first *g* sportsmen in the table will get golden medals, the next *s* sportsmen will get silver medals and the rest will get bronze medals. Besides, if two or more sportsmen spend the same amount of time to cover the distance, they are sorted according to the number of the city where a sportsman started to run in the ascending order. That means no two sportsmen share one and the same place.
According to the rules of the competition the number of gold medals *g* must satisfy the inequation *g*1<=≤<=*g*<=≤<=*g*2, where *g*1 and *g*2 are values formed historically. In a similar way, the number of silver medals *s* must satisfy the inequation *s*1<=≤<=*s*<=≤<=*s*2, where *s*1 and *s*2 are also values formed historically.
At present, before the start of the competition, the destination points of every sportsman are unknown. However, the press demands details and that's why you are given the task of counting the number of the ways to distribute the medals. Two ways to distribute the medals are considered different if at least one sportsman could have received during those distributions different kinds of medals. | The first input line contains given integers *n* and *m* (3<=≤<=*n*<=≤<=50, *n*<=-<=1<=≤<=*m*<=≤<=1000), where *n* is the number of Berland towns and *m* is the number of roads.
Next in *m* lines road descriptions are given as groups of three integers *v*, *u*, *c*, which are the numbers of linked towns and its length (1<=≤<=*v*,<=*u*<=≤<=*n*, *v*<=≠<=*u*, 1<=≤<=*c*<=≤<=1000). Every pair of cities have no more than one road between them.
The last line contains integers *g*1, *g*2, *s*1, *s*2 (1<=≤<=*g*1<=≤<=*g*2, 1<=≤<=*s*1<=≤<=*s*2, *g*2<=+<=*s*2<=<<=*n*). The input data numbers, located on one line, are space-separated. | Print the single number — the number of ways to distribute the medals. It is guaranteed that the number fits in the standard 64-bit signed data type. | [
"3 2\n1 2 1\n2 3 1\n1 1 1 1\n",
"4 5\n1 2 2\n2 3 1\n3 4 2\n4 1 2\n1 3 3\n1 2 1 1\n",
"3 3\n1 2 2\n2 3 1\n3 1 2\n1 1 1 1\n"
] | [
"3\n",
"19\n",
"4\n"
] | none | 0 | [] | 1,693,303,470 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 92 | 0 | print("_RANDOM_GUESS_1693303470.5344942")# 1693303470.53451 | Title: The Great Marathon
Time Limit: 4 seconds
Memory Limit: 256 megabytes
Problem Description:
On the Berland Dependence Day it was decided to organize a great marathon. Berland consists of *n* cities, some of which are linked by two-way roads. Each road has a certain length. The cities are numbered from 1 to *n*. It is known that one can get from any city to any other one by the roads.
*n* runners take part in the competition, one from each city. But Berland runners are talkative by nature and that's why the juries took measures to avoid large crowds of marathon participants. The jury decided that every runner should start the marathon from their hometown. Before the start every sportsman will get a piece of paper containing the name of the city where the sportsman's finishing line is. The finish is chosen randomly for every sportsman but it can't coincide with the sportsman's starting point. Several sportsmen are allowed to finish in one and the same city. All the sportsmen start simultaneously and everyone runs the shortest route from the starting point to the finishing one. All the sportsmen run at one speed which equals to 1.
After the competition a follow-up table of the results will be composed where the sportsmen will be sorted according to the nondecrease of time they spent to cover the distance. The first *g* sportsmen in the table will get golden medals, the next *s* sportsmen will get silver medals and the rest will get bronze medals. Besides, if two or more sportsmen spend the same amount of time to cover the distance, they are sorted according to the number of the city where a sportsman started to run in the ascending order. That means no two sportsmen share one and the same place.
According to the rules of the competition the number of gold medals *g* must satisfy the inequation *g*1<=≤<=*g*<=≤<=*g*2, where *g*1 and *g*2 are values formed historically. In a similar way, the number of silver medals *s* must satisfy the inequation *s*1<=≤<=*s*<=≤<=*s*2, where *s*1 and *s*2 are also values formed historically.
At present, before the start of the competition, the destination points of every sportsman are unknown. However, the press demands details and that's why you are given the task of counting the number of the ways to distribute the medals. Two ways to distribute the medals are considered different if at least one sportsman could have received during those distributions different kinds of medals.
Input Specification:
The first input line contains given integers *n* and *m* (3<=≤<=*n*<=≤<=50, *n*<=-<=1<=≤<=*m*<=≤<=1000), where *n* is the number of Berland towns and *m* is the number of roads.
Next in *m* lines road descriptions are given as groups of three integers *v*, *u*, *c*, which are the numbers of linked towns and its length (1<=≤<=*v*,<=*u*<=≤<=*n*, *v*<=≠<=*u*, 1<=≤<=*c*<=≤<=1000). Every pair of cities have no more than one road between them.
The last line contains integers *g*1, *g*2, *s*1, *s*2 (1<=≤<=*g*1<=≤<=*g*2, 1<=≤<=*s*1<=≤<=*s*2, *g*2<=+<=*s*2<=<<=*n*). The input data numbers, located on one line, are space-separated.
Output Specification:
Print the single number — the number of ways to distribute the medals. It is guaranteed that the number fits in the standard 64-bit signed data type.
Demo Input:
['3 2\n1 2 1\n2 3 1\n1 1 1 1\n', '4 5\n1 2 2\n2 3 1\n3 4 2\n4 1 2\n1 3 3\n1 2 1 1\n', '3 3\n1 2 2\n2 3 1\n3 1 2\n1 1 1 1\n']
Demo Output:
['3\n', '19\n', '4\n']
Note:
none | ```python
print("_RANDOM_GUESS_1693303470.5344942")# 1693303470.53451
``` | 0 |
226 | A | Flying Saucer Segments | PROGRAMMING | 1,400 | [
"math"
] | null | null | An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).
The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one — to the 1-st and the 3-rd ones, the 3-rd one — only to the 2-nd one. The transitions are possible only between the adjacent sections.
The spacecraft team consists of *n* aliens. Each of them is given a rank — an integer from 1 to *n*. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section *a* to section *b* only if it is senior in rank to all aliens who are in the segments *a* and *b* (besides, the segments *a* and *b* are of course required to be adjacent). Any alien requires exactly 1 minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship.
Alien *A* is senior in rank to alien *B*, if the number indicating rank *A*, is more than the corresponding number for *B*.
At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task.
Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo *m*. | The first line contains two space-separated integers: *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=109) — the number of aliens on the saucer and the number, modulo which you should print the answer, correspondingly. | Print a single number — the answer to the problem modulo *m*. | [
"1 10\n",
"3 8\n"
] | [
"2\n",
"2\n"
] | In the first sample the only crew member moves from segment 3 to segment 2, and then from segment 2 to segment 1 without any problems. Thus, the whole moving will take two minutes.
To briefly describe the movements in the second sample we will use value <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4c7c8e716067e9c6251e8ca82a4ca7fde74fbacb.png" style="max-width: 100.0%;max-height: 100.0%;"/>, which would correspond to an alien with rank *i* moving from the segment in which it is at the moment, to the segment number *j*. Using these values, we will describe the movements between the segments in the second sample: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/954e2f634474269f53df1edbf2e7b214d8a2611c.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/d4fd9e68a9c6a277942eb188291d6d2744ea21d3.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/b73a9870e1b41a5e048c3ab3e3fd4b92c336c9ec.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/954e2f634474269f53df1edbf2e7b214d8a2611c.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/49b1ffd4dcd2e0da0acec04559e0c3efc7854b07.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ef8b3f32ee76c86f57fa63f7251fa290642f17f8.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/954e2f634474269f53df1edbf2e7b214d8a2611c.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/d4fd9e68a9c6a277942eb188291d6d2744ea21d3.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>; In total: the aliens need 26 moves. The remainder after dividing 26 by 8 equals 2, so the answer to this test is 2. | 500 | [
{
"input": "1 10",
"output": "2"
},
{
"input": "3 8",
"output": "2"
},
{
"input": "8 12",
"output": "8"
},
{
"input": "4 84",
"output": "80"
},
{
"input": "9 95",
"output": "17"
},
{
"input": "331358794 820674098",
"output": "2619146"
},
{
... | 1,501,047,068 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | a = b++ | Title: Flying Saucer Segments
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).
The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one — to the 1-st and the 3-rd ones, the 3-rd one — only to the 2-nd one. The transitions are possible only between the adjacent sections.
The spacecraft team consists of *n* aliens. Each of them is given a rank — an integer from 1 to *n*. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section *a* to section *b* only if it is senior in rank to all aliens who are in the segments *a* and *b* (besides, the segments *a* and *b* are of course required to be adjacent). Any alien requires exactly 1 minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship.
Alien *A* is senior in rank to alien *B*, if the number indicating rank *A*, is more than the corresponding number for *B*.
At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task.
Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo *m*.
Input Specification:
The first line contains two space-separated integers: *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=109) — the number of aliens on the saucer and the number, modulo which you should print the answer, correspondingly.
Output Specification:
Print a single number — the answer to the problem modulo *m*.
Demo Input:
['1 10\n', '3 8\n']
Demo Output:
['2\n', '2\n']
Note:
In the first sample the only crew member moves from segment 3 to segment 2, and then from segment 2 to segment 1 without any problems. Thus, the whole moving will take two minutes.
To briefly describe the movements in the second sample we will use value <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4c7c8e716067e9c6251e8ca82a4ca7fde74fbacb.png" style="max-width: 100.0%;max-height: 100.0%;"/>, which would correspond to an alien with rank *i* moving from the segment in which it is at the moment, to the segment number *j*. Using these values, we will describe the movements between the segments in the second sample: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/954e2f634474269f53df1edbf2e7b214d8a2611c.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/d4fd9e68a9c6a277942eb188291d6d2744ea21d3.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/b73a9870e1b41a5e048c3ab3e3fd4b92c336c9ec.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/954e2f634474269f53df1edbf2e7b214d8a2611c.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/49b1ffd4dcd2e0da0acec04559e0c3efc7854b07.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ef8b3f32ee76c86f57fa63f7251fa290642f17f8.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/954e2f634474269f53df1edbf2e7b214d8a2611c.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/d4fd9e68a9c6a277942eb188291d6d2744ea21d3.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>; In total: the aliens need 26 moves. The remainder after dividing 26 by 8 equals 2, so the answer to this test is 2. | ```python
a = b++
``` | -1 | |
158 | A | Next Round | PROGRAMMING | 800 | [
"*special",
"implementation"
] | null | null | "Contestant who earns a score equal to or greater than the *k*-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of *n* participants took part in the contest (*n*<=≥<=*k*), and you already know their scores. Calculate how many participants will advance to the next round. | The first line of the input contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=50) separated by a single space.
The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=100), where *a**i* is the score earned by the participant who got the *i*-th place. The given sequence is non-increasing (that is, for all *i* from 1 to *n*<=-<=1 the following condition is fulfilled: *a**i*<=≥<=*a**i*<=+<=1). | Output the number of participants who advance to the next round. | [
"8 5\n10 9 8 7 7 7 5 5\n",
"4 2\n0 0 0 0\n"
] | [
"6\n",
"0\n"
] | In the first example the participant on the 5th place earned 7 points. As the participant on the 6th place also earned 7 points, there are 6 advancers.
In the second example nobody got a positive score. | 500 | [
{
"input": "8 5\n10 9 8 7 7 7 5 5",
"output": "6"
},
{
"input": "4 2\n0 0 0 0",
"output": "0"
},
{
"input": "5 1\n1 1 1 1 1",
"output": "5"
},
{
"input": "5 5\n1 1 1 1 1",
"output": "5"
},
{
"input": "1 1\n10",
"output": "1"
},
{
"input": "17 14\n16 15... | 1,696,584,739 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 62 | 0 | #codeforce test
n ,k= input().split(' ')
k = int(k)
n = int(n)
arr = []
arr = input().split(' ')
while arr[k-1] == arr[k] and k < n-1 and arr[k-1] != 0:
k +=1
while arr[k-1] == 0 :
k -=1
print(k+1) | Title: Next Round
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
"Contestant who earns a score equal to or greater than the *k*-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of *n* participants took part in the contest (*n*<=≥<=*k*), and you already know their scores. Calculate how many participants will advance to the next round.
Input Specification:
The first line of the input contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=50) separated by a single space.
The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=100), where *a**i* is the score earned by the participant who got the *i*-th place. The given sequence is non-increasing (that is, for all *i* from 1 to *n*<=-<=1 the following condition is fulfilled: *a**i*<=≥<=*a**i*<=+<=1).
Output Specification:
Output the number of participants who advance to the next round.
Demo Input:
['8 5\n10 9 8 7 7 7 5 5\n', '4 2\n0 0 0 0\n']
Demo Output:
['6\n', '0\n']
Note:
In the first example the participant on the 5th place earned 7 points. As the participant on the 6th place also earned 7 points, there are 6 advancers.
In the second example nobody got a positive score. | ```python
#codeforce test
n ,k= input().split(' ')
k = int(k)
n = int(n)
arr = []
arr = input().split(' ')
while arr[k-1] == arr[k] and k < n-1 and arr[k-1] != 0:
k +=1
while arr[k-1] == 0 :
k -=1
print(k+1)
``` | 0 | |
465 | A | inc ARG | PROGRAMMING | 900 | [
"implementation"
] | null | null | Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of *n* bits. These bits are numbered from 1 to *n*. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the *n*-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation? | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of bits in the cell.
The second line contains a string consisting of *n* characters — the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit. | Print a single integer — the number of bits in the cell which change their state after we add 1 to the cell. | [
"4\n1100\n",
"4\n1111\n"
] | [
"3\n",
"4\n"
] | In the first sample the cell ends up with value 0010, in the second sample — with 0000. | 500 | [
{
"input": "4\n1100",
"output": "3"
},
{
"input": "4\n1111",
"output": "4"
},
{
"input": "1\n0",
"output": "1"
},
{
"input": "1\n1",
"output": "1"
},
{
"input": "2\n00",
"output": "1"
},
{
"input": "2\n01",
"output": "1"
},
{
"input": "2\n1... | 1,664,543,379 | 2,147,483,647 | Python 3 | OK | TESTS | 29 | 46 | 0 | n=int(input())
cell=input()
b=0
place=cell.find("0")
if place==(-1):
print(n)
else:
print(place+1)
| Title: inc ARG
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of *n* bits. These bits are numbered from 1 to *n*. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the *n*-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of bits in the cell.
The second line contains a string consisting of *n* characters — the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output Specification:
Print a single integer — the number of bits in the cell which change their state after we add 1 to the cell.
Demo Input:
['4\n1100\n', '4\n1111\n']
Demo Output:
['3\n', '4\n']
Note:
In the first sample the cell ends up with value 0010, in the second sample — with 0000. | ```python
n=int(input())
cell=input()
b=0
place=cell.find("0")
if place==(-1):
print(n)
else:
print(place+1)
``` | 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,662,217,494 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 92 | 0 | s=input()
l=[x for x in s if 97<=ord(x)<=122]
u=[x for x in s if 65<=ord(x)<=90]
m=len(l)
n=len(u)
if m==n:
print(s.lower())
elif m>n:
print(s.lower())
else:
print(s.upper())
| 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()
l=[x for x in s if 97<=ord(x)<=122]
u=[x for x in s if 65<=ord(x)<=90]
m=len(l)
n=len(u)
if m==n:
print(s.lower())
elif m>n:
print(s.lower())
else:
print(s.upper())
``` | 3.977 |
129 | B | Students and Shoelaces | PROGRAMMING | 1,200 | [
"brute force",
"dfs and similar",
"graphs",
"implementation"
] | null | null | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club. | The first line contains two integers *n* and *m* — the initial number of students and laces (). The students are numbered from 1 to *n*, and the laces are numbered from 1 to *m*. Next *m* lines each contain two integers *a* and *b* — the numbers of students tied by the *i*-th lace (1<=≤<=*a*,<=*b*<=≤<=*n*,<=*a*<=≠<=*b*). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | Print the single number — the number of groups of students that will be kicked out from the club. | [
"3 3\n1 2\n2 3\n3 1\n",
"6 3\n1 2\n2 3\n3 4\n",
"6 5\n1 4\n2 4\n3 4\n5 4\n6 4\n"
] | [
"0\n",
"2\n",
"1\n"
] | In the first sample Anna and Maria won't kick out any group of students — in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then — two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | 1,000 | [
{
"input": "3 3\n1 2\n2 3\n3 1",
"output": "0"
},
{
"input": "6 3\n1 2\n2 3\n3 4",
"output": "2"
},
{
"input": "6 5\n1 4\n2 4\n3 4\n5 4\n6 4",
"output": "1"
},
{
"input": "100 0",
"output": "0"
},
{
"input": "5 5\n1 2\n2 3\n3 4\n4 5\n5 1",
"output": "0"
},
... | 1,610,271,929 | 2,147,483,647 | Python 3 | OK | TESTS | 70 | 154 | 307,200 | s,l = [int(x) for x in input().split()]
group = {}
for i in range(1,s+1):
group[i] = []
for i in range(1, l+1):
num,num2 = [int(x) for x in input().split()]
group[num].append(num2)
group[num2].append(num)
grp = 0
while 1:
visited = []
check = False
for i in range(1, s + 1):
if len(group[i]) == 1 and i not in visited:
check = True
index = group[i][-1]
group[index].remove(i)
group[i].remove(index)
visited.append(index)
if check:
grp += 1
else:
break
print(grp)
| Title: Students and Shoelaces
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input Specification:
The first line contains two integers *n* and *m* — the initial number of students and laces (). The students are numbered from 1 to *n*, and the laces are numbered from 1 to *m*. Next *m* lines each contain two integers *a* and *b* — the numbers of students tied by the *i*-th lace (1<=≤<=*a*,<=*b*<=≤<=*n*,<=*a*<=≠<=*b*). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output Specification:
Print the single number — the number of groups of students that will be kicked out from the club.
Demo Input:
['3 3\n1 2\n2 3\n3 1\n', '6 3\n1 2\n2 3\n3 4\n', '6 5\n1 4\n2 4\n3 4\n5 4\n6 4\n']
Demo Output:
['0\n', '2\n', '1\n']
Note:
In the first sample Anna and Maria won't kick out any group of students — in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then — two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | ```python
s,l = [int(x) for x in input().split()]
group = {}
for i in range(1,s+1):
group[i] = []
for i in range(1, l+1):
num,num2 = [int(x) for x in input().split()]
group[num].append(num2)
group[num2].append(num)
grp = 0
while 1:
visited = []
check = False
for i in range(1, s + 1):
if len(group[i]) == 1 and i not in visited:
check = True
index = group[i][-1]
group[index].remove(i)
group[i].remove(index)
visited.append(index)
if check:
grp += 1
else:
break
print(grp)
``` | 3 | |
797 | C | Minimal string | PROGRAMMING | 1,700 | [
"data structures",
"greedy",
"strings"
] | null | null | Petya recieved a gift of a string *s* with length up to 105 characters for his birthday. He took two more empty strings *t* and *u* and decided to play a game. This game has two possible moves:
- Extract the first character of *s* and append *t* with this character. - Extract the last character of *t* and append *u* with this character.
Petya wants to get strings *s* and *t* empty and string *u* lexicographically minimal.
You should write a program that will help Petya win the game. | First line contains non-empty string *s* (1<=≤<=|*s*|<=≤<=105), consisting of lowercase English letters. | Print resulting string *u*. | [
"cab\n",
"acdb\n"
] | [
"abc\n",
"abdc\n"
] | none | 0 | [
{
"input": "cab",
"output": "abc"
},
{
"input": "acdb",
"output": "abdc"
},
{
"input": "a",
"output": "a"
},
{
"input": "ab",
"output": "ab"
},
{
"input": "ba",
"output": "ab"
},
{
"input": "dijee",
"output": "deeji"
},
{
"input": "bhrmc",
... | 1,584,980,803 | 2,147,483,647 | Python 3 | OK | TESTS | 189 | 561 | 1,843,200 | def fnz(l):
for i in range(len(l)):
if l[i] != 0:
return i
return i
alphabets = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
count_alph = [0]*26
s = input()
t = []
u = []
for i in s:
count_alph[alphabets.index(i)] +=1
for i in s:
t.append(i)
count_alph[alphabets.index(i)] -=1
while t[-1] <= alphabets[fnz(count_alph)]:
u.append(t.pop())
if len(t) == 0:
break
u = u + t[::-1]
ans = ""
for i in u:
ans += i
print(ans) | Title: Minimal string
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya recieved a gift of a string *s* with length up to 105 characters for his birthday. He took two more empty strings *t* and *u* and decided to play a game. This game has two possible moves:
- Extract the first character of *s* and append *t* with this character. - Extract the last character of *t* and append *u* with this character.
Petya wants to get strings *s* and *t* empty and string *u* lexicographically minimal.
You should write a program that will help Petya win the game.
Input Specification:
First line contains non-empty string *s* (1<=≤<=|*s*|<=≤<=105), consisting of lowercase English letters.
Output Specification:
Print resulting string *u*.
Demo Input:
['cab\n', 'acdb\n']
Demo Output:
['abc\n', 'abdc\n']
Note:
none | ```python
def fnz(l):
for i in range(len(l)):
if l[i] != 0:
return i
return i
alphabets = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
count_alph = [0]*26
s = input()
t = []
u = []
for i in s:
count_alph[alphabets.index(i)] +=1
for i in s:
t.append(i)
count_alph[alphabets.index(i)] -=1
while t[-1] <= alphabets[fnz(count_alph)]:
u.append(t.pop())
if len(t) == 0:
break
u = u + t[::-1]
ans = ""
for i in u:
ans += i
print(ans)
``` | 3 | |
222 | D | Olympiad | PROGRAMMING | 1,900 | [
"binary search",
"greedy",
"sortings",
"two pointers"
] | null | null | A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least *x* points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.
Help Vasya's teacher, find two numbers — the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad. | The first line contains two space-separated integers *n*,<=*x* (1<=≤<=*n*<=≤<=105; 0<=≤<=*x*<=≤<=2·105) — the number of Olympiad participants and the minimum number of points Vasya earned.
The second line contains *n* space-separated integers: *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=105) — the participants' points in the first tour.
The third line contains *n* space-separated integers: *b*1,<=*b*2,<=...,<=*b**n* (0<=≤<=*b**i*<=≤<=105) — the participants' points in the second tour.
The participants' points are given in the arbitrary order. It is guaranteed that Vasya was present in the Olympiad — there are two integers *i*,<=*j* (1<=≤<=*i*,<=*j*<=≤<=*n*) such, that *a**i*<=+<=*b**j*<=≥<=*x*. | Print two space-separated integers — the best and the worst place Vasya could have got on the Olympiad. | [
"5 2\n1 1 1 1 1\n1 1 1 1 1\n",
"6 7\n4 3 5 6 4 4\n8 6 0 4 3 4\n"
] | [
"1 5\n",
"1 5\n"
] | In the first text sample all 5 participants earn 2 points each in any case. Depending on the jury's decision, Vasya can get the first (the best) as well as the last (the worst) fifth place.
In the second test sample in the best case scenario Vasya wins again: he can win 12 points and become the absolute winner if the total results' table looks like that — {4:8, 6:4, 3:6, 4:4, 4:3, 5:0}.
In this table all participants are sorted by decreasing points and we can see how much a participant earned in the first and in the second tour.
In the worst case scenario Vasya can get the fifth place if the table looks like that — {4:8, 4:6, 6:4, 5:4, 4:3, 3:0}, and he earned 4 and 3 points in the first and second tours, correspondingly. | 2,000 | [
{
"input": "5 2\n1 1 1 1 1\n1 1 1 1 1",
"output": "1 5"
},
{
"input": "6 7\n4 3 5 6 4 4\n8 6 0 4 3 4",
"output": "1 5"
},
{
"input": "1 100\n56\n44",
"output": "1 1"
},
{
"input": "5 1\n1 2 3 4 5\n1 2 3 4 5",
"output": "1 5"
},
{
"input": "5 5\n2 2 2 2 2\n3 3 3 3 ... | 1,690,495,770 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 62 | 0 | print("_RANDOM_GUESS_1690495770.1686215")# 1690495770.1686435 | Title: Olympiad
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least *x* points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.
Help Vasya's teacher, find two numbers — the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad.
Input Specification:
The first line contains two space-separated integers *n*,<=*x* (1<=≤<=*n*<=≤<=105; 0<=≤<=*x*<=≤<=2·105) — the number of Olympiad participants and the minimum number of points Vasya earned.
The second line contains *n* space-separated integers: *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=105) — the participants' points in the first tour.
The third line contains *n* space-separated integers: *b*1,<=*b*2,<=...,<=*b**n* (0<=≤<=*b**i*<=≤<=105) — the participants' points in the second tour.
The participants' points are given in the arbitrary order. It is guaranteed that Vasya was present in the Olympiad — there are two integers *i*,<=*j* (1<=≤<=*i*,<=*j*<=≤<=*n*) such, that *a**i*<=+<=*b**j*<=≥<=*x*.
Output Specification:
Print two space-separated integers — the best and the worst place Vasya could have got on the Olympiad.
Demo Input:
['5 2\n1 1 1 1 1\n1 1 1 1 1\n', '6 7\n4 3 5 6 4 4\n8 6 0 4 3 4\n']
Demo Output:
['1 5\n', '1 5\n']
Note:
In the first text sample all 5 participants earn 2 points each in any case. Depending on the jury's decision, Vasya can get the first (the best) as well as the last (the worst) fifth place.
In the second test sample in the best case scenario Vasya wins again: he can win 12 points and become the absolute winner if the total results' table looks like that — {4:8, 6:4, 3:6, 4:4, 4:3, 5:0}.
In this table all participants are sorted by decreasing points and we can see how much a participant earned in the first and in the second tour.
In the worst case scenario Vasya can get the fifth place if the table looks like that — {4:8, 4:6, 6:4, 5:4, 4:3, 3:0}, and he earned 4 and 3 points in the first and second tours, correspondingly. | ```python
print("_RANDOM_GUESS_1690495770.1686215")# 1690495770.1686435
``` | 0 | |
430 | B | Balls Game | PROGRAMMING | 1,400 | [
"brute force",
"two pointers"
] | null | null | Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game?
There are *n* balls put in a row. Each ball is colored in one of *k* colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color *x*. He can insert his ball at any position in the row (probably, between two other balls). If at any moment there are three or more contiguous balls of the same color in the row, they are destroyed immediately. This rule is applied multiple times, until there are no more sets of 3 or more contiguous balls of the same color.
For example, if Iahub has the row of balls [black, black, white, white, black, black] and a white ball, he can insert the ball between two white balls. Thus three white balls are destroyed, and then four black balls become contiguous, so all four balls are destroyed. The row will not contain any ball in the end, so Iahub can destroy all 6 balls.
Iahub wants to destroy as many balls as possible. You are given the description of the row of balls, and the color of Iahub's ball. Help Iahub train for the IOI by telling him the maximum number of balls from the row he can destroy. | The first line of input contains three integers: *n* (1<=≤<=*n*<=≤<=100), *k* (1<=≤<=*k*<=≤<=100) and *x* (1<=≤<=*x*<=≤<=*k*). The next line contains *n* space-separated integers *c*1,<=*c*2,<=...,<=*c**n* (1<=≤<=*c**i*<=≤<=*k*). Number *c**i* means that the *i*-th ball in the row has color *c**i*.
It is guaranteed that the initial row of balls will never contain three or more contiguous balls of the same color. | Print a single integer — the maximum number of balls Iahub can destroy. | [
"6 2 2\n1 1 2 2 1 1\n",
"1 1 1\n1\n"
] | [
"6\n",
"0\n"
] | none | 1,000 | [
{
"input": "6 2 2\n1 1 2 2 1 1",
"output": "6"
},
{
"input": "1 1 1\n1",
"output": "0"
},
{
"input": "10 2 1\n2 1 2 2 1 2 2 1 1 2",
"output": "5"
},
{
"input": "50 2 1\n1 1 2 2 1 2 1 1 2 2 1 2 1 2 1 1 2 2 1 2 1 2 2 1 2 1 2 1 2 2 1 1 2 2 1 1 2 2 1 2 1 1 2 1 1 2 2 1 1 2",
"... | 1,599,965,703 | 2,147,483,647 | PyPy 3 | OK | TESTS | 18 | 170 | 1,433,600 | #! /usr/bin/python3
def remove_contiguous(arr):
left = 0
right = 1
while(right < len(arr)):
while(right < len(arr) and arr[left] == arr[right]):
right += 1
if (right - left >= 3):
del arr[left:right]
modified = True
return arr
left = right
right += 1
return arr
n, k, x = map(int, input().strip().split())
c = [int(x) for x in input().strip().split()]
ans = 0
for i in range(1, len(c)):
if c[i - 1] == c[i] and c[i] == x:
d = c[:i] + [x] + c[i:]
len_prev = len(d)
while(True):
d = remove_contiguous(d)
if (len_prev == len(d)):
break
len_prev = len(d)
ans = max(ans, n - len(d))
print(ans) | Title: Balls Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game?
There are *n* balls put in a row. Each ball is colored in one of *k* colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color *x*. He can insert his ball at any position in the row (probably, between two other balls). If at any moment there are three or more contiguous balls of the same color in the row, they are destroyed immediately. This rule is applied multiple times, until there are no more sets of 3 or more contiguous balls of the same color.
For example, if Iahub has the row of balls [black, black, white, white, black, black] and a white ball, he can insert the ball between two white balls. Thus three white balls are destroyed, and then four black balls become contiguous, so all four balls are destroyed. The row will not contain any ball in the end, so Iahub can destroy all 6 balls.
Iahub wants to destroy as many balls as possible. You are given the description of the row of balls, and the color of Iahub's ball. Help Iahub train for the IOI by telling him the maximum number of balls from the row he can destroy.
Input Specification:
The first line of input contains three integers: *n* (1<=≤<=*n*<=≤<=100), *k* (1<=≤<=*k*<=≤<=100) and *x* (1<=≤<=*x*<=≤<=*k*). The next line contains *n* space-separated integers *c*1,<=*c*2,<=...,<=*c**n* (1<=≤<=*c**i*<=≤<=*k*). Number *c**i* means that the *i*-th ball in the row has color *c**i*.
It is guaranteed that the initial row of balls will never contain three or more contiguous balls of the same color.
Output Specification:
Print a single integer — the maximum number of balls Iahub can destroy.
Demo Input:
['6 2 2\n1 1 2 2 1 1\n', '1 1 1\n1\n']
Demo Output:
['6\n', '0\n']
Note:
none | ```python
#! /usr/bin/python3
def remove_contiguous(arr):
left = 0
right = 1
while(right < len(arr)):
while(right < len(arr) and arr[left] == arr[right]):
right += 1
if (right - left >= 3):
del arr[left:right]
modified = True
return arr
left = right
right += 1
return arr
n, k, x = map(int, input().strip().split())
c = [int(x) for x in input().strip().split()]
ans = 0
for i in range(1, len(c)):
if c[i - 1] == c[i] and c[i] == x:
d = c[:i] + [x] + c[i:]
len_prev = len(d)
while(True):
d = remove_contiguous(d)
if (len_prev == len(d)):
break
len_prev = len(d)
ans = max(ans, n - len(d))
print(ans)
``` | 3 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation.
A set ρ of pairs (*a*,<=*b*) of elements of some set *A* is called a binary relation on set *A*. For two elements *a* and *b* of the set *A* we say that they are in relation ρ, if pair , in this case we use a notation .
Binary relation is equivalence relation, if:
1. It is reflexive (for any *a* it is true that );1. It is symmetric (for any *a*, *b* it is true that if , then );1. It is transitive (if and , than ).
Little Johnny is not completely a fool and he noticed that the first condition is not necessary! Here is his "proof":
Take any two elements, *a* and *b*. If , then (according to property (2)), which means (according to property (3)).
It's very simple, isn't it? However, you noticed that Johnny's "proof" is wrong, and decided to show him a lot of examples that prove him wrong.
Here's your task: count the number of binary relations over a set of size *n* such that they are symmetric, transitive, but not an equivalence relations (i.e. they are not reflexive).
Since their number may be very large (not 0, according to Little Johnny), print the remainder of integer division of this number by 109<=+<=7. | A single line contains a single integer *n* (1<=≤<=*n*<=≤<=4000). | In a single line print the answer to the problem modulo 109<=+<=7. | [
"1\n",
"2\n",
"3\n"
] | [
"1\n",
"3\n",
"10\n"
] | If *n* = 1 there is only one such relation — an empty one, i.e. <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8891a227c918474e5d76377d4644cd7cc01e1ffd.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In other words, for a single element *x* of set *A* the following is hold: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/947c6cf761375432db9bd77796bccc89f1f1546d.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
If *n* = 2 there are three such relations. Let's assume that set *A* consists of two elements, *x* and *y*. Then the valid relations are <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8891a227c918474e5d76377d4644cd7cc01e1ffd.png" style="max-width: 100.0%;max-height: 100.0%;"/>, ρ = {(*x*, *x*)}, ρ = {(*y*, *y*)}. It is easy to see that the three listed binary relations are symmetric and transitive relations, but they are not equivalence relations. | 0 | [
{
"input": "1",
"output": "1"
},
{
"input": "2",
"output": "3"
},
{
"input": "3",
"output": "10"
},
{
"input": "4",
"output": "37"
},
{
"input": "5",
"output": "151"
},
{
"input": "6",
"output": "674"
},
{
"input": "7",
"output": "3263"... | 1,439,230,232 | 6,032 | Python 3 | WRONG_ANSWER | PRETESTS | 3 | 62 | 10,752,000 | factorials = [1]
tmp=1
for i in range(1,4001):
tmp = tmp * i
factorials.append(tmp)
ans = 1
n = int(input())
for i in range(1,n):
ans = ans + factorials[n]//factorials[i]
print(ans) | Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation.
A set ρ of pairs (*a*,<=*b*) of elements of some set *A* is called a binary relation on set *A*. For two elements *a* and *b* of the set *A* we say that they are in relation ρ, if pair , in this case we use a notation .
Binary relation is equivalence relation, if:
1. It is reflexive (for any *a* it is true that );1. It is symmetric (for any *a*, *b* it is true that if , then );1. It is transitive (if and , than ).
Little Johnny is not completely a fool and he noticed that the first condition is not necessary! Here is his "proof":
Take any two elements, *a* and *b*. If , then (according to property (2)), which means (according to property (3)).
It's very simple, isn't it? However, you noticed that Johnny's "proof" is wrong, and decided to show him a lot of examples that prove him wrong.
Here's your task: count the number of binary relations over a set of size *n* such that they are symmetric, transitive, but not an equivalence relations (i.e. they are not reflexive).
Since their number may be very large (not 0, according to Little Johnny), print the remainder of integer division of this number by 109<=+<=7.
Input Specification:
A single line contains a single integer *n* (1<=≤<=*n*<=≤<=4000).
Output Specification:
In a single line print the answer to the problem modulo 109<=+<=7.
Demo Input:
['1\n', '2\n', '3\n']
Demo Output:
['1\n', '3\n', '10\n']
Note:
If *n* = 1 there is only one such relation — an empty one, i.e. <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8891a227c918474e5d76377d4644cd7cc01e1ffd.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In other words, for a single element *x* of set *A* the following is hold: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/947c6cf761375432db9bd77796bccc89f1f1546d.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
If *n* = 2 there are three such relations. Let's assume that set *A* consists of two elements, *x* and *y*. Then the valid relations are <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8891a227c918474e5d76377d4644cd7cc01e1ffd.png" style="max-width: 100.0%;max-height: 100.0%;"/>, ρ = {(*x*, *x*)}, ρ = {(*y*, *y*)}. It is easy to see that the three listed binary relations are symmetric and transitive relations, but they are not equivalence relations. | ```python
factorials = [1]
tmp=1
for i in range(1,4001):
tmp = tmp * i
factorials.append(tmp)
ans = 1
n = int(input())
for i in range(1,n):
ans = ans + factorials[n]//factorials[i]
print(ans)
``` | 0 | |
791 | A | Bear and Big Brother | PROGRAMMING | 800 | [
"implementation"
] | null | null | Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh *a* and *b* respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.
After how many full years will Limak become strictly larger (strictly heavier) than Bob? | The only line of the input contains two integers *a* and *b* (1<=≤<=*a*<=≤<=*b*<=≤<=10) — the weight of Limak and the weight of Bob respectively. | Print one integer, denoting the integer number of years after which Limak will become strictly larger than Bob. | [
"4 7\n",
"4 9\n",
"1 1\n"
] | [
"2\n",
"3\n",
"1\n"
] | In the first sample, Limak weighs 4 and Bob weighs 7 initially. After one year their weights are 4·3 = 12 and 7·2 = 14 respectively (one weight is tripled while the other one is doubled). Limak isn't larger than Bob yet. After the second year weights are 36 and 28, so the first weight is greater than the second one. Limak became larger than Bob after two years so you should print 2.
In the second sample, Limak's and Bob's weights in next years are: 12 and 18, then 36 and 36, and finally 108 and 72 (after three years). The answer is 3. Remember that Limak wants to be larger than Bob and he won't be satisfied with equal weights.
In the third sample, Limak becomes larger than Bob after the first year. Their weights will be 3 and 2 then. | 500 | [
{
"input": "4 7",
"output": "2"
},
{
"input": "4 9",
"output": "3"
},
{
"input": "1 1",
"output": "1"
},
{
"input": "4 6",
"output": "2"
},
{
"input": "1 10",
"output": "6"
},
{
"input": "1 1",
"output": "1"
},
{
"input": "1 2",
"output... | 1,697,009,607 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 62 | 77 | 0 | def solve():
a,b = list(map(int,input().split()))
res = 0
while a <= b:
a*=3
b*=2
res+=1
return res
print(solve()) | Title: Bear and Big Brother
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh *a* and *b* respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.
After how many full years will Limak become strictly larger (strictly heavier) than Bob?
Input Specification:
The only line of the input contains two integers *a* and *b* (1<=≤<=*a*<=≤<=*b*<=≤<=10) — the weight of Limak and the weight of Bob respectively.
Output Specification:
Print one integer, denoting the integer number of years after which Limak will become strictly larger than Bob.
Demo Input:
['4 7\n', '4 9\n', '1 1\n']
Demo Output:
['2\n', '3\n', '1\n']
Note:
In the first sample, Limak weighs 4 and Bob weighs 7 initially. After one year their weights are 4·3 = 12 and 7·2 = 14 respectively (one weight is tripled while the other one is doubled). Limak isn't larger than Bob yet. After the second year weights are 36 and 28, so the first weight is greater than the second one. Limak became larger than Bob after two years so you should print 2.
In the second sample, Limak's and Bob's weights in next years are: 12 and 18, then 36 and 36, and finally 108 and 72 (after three years). The answer is 3. Remember that Limak wants to be larger than Bob and he won't be satisfied with equal weights.
In the third sample, Limak becomes larger than Bob after the first year. Their weights will be 3 and 2 then. | ```python
def solve():
a,b = list(map(int,input().split()))
res = 0
while a <= b:
a*=3
b*=2
res+=1
return res
print(solve())
``` | 3 | |
808 | B | Average Sleep Time | PROGRAMMING | 1,300 | [
"data structures",
"implementation",
"math"
] | null | null | It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts *k* days!
When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last *n* days. So now he has a sequence *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the sleep time on the *i*-th day.
The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider *k* consecutive days as a week. So there will be *n*<=-<=*k*<=+<=1 weeks to take into consideration. For example, if *k*<==<=2, *n*<==<=3 and *a*<==<=[3,<=4,<=7], then the result is .
You should write a program which will calculate average sleep times of Polycarp over all weeks. | The first line contains two integer numbers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=2·105).
The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=105). | Output average sleeping time over all weeks.
The answer is considered to be correct if its absolute or relative error does not exceed 10<=-<=6. In particular, it is enough to output real number with at least 6 digits after the decimal point. | [
"3 2\n3 4 7\n",
"1 1\n10\n",
"8 2\n1 2 4 100000 123 456 789 1\n"
] | [
"9.0000000000\n",
"10.0000000000\n",
"28964.2857142857\n"
] | In the third example there are *n* - *k* + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. | 0 | [
{
"input": "3 2\n3 4 7",
"output": "9.0000000000"
},
{
"input": "1 1\n10",
"output": "10.0000000000"
},
{
"input": "8 2\n1 2 4 100000 123 456 789 1",
"output": "28964.2857142857"
},
{
"input": "1 1\n1",
"output": "1.0000000000"
},
{
"input": "1 1\n100000",
"ou... | 1,495,222,938 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 62 | 0 | import sys
line = sys.stdin.readline().split(" ")
n = int(line[0])
k = int(line[1])
s = 0
days = sys.stdin.readline().split(" ")
kCount = 1
kReverseCount = k
v = []
for i in range (n):
v.append(int(days[i]))
v1 = v[0:k-1]
if n-k > k:
v2 = v[k:n-k]
else:
v2 = v[n-k:k]
v3 = v[(n-k+1):n]
sum1 = 0
sum2 = 0
for i in range(k-1):
sum1 = v1[i] * (i+1)
for i in range(k-1, 0, -1):
sum2 = v3[k-i-1] * (i)
totalSum = sum1 + sum2 + sum(v2)*k
print("%.10f" % (totalSum/(n-k+1)))
# 1495222936160
| Title: Average Sleep Time
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts *k* days!
When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last *n* days. So now he has a sequence *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the sleep time on the *i*-th day.
The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider *k* consecutive days as a week. So there will be *n*<=-<=*k*<=+<=1 weeks to take into consideration. For example, if *k*<==<=2, *n*<==<=3 and *a*<==<=[3,<=4,<=7], then the result is .
You should write a program which will calculate average sleep times of Polycarp over all weeks.
Input Specification:
The first line contains two integer numbers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=2·105).
The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=105).
Output Specification:
Output average sleeping time over all weeks.
The answer is considered to be correct if its absolute or relative error does not exceed 10<=-<=6. In particular, it is enough to output real number with at least 6 digits after the decimal point.
Demo Input:
['3 2\n3 4 7\n', '1 1\n10\n', '8 2\n1 2 4 100000 123 456 789 1\n']
Demo Output:
['9.0000000000\n', '10.0000000000\n', '28964.2857142857\n']
Note:
In the third example there are *n* - *k* + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. | ```python
import sys
line = sys.stdin.readline().split(" ")
n = int(line[0])
k = int(line[1])
s = 0
days = sys.stdin.readline().split(" ")
kCount = 1
kReverseCount = k
v = []
for i in range (n):
v.append(int(days[i]))
v1 = v[0:k-1]
if n-k > k:
v2 = v[k:n-k]
else:
v2 = v[n-k:k]
v3 = v[(n-k+1):n]
sum1 = 0
sum2 = 0
for i in range(k-1):
sum1 = v1[i] * (i+1)
for i in range(k-1, 0, -1):
sum2 = v3[k-i-1] * (i)
totalSum = sum1 + sum2 + sum(v2)*k
print("%.10f" % (totalSum/(n-k+1)))
# 1495222936160
``` | 0 | |
34 | A | Reconnaissance 2 | PROGRAMMING | 800 | [
"implementation"
] | A. Reconnaissance 2 | 2 | 256 | *n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit. | The first line contains integer *n* (2<=≤<=*n*<=≤<=100) — amount of soldiers. Then follow the heights of the soldiers in their order in the circle — *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1000). The soldier heights are given in clockwise or counterclockwise direction. | Output two integers — indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle. | [
"5\n10 12 13 15 10\n",
"4\n10 20 30 40\n"
] | [
"5 1\n",
"1 2\n"
] | none | 500 | [
{
"input": "5\n10 12 13 15 10",
"output": "5 1"
},
{
"input": "4\n10 20 30 40",
"output": "1 2"
},
{
"input": "6\n744 359 230 586 944 442",
"output": "2 3"
},
{
"input": "5\n826 747 849 687 437",
"output": "1 2"
},
{
"input": "5\n999 999 993 969 999",
"output"... | 1,635,965,452 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 2 | 122 | 28,364,800 | def solve():
n = int(input())
tempList = []
tempList += map(int, input().split(' '))
pairI, pairJ = 0, 0
min = max(tempList)
for i in range(0, len(tempList)):
for j in range(i+1,len(tempList)):
if min > abs(tempList[i] - tempList[j]):
min = abs(tempList[i] - tempList[j])
pairI = i+1
pairJ = j+1
print(pairI, pairJ)
solve() | Title: Reconnaissance 2
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
*n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.
Input Specification:
The first line contains integer *n* (2<=≤<=*n*<=≤<=100) — amount of soldiers. Then follow the heights of the soldiers in their order in the circle — *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1000). The soldier heights are given in clockwise or counterclockwise direction.
Output Specification:
Output two integers — indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.
Demo Input:
['5\n10 12 13 15 10\n', '4\n10 20 30 40\n']
Demo Output:
['5 1\n', '1 2\n']
Note:
none | ```python
def solve():
n = int(input())
tempList = []
tempList += map(int, input().split(' '))
pairI, pairJ = 0, 0
min = max(tempList)
for i in range(0, len(tempList)):
for j in range(i+1,len(tempList)):
if min > abs(tempList[i] - tempList[j]):
min = abs(tempList[i] - tempList[j])
pairI = i+1
pairJ = j+1
print(pairI, pairJ)
solve()
``` | 0 |
392 | A | Blocked Points | PROGRAMMING | 0 | [
"math"
] | null | null | Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points *A* and *B* on the plane are 4-connected if and only if:
- the Euclidean distance between *A* and *B* is one unit and neither *A* nor *B* is blocked; - or there is some integral point *C*, such that *A* is 4-connected with *C*, and *C* is 4-connected with *B*.
Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than *n*, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick? | The first line contains an integer *n* (0<=≤<=*n*<=≤<=4·107). | Print a single integer — the minimum number of points that should be blocked. | [
"1\n",
"2\n",
"3\n"
] | [
"4\n",
"8\n",
"16\n"
] | none | 500 | [
{
"input": "1",
"output": "4"
},
{
"input": "2",
"output": "8"
},
{
"input": "3",
"output": "16"
},
{
"input": "4",
"output": "20"
},
{
"input": "0",
"output": "1"
},
{
"input": "30426905",
"output": "172120564"
},
{
"input": "38450759",
... | 1,395,451,694 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 46 | 307,200 | import math
import fileinput
for line in fileinput.input():
n = int(line)
def countPoints(n):
if n==0:
return 1
elif n==1:
return 4
else:
X = math.floor(math.sqrt(2)/2*n)
return 8*X
print(countpoints(n)) | Title: Blocked Points
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points *A* and *B* on the plane are 4-connected if and only if:
- the Euclidean distance between *A* and *B* is one unit and neither *A* nor *B* is blocked; - or there is some integral point *C*, such that *A* is 4-connected with *C*, and *C* is 4-connected with *B*.
Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than *n*, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?
Input Specification:
The first line contains an integer *n* (0<=≤<=*n*<=≤<=4·107).
Output Specification:
Print a single integer — the minimum number of points that should be blocked.
Demo Input:
['1\n', '2\n', '3\n']
Demo Output:
['4\n', '8\n', '16\n']
Note:
none | ```python
import math
import fileinput
for line in fileinput.input():
n = int(line)
def countPoints(n):
if n==0:
return 1
elif n==1:
return 4
else:
X = math.floor(math.sqrt(2)/2*n)
return 8*X
print(countpoints(n))
``` | -1 | |
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,696,361,962 | 2,147,483,647 | Python 3 | OK | TESTS | 15 | 46 | 0 | k,n,w=list(map(int,input().split()))
c=0
for i in range(1,w+1):
c+=i*k
a=c-n
if a>0:
print(a)
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
k,n,w=list(map(int,input().split()))
c=0
for i in range(1,w+1):
c+=i*k
a=c-n
if a>0:
print(a)
else:
print("0")
``` | 3 | |
818 | A | Diplomas and Certificates | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | There are *n* students who have taken part in an olympiad. Now it's time to award the students.
Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and certificates. The number of certificates must be exactly *k* times greater than the number of diplomas. The number of winners must not be greater than half of the number of all students (i.e. not be greater than half of *n*). It's possible that there are no winners.
You have to identify the maximum possible number of winners, according to these rules. Also for this case you have to calculate the number of students with diplomas, the number of students with certificates and the number of students who are not winners. | The first (and the only) line of input contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=1012), where *n* is the number of students and *k* is the ratio between the number of certificates and the number of diplomas. | Output three numbers: the number of students with diplomas, the number of students with certificates and the number of students who are not winners in case when the number of winners is maximum possible.
It's possible that there are no winners. | [
"18 2\n",
"9 10\n",
"1000000000000 5\n",
"1000000000000 499999999999\n"
] | [
"3 6 9\n",
"0 0 9\n",
"83333333333 416666666665 500000000002\n",
"1 499999999999 500000000000\n"
] | none | 0 | [
{
"input": "18 2",
"output": "3 6 9"
},
{
"input": "9 10",
"output": "0 0 9"
},
{
"input": "1000000000000 5",
"output": "83333333333 416666666665 500000000002"
},
{
"input": "1000000000000 499999999999",
"output": "1 499999999999 500000000000"
},
{
"input": "1 1",... | 1,498,750,117 | 1,417 | Python 3 | OK | TESTS | 44 | 77 | 5,529,600 | n, k = input().split()
n, k = int(n), int(k)
lo, hi = 0, n // (k + 1)
while lo < hi:
mid = (lo + hi + 1) // 2
if mid * (k + 1) > n // 2:
hi = mid - 1
else:
lo = mid
print(lo, lo * k, n - lo * (k + 1))
| Title: Diplomas and Certificates
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* students who have taken part in an olympiad. Now it's time to award the students.
Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and certificates. The number of certificates must be exactly *k* times greater than the number of diplomas. The number of winners must not be greater than half of the number of all students (i.e. not be greater than half of *n*). It's possible that there are no winners.
You have to identify the maximum possible number of winners, according to these rules. Also for this case you have to calculate the number of students with diplomas, the number of students with certificates and the number of students who are not winners.
Input Specification:
The first (and the only) line of input contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=1012), where *n* is the number of students and *k* is the ratio between the number of certificates and the number of diplomas.
Output Specification:
Output three numbers: the number of students with diplomas, the number of students with certificates and the number of students who are not winners in case when the number of winners is maximum possible.
It's possible that there are no winners.
Demo Input:
['18 2\n', '9 10\n', '1000000000000 5\n', '1000000000000 499999999999\n']
Demo Output:
['3 6 9\n', '0 0 9\n', '83333333333 416666666665 500000000002\n', '1 499999999999 500000000000\n']
Note:
none | ```python
n, k = input().split()
n, k = int(n), int(k)
lo, hi = 0, n // (k + 1)
while lo < hi:
mid = (lo + hi + 1) // 2
if mid * (k + 1) > n // 2:
hi = mid - 1
else:
lo = mid
print(lo, lo * k, n - lo * (k + 1))
``` | 3 | |
169 | A | Chores | PROGRAMMING | 800 | [
"sortings"
] | null | null | Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do *n* chores. Each chore is characterized by a single parameter — its complexity. The complexity of the *i*-th chore equals *h**i*.
As Petya is older, he wants to take the chores with complexity larger than some value *x* (*h**i*<=><=*x*) to leave to Vasya the chores with complexity less than or equal to *x* (*h**i*<=≤<=*x*). The brothers have already decided that Petya will do exactly *a* chores and Vasya will do exactly *b* chores (*a*<=+<=*b*<==<=*n*).
In how many ways can they choose an integer *x* so that Petya got exactly *a* chores and Vasya got exactly *b* chores? | The first input line contains three integers *n*,<=*a* and *b* (2<=≤<=*n*<=≤<=2000; *a*,<=*b*<=≥<=1; *a*<=+<=*b*<==<=*n*) — the total number of chores, the number of Petya's chores and the number of Vasya's chores.
The next line contains a sequence of integers *h*1,<=*h*2,<=...,<=*h**n* (1<=≤<=*h**i*<=≤<=109), *h**i* is the complexity of the *i*-th chore. The numbers in the given sequence are not necessarily different.
All numbers on the lines are separated by single spaces. | Print the required number of ways to choose an integer value of *x*. If there are no such ways, print 0. | [
"5 2 3\n6 2 3 100 1\n",
"7 3 4\n1 1 9 1 1 1 1\n"
] | [
"3\n",
"0\n"
] | In the first sample the possible values of *x* are 3, 4 or 5.
In the second sample it is impossible to find such *x*, that Petya got 3 chores and Vasya got 4. | 500 | [
{
"input": "5 2 3\n6 2 3 100 1",
"output": "3"
},
{
"input": "7 3 4\n1 1 9 1 1 1 1",
"output": "0"
},
{
"input": "2 1 1\n10 2",
"output": "8"
},
{
"input": "2 1 1\n7 7",
"output": "0"
},
{
"input": "2 1 1\n1 1000000000",
"output": "999999999"
},
{
"inp... | 1,697,781,105 | 2,147,483,647 | PyPy 3 | OK | TESTS | 29 | 93 | 1,228,800 | from sys import stdin, stdout
n, a, b = map(int, stdin.readline().split())
H = list(map(int, stdin.readline().split()))
H.sort()
hardest_for_vasya = H[b-1]
easiest_for_petya = H[b]
ans = easiest_for_petya - hardest_for_vasya
stdout.write(str(ans)) if ans > 0 else stdout.write(str(ans))
| Title: Chores
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do *n* chores. Each chore is characterized by a single parameter — its complexity. The complexity of the *i*-th chore equals *h**i*.
As Petya is older, he wants to take the chores with complexity larger than some value *x* (*h**i*<=><=*x*) to leave to Vasya the chores with complexity less than or equal to *x* (*h**i*<=≤<=*x*). The brothers have already decided that Petya will do exactly *a* chores and Vasya will do exactly *b* chores (*a*<=+<=*b*<==<=*n*).
In how many ways can they choose an integer *x* so that Petya got exactly *a* chores and Vasya got exactly *b* chores?
Input Specification:
The first input line contains three integers *n*,<=*a* and *b* (2<=≤<=*n*<=≤<=2000; *a*,<=*b*<=≥<=1; *a*<=+<=*b*<==<=*n*) — the total number of chores, the number of Petya's chores and the number of Vasya's chores.
The next line contains a sequence of integers *h*1,<=*h*2,<=...,<=*h**n* (1<=≤<=*h**i*<=≤<=109), *h**i* is the complexity of the *i*-th chore. The numbers in the given sequence are not necessarily different.
All numbers on the lines are separated by single spaces.
Output Specification:
Print the required number of ways to choose an integer value of *x*. If there are no such ways, print 0.
Demo Input:
['5 2 3\n6 2 3 100 1\n', '7 3 4\n1 1 9 1 1 1 1\n']
Demo Output:
['3\n', '0\n']
Note:
In the first sample the possible values of *x* are 3, 4 or 5.
In the second sample it is impossible to find such *x*, that Petya got 3 chores and Vasya got 4. | ```python
from sys import stdin, stdout
n, a, b = map(int, stdin.readline().split())
H = list(map(int, stdin.readline().split()))
H.sort()
hardest_for_vasya = H[b-1]
easiest_for_petya = H[b]
ans = easiest_for_petya - hardest_for_vasya
stdout.write(str(ans)) if ans > 0 else stdout.write(str(ans))
``` | 3 | |
977 | E | Cyclic Components | PROGRAMMING | 1,500 | [
"dfs and similar",
"dsu",
"graphs"
] | null | null | You are given an undirected graph consisting of $n$ vertices and $m$ edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex $a$ is connected with a vertex $b$, a vertex $b$ is also connected with a vertex $a$). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices $u$ and $v$ belong to the same connected component if and only if there is at least one path along edges connecting $u$ and $v$.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
- the first vertex is connected with the second vertex by an edge, - the second vertex is connected with the third vertex by an edge, - ... - the last vertex is connected with the first vertex by an edge, - all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices. | The first line contains two integer numbers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $0 \le m \le 2 \cdot 10^5$) — number of vertices and edges.
The following $m$ lines contains edges: edge $i$ is given as a pair of vertices $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$). There is no multiple edges in the given graph, i.e. for each pair ($v_i, u_i$) there no other pairs ($v_i, u_i$) and ($u_i, v_i$) in the list of edges. | Print one integer — the number of connected components which are also cycles. | [
"5 4\n1 2\n3 4\n5 4\n3 5\n",
"17 15\n1 8\n1 12\n5 11\n11 9\n9 15\n15 5\n4 13\n3 13\n4 3\n10 16\n7 10\n16 7\n14 3\n14 4\n17 6\n"
] | [
"1\n",
"2\n"
] | In the first example only component $[3, 4, 5]$ is also a cycle.
The illustration above corresponds to the second example. | 0 | [
{
"input": "5 4\n1 2\n3 4\n5 4\n3 5",
"output": "1"
},
{
"input": "17 15\n1 8\n1 12\n5 11\n11 9\n9 15\n15 5\n4 13\n3 13\n4 3\n10 16\n7 10\n16 7\n14 3\n14 4\n17 6",
"output": "2"
},
{
"input": "4 4\n1 2\n2 3\n1 3\n1 4",
"output": "0"
},
{
"input": "5 5\n1 2\n2 3\n3 4\n4 1\n3 5... | 1,698,385,717 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 31 | 0 | def cyclic_components(graph):
visited = set()
components = []
def dfs(node):
visited.add(node)
component.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs(neighbor)
elif neighbor in component:
# We have found a cycle.
components.append(component)
return
for node in graph:
if node not in visited:
component = []
dfs(node)
return len(components)
def main():
n, m = map(int, input().split())
graph = {}
for _ in range(m):
u, v = map(int, input().split())
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u)
print(cyclic_components(graph))
if __name__ == '__main__':
main()
| Title: Cyclic Components
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an undirected graph consisting of $n$ vertices and $m$ edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex $a$ is connected with a vertex $b$, a vertex $b$ is also connected with a vertex $a$). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices $u$ and $v$ belong to the same connected component if and only if there is at least one path along edges connecting $u$ and $v$.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
- the first vertex is connected with the second vertex by an edge, - the second vertex is connected with the third vertex by an edge, - ... - the last vertex is connected with the first vertex by an edge, - all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
Input Specification:
The first line contains two integer numbers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $0 \le m \le 2 \cdot 10^5$) — number of vertices and edges.
The following $m$ lines contains edges: edge $i$ is given as a pair of vertices $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$). There is no multiple edges in the given graph, i.e. for each pair ($v_i, u_i$) there no other pairs ($v_i, u_i$) and ($u_i, v_i$) in the list of edges.
Output Specification:
Print one integer — the number of connected components which are also cycles.
Demo Input:
['5 4\n1 2\n3 4\n5 4\n3 5\n', '17 15\n1 8\n1 12\n5 11\n11 9\n9 15\n15 5\n4 13\n3 13\n4 3\n10 16\n7 10\n16 7\n14 3\n14 4\n17 6\n']
Demo Output:
['1\n', '2\n']
Note:
In the first example only component $[3, 4, 5]$ is also a cycle.
The illustration above corresponds to the second example. | ```python
def cyclic_components(graph):
visited = set()
components = []
def dfs(node):
visited.add(node)
component.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs(neighbor)
elif neighbor in component:
# We have found a cycle.
components.append(component)
return
for node in graph:
if node not in visited:
component = []
dfs(node)
return len(components)
def main():
n, m = map(int, input().split())
graph = {}
for _ in range(m):
u, v = map(int, input().split())
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u)
print(cyclic_components(graph))
if __name__ == '__main__':
main()
``` | 0 | |
825 | D | Suitable Replacement | PROGRAMMING | 1,500 | [
"binary search",
"greedy",
"implementation"
] | null | null | You are given two strings *s* and *t* consisting of small Latin letters, string *s* can also contain '?' characters.
Suitability of string *s* is calculated by following metric:
Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings *s*, you choose the one with the largest number of non-intersecting occurrences of string *t*. Suitability is this number of occurrences.
You should replace all '?' characters with small Latin letters in such a way that the suitability of string *s* is maximal. | The first line contains string *s* (1<=≤<=|*s*|<=≤<=106).
The second line contains string *t* (1<=≤<=|*t*|<=≤<=106). | Print string *s* with '?' replaced with small Latin letters in such a way that suitability of that string is maximal.
If there are multiple strings with maximal suitability then print any of them. | [
"?aa?\nab\n",
"??b?\nza\n",
"abcd\nabacaba\n"
] | [
"baab\n",
"azbz\n",
"abcd\n"
] | In the first example string "baab" can be transformed to "abab" with swaps, this one has suitability of 2. That means that string "baab" also has suitability of 2.
In the second example maximal suitability you can achieve is 1 and there are several dozens of such strings, "azbz" is just one of them.
In the third example there are no '?' characters and the suitability of the string is 0. | 0 | [
{
"input": "?aa?\nab",
"output": "baab"
},
{
"input": "??b?\nza",
"output": "azbz"
},
{
"input": "abcd\nabacaba",
"output": "abcd"
},
{
"input": "mqwstphetbfrsyxuzdww\nrutseqtsbh",
"output": "mqwstphetbfrsyxuzdww"
},
{
"input": "????????????????????\nxwkxsxlrre",
... | 1,500,411,569 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 62 | 5,017,600 | from collections import Counter
# s = input()
# t = input()
s = 'aa??aa' * 1000
t = 'babc'
new_s = ''
c = Counter(s)
while True:
for i in t:
if c[i] and c[i] > 0:
c[i] -= 1
elif c['?'] and c['?'] > 0:
c['?'] -= 1
new_s += i
else:
break
else:
continue
break
i = 0
for i in new_s:
s = s.replace('?', i, 1)
s = s.replace('?', 'a')
print(s)
| Title: Suitable Replacement
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two strings *s* and *t* consisting of small Latin letters, string *s* can also contain '?' characters.
Suitability of string *s* is calculated by following metric:
Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings *s*, you choose the one with the largest number of non-intersecting occurrences of string *t*. Suitability is this number of occurrences.
You should replace all '?' characters with small Latin letters in such a way that the suitability of string *s* is maximal.
Input Specification:
The first line contains string *s* (1<=≤<=|*s*|<=≤<=106).
The second line contains string *t* (1<=≤<=|*t*|<=≤<=106).
Output Specification:
Print string *s* with '?' replaced with small Latin letters in such a way that suitability of that string is maximal.
If there are multiple strings with maximal suitability then print any of them.
Demo Input:
['?aa?\nab\n', '??b?\nza\n', 'abcd\nabacaba\n']
Demo Output:
['baab\n', 'azbz\n', 'abcd\n']
Note:
In the first example string "baab" can be transformed to "abab" with swaps, this one has suitability of 2. That means that string "baab" also has suitability of 2.
In the second example maximal suitability you can achieve is 1 and there are several dozens of such strings, "azbz" is just one of them.
In the third example there are no '?' characters and the suitability of the string is 0. | ```python
from collections import Counter
# s = input()
# t = input()
s = 'aa??aa' * 1000
t = 'babc'
new_s = ''
c = Counter(s)
while True:
for i in t:
if c[i] and c[i] > 0:
c[i] -= 1
elif c['?'] and c['?'] > 0:
c['?'] -= 1
new_s += i
else:
break
else:
continue
break
i = 0
for i in new_s:
s = s.replace('?', i, 1)
s = s.replace('?', 'a')
print(s)
``` | 0 | |
701 | A | Cards | PROGRAMMING | 800 | [
"greedy",
"implementation"
] | null | null | There are *n* cards (*n* is even) in the deck. Each card has a positive integer written on it. *n*<=/<=2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible. | The first line of the input contains integer *n* (2<=≤<=*n*<=≤<=100) — the number of cards in the deck. It is guaranteed that *n* is even.
The second line contains the sequence of *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100), where *a**i* is equal to the number written on the *i*-th card. | Print *n*<=/<=2 pairs of integers, the *i*-th pair denote the cards that should be given to the *i*-th player. Each card should be given to exactly one player. Cards are numbered in the order they appear in the input.
It is guaranteed that solution exists. If there are several correct answers, you are allowed to print any of them. | [
"6\n1 5 7 4 4 3\n",
"4\n10 10 10 10\n"
] | [
"1 3\n6 2\n4 5\n",
"1 2\n3 4\n"
] | In the first sample, cards are distributed in such a way that each player has the sum of numbers written on his cards equal to 8.
In the second sample, all values *a*<sub class="lower-index">*i*</sub> are equal. Thus, any distribution is acceptable. | 500 | [
{
"input": "6\n1 5 7 4 4 3",
"output": "1 3\n6 2\n4 5"
},
{
"input": "4\n10 10 10 10",
"output": "1 4\n2 3"
},
{
"input": "100\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 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 2 2 2 2 2 2 2 2 2 ... | 1,588,684,237 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 32 | 155 | 2,150,400 | n=int(input())
l=list(map(int,input().split()))
a=[]
d={}
for i in range(n):
for j in range(i+1,n):
s=sum([l[i],l[j]])
a.append([s,i+1,j+1])
if s in d:
d[s]+=1
else:
d[s]=1
a.sort()
k=max(d,key=d.get)
b=[]
for i in a:
if(i[0]==k):
if(i[1]not in b and i[2] not in b):
print(i[1],i[2])
b.append(i[1])
b.append(i[2]) | Title: Cards
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* cards (*n* is even) in the deck. Each card has a positive integer written on it. *n*<=/<=2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.
Input Specification:
The first line of the input contains integer *n* (2<=≤<=*n*<=≤<=100) — the number of cards in the deck. It is guaranteed that *n* is even.
The second line contains the sequence of *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100), where *a**i* is equal to the number written on the *i*-th card.
Output Specification:
Print *n*<=/<=2 pairs of integers, the *i*-th pair denote the cards that should be given to the *i*-th player. Each card should be given to exactly one player. Cards are numbered in the order they appear in the input.
It is guaranteed that solution exists. If there are several correct answers, you are allowed to print any of them.
Demo Input:
['6\n1 5 7 4 4 3\n', '4\n10 10 10 10\n']
Demo Output:
['1 3\n6 2\n4 5\n', '1 2\n3 4\n']
Note:
In the first sample, cards are distributed in such a way that each player has the sum of numbers written on his cards equal to 8.
In the second sample, all values *a*<sub class="lower-index">*i*</sub> are equal. Thus, any distribution is acceptable. | ```python
n=int(input())
l=list(map(int,input().split()))
a=[]
d={}
for i in range(n):
for j in range(i+1,n):
s=sum([l[i],l[j]])
a.append([s,i+1,j+1])
if s in d:
d[s]+=1
else:
d[s]=1
a.sort()
k=max(d,key=d.get)
b=[]
for i in a:
if(i[0]==k):
if(i[1]not in b and i[2] not in b):
print(i[1],i[2])
b.append(i[1])
b.append(i[2])
``` | 0 | |
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,618,503,049 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 62 | 0 | # collaborated with no one
vowels = ["a", "e", "i", "o", "u", "y"]
counter = 0
userInput = input()
for letter in userInput:
if letter.isdigit():
if int(letter) % 2 == 0:
counter += 1
elif letter in vowels:
counter += 1
print(counter)
| 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
# collaborated with no one
vowels = ["a", "e", "i", "o", "u", "y"]
counter = 0
userInput = input()
for letter in userInput:
if letter.isdigit():
if int(letter) % 2 == 0:
counter += 1
elif letter in vowels:
counter += 1
print(counter)
``` | 0 | |
13 | A | Numbers | PROGRAMMING | 1,000 | [
"implementation",
"math"
] | A. Numbers | 1 | 64 | Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.
Now he wonders what is an average value of sum of digits of the number *A* written in all bases from 2 to *A*<=-<=1.
Note that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10. | Input contains one integer number *A* (3<=≤<=*A*<=≤<=1000). | Output should contain required average value in format «X/Y», where X is the numerator and Y is the denominator. | [
"5\n",
"3\n"
] | [
"7/3\n",
"2/1\n"
] | In the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | 0 | [
{
"input": "5",
"output": "7/3"
},
{
"input": "3",
"output": "2/1"
},
{
"input": "1000",
"output": "90132/499"
},
{
"input": "927",
"output": "155449/925"
},
{
"input": "260",
"output": "6265/129"
},
{
"input": "131",
"output": "3370/129"
},
{
... | 1,608,039,012 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 2 | 248 | 1,228,800 | def f(n, k):
s = 0
while n > 0:
s += n % k
n = int(n / k)
return s
n = int(input())
s = 0
for j in range(2, n):
s += f(n, j)
print(end = str(s) + '/' + str(n - 2))
| Title: Numbers
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.
Now he wonders what is an average value of sum of digits of the number *A* written in all bases from 2 to *A*<=-<=1.
Note that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10.
Input Specification:
Input contains one integer number *A* (3<=≤<=*A*<=≤<=1000).
Output Specification:
Output should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.
Demo Input:
['5\n', '3\n']
Demo Output:
['7/3\n', '2/1\n']
Note:
In the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | ```python
def f(n, k):
s = 0
while n > 0:
s += n % k
n = int(n / k)
return s
n = int(input())
s = 0
for j in range(2, n):
s += f(n, j)
print(end = str(s) + '/' + str(n - 2))
``` | 0 |
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,696,594,960 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 31 | 0 | n = int(input())
mas = sorted(list(map(int, input().split())))[::-1]
ser = 0
dima = 0
for i in range(n):
if i%2==0:
ser+=mas[i]
else:
dima+=mas[i]
print(ser, dima) | 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
n = int(input())
mas = sorted(list(map(int, input().split())))[::-1]
ser = 0
dima = 0
for i in range(n):
if i%2==0:
ser+=mas[i]
else:
dima+=mas[i]
print(ser, dima)
``` | 0 | |
992 | A | Nastya and an Array | PROGRAMMING | 800 | [
"implementation",
"sortings"
] | null | null | Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:
- In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. - When all elements of the array become equal to zero, the array explodes.
Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the size of the array.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=105<=≤<=*a**i*<=≤<=105) — the elements of the array. | Print a single integer — the minimum number of seconds needed to make all elements of the array equal to zero. | [
"5\n1 1 1 1 1\n",
"3\n2 0 -1\n",
"4\n5 -6 -5 1\n"
] | [
"1\n",
"2\n",
"4\n"
] | In the first example you can add - 1 to all non-zero elements in one second and make them equal to zero.
In the second example you can add - 2 on the first second, then the array becomes equal to [0, 0, - 3]. On the second second you can add 3 to the third (the only non-zero) element. | 500 | [
{
"input": "5\n1 1 1 1 1",
"output": "1"
},
{
"input": "3\n2 0 -1",
"output": "2"
},
{
"input": "4\n5 -6 -5 1",
"output": "4"
},
{
"input": "1\n0",
"output": "0"
},
{
"input": "2\n21794 -79194",
"output": "2"
},
{
"input": "3\n-63526 95085 -5239",
... | 1,590,996,775 | 2,147,483,647 | PyPy 3 | OK | TESTS | 79 | 218 | 13,004,800 | n=(int)(input())
l=list(map(int,input().split()))
c=0
for i in range(n):
if l[i]==0:
c+=1
if c>1:
c=1
print(len(set(l))-c) | Title: Nastya and an Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:
- In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. - When all elements of the array become equal to zero, the array explodes.
Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the size of the array.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=105<=≤<=*a**i*<=≤<=105) — the elements of the array.
Output Specification:
Print a single integer — the minimum number of seconds needed to make all elements of the array equal to zero.
Demo Input:
['5\n1 1 1 1 1\n', '3\n2 0 -1\n', '4\n5 -6 -5 1\n']
Demo Output:
['1\n', '2\n', '4\n']
Note:
In the first example you can add - 1 to all non-zero elements in one second and make them equal to zero.
In the second example you can add - 2 on the first second, then the array becomes equal to [0, 0, - 3]. On the second second you can add 3 to the third (the only non-zero) element. | ```python
n=(int)(input())
l=list(map(int,input().split()))
c=0
for i in range(n):
if l[i]==0:
c+=1
if c>1:
c=1
print(len(set(l))-c)
``` | 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,599,916,667 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 122 | 0 | strz = "PranAv"
sm_cnt, cap_cnt = 0, 0
for i in range(len(strz)):
if strz[i].islower():
sm_cnt += 1
elif strz[i].isupper():
cap_cnt += 1
if sm_cnt >= cap_cnt:
print(strz.lower())
else:
print(strz.upper())
| 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
strz = "PranAv"
sm_cnt, cap_cnt = 0, 0
for i in range(len(strz)):
if strz[i].islower():
sm_cnt += 1
elif strz[i].isupper():
cap_cnt += 1
if sm_cnt >= cap_cnt:
print(strz.lower())
else:
print(strz.upper())
``` | 0 |
999 | E | Reachability from the Capital | PROGRAMMING | 2,000 | [
"dfs and similar",
"graphs",
"greedy"
] | null | null | There are $n$ cities and $m$ roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.
What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?
New roads will also be one-way. | The first line of input consists of three integers $n$, $m$ and $s$ ($1 \le n \le 5000, 0 \le m \le 5000, 1 \le s \le n$) — the number of cities, the number of roads and the index of the capital. Cities are indexed from $1$ to $n$.
The following $m$ lines contain roads: road $i$ is given as a pair of cities $u_i$, $v_i$ ($1 \le u_i, v_i \le n$, $u_i \ne v_i$). For each pair of cities $(u, v)$, there can be at most one road from $u$ to $v$. Roads in opposite directions between a pair of cities are allowed (i.e. from $u$ to $v$ and from $v$ to $u$). | Print one integer — the minimum number of extra roads needed to make all the cities reachable from city $s$. If all the cities are already reachable from $s$, print 0. | [
"9 9 1\n1 2\n1 3\n2 3\n1 5\n5 6\n6 1\n1 8\n9 8\n7 1\n",
"5 4 5\n1 2\n2 3\n3 4\n4 1\n"
] | [
"3\n",
"1\n"
] | The first example is illustrated by the following:
For example, you can add roads ($6, 4$), ($7, 9$), ($1, 7$) to make all the cities reachable from $s = 1$.
The second example is illustrated by the following:
In this example, you can add any one of the roads ($5, 1$), ($5, 2$), ($5, 3$), ($5, 4$) to make all the cities reachable from $s = 5$. | 0 | [
{
"input": "9 9 1\n1 2\n1 3\n2 3\n1 5\n5 6\n6 1\n1 8\n9 8\n7 1",
"output": "3"
},
{
"input": "5 4 5\n1 2\n2 3\n3 4\n4 1",
"output": "1"
},
{
"input": "5000 0 2956",
"output": "4999"
},
{
"input": "2 0 2",
"output": "1"
},
{
"input": "2 1 1\n1 2",
"output": "0"... | 1,635,549,996 | 2,147,483,647 | PyPy 3-64 | RUNTIME_ERROR | TESTS | 30 | 171 | 38,809,600 |
def bfs(g, node, unseen):
start = [node]
unseen.remove(node)
while len(start) > 0:
next_s = []
for x in start:
for y in g[x][0]:
if y in unseen:
next_s.append(y)
unseen.remove(y)
start = next_s
return unseen
def find_cycle_parents(g, node, unseen):
#Everything left in unseen is descended only from elements in cycles
#how few cycles do we have to get?
#a <- (b, c, d) - (e, f, g, h)
#we want a -> b->c->d(cycle)->e->f->g->h(cycle)
parent = {node: None}
cycles = {}
start = [node]
g2 = set([])
while len(start) > 0:
next_s = []
for x in start:
for y in g[x][1]:
if y in unseen:
#Things pointing to x
if y in parent:
my_cycle = [x, parent[x]]
while my_cycle[-1] != y:
my_cycle.append(parent[my_cycle[-1]])
for y2 in my_cycle:
cycles[y2] = y
else:
g2.add((y, x))
parent[y] = x
next_s.append(y)
start = next_s
g3 = {}
for a, b in g2:
if a in cycles:
a = cycles[a]
if b in cycles:
b = cycles[b]
if a != b:
if a not in g3:
g3[a] = set([])
if b not in g3:
g3[b] = set([])
g3[b].add(a)
elif a not in g3:
g3[a] = set([])
return [x for x in g3 if len(g3[x])==0]
def process(A, n, s):
m = len(A)
s = s-1
max_elements = set(range(n))
g = [[[], []] for i in range(n)]
for i in range(m):
u, v = A[i]
u, v = u-1, v-1
g[u][0].append(v)
g[v][1].append(u)
if v in max_elements:
max_elements.remove(v)
unseen = bfs(g, s, set(range(n)))
answer = 0
#Things reachable from max elements:
for root in max_elements:
if root in unseen:
answer+=1
unseen = bfs(g, root, unseen)
#Things reachable from cycles:
while len(unseen) > 0:
for x in unseen:
break
cycles = find_cycle_parents(g, x, unseen)
for y in cycles:
if y in unseen:
answer+=1
unseen = bfs(g, y, unseen)
return answer
n, m, s = [int(x) for x in input().split()]
A = []
for i in range(m):
u, v = [int(x) for x in input().split()]
A.append([u, v])
print(process(A, n, s)) | Title: Reachability from the Capital
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are $n$ cities and $m$ roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.
What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?
New roads will also be one-way.
Input Specification:
The first line of input consists of three integers $n$, $m$ and $s$ ($1 \le n \le 5000, 0 \le m \le 5000, 1 \le s \le n$) — the number of cities, the number of roads and the index of the capital. Cities are indexed from $1$ to $n$.
The following $m$ lines contain roads: road $i$ is given as a pair of cities $u_i$, $v_i$ ($1 \le u_i, v_i \le n$, $u_i \ne v_i$). For each pair of cities $(u, v)$, there can be at most one road from $u$ to $v$. Roads in opposite directions between a pair of cities are allowed (i.e. from $u$ to $v$ and from $v$ to $u$).
Output Specification:
Print one integer — the minimum number of extra roads needed to make all the cities reachable from city $s$. If all the cities are already reachable from $s$, print 0.
Demo Input:
['9 9 1\n1 2\n1 3\n2 3\n1 5\n5 6\n6 1\n1 8\n9 8\n7 1\n', '5 4 5\n1 2\n2 3\n3 4\n4 1\n']
Demo Output:
['3\n', '1\n']
Note:
The first example is illustrated by the following:
For example, you can add roads ($6, 4$), ($7, 9$), ($1, 7$) to make all the cities reachable from $s = 1$.
The second example is illustrated by the following:
In this example, you can add any one of the roads ($5, 1$), ($5, 2$), ($5, 3$), ($5, 4$) to make all the cities reachable from $s = 5$. | ```python
def bfs(g, node, unseen):
start = [node]
unseen.remove(node)
while len(start) > 0:
next_s = []
for x in start:
for y in g[x][0]:
if y in unseen:
next_s.append(y)
unseen.remove(y)
start = next_s
return unseen
def find_cycle_parents(g, node, unseen):
#Everything left in unseen is descended only from elements in cycles
#how few cycles do we have to get?
#a <- (b, c, d) - (e, f, g, h)
#we want a -> b->c->d(cycle)->e->f->g->h(cycle)
parent = {node: None}
cycles = {}
start = [node]
g2 = set([])
while len(start) > 0:
next_s = []
for x in start:
for y in g[x][1]:
if y in unseen:
#Things pointing to x
if y in parent:
my_cycle = [x, parent[x]]
while my_cycle[-1] != y:
my_cycle.append(parent[my_cycle[-1]])
for y2 in my_cycle:
cycles[y2] = y
else:
g2.add((y, x))
parent[y] = x
next_s.append(y)
start = next_s
g3 = {}
for a, b in g2:
if a in cycles:
a = cycles[a]
if b in cycles:
b = cycles[b]
if a != b:
if a not in g3:
g3[a] = set([])
if b not in g3:
g3[b] = set([])
g3[b].add(a)
elif a not in g3:
g3[a] = set([])
return [x for x in g3 if len(g3[x])==0]
def process(A, n, s):
m = len(A)
s = s-1
max_elements = set(range(n))
g = [[[], []] for i in range(n)]
for i in range(m):
u, v = A[i]
u, v = u-1, v-1
g[u][0].append(v)
g[v][1].append(u)
if v in max_elements:
max_elements.remove(v)
unseen = bfs(g, s, set(range(n)))
answer = 0
#Things reachable from max elements:
for root in max_elements:
if root in unseen:
answer+=1
unseen = bfs(g, root, unseen)
#Things reachable from cycles:
while len(unseen) > 0:
for x in unseen:
break
cycles = find_cycle_parents(g, x, unseen)
for y in cycles:
if y in unseen:
answer+=1
unseen = bfs(g, y, unseen)
return answer
n, m, s = [int(x) for x in input().split()]
A = []
for i in range(m):
u, v = [int(x) for x in input().split()]
A.append([u, v])
print(process(A, n, s))
``` | -1 | |
598 | D | Igor In the Museum | PROGRAMMING | 1,700 | [
"dfs and similar",
"graphs",
"shortest paths"
] | null | null | Igor is in the museum and he wants to see as many pictures as possible.
Museum can be represented as a rectangular field of *n*<=×<=*m* cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.
At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.
For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see. | First line of the input contains three integers *n*, *m* and *k* (3<=≤<=*n*,<=*m*<=≤<=1000,<=1<=≤<=*k*<=≤<=*min*(*n*·*m*,<=100<=000)) — the museum dimensions and the number of starting positions to process.
Each of the next *n* lines contains *m* symbols '.', '*' — the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum.
Each of the last *k* lines contains two integers *x* and *y* (1<=≤<=*x*<=≤<=*n*,<=1<=≤<=*y*<=≤<=*m*) — the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns — from left to right. It is guaranteed that all starting positions are empty cells. | Print *k* integers — the maximum number of pictures, that Igor can see if he starts in corresponding position. | [
"5 6 3\n******\n*..*.*\n******\n*....*\n******\n2 2\n2 5\n4 3\n",
"4 4 1\n****\n*..*\n*.**\n****\n3 2\n"
] | [
"6\n4\n10\n",
"8\n"
] | none | 0 | [
{
"input": "5 6 3\n******\n*..*.*\n******\n*....*\n******\n2 2\n2 5\n4 3",
"output": "6\n4\n10"
},
{
"input": "4 4 1\n****\n*..*\n*.**\n****\n3 2",
"output": "8"
},
{
"input": "3 3 1\n***\n*.*\n***\n2 2",
"output": "4"
},
{
"input": "5 5 10\n*****\n*...*\n*..**\n*.***\n*****\... | 1,644,068,182 | 2,147,483,647 | PyPy 3-64 | TIME_LIMIT_EXCEEDED | TESTS | 10 | 1,000 | 51,200,000 | n,m,p=[int(e)for e in input().split()]
h=[list(input())for i in range(n)]
s=[]
for i in range(p):
s.append([int(e)for e in input().split()])
w=[]
k=0
def go(y,x):
global n,m,h,w,k
w+=[[y,x]]
if x+1<m and h[y][x+1]=='*':
k+=1
if x-1>=0 and h[y][x-1]=='*':
k+=1
if y+1<n and h[y+1][x]=='*':
k+=1
if y-1>=0 and h[y-1][x]=='*':
k+=1
if x+1<m and h[y][x+1]=='.'and[y,x+1]not in w:
go(y,x+1)
if x-1>=0 and h[y][x-1]=='.'and[y,x-1]not in w:
go(y,x-1)
if y+1<n and h[y+1][x]=='.'and[y+1,x]not in w:
go(y+1,x)
if y-1>=0 and h[y-1][x]=='.'and[y-1,x]not in w:
go(y-1,x)
def t(y,x):
global w,k
k=0
w=[]
go(y,x)
return k
for e in s:
print(t(e[0]-1,e[1]-1))
| Title: Igor In the Museum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Igor is in the museum and he wants to see as many pictures as possible.
Museum can be represented as a rectangular field of *n*<=×<=*m* cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.
At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.
For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.
Input Specification:
First line of the input contains three integers *n*, *m* and *k* (3<=≤<=*n*,<=*m*<=≤<=1000,<=1<=≤<=*k*<=≤<=*min*(*n*·*m*,<=100<=000)) — the museum dimensions and the number of starting positions to process.
Each of the next *n* lines contains *m* symbols '.', '*' — the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum.
Each of the last *k* lines contains two integers *x* and *y* (1<=≤<=*x*<=≤<=*n*,<=1<=≤<=*y*<=≤<=*m*) — the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns — from left to right. It is guaranteed that all starting positions are empty cells.
Output Specification:
Print *k* integers — the maximum number of pictures, that Igor can see if he starts in corresponding position.
Demo Input:
['5 6 3\n******\n*..*.*\n******\n*....*\n******\n2 2\n2 5\n4 3\n', '4 4 1\n****\n*..*\n*.**\n****\n3 2\n']
Demo Output:
['6\n4\n10\n', '8\n']
Note:
none | ```python
n,m,p=[int(e)for e in input().split()]
h=[list(input())for i in range(n)]
s=[]
for i in range(p):
s.append([int(e)for e in input().split()])
w=[]
k=0
def go(y,x):
global n,m,h,w,k
w+=[[y,x]]
if x+1<m and h[y][x+1]=='*':
k+=1
if x-1>=0 and h[y][x-1]=='*':
k+=1
if y+1<n and h[y+1][x]=='*':
k+=1
if y-1>=0 and h[y-1][x]=='*':
k+=1
if x+1<m and h[y][x+1]=='.'and[y,x+1]not in w:
go(y,x+1)
if x-1>=0 and h[y][x-1]=='.'and[y,x-1]not in w:
go(y,x-1)
if y+1<n and h[y+1][x]=='.'and[y+1,x]not in w:
go(y+1,x)
if y-1>=0 and h[y-1][x]=='.'and[y-1,x]not in w:
go(y-1,x)
def t(y,x):
global w,k
k=0
w=[]
go(y,x)
return k
for e in s:
print(t(e[0]-1,e[1]-1))
``` | 0 | |
115 | A | Party | PROGRAMMING | 900 | [
"dfs and similar",
"graphs",
"trees"
] | null | null | A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true:
- Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*.
What is the minimum number of groups that must be formed? | The first line contains integer *n* (1<=≤<=*n*<=≤<=2000) — the number of employees.
The next *n* lines contain the integers *p**i* (1<=≤<=*p**i*<=≤<=*n* or *p**i*<==<=-1). Every *p**i* denotes the immediate manager for the *i*-th employee. If *p**i* is -1, that means that the *i*-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (*p**i*<=≠<=*i*). Also, there will be no managerial cycles. | Print a single integer denoting the minimum number of groups that will be formed in the party. | [
"5\n-1\n1\n2\n1\n-1\n"
] | [
"3\n"
] | For the first example, three groups are sufficient, for example:
- Employee 1 - Employees 2 and 4 - Employees 3 and 5 | 500 | [
{
"input": "5\n-1\n1\n2\n1\n-1",
"output": "3"
},
{
"input": "4\n-1\n1\n2\n3",
"output": "4"
},
{
"input": "12\n-1\n1\n2\n3\n-1\n5\n6\n7\n-1\n9\n10\n11",
"output": "4"
},
{
"input": "6\n-1\n-1\n2\n3\n1\n1",
"output": "3"
},
{
"input": "3\n-1\n1\n1",
"output": ... | 1,677,739,164 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 62 | 0 | print(len(set([int(input()) for _ in range(int(input()))])))
| Title: Party
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true:
- Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*.
What is the minimum number of groups that must be formed?
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=2000) — the number of employees.
The next *n* lines contain the integers *p**i* (1<=≤<=*p**i*<=≤<=*n* or *p**i*<==<=-1). Every *p**i* denotes the immediate manager for the *i*-th employee. If *p**i* is -1, that means that the *i*-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (*p**i*<=≠<=*i*). Also, there will be no managerial cycles.
Output Specification:
Print a single integer denoting the minimum number of groups that will be formed in the party.
Demo Input:
['5\n-1\n1\n2\n1\n-1\n']
Demo Output:
['3\n']
Note:
For the first example, three groups are sufficient, for example:
- Employee 1 - Employees 2 and 4 - Employees 3 and 5 | ```python
print(len(set([int(input()) for _ in range(int(input()))])))
``` | 0 | |
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,689,607,029 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 187 | 0 | n = int(input())
check = {'Tetrahedron': 4,'Cube':6,'Octahedron':8,'Dodecahedron':12,'Icosahedron':20}
res = 0
for i in range(n):
res += check[input()]
print(res) | 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
n = int(input())
check = {'Tetrahedron': 4,'Cube':6,'Octahedron':8,'Dodecahedron':12,'Icosahedron':20}
res = 0
for i in range(n):
res += check[input()]
print(res)
``` | 3 | |
821 | B | Okabe and Banana Trees | PROGRAMMING | 1,300 | [
"brute force",
"math"
] | null | null | Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees.
Consider the point (*x*,<=*y*) in the 2D plane such that *x* and *y* are integers and 0<=≤<=*x*,<=*y*. There is a tree in such a point, and it has *x*<=+<=*y* bananas. There are no trees nor bananas in other points. Now, Okabe draws a line with equation . Okabe can select a single rectangle with axis aligned sides with all points on or under the line and cut all the trees in all points that are inside or on the border of this rectangle and take their bananas. Okabe's rectangle can be degenerate; that is, it can be a line segment or even a point.
Help Okabe and find the maximum number of bananas he can get if he chooses the rectangle wisely.
Okabe is sure that the answer does not exceed 1018. You can trust him. | The first line of input contains two space-separated integers *m* and *b* (1<=≤<=*m*<=≤<=1000, 1<=≤<=*b*<=≤<=10000). | Print the maximum number of bananas Okabe can get from the trees he cuts. | [
"1 5\n",
"2 3\n"
] | [
"30\n",
"25\n"
] | The graph above corresponds to sample test 1. The optimal rectangle is shown in red and has 30 bananas. | 1,000 | [
{
"input": "1 5",
"output": "30"
},
{
"input": "2 3",
"output": "25"
},
{
"input": "4 6",
"output": "459"
},
{
"input": "6 3",
"output": "171"
},
{
"input": "1 1",
"output": "1"
},
{
"input": "10 1",
"output": "55"
},
{
"input": "20 10",
... | 1,498,408,157 | 6,857 | Python 3 | TIME_LIMIT_EXCEEDED | PRETESTS | 7 | 2,000 | 4,608,000 | ## 2
m, b = list(map(int, input().split()))
ans = 0
for x in range(m*b + 1):
y = int(float(b) - x/m)
suma = int(x*(x+1)/2); sumb = int(y*(y+1)/2)
ans = max(ans, (y+1)*suma+(x+1)*sumb)
print(ans)
| Title: Okabe and Banana Trees
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees.
Consider the point (*x*,<=*y*) in the 2D plane such that *x* and *y* are integers and 0<=≤<=*x*,<=*y*. There is a tree in such a point, and it has *x*<=+<=*y* bananas. There are no trees nor bananas in other points. Now, Okabe draws a line with equation . Okabe can select a single rectangle with axis aligned sides with all points on or under the line and cut all the trees in all points that are inside or on the border of this rectangle and take their bananas. Okabe's rectangle can be degenerate; that is, it can be a line segment or even a point.
Help Okabe and find the maximum number of bananas he can get if he chooses the rectangle wisely.
Okabe is sure that the answer does not exceed 1018. You can trust him.
Input Specification:
The first line of input contains two space-separated integers *m* and *b* (1<=≤<=*m*<=≤<=1000, 1<=≤<=*b*<=≤<=10000).
Output Specification:
Print the maximum number of bananas Okabe can get from the trees he cuts.
Demo Input:
['1 5\n', '2 3\n']
Demo Output:
['30\n', '25\n']
Note:
The graph above corresponds to sample test 1. The optimal rectangle is shown in red and has 30 bananas. | ```python
## 2
m, b = list(map(int, input().split()))
ans = 0
for x in range(m*b + 1):
y = int(float(b) - x/m)
suma = int(x*(x+1)/2); sumb = int(y*(y+1)/2)
ans = max(ans, (y+1)*suma+(x+1)*sumb)
print(ans)
``` | 0 | |
25 | B | Phone numbers | PROGRAMMING | 1,100 | [
"implementation"
] | B. Phone numbers | 2 | 256 | Phone number in Berland is a sequence of *n* digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits. | The first line contains integer *n* (2<=≤<=*n*<=≤<=100) — amount of digits in the phone number. The second line contains *n* digits — the phone number to divide into groups. | Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any. | [
"6\n549871\n",
"7\n1198733\n"
] | [
"54-98-71",
"11-987-33\n"
] | none | 0 | [
{
"input": "6\n549871",
"output": "54-98-71"
},
{
"input": "7\n1198733",
"output": "119-87-33"
},
{
"input": "2\n74",
"output": "74"
},
{
"input": "2\n33",
"output": "33"
},
{
"input": "3\n074",
"output": "074"
},
{
"input": "3\n081",
"output": "08... | 1,505,568,412 | 2,147,483,647 | Python 3 | OK | TESTS | 20 | 124 | 0 | n = int(input())
s = input()
for i in range(n):
print(s[i], end = '')
if (i + 1) % 2 == 0:
if n % 2 == 0 and i != n - 1:
print('-', end = '')
if n % 2 != 0 and i != n - 2:
print('-', end = '') | Title: Phone numbers
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Phone number in Berland is a sequence of *n* digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
Input Specification:
The first line contains integer *n* (2<=≤<=*n*<=≤<=100) — amount of digits in the phone number. The second line contains *n* digits — the phone number to divide into groups.
Output Specification:
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
Demo Input:
['6\n549871\n', '7\n1198733\n']
Demo Output:
['54-98-71', '11-987-33\n']
Note:
none | ```python
n = int(input())
s = input()
for i in range(n):
print(s[i], end = '')
if (i + 1) % 2 == 0:
if n % 2 == 0 and i != n - 1:
print('-', end = '')
if n % 2 != 0 and i != n - 2:
print('-', end = '')
``` | 3.969 |
313 | B | Ilya and Queries | PROGRAMMING | 1,100 | [
"dp",
"implementation"
] | null | null | Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string *s*<==<=*s*1*s*2... *s**n* (*n* is the length of the string), consisting only of characters "." and "#" and *m* queries. Each query is described by a pair of integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=<<=*r**i*<=≤<=*n*). The answer to the query *l**i*,<=*r**i* is the number of such integers *i* (*l**i*<=≤<=*i*<=<<=*r**i*), that *s**i*<==<=*s**i*<=+<=1.
Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem. | The first line contains string *s* of length *n* (2<=≤<=*n*<=≤<=105). It is guaranteed that the given string only consists of characters "." and "#".
The next line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of queries. Each of the next *m* lines contains the description of the corresponding query. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=<<=*r**i*<=≤<=*n*). | Print *m* integers — the answers to the queries in the order in which they are given in the input. | [
"......\n4\n3 4\n2 3\n1 6\n2 6\n",
"#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4\n"
] | [
"1\n1\n5\n4\n",
"1\n1\n2\n2\n0\n"
] | none | 1,000 | [
{
"input": "......\n4\n3 4\n2 3\n1 6\n2 6",
"output": "1\n1\n5\n4"
},
{
"input": "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4",
"output": "1\n1\n2\n2\n0"
},
{
"input": ".#...#..\n6\n1 5\n2 3\n6 7\n2 4\n2 5\n1 3",
"output": "2\n0\n0\n1\n2\n0"
},
{
"input": "#.#.#..\n5\n3 4\n4 5\n5 7\n5... | 1,698,520,114 | 2,147,483,647 | PyPy 3 | TIME_LIMIT_EXCEEDED | TESTS | 9 | 2,000 | 9,523,200 | s = input()
Pref = [0]
for i in range(1, len(s)):
Pref.append(Pref[-1] + (s[i] == s[i - 1]))
m = int(input())
for _ in range(m):
l, r = map(int, input().split())
l -= 1
r -= 1
print(Pref[r] - Pref[l])
# Sat Oct 28 2023 22:08:33 GMT+0300 (Moscow Standard Time)
| Title: Ilya and Queries
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string *s*<==<=*s*1*s*2... *s**n* (*n* is the length of the string), consisting only of characters "." and "#" and *m* queries. Each query is described by a pair of integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=<<=*r**i*<=≤<=*n*). The answer to the query *l**i*,<=*r**i* is the number of such integers *i* (*l**i*<=≤<=*i*<=<<=*r**i*), that *s**i*<==<=*s**i*<=+<=1.
Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
Input Specification:
The first line contains string *s* of length *n* (2<=≤<=*n*<=≤<=105). It is guaranteed that the given string only consists of characters "." and "#".
The next line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of queries. Each of the next *m* lines contains the description of the corresponding query. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=<<=*r**i*<=≤<=*n*).
Output Specification:
Print *m* integers — the answers to the queries in the order in which they are given in the input.
Demo Input:
['......\n4\n3 4\n2 3\n1 6\n2 6\n', '#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4\n']
Demo Output:
['1\n1\n5\n4\n', '1\n1\n2\n2\n0\n']
Note:
none | ```python
s = input()
Pref = [0]
for i in range(1, len(s)):
Pref.append(Pref[-1] + (s[i] == s[i - 1]))
m = int(input())
for _ in range(m):
l, r = map(int, input().split())
l -= 1
r -= 1
print(Pref[r] - Pref[l])
# Sat Oct 28 2023 22:08:33 GMT+0300 (Moscow Standard Time)
``` | 0 | |
1,003 | A | Polycarp's Pockets | PROGRAMMING | 800 | [
"implementation"
] | null | null | Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins into two pockets as follows: $[1, 2, 3], [2, 3, 4]$.
Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that. | The first line of the input contains one integer $n$ ($1 \le n \le 100$) — the number of coins.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$) — values of coins. | Print only one integer — the minimum number of pockets Polycarp needs to distribute all the coins so no two coins with the same value are put into the same pocket. | [
"6\n1 2 4 3 3 2\n",
"1\n100\n"
] | [
"2\n",
"1\n"
] | none | 0 | [
{
"input": "6\n1 2 4 3 3 2",
"output": "2"
},
{
"input": "1\n100",
"output": "1"
},
{
"input": "100\n100 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 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100... | 1,618,927,959 | 2,147,483,647 | Python 3 | OK | TESTS | 37 | 77 | 0 | n=int(input())
x=[int(w) for w in input().split()]
a=0
m=[]
for i in set(x):
m.append(x.count(i))
print(max(m)) | Title: Polycarp's Pockets
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins into two pockets as follows: $[1, 2, 3], [2, 3, 4]$.
Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that.
Input Specification:
The first line of the input contains one integer $n$ ($1 \le n \le 100$) — the number of coins.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$) — values of coins.
Output Specification:
Print only one integer — the minimum number of pockets Polycarp needs to distribute all the coins so no two coins with the same value are put into the same pocket.
Demo Input:
['6\n1 2 4 3 3 2\n', '1\n100\n']
Demo Output:
['2\n', '1\n']
Note:
none | ```python
n=int(input())
x=[int(w) for w in input().split()]
a=0
m=[]
for i in set(x):
m.append(x.count(i))
print(max(m))
``` | 3 | |
887 | A | Div. 64 | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system. | In the only line given a non-empty binary string *s* with length up to 100. | Print «yes» (without quotes) if it's possible to remove digits required way and «no» otherwise. | [
"100010001\n",
"100\n"
] | [
"yes",
"no"
] | In the first test case, you can get string 1 000 000 after removing two ones which is a representation of number 64 in the binary numerical system.
You can read more about binary numeral system representation here: [https://en.wikipedia.org/wiki/Binary_system](https://en.wikipedia.org/wiki/Binary_system) | 500 | [
{
"input": "100010001",
"output": "yes"
},
{
"input": "100",
"output": "no"
},
{
"input": "0000001000000",
"output": "yes"
},
{
"input": "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
"output": "no"
},
{
"in... | 1,510,166,361 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 4 | 46 | 0 | ch=input()
t=False
s=0
f=False
for x in ch:
f= f or x=='0'
if not f:
break
for x in range(len(ch)):
if ch[x]=='1':
i=x+1
for j in range(i,len(ch)):
if ch[j]=='0':
s+=1
if s>=6:
t=True
break
if ((t or f) and (len(ch)>=7)) :
print('yes')
else:
print('no')
| Title: Div. 64
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.
Input Specification:
In the only line given a non-empty binary string *s* with length up to 100.
Output Specification:
Print «yes» (without quotes) if it's possible to remove digits required way and «no» otherwise.
Demo Input:
['100010001\n', '100\n']
Demo Output:
['yes', 'no']
Note:
In the first test case, you can get string 1 000 000 after removing two ones which is a representation of number 64 in the binary numerical system.
You can read more about binary numeral system representation here: [https://en.wikipedia.org/wiki/Binary_system](https://en.wikipedia.org/wiki/Binary_system) | ```python
ch=input()
t=False
s=0
f=False
for x in ch:
f= f or x=='0'
if not f:
break
for x in range(len(ch)):
if ch[x]=='1':
i=x+1
for j in range(i,len(ch)):
if ch[j]=='0':
s+=1
if s>=6:
t=True
break
if ((t or f) and (len(ch)>=7)) :
print('yes')
else:
print('no')
``` | 0 | |
133 | A | HQ9+ | PROGRAMMING | 900 | [
"implementation"
] | null | null | HQ9+ is a joke programming language which has only four one-character instructions:
- "H" prints "Hello, World!",- "Q" prints the source code of the program itself,- "9" prints the lyrics of "99 Bottles of Beer" song, - "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.
You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output. | The input will consist of a single line *p* which will give a program in HQ9+. String *p* will contain between 1 and 100 characters, inclusive. ASCII-code of each character of *p* will be between 33 (exclamation mark) and 126 (tilde), inclusive. | Output "YES", if executing the program will produce any output, and "NO" otherwise. | [
"Hi!\n",
"Codeforces\n"
] | [
"YES\n",
"NO\n"
] | In the first case the program contains only one instruction — "H", which prints "Hello, World!".
In the second case none of the program characters are language instructions. | 500 | [
{
"input": "Hi!",
"output": "YES"
},
{
"input": "Codeforces",
"output": "NO"
},
{
"input": "a+b=c",
"output": "NO"
},
{
"input": "hq-lowercase",
"output": "NO"
},
{
"input": "Q",
"output": "YES"
},
{
"input": "9",
"output": "YES"
},
{
"inpu... | 1,684,168,204 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 2 | 124 | 0 | a=input()
h=['H','Q','9','+']
flag=0
for i in a:
if i in h:
print("YES")
flag=1
break
if(flag==0):
print("NO") | Title: HQ9+
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
HQ9+ is a joke programming language which has only four one-character instructions:
- "H" prints "Hello, World!",- "Q" prints the source code of the program itself,- "9" prints the lyrics of "99 Bottles of Beer" song, - "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.
You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.
Input Specification:
The input will consist of a single line *p* which will give a program in HQ9+. String *p* will contain between 1 and 100 characters, inclusive. ASCII-code of each character of *p* will be between 33 (exclamation mark) and 126 (tilde), inclusive.
Output Specification:
Output "YES", if executing the program will produce any output, and "NO" otherwise.
Demo Input:
['Hi!\n', 'Codeforces\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first case the program contains only one instruction — "H", which prints "Hello, World!".
In the second case none of the program characters are language instructions. | ```python
a=input()
h=['H','Q','9','+']
flag=0
for i in a:
if i in h:
print("YES")
flag=1
break
if(flag==0):
print("NO")
``` | 0 |
Subsets and Splits
Successful Python Submissions
Retrieves all records from the train dataset where the verdict is 'OK', providing basic filtering but limited analytical value.
SQL Console for MatrixStudio/Codeforces-Python-Submissions
Retrieves records of users with a rating of 1600 or higher and a verdict of 'OK', providing basic filtering but limited analytical value.
SQL Console for MatrixStudio/Codeforces-Python-Submissions
Counts the number of entries with a rating above 2000 and a verdict of 'OK', providing basic filtering but limited analytical value.
SQL Console for MatrixStudio/Codeforces-Python-Submissions
Counts the number of entries with a 'OK' verdict, providing a basic overview of a specific category within the dataset.