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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
552 | C | Vanya and Scales | PROGRAMMING | 1,900 | [
"brute force",
"dp",
"greedy",
"math",
"meet-in-the-middle",
"number theory"
] | null | null | Vanya has a scales for weighing loads and weights of masses *w*0,<=*w*1,<=*w*2,<=...,<=*w*100 grams where *w* is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass *m* using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass *m* and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. | The first line contains two integers *w*,<=*m* (2<=≤<=*w*<=≤<=109, 1<=≤<=*m*<=≤<=109) — the number defining the masses of the weights and the mass of the item. | Print word 'YES' if the item can be weighted and 'NO' if it cannot. | [
"3 7\n",
"100 99\n",
"100 50\n"
] | [
"YES\n",
"YES\n",
"NO\n"
] | Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1.
Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100.
Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. | 1,500 | [
{
"input": "3 7",
"output": "YES"
},
{
"input": "100 99",
"output": "YES"
},
{
"input": "100 50",
"output": "NO"
},
{
"input": "1000000000 1",
"output": "YES"
},
{
"input": "100 10002",
"output": "NO"
},
{
"input": "4 7",
"output": "NO"
},
{
... | 1,622,976,279 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 6 | 218 | 0 | import sys
input=sys.stdin.readline
w,m=map(int,input().split())
c=[1]*101
i=0
while m>0:
r=m%w
if r==1 and c[i]==1:
c[i]=0
elif r==w-1 and c[i]==1 and c[i+1]==1:
c[i]=0
c[i+1]=0
else:
print("NO")
exit()
i+=1
m//=w
print("YES") | Title: Vanya and Scales
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya has a scales for weighing loads and weights of masses *w*0,<=*w*1,<=*w*2,<=...,<=*w*100 grams where *w* is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass *m* using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass *m* and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance.
Input Specification:
The first line contains two integers *w*,<=*m* (2<=≤<=*w*<=≤<=109, 1<=≤<=*m*<=≤<=109) — the number defining the masses of the weights and the mass of the item.
Output Specification:
Print word 'YES' if the item can be weighted and 'NO' if it cannot.
Demo Input:
['3 7\n', '100 99\n', '100 50\n']
Demo Output:
['YES\n', 'YES\n', 'NO\n']
Note:
Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1.
Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100.
Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. | ```python
import sys
input=sys.stdin.readline
w,m=map(int,input().split())
c=[1]*101
i=0
while m>0:
r=m%w
if r==1 and c[i]==1:
c[i]=0
elif r==w-1 and c[i]==1 and c[i+1]==1:
c[i]=0
c[i+1]=0
else:
print("NO")
exit()
i+=1
m//=w
print("YES")
``` | 0 | |
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,651,058,864 | 2,147,483,647 | PyPy 3-64 | MEMORY_LIMIT_EXCEEDED | TESTS | 3 | 1,232 | 268,390,400 | from itertools import permutations
n=int(input())
l=list(map(int,input().split()))
B=list(permutations(l,3))
cc=0
for i in B:
a=i[0]
b=i[1]
c=i[2]
if a+b>c and b+c>a and a+c>b:
print("YES")
cc=1
break
if cc==0:
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
from itertools import permutations
n=int(input())
l=list(map(int,input().split()))
B=list(permutations(l,3))
cc=0
for i in B:
a=i[0]
b=i[1]
c=i[2]
if a+b>c and b+c>a and a+c>b:
print("YES")
cc=1
break
if cc==0:
print("NO")
``` | 0 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
- A BC - B AC - C AB - AAA empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source. | The first line contains a string *S* (1<=≤<=|*S*|<=≤<=105). The second line contains a string *T* (1<=≤<=|*T*|<=≤<=105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries *Q* (1<=≤<=*Q*<=≤<=105).
The following *Q* lines describe queries. The *i*-th of these lines contains four space separated integers *a**i*, *b**i*, *c**i*, *d**i*. These represent the *i*-th query: is it possible to create *T*[*c**i*..*d**i*] from *S*[*a**i*..*b**i*] by applying the above transitions finite amount of times?
Here, *U*[*x*..*y*] is a substring of *U* that begins at index *x* (indexed from 1) and ends at index *y*. In particular, *U*[1..|*U*|] is the whole string *U*.
It is guaranteed that 1<=≤<=*a*<=≤<=*b*<=≤<=|*S*| and 1<=≤<=*c*<=≤<=*d*<=≤<=|*T*|. | Print a string of *Q* characters, where the *i*-th character is '1' if the answer to the *i*-th query is positive, and '0' otherwise. | [
"AABCCBAAB\nABCB\n5\n1 3 1 2\n2 2 2 4\n7 9 1 1\n3 4 2 3\n4 5 1 3\n"
] | [
"10011\n"
] | In the first query we can achieve the result, for instance, by using transitions <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/2c164f8b6e335aa51b97bbd019ca0d7326927314.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'. | 0 | [] | 1,520,702,555 | 6,455 | Python 3 | WRONG_ANSWER | PRETESTS | 1 | 46 | 5,632,000 | x = input()
y = input()
s = []
bc = 0
a = 0
for l in x:
if l in 'BC':
bc += 1
a = 0
else:
a += 1
s.append((bc,a))
t = []
bc = 0
a = 0
for l in y:
if l in 'BC':
bc += 1
a = 0
else:
a += 1
t.append((bc,a))
q = int(input())
for i in range(q):
ls,rs,lt,rt = map(int, input().split())
lens = rs - ls + 1
lent = rt - lt + 1
sbc = s[rs-1][0] - s[ls-1][0]
tbc = t[rt-1][0] - t[lt-1][0]
sa = s[rs-1][1]
ta = t[rt-1][1]
if sa > lens: sa = lens
if ta > lent: ta = lent
if sa != ta: sbc += 2
a = ta - sa
if a < 0 or a % 2 != 0:
print('0', end = '')
else:
print('1', end = '')
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
- A BC - B AC - C AB - AAA empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
Input Specification:
The first line contains a string *S* (1<=≤<=|*S*|<=≤<=105). The second line contains a string *T* (1<=≤<=|*T*|<=≤<=105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries *Q* (1<=≤<=*Q*<=≤<=105).
The following *Q* lines describe queries. The *i*-th of these lines contains four space separated integers *a**i*, *b**i*, *c**i*, *d**i*. These represent the *i*-th query: is it possible to create *T*[*c**i*..*d**i*] from *S*[*a**i*..*b**i*] by applying the above transitions finite amount of times?
Here, *U*[*x*..*y*] is a substring of *U* that begins at index *x* (indexed from 1) and ends at index *y*. In particular, *U*[1..|*U*|] is the whole string *U*.
It is guaranteed that 1<=≤<=*a*<=≤<=*b*<=≤<=|*S*| and 1<=≤<=*c*<=≤<=*d*<=≤<=|*T*|.
Output Specification:
Print a string of *Q* characters, where the *i*-th character is '1' if the answer to the *i*-th query is positive, and '0' otherwise.
Demo Input:
['AABCCBAAB\nABCB\n5\n1 3 1 2\n2 2 2 4\n7 9 1 1\n3 4 2 3\n4 5 1 3\n']
Demo Output:
['10011\n']
Note:
In the first query we can achieve the result, for instance, by using transitions <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/2c164f8b6e335aa51b97bbd019ca0d7326927314.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'. | ```python
x = input()
y = input()
s = []
bc = 0
a = 0
for l in x:
if l in 'BC':
bc += 1
a = 0
else:
a += 1
s.append((bc,a))
t = []
bc = 0
a = 0
for l in y:
if l in 'BC':
bc += 1
a = 0
else:
a += 1
t.append((bc,a))
q = int(input())
for i in range(q):
ls,rs,lt,rt = map(int, input().split())
lens = rs - ls + 1
lent = rt - lt + 1
sbc = s[rs-1][0] - s[ls-1][0]
tbc = t[rt-1][0] - t[lt-1][0]
sa = s[rs-1][1]
ta = t[rt-1][1]
if sa > lens: sa = lens
if ta > lent: ta = lent
if sa != ta: sbc += 2
a = ta - sa
if a < 0 or a % 2 != 0:
print('0', end = '')
else:
print('1', end = '')
``` | 0 | |
492 | B | Vanya and Lanterns | PROGRAMMING | 1,200 | [
"binary search",
"implementation",
"math",
"sortings"
] | null | null | Vanya walks late at night along a straight street of length *l*, lit by *n* lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point *l*. Then the *i*-th lantern is at the point *a**i*. The lantern lights all points of the street that are at the distance of at most *d* from it, where *d* is some positive number, common for all lanterns.
Vanya wonders: what is the minimum light radius *d* should the lanterns have to light the whole street? | The first line contains two integers *n*, *l* (1<=≤<=*n*<=≤<=1000, 1<=≤<=*l*<=≤<=109) — the number of lanterns and the length of the street respectively.
The next line contains *n* integers *a**i* (0<=≤<=*a**i*<=≤<=*l*). Multiple lanterns can be located at the same point. The lanterns may be located at the ends of the street. | Print the minimum light radius *d*, needed to light the whole street. The answer will be considered correct if its absolute or relative error doesn't exceed 10<=-<=9. | [
"7 15\n15 5 3 7 9 14 0\n",
"2 5\n2 5\n"
] | [
"2.5000000000\n",
"2.0000000000\n"
] | Consider the second sample. At *d* = 2 the first lantern will light the segment [0, 4] of the street, and the second lantern will light segment [3, 5]. Thus, the whole street will be lit. | 1,000 | [
{
"input": "7 15\n15 5 3 7 9 14 0",
"output": "2.5000000000"
},
{
"input": "2 5\n2 5",
"output": "2.0000000000"
},
{
"input": "46 615683844\n431749087 271781274 274974690 324606253 480870261 401650581 13285442 478090364 266585394 425024433 588791449 492057200 391293435 563090494 317950 1... | 1,689,907,416 | 2,147,483,647 | Python 3 | OK | TESTS | 32 | 46 | 0 | n,d=map(int,input().split())
li=[int(i) for i in input().split()]
li.sort()
maxx=0
for i in range(n-1):
if li[i+1]-li[i]>maxx:
maxx=li[i+1]-li[i]
maxx=maxx/2
left=li[0]
right=d-li[n-1]
maxx=max(left,right,maxx)
print(maxx) | Title: Vanya and Lanterns
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya walks late at night along a straight street of length *l*, lit by *n* lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point *l*. Then the *i*-th lantern is at the point *a**i*. The lantern lights all points of the street that are at the distance of at most *d* from it, where *d* is some positive number, common for all lanterns.
Vanya wonders: what is the minimum light radius *d* should the lanterns have to light the whole street?
Input Specification:
The first line contains two integers *n*, *l* (1<=≤<=*n*<=≤<=1000, 1<=≤<=*l*<=≤<=109) — the number of lanterns and the length of the street respectively.
The next line contains *n* integers *a**i* (0<=≤<=*a**i*<=≤<=*l*). Multiple lanterns can be located at the same point. The lanterns may be located at the ends of the street.
Output Specification:
Print the minimum light radius *d*, needed to light the whole street. The answer will be considered correct if its absolute or relative error doesn't exceed 10<=-<=9.
Demo Input:
['7 15\n15 5 3 7 9 14 0\n', '2 5\n2 5\n']
Demo Output:
['2.5000000000\n', '2.0000000000\n']
Note:
Consider the second sample. At *d* = 2 the first lantern will light the segment [0, 4] of the street, and the second lantern will light segment [3, 5]. Thus, the whole street will be lit. | ```python
n,d=map(int,input().split())
li=[int(i) for i in input().split()]
li.sort()
maxx=0
for i in range(n-1):
if li[i+1]-li[i]>maxx:
maxx=li[i+1]-li[i]
maxx=maxx/2
left=li[0]
right=d-li[n-1]
maxx=max(left,right,maxx)
print(maxx)
``` | 3 | |
810 | B | Summer sell-off | PROGRAMMING | 1,300 | [
"greedy",
"sortings"
] | null | null | Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.
Shop, where Noora is working, has a plan on the following *n* days. For each day sales manager knows exactly, that in *i*-th day *k**i* products will be put up for sale and exactly *l**i* clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.
For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any *f* days from *n* next for sell-outs. On each of *f* chosen days the number of products were put up for sale would be doubled. Thus, if on *i*-th day shop planned to put up for sale *k**i* products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·*k**i* products. Consequently, there is an opportunity to sell two times more products on days of sell-out.
Noora's task is to choose *f* days to maximize total number of sold products. She asks you to help her with such a difficult problem. | The first line contains two integers *n* and *f* (1<=≤<=*n*<=≤<=105,<=0<=≤<=*f*<=≤<=*n*) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out.
Each line of the following *n* subsequent lines contains two integers *k**i*,<=*l**i* (0<=≤<=*k**i*,<=*l**i*<=≤<=109) denoting the number of products on the shelves of the shop on the *i*-th day and the number of clients that will come to the shop on *i*-th day. | Print a single integer denoting the maximal number of products that shop can sell. | [
"4 2\n2 1\n3 5\n2 3\n1 5\n",
"4 1\n0 2\n0 3\n3 5\n0 6\n"
] | [
"10",
"5"
] | In the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2, 6, 2, 2] respectively. So on the first day shop will sell 1 product, on the second — 5, on the third — 2, on the fourth — 2. In total 1 + 5 + 2 + 2 = 10 product units.
In the second example it is possible to sell 5 products, if you choose third day for sell-out. | 1,000 | [
{
"input": "4 2\n2 1\n3 5\n2 3\n1 5",
"output": "10"
},
{
"input": "4 1\n0 2\n0 3\n3 5\n0 6",
"output": "5"
},
{
"input": "1 1\n5 8",
"output": "8"
},
{
"input": "2 1\n8 12\n6 11",
"output": "19"
},
{
"input": "2 1\n6 7\n5 7",
"output": "13"
},
{
"inpu... | 1,497,698,685 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 46 | 0 | n,f=list(map(int,input().split()))
k,l=[0 for i in range(n)],[0 for i in range(n)]
for i in range(n):
k[i],l[i]=list(map(int,input().split()))
p=[max(k[i],l[i]) for i in range(n)]
q=[max(2*k[i],l[i]) for i in range(n)]
r=[q[i]-p[i] for i in range(n)]
r.sort()
print(sum(a)+sum(r[:f])) | Title: Summer sell-off
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.
Shop, where Noora is working, has a plan on the following *n* days. For each day sales manager knows exactly, that in *i*-th day *k**i* products will be put up for sale and exactly *l**i* clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.
For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any *f* days from *n* next for sell-outs. On each of *f* chosen days the number of products were put up for sale would be doubled. Thus, if on *i*-th day shop planned to put up for sale *k**i* products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·*k**i* products. Consequently, there is an opportunity to sell two times more products on days of sell-out.
Noora's task is to choose *f* days to maximize total number of sold products. She asks you to help her with such a difficult problem.
Input Specification:
The first line contains two integers *n* and *f* (1<=≤<=*n*<=≤<=105,<=0<=≤<=*f*<=≤<=*n*) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out.
Each line of the following *n* subsequent lines contains two integers *k**i*,<=*l**i* (0<=≤<=*k**i*,<=*l**i*<=≤<=109) denoting the number of products on the shelves of the shop on the *i*-th day and the number of clients that will come to the shop on *i*-th day.
Output Specification:
Print a single integer denoting the maximal number of products that shop can sell.
Demo Input:
['4 2\n2 1\n3 5\n2 3\n1 5\n', '4 1\n0 2\n0 3\n3 5\n0 6\n']
Demo Output:
['10', '5']
Note:
In the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2, 6, 2, 2] respectively. So on the first day shop will sell 1 product, on the second — 5, on the third — 2, on the fourth — 2. In total 1 + 5 + 2 + 2 = 10 product units.
In the second example it is possible to sell 5 products, if you choose third day for sell-out. | ```python
n,f=list(map(int,input().split()))
k,l=[0 for i in range(n)],[0 for i in range(n)]
for i in range(n):
k[i],l[i]=list(map(int,input().split()))
p=[max(k[i],l[i]) for i in range(n)]
q=[max(2*k[i],l[i]) for i in range(n)]
r=[q[i]-p[i] for i in range(n)]
r.sort()
print(sum(a)+sum(r[:f]))
``` | -1 | |
754 | B | Ilya and tic-tac-toe game | PROGRAMMING | 1,100 | [
"brute force",
"implementation"
] | null | null | Ilya is an experienced player in tic-tac-toe on the 4<=×<=4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making single turn or not.
The rules of tic-tac-toe on the 4<=×<=4 field are as follows. Before the first turn all the field cells are empty. The two players take turns placing their signs into empty cells (the first player places Xs, the second player places Os). The player who places Xs goes first, the another one goes second. The winner is the player who first gets three of his signs in a row next to each other (horizontal, vertical or diagonal). | The tic-tac-toe position is given in four lines.
Each of these lines contains four characters. Each character is '.' (empty cell), 'x' (lowercase English letter x), or 'o' (lowercase English letter o). It is guaranteed that the position is reachable playing tic-tac-toe, and it is Ilya's turn now (in particular, it means that the game is not finished). It is possible that all the cells are empty, it means that the friends left without making single turn. | Print single line: "YES" in case Ilya could have won by making single turn, and "NO" otherwise. | [
"xx..\n.oo.\nx...\noox.\n",
"x.ox\nox..\nx.o.\noo.x\n",
"x..x\n..oo\no...\nx.xo\n",
"o.x.\no...\n.x..\nooxx\n"
] | [
"YES\n",
"NO\n",
"YES\n",
"NO\n"
] | In the first example Ilya had two winning moves: to the empty cell in the left column and to the leftmost empty cell in the first row.
In the second example it wasn't possible to win by making single turn.
In the third example Ilya could have won by placing X in the last row between two existing Xs.
In the fourth example it wasn't possible to win by making single turn. | 1,000 | [
{
"input": "xx..\n.oo.\nx...\noox.",
"output": "YES"
},
{
"input": "x.ox\nox..\nx.o.\noo.x",
"output": "NO"
},
{
"input": "x..x\n..oo\no...\nx.xo",
"output": "YES"
},
{
"input": "o.x.\no...\n.x..\nooxx",
"output": "NO"
},
{
"input": ".xox\no.x.\nx.o.\n..o.",
"... | 1,660,964,556 | 2,147,483,647 | Python 3 | OK | TESTS | 95 | 46 | 0 | def check_if_won(matrix):
for row in matrix:
row_str = ''.join(str(x) for x in row)
if 'xxx' in row_str:
return True
for j in range(len(matrix[0])):
col_str = ''
col_str += matrix[0][j]
col_str += matrix[1][j]
col_str += matrix[2][j]
col_str += matrix[3][j]
if 'xxx' in col_str:
return True
# diagonais
dig1 = ''
dig1 += matrix[0][0]
dig1 += matrix[1][1]
dig1 += matrix[2][2]
dig1 += matrix[3][3]
if 'xxx' in dig1:
return True
dig2 = ''
dig2 += matrix[1][0]
dig2 += matrix[2][1]
dig2 += matrix[3][2]
if 'xxx' in dig2:
return True
dig3 = ''
dig3 += matrix[0][1]
dig3 += matrix[1][2]
dig3 += matrix[2][3]
if 'xxx' in dig3:
return True
dig_inv1 = ''
dig_inv1 += matrix[0][3]
dig_inv1 += matrix[1][2]
dig_inv1 += matrix[2][1]
dig_inv1 += matrix[3][0]
if 'xxx' in dig_inv1:
return True
dig_inv2 = ''
dig_inv2 += matrix[0][2]
dig_inv2 += matrix[1][1]
dig_inv2 += matrix[2][0]
if 'xxx' in dig_inv2:
return True
dig_inv3 = ''
dig_inv3 += matrix[1][3]
dig_inv3 += matrix[2][2]
dig_inv3 += matrix[3][1]
if 'xxx' in dig_inv3:
return True
return False
str1 = str(input())
str2 = str(input())
str3 = str(input())
str4 = str(input())
l1 = [c for c in str1]
l2 = [c for c in str2]
l3 = [c for c in str3]
l4 = [c for c in str4]
m = []
m.append(l1)
m.append(l2)
m.append(l3)
m.append(l4)
for i in range(len(m)):
for j in range(len(l1)):
if m[i][j] == '.':
m[i][j] = 'x'
won = check_if_won(m)
if won:
print('YES')
exit()
else:
m[i][j] = '.'
print('NO')
| Title: Ilya and tic-tac-toe game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ilya is an experienced player in tic-tac-toe on the 4<=×<=4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making single turn or not.
The rules of tic-tac-toe on the 4<=×<=4 field are as follows. Before the first turn all the field cells are empty. The two players take turns placing their signs into empty cells (the first player places Xs, the second player places Os). The player who places Xs goes first, the another one goes second. The winner is the player who first gets three of his signs in a row next to each other (horizontal, vertical or diagonal).
Input Specification:
The tic-tac-toe position is given in four lines.
Each of these lines contains four characters. Each character is '.' (empty cell), 'x' (lowercase English letter x), or 'o' (lowercase English letter o). It is guaranteed that the position is reachable playing tic-tac-toe, and it is Ilya's turn now (in particular, it means that the game is not finished). It is possible that all the cells are empty, it means that the friends left without making single turn.
Output Specification:
Print single line: "YES" in case Ilya could have won by making single turn, and "NO" otherwise.
Demo Input:
['xx..\n.oo.\nx...\noox.\n', 'x.ox\nox..\nx.o.\noo.x\n', 'x..x\n..oo\no...\nx.xo\n', 'o.x.\no...\n.x..\nooxx\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n', 'NO\n']
Note:
In the first example Ilya had two winning moves: to the empty cell in the left column and to the leftmost empty cell in the first row.
In the second example it wasn't possible to win by making single turn.
In the third example Ilya could have won by placing X in the last row between two existing Xs.
In the fourth example it wasn't possible to win by making single turn. | ```python
def check_if_won(matrix):
for row in matrix:
row_str = ''.join(str(x) for x in row)
if 'xxx' in row_str:
return True
for j in range(len(matrix[0])):
col_str = ''
col_str += matrix[0][j]
col_str += matrix[1][j]
col_str += matrix[2][j]
col_str += matrix[3][j]
if 'xxx' in col_str:
return True
# diagonais
dig1 = ''
dig1 += matrix[0][0]
dig1 += matrix[1][1]
dig1 += matrix[2][2]
dig1 += matrix[3][3]
if 'xxx' in dig1:
return True
dig2 = ''
dig2 += matrix[1][0]
dig2 += matrix[2][1]
dig2 += matrix[3][2]
if 'xxx' in dig2:
return True
dig3 = ''
dig3 += matrix[0][1]
dig3 += matrix[1][2]
dig3 += matrix[2][3]
if 'xxx' in dig3:
return True
dig_inv1 = ''
dig_inv1 += matrix[0][3]
dig_inv1 += matrix[1][2]
dig_inv1 += matrix[2][1]
dig_inv1 += matrix[3][0]
if 'xxx' in dig_inv1:
return True
dig_inv2 = ''
dig_inv2 += matrix[0][2]
dig_inv2 += matrix[1][1]
dig_inv2 += matrix[2][0]
if 'xxx' in dig_inv2:
return True
dig_inv3 = ''
dig_inv3 += matrix[1][3]
dig_inv3 += matrix[2][2]
dig_inv3 += matrix[3][1]
if 'xxx' in dig_inv3:
return True
return False
str1 = str(input())
str2 = str(input())
str3 = str(input())
str4 = str(input())
l1 = [c for c in str1]
l2 = [c for c in str2]
l3 = [c for c in str3]
l4 = [c for c in str4]
m = []
m.append(l1)
m.append(l2)
m.append(l3)
m.append(l4)
for i in range(len(m)):
for j in range(len(l1)):
if m[i][j] == '.':
m[i][j] = 'x'
won = check_if_won(m)
if won:
print('YES')
exit()
else:
m[i][j] = '.'
print('NO')
``` | 3 | |
572 | A | Arrays | PROGRAMMING | 900 | [
"sortings"
] | null | null | You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array. | The first line contains two integers *n**A*,<=*n**B* (1<=≤<=*n**A*,<=*n**B*<=≤<=105), separated by a space — the sizes of arrays *A* and *B*, correspondingly.
The second line contains two integers *k* and *m* (1<=≤<=*k*<=≤<=*n**A*,<=1<=≤<=*m*<=≤<=*n**B*), separated by a space.
The third line contains *n**A* numbers *a*1,<=*a*2,<=... *a**n**A* (<=-<=109<=≤<=*a*1<=≤<=*a*2<=≤<=...<=≤<=*a**n**A*<=≤<=109), separated by spaces — elements of array *A*.
The fourth line contains *n**B* integers *b*1,<=*b*2,<=... *b**n**B* (<=-<=109<=≤<=*b*1<=≤<=*b*2<=≤<=...<=≤<=*b**n**B*<=≤<=109), separated by spaces — elements of array *B*. | Print "YES" (without the quotes), if you can choose *k* numbers in array *A* and *m* numbers in array *B* so that any number chosen in array *A* was strictly less than any number chosen in array *B*. Otherwise, print "NO" (without the quotes). | [
"3 3\n2 1\n1 2 3\n3 4 5\n",
"3 3\n3 3\n1 2 3\n3 4 5\n",
"5 2\n3 1\n1 1 1 1 1\n2 2\n"
] | [
"YES\n",
"NO\n",
"YES\n"
] | In the first sample test you can, for example, choose numbers 1 and 2 from array *A* and number 3 from array *B* (1 < 3 and 2 < 3).
In the second sample test the only way to choose *k* elements in the first array and *m* elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in *A* will be less than all the numbers chosen in *B*: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7280148ed5eab0a7d418d4f92b32061243a8ca58.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | 500 | [
{
"input": "3 3\n2 1\n1 2 3\n3 4 5",
"output": "YES"
},
{
"input": "3 3\n3 3\n1 2 3\n3 4 5",
"output": "NO"
},
{
"input": "5 2\n3 1\n1 1 1 1 1\n2 2",
"output": "YES"
},
{
"input": "3 5\n1 1\n5 5 5\n5 5 5 5 5",
"output": "NO"
},
{
"input": "1 1\n1 1\n1\n1",
"ou... | 1,600,249,092 | 2,147,483,647 | Python 3 | OK | TESTS | 52 | 187 | 10,854,400 | a = list(map(int,input().split()))
b= list(map(int,input().split()))
c=list(map(int,input().split()))
d=list(map(int,input().split()))
e = 0
f = b[1]
for i in range(len(c)):
if d[-f] > c[i]:
e+=1
if e>=b[0]:
print('Yes')
else:
print('NO')
| Title: Arrays
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array.
Input Specification:
The first line contains two integers *n**A*,<=*n**B* (1<=≤<=*n**A*,<=*n**B*<=≤<=105), separated by a space — the sizes of arrays *A* and *B*, correspondingly.
The second line contains two integers *k* and *m* (1<=≤<=*k*<=≤<=*n**A*,<=1<=≤<=*m*<=≤<=*n**B*), separated by a space.
The third line contains *n**A* numbers *a*1,<=*a*2,<=... *a**n**A* (<=-<=109<=≤<=*a*1<=≤<=*a*2<=≤<=...<=≤<=*a**n**A*<=≤<=109), separated by spaces — elements of array *A*.
The fourth line contains *n**B* integers *b*1,<=*b*2,<=... *b**n**B* (<=-<=109<=≤<=*b*1<=≤<=*b*2<=≤<=...<=≤<=*b**n**B*<=≤<=109), separated by spaces — elements of array *B*.
Output Specification:
Print "YES" (without the quotes), if you can choose *k* numbers in array *A* and *m* numbers in array *B* so that any number chosen in array *A* was strictly less than any number chosen in array *B*. Otherwise, print "NO" (without the quotes).
Demo Input:
['3 3\n2 1\n1 2 3\n3 4 5\n', '3 3\n3 3\n1 2 3\n3 4 5\n', '5 2\n3 1\n1 1 1 1 1\n2 2\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
In the first sample test you can, for example, choose numbers 1 and 2 from array *A* and number 3 from array *B* (1 < 3 and 2 < 3).
In the second sample test the only way to choose *k* elements in the first array and *m* elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in *A* will be less than all the numbers chosen in *B*: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7280148ed5eab0a7d418d4f92b32061243a8ca58.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | ```python
a = list(map(int,input().split()))
b= list(map(int,input().split()))
c=list(map(int,input().split()))
d=list(map(int,input().split()))
e = 0
f = b[1]
for i in range(len(c)):
if d[-f] > c[i]:
e+=1
if e>=b[0]:
print('Yes')
else:
print('NO')
``` | 3 | |
71 | A | Way Too Long Words | PROGRAMMING | 800 | [
"strings"
] | A. Way Too Long Words | 1 | 256 | Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). Each of the following *n* lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters. | Print *n* lines. The *i*-th line should contain the result of replacing of the *i*-th word from the input data. | [
"4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis\n"
] | [
"word\nl10n\ni18n\np43s\n"
] | none | 500 | [
{
"input": "4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis",
"output": "word\nl10n\ni18n\np43s"
},
{
"input": "5\nabcdefgh\nabcdefghi\nabcdefghij\nabcdefghijk\nabcdefghijklm",
"output": "abcdefgh\nabcdefghi\nabcdefghij\na9k\na11m"
},
{
"input":... | 1,682,269,055 | 2,147,483,647 | Python 3 | OK | TESTS | 20 | 61 | 0 | n = int(input()) # Read input n
# Iterate over n words
for i in range(n):
word = input() # Read input word
if len(word) > 10: # Check if word is too long
abb = word[0] + str(len(word)-2) + word[-1] # Create abbreviation
print(abb) # Print abbreviation
else:
print(word) # Print word as is
| Title: Way Too Long Words
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). Each of the following *n* lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output Specification:
Print *n* lines. The *i*-th line should contain the result of replacing of the *i*-th word from the input data.
Demo Input:
['4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis\n']
Demo Output:
['word\nl10n\ni18n\np43s\n']
Note:
none | ```python
n = int(input()) # Read input n
# Iterate over n words
for i in range(n):
word = input() # Read input word
if len(word) > 10: # Check if word is too long
abb = word[0] + str(len(word)-2) + word[-1] # Create abbreviation
print(abb) # Print abbreviation
else:
print(word) # Print word as is
``` | 3.9695 |
109 | A | Lucky Sum of Digits | PROGRAMMING | 1,000 | [
"brute force",
"implementation"
] | A. Lucky Sum of Digits | 2 | 256 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to *n*. Help him cope with the task. | The single line contains an integer *n* (1<=≤<=*n*<=≤<=106) — the sum of digits of the required lucky number. | Print on the single line the result — the minimum lucky number, whose sum of digits equals *n*. If such number does not exist, print -1. | [
"11\n",
"10\n"
] | [
"47\n",
"-1\n"
] | none | 500 | [
{
"input": "11",
"output": "47"
},
{
"input": "10",
"output": "-1"
},
{
"input": "64",
"output": "4477777777"
},
{
"input": "1",
"output": "-1"
},
{
"input": "4",
"output": "4"
},
{
"input": "7",
"output": "7"
},
{
"input": "12",
"outpu... | 1,596,258,911 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 186 | 6,963,200 | n=int(raw_input())
x=0
final=[]
while 4*x<=n:
if (n-4*x)%7==0:
y=(n-4*x)/7
final.append([x,y])
x+=1
if not final:
print -1
else:
k=min(final,key=lambda k:k[0]+k[1])
print ("4"*(k[0])+"7"*(k[1])) | Title: Lucky Sum of Digits
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to *n*. Help him cope with the task.
Input Specification:
The single line contains an integer *n* (1<=≤<=*n*<=≤<=106) — the sum of digits of the required lucky number.
Output Specification:
Print on the single line the result — the minimum lucky number, whose sum of digits equals *n*. If such number does not exist, print -1.
Demo Input:
['11\n', '10\n']
Demo Output:
['47\n', '-1\n']
Note:
none | ```python
n=int(raw_input())
x=0
final=[]
while 4*x<=n:
if (n-4*x)%7==0:
y=(n-4*x)/7
final.append([x,y])
x+=1
if not final:
print -1
else:
k=min(final,key=lambda k:k[0]+k[1])
print ("4"*(k[0])+"7"*(k[1]))
``` | -1 |
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,581,351,453 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 7 | 218 | 307,200 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
n=input()
# In[4]:
i=0
st=[]
while i<len(n)-1:
if n[i]=='-' and n[i+1]=='-':
st.append('2')
i+=2
elif n[i]=='-' and n[i+1]=='.':
st.append('1')
i+=2
else:
st.append('0')
i+=1
if n[-1]=='.':
st.append('0')
s=''.join(st)
# In[5]:
print(s)
# In[ ]:
| 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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
n=input()
# In[4]:
i=0
st=[]
while i<len(n)-1:
if n[i]=='-' and n[i+1]=='-':
st.append('2')
i+=2
elif n[i]=='-' and n[i+1]=='.':
st.append('1')
i+=2
else:
st.append('0')
i+=1
if n[-1]=='.':
st.append('0')
s=''.join(st)
# In[5]:
print(s)
# In[ ]:
``` | 0 |
981 | E | Addition on Segments | PROGRAMMING | 2,200 | [
"bitmasks",
"data structures",
"divide and conquer",
"dp"
] | null | null | Grisha come to a contest and faced the following problem.
You are given an array of size $n$, initially consisting of zeros. The elements of the array are enumerated from $1$ to $n$. You perform $q$ operations on the array. The $i$-th operation is described with three integers $l_i$, $r_i$ and $x_i$ ($1 \leq l_i \leq r_i \leq n$, $1 \leq x_i \leq n$) and means that you should add $x_i$ to each of the elements with indices $l_i, l_i + 1, \ldots, r_i$. After all operations you should find the maximum in the array.
Grisha is clever, so he solved the problem quickly.
However something went wrong inside his head and now he thinks of the following question: "consider we applied some subset of the operations to the array. What are the possible values of the maximum in the array?"
Help Grisha, find all integers $y$ between $1$ and $n$ such that if you apply some subset (possibly empty) of the operations, then the maximum in the array becomes equal to $y$. | The first line contains two integers $n$ and $q$ ($1 \leq n, q \leq 10^{4}$) — the length of the array and the number of queries in the initial problem.
The following $q$ lines contain queries, one per line. The $i$-th of these lines contains three integers $l_i$, $r_i$ and $x_i$ ($1 \leq l_i \leq r_i \leq n$, $1 \leq x_i \leq n$), denoting a query of adding $x_i$ to the segment from $l_i$-th to $r_i$-th elements of the array, inclusive. | In the first line print the only integer $k$, denoting the number of integers from $1$ to $n$, inclusive, that can be equal to the maximum in the array after applying some subset (possibly empty) of the given operations.
In the next line print these $k$ integers from $1$ to $n$ — the possible values of the maximum. Print these integers in increasing order. | [
"4 3\n1 3 1\n2 4 2\n3 4 4\n",
"7 2\n1 5 1\n3 7 2\n",
"10 3\n1 1 2\n1 1 3\n1 1 6\n"
] | [
"4\n1 2 3 4 \n",
"3\n1 2 3 \n",
"6\n2 3 5 6 8 9 \n"
] | Consider the first example. If you consider the subset only of the first query, the maximum is equal to $1$. If you take only the second query, the maximum equals to $2$. If you take the first two queries, the maximum becomes $3$. If you take only the fourth query, the maximum becomes $4$. If you take the fourth query and something more, the maximum becomes greater that $n$, so you shouldn't print it.
In the second example you can take the first query to obtain $1$. You can take only the second query to obtain $2$. You can take all queries to obtain $3$.
In the third example you can obtain the following maximums:
- You can achieve the maximim of $2$ by using queries: $(1)$. - You can achieve the maximim of $3$ by using queries: $(2)$. - You can achieve the maximim of $5$ by using queries: $(1, 2)$. - You can achieve the maximim of $6$ by using queries: $(3)$. - You can achieve the maximim of $8$ by using queries: $(1, 3)$. - You can achieve the maximim of $9$ by using queries: $(2, 3)$. | 2,250 | [
{
"input": "4 3\n1 3 1\n2 4 2\n3 4 4",
"output": "4\n1 2 3 4 "
},
{
"input": "7 2\n1 5 1\n3 7 2",
"output": "3\n1 2 3 "
},
{
"input": "10 3\n1 1 2\n1 1 3\n1 1 6",
"output": "6\n2 3 5 6 8 9 "
},
{
"input": "45 5\n37 38 16\n5 7 34\n1 42 31\n8 27 19\n15 28 39",
"output": "5\... | 1,691,892,946 | 2,147,483,647 | PyPy 3-64 | RUNTIME_ERROR | TESTS | 0 | 46 | 3,072,000 | nmax = 10010
inf = 1e9
mod = 1e9 + 7
n, q = map(int, input().split())
ok = [0] * (nmax + 1)
dp = [0] * (nmax + 1)
v = []
def add(x):
for i in range(n, x - 1, -1):
dp[i] += dp[i - x]
dp[i] %= mod
ok[i] |= dp[i] > 0
def remove(x):
for i in range(x, n + 1):
dp[i] -= dp[i - x]
dp[i] += mod
dp[i] %= mod
dp[0] = 1
for i in range(q):
l, r, x = map(int, input().split())
v.append((l, x))
v.append((r + 1, -x))
v.sort()
for i in v:
if i[1] < 0:
remove(-i[1])
else:
add(i[1])
count_ok = sum(1 for i in ok[1:n + 1] if i == 1)
print(count_ok + 1)
result = [i for i in range(1, n + 1) if ok[i] == 1]
print(*result + 1)# 1691892946.2425966 | Title: Addition on Segments
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Grisha come to a contest and faced the following problem.
You are given an array of size $n$, initially consisting of zeros. The elements of the array are enumerated from $1$ to $n$. You perform $q$ operations on the array. The $i$-th operation is described with three integers $l_i$, $r_i$ and $x_i$ ($1 \leq l_i \leq r_i \leq n$, $1 \leq x_i \leq n$) and means that you should add $x_i$ to each of the elements with indices $l_i, l_i + 1, \ldots, r_i$. After all operations you should find the maximum in the array.
Grisha is clever, so he solved the problem quickly.
However something went wrong inside his head and now he thinks of the following question: "consider we applied some subset of the operations to the array. What are the possible values of the maximum in the array?"
Help Grisha, find all integers $y$ between $1$ and $n$ such that if you apply some subset (possibly empty) of the operations, then the maximum in the array becomes equal to $y$.
Input Specification:
The first line contains two integers $n$ and $q$ ($1 \leq n, q \leq 10^{4}$) — the length of the array and the number of queries in the initial problem.
The following $q$ lines contain queries, one per line. The $i$-th of these lines contains three integers $l_i$, $r_i$ and $x_i$ ($1 \leq l_i \leq r_i \leq n$, $1 \leq x_i \leq n$), denoting a query of adding $x_i$ to the segment from $l_i$-th to $r_i$-th elements of the array, inclusive.
Output Specification:
In the first line print the only integer $k$, denoting the number of integers from $1$ to $n$, inclusive, that can be equal to the maximum in the array after applying some subset (possibly empty) of the given operations.
In the next line print these $k$ integers from $1$ to $n$ — the possible values of the maximum. Print these integers in increasing order.
Demo Input:
['4 3\n1 3 1\n2 4 2\n3 4 4\n', '7 2\n1 5 1\n3 7 2\n', '10 3\n1 1 2\n1 1 3\n1 1 6\n']
Demo Output:
['4\n1 2 3 4 \n', '3\n1 2 3 \n', '6\n2 3 5 6 8 9 \n']
Note:
Consider the first example. If you consider the subset only of the first query, the maximum is equal to $1$. If you take only the second query, the maximum equals to $2$. If you take the first two queries, the maximum becomes $3$. If you take only the fourth query, the maximum becomes $4$. If you take the fourth query and something more, the maximum becomes greater that $n$, so you shouldn't print it.
In the second example you can take the first query to obtain $1$. You can take only the second query to obtain $2$. You can take all queries to obtain $3$.
In the third example you can obtain the following maximums:
- You can achieve the maximim of $2$ by using queries: $(1)$. - You can achieve the maximim of $3$ by using queries: $(2)$. - You can achieve the maximim of $5$ by using queries: $(1, 2)$. - You can achieve the maximim of $6$ by using queries: $(3)$. - You can achieve the maximim of $8$ by using queries: $(1, 3)$. - You can achieve the maximim of $9$ by using queries: $(2, 3)$. | ```python
nmax = 10010
inf = 1e9
mod = 1e9 + 7
n, q = map(int, input().split())
ok = [0] * (nmax + 1)
dp = [0] * (nmax + 1)
v = []
def add(x):
for i in range(n, x - 1, -1):
dp[i] += dp[i - x]
dp[i] %= mod
ok[i] |= dp[i] > 0
def remove(x):
for i in range(x, n + 1):
dp[i] -= dp[i - x]
dp[i] += mod
dp[i] %= mod
dp[0] = 1
for i in range(q):
l, r, x = map(int, input().split())
v.append((l, x))
v.append((r + 1, -x))
v.sort()
for i in v:
if i[1] < 0:
remove(-i[1])
else:
add(i[1])
count_ok = sum(1 for i in ok[1:n + 1] if i == 1)
print(count_ok + 1)
result = [i for i in range(1, n + 1) if ok[i] == 1]
print(*result + 1)# 1691892946.2425966
``` | -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,534,271 | 2,147,483,647 | Python 3 | OK | TESTS | 50 | 92 | 0 | nk = input()
l = nk.split(' ')
l = [int(s) for s in l]
n = l[0]
k = l[1]
a = input()
lst = a.split(' ')
lst = [int(s) for s in lst]
kmarks = lst[k-1]
count = 0
for i in lst:
if i > 0:
if i >= kmarks:
count += 1
else:
break
else:
break
print(count) | 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
nk = input()
l = nk.split(' ')
l = [int(s) for s in l]
n = l[0]
k = l[1]
a = input()
lst = a.split(' ')
lst = [int(s) for s in lst]
kmarks = lst[k-1]
count = 0
for i in lst:
if i > 0:
if i >= kmarks:
count += 1
else:
break
else:
break
print(count)
``` | 3 | |
748 | A | Santa Claus and a Place in a Class | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are *n* lanes of *m* desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to *n* from the left to the right, the desks in a lane are numbered from 1 to *m* starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture).
The organizers numbered all the working places from 1 to 2*nm*. The places are numbered by lanes (i. e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i. e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right.
Santa Clause knows that his place has number *k*. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right! | The only line contains three integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=10<=000, 1<=≤<=*k*<=≤<=2*nm*) — the number of lanes, the number of desks in each lane and the number of Santa Claus' place. | Print two integers: the number of lane *r*, the number of desk *d*, and a character *s*, which stands for the side of the desk Santa Claus. The character *s* should be "L", if Santa Clause should sit on the left, and "R" if his place is on the right. | [
"4 3 9\n",
"4 3 24\n",
"2 4 4\n"
] | [
"2 2 L\n",
"4 3 R\n",
"1 2 R\n"
] | The first and the second samples are shown on the picture. The green place corresponds to Santa Claus' place in the first example, the blue place corresponds to Santa Claus' place in the second example.
In the third sample there are two lanes with four desks in each, and Santa Claus has the fourth place. Thus, his place is in the first lane at the second desk on the right. | 500 | [
{
"input": "4 3 9",
"output": "2 2 L"
},
{
"input": "4 3 24",
"output": "4 3 R"
},
{
"input": "2 4 4",
"output": "1 2 R"
},
{
"input": "3 10 24",
"output": "2 2 R"
},
{
"input": "10 3 59",
"output": "10 3 L"
},
{
"input": "10000 10000 160845880",
"... | 1,484,378,734 | 2,147,483,647 | Python 3 | OK | TESTS | 46 | 93 | 4,608,000 | n, m, k = map(int, input().split())
i = 1
stop = 0
while stop != 1:
if (k >= 2 * (i - 1) * m + 1) and (k <= 2 * i * m) :
r = i
d = 1 + (k - (2 * (i - 1) * m + 1)) // 2
if k % 2 == 0:
s = "R"
else:
s = "L"
stop = 1
i += 1
print(r,d,s)
| Title: Santa Claus and a Place in a Class
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are *n* lanes of *m* desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to *n* from the left to the right, the desks in a lane are numbered from 1 to *m* starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture).
The organizers numbered all the working places from 1 to 2*nm*. The places are numbered by lanes (i. e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i. e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right.
Santa Clause knows that his place has number *k*. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right!
Input Specification:
The only line contains three integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=10<=000, 1<=≤<=*k*<=≤<=2*nm*) — the number of lanes, the number of desks in each lane and the number of Santa Claus' place.
Output Specification:
Print two integers: the number of lane *r*, the number of desk *d*, and a character *s*, which stands for the side of the desk Santa Claus. The character *s* should be "L", if Santa Clause should sit on the left, and "R" if his place is on the right.
Demo Input:
['4 3 9\n', '4 3 24\n', '2 4 4\n']
Demo Output:
['2 2 L\n', '4 3 R\n', '1 2 R\n']
Note:
The first and the second samples are shown on the picture. The green place corresponds to Santa Claus' place in the first example, the blue place corresponds to Santa Claus' place in the second example.
In the third sample there are two lanes with four desks in each, and Santa Claus has the fourth place. Thus, his place is in the first lane at the second desk on the right. | ```python
n, m, k = map(int, input().split())
i = 1
stop = 0
while stop != 1:
if (k >= 2 * (i - 1) * m + 1) and (k <= 2 * i * m) :
r = i
d = 1 + (k - (2 * (i - 1) * m + 1)) // 2
if k % 2 == 0:
s = "R"
else:
s = "L"
stop = 1
i += 1
print(r,d,s)
``` | 3 | |
975 | A | Aramic script | PROGRAMMING | 900 | [
"implementation",
"strings"
] | null | null | In Aramic language words can only represent objects.
Words in Aramic have special properties:
- A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script? | The first line contains one integer $n$ ($1 \leq n \leq 10^3$) — the number of words in the script.
The second line contains $n$ words $s_1, s_2, \ldots, s_n$ — the script itself. The length of each string does not exceed $10^3$.
It is guaranteed that all characters of the strings are small latin letters. | Output one integer — the number of different objects mentioned in the given ancient Aramic script. | [
"5\na aa aaa ab abb\n",
"3\namer arem mrea\n"
] | [
"2",
"1"
] | In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer". | 500 | [
{
"input": "5\na aa aaa ab abb",
"output": "2"
},
{
"input": "3\namer arem mrea",
"output": "1"
},
{
"input": "10\nbda bbb cda dca dda dcb bcd dcb ada ddd",
"output": "6"
},
{
"input": "2\nfhjlqs aceginpr",
"output": "2"
},
{
"input": "2\nbcdfghimn efghijlmo",
... | 1,525,184,957 | 1,457 | Python 3 | OK | TESTS | 30 | 343 | 10,240,000 | n = int(input())
A = input().split()
final = {}
#print(A)
for st in A:
count = {}
for j in st:
if count.get(j,0) == 0:
count[j] = 1
count = sorted(list(count))
#print(count)
key = ''.join(count)
if final.get(key,0) == 0:
final[key] = 1
print(len(final))
| Title: Aramic script
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In Aramic language words can only represent objects.
Words in Aramic have special properties:
- A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input Specification:
The first line contains one integer $n$ ($1 \leq n \leq 10^3$) — the number of words in the script.
The second line contains $n$ words $s_1, s_2, \ldots, s_n$ — the script itself. The length of each string does not exceed $10^3$.
It is guaranteed that all characters of the strings are small latin letters.
Output Specification:
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Demo Input:
['5\na aa aaa ab abb\n', '3\namer arem mrea\n']
Demo Output:
['2', '1']
Note:
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer". | ```python
n = int(input())
A = input().split()
final = {}
#print(A)
for st in A:
count = {}
for j in st:
if count.get(j,0) == 0:
count[j] = 1
count = sorted(list(count))
#print(count)
key = ''.join(count)
if final.get(key,0) == 0:
final[key] = 1
print(len(final))
``` | 3 | |
598 | A | Tricky Sum | PROGRAMMING | 900 | [
"math"
] | null | null | In this problem you are to calculate the sum of all integers from 1 to *n*, but you should take all powers of two with minus in the sum.
For example, for *n*<==<=4 the sum is equal to <=-<=1<=-<=2<=+<=3<=-<=4<==<=<=-<=4, because 1, 2 and 4 are 20, 21 and 22 respectively.
Calculate the answer for *t* values of *n*. | The first line of the input contains a single integer *t* (1<=≤<=*t*<=≤<=100) — the number of values of *n* to be processed.
Each of next *t* lines contains a single integer *n* (1<=≤<=*n*<=≤<=109). | Print the requested sum for each of *t* integers *n* given in the input. | [
"2\n4\n1000000000\n"
] | [
"-4\n499999998352516354\n"
] | The answer for the first sample is explained in the statement. | 0 | [
{
"input": "2\n4\n1000000000",
"output": "-4\n499999998352516354"
},
{
"input": "10\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10",
"output": "-1\n-3\n0\n-4\n1\n7\n14\n6\n15\n25"
},
{
"input": "10\n10\n9\n47\n33\n99\n83\n62\n1\n100\n53",
"output": "25\n15\n1002\n435\n4696\n3232\n1827\n-1\n4796\n130... | 1,657,366,204 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 0 | 1,000 | 0 | n=int(input())
for i in range(n):
k=int(input())
t=1
j=1
num=0
while j<=k:
if j==t:
num-=j
t*=2
else:
num+=j
j+=1
print(num)
| Title: Tricky Sum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In this problem you are to calculate the sum of all integers from 1 to *n*, but you should take all powers of two with minus in the sum.
For example, for *n*<==<=4 the sum is equal to <=-<=1<=-<=2<=+<=3<=-<=4<==<=<=-<=4, because 1, 2 and 4 are 20, 21 and 22 respectively.
Calculate the answer for *t* values of *n*.
Input Specification:
The first line of the input contains a single integer *t* (1<=≤<=*t*<=≤<=100) — the number of values of *n* to be processed.
Each of next *t* lines contains a single integer *n* (1<=≤<=*n*<=≤<=109).
Output Specification:
Print the requested sum for each of *t* integers *n* given in the input.
Demo Input:
['2\n4\n1000000000\n']
Demo Output:
['-4\n499999998352516354\n']
Note:
The answer for the first sample is explained in the statement. | ```python
n=int(input())
for i in range(n):
k=int(input())
t=1
j=1
num=0
while j<=k:
if j==t:
num-=j
t*=2
else:
num+=j
j+=1
print(num)
``` | 0 | |
290 | E | HQ | PROGRAMMING | 2,500 | [
"*special",
"constructive algorithms"
] | null | null | The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset — a language called HQ... | The only line of the input is a string between 1 and 106 characters long. | Output "Yes" or "No". | [
"HHHH\n",
"HQHQH\n",
"HHQHHQH\n",
"HHQQHHQQHH\n"
] | [
"Yes\n",
"No\n",
"No\n",
"Yes\n"
] | The rest of the problem statement was destroyed by a stray raccoon. We are terribly sorry for the inconvenience. | 0 | [
{
"input": "HHHH",
"output": "Yes"
},
{
"input": "HQHQH",
"output": "No"
},
{
"input": "HHQHHQH",
"output": "No"
},
{
"input": "HHQQHHQQHH",
"output": "Yes"
},
{
"input": "Q",
"output": "Yes"
},
{
"input": "HHHHHHHHHHQHHH",
"output": "No"
},
{
... | 1,678,965,880 | 2,147,483,647 | PyPy 3 | OK | TESTS | 28 | 1,090 | 56,320,000 | a = input()
b = []
h = ''
c = 0
for i in a:
if i == 'Q':
c += 1
if c == 0:
print('Yes')
exit(0)
r = -1
for i in range(1001):
if i*i == c:
r = i
break
if r == -1:
print('No')
exit(0)
h = [a.split('Q')[0], a.split('Q')[-1]]
c = [len(h[0]), len(h[1])]
if c[0] % 2 != 0 or c[1] % 2 != 0:
print('No')
exit(0)
c[0] //= 2
c[1] //= 2
resp = ''
i = c[0]
while True:
if i >= len(a):
break
if r == 0 and a[i] == 'Q':
break
resp += a[i]
if r == 0 and a[i] == 'H':
c[1] -= 1
if c[1] == 0 and r == 0:
break
if a[i] == 'Q':
r -= 1
if r == -1:
print('No')
exit(0)
i += 1
def hq(a):
resp = ''
for i in a:
if i == 'H':
resp += 'H'
else:
resp += a
return resp
if a == hq(resp):
print('Yes')
else:
print('No')
| Title: HQ
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset — a language called HQ...
Input Specification:
The only line of the input is a string between 1 and 106 characters long.
Output Specification:
Output "Yes" or "No".
Demo Input:
['HHHH\n', 'HQHQH\n', 'HHQHHQH\n', 'HHQQHHQQHH\n']
Demo Output:
['Yes\n', 'No\n', 'No\n', 'Yes\n']
Note:
The rest of the problem statement was destroyed by a stray raccoon. We are terribly sorry for the inconvenience. | ```python
a = input()
b = []
h = ''
c = 0
for i in a:
if i == 'Q':
c += 1
if c == 0:
print('Yes')
exit(0)
r = -1
for i in range(1001):
if i*i == c:
r = i
break
if r == -1:
print('No')
exit(0)
h = [a.split('Q')[0], a.split('Q')[-1]]
c = [len(h[0]), len(h[1])]
if c[0] % 2 != 0 or c[1] % 2 != 0:
print('No')
exit(0)
c[0] //= 2
c[1] //= 2
resp = ''
i = c[0]
while True:
if i >= len(a):
break
if r == 0 and a[i] == 'Q':
break
resp += a[i]
if r == 0 and a[i] == 'H':
c[1] -= 1
if c[1] == 0 and r == 0:
break
if a[i] == 'Q':
r -= 1
if r == -1:
print('No')
exit(0)
i += 1
def hq(a):
resp = ''
for i in a:
if i == 'H':
resp += 'H'
else:
resp += a
return resp
if a == hq(resp):
print('Yes')
else:
print('No')
``` | 3 | |
879 | B | Table Tennis | PROGRAMMING | 1,200 | [
"data structures",
"implementation"
] | null | null | *n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner. | The first line contains two integers: *n* and *k* (2<=≤<=*n*<=≤<=500, 2<=≤<=*k*<=≤<=1012) — the number of people and the number of wins.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all *a**i* are distinct. | Output a single integer — power of the winner. | [
"2 2\n1 2\n",
"4 2\n3 1 2 4\n",
"6 2\n6 5 3 1 2 4\n",
"2 10000000000\n2 1\n"
] | [
"2 ",
"3 ",
"6 ",
"2\n"
] | Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 1,000 | [
{
"input": "2 2\n1 2",
"output": "2 "
},
{
"input": "4 2\n3 1 2 4",
"output": "3 "
},
{
"input": "6 2\n6 5 3 1 2 4",
"output": "6 "
},
{
"input": "2 10000000000\n2 1",
"output": "2"
},
{
"input": "4 4\n1 3 4 2",
"output": "4 "
},
{
"input": "2 21474836... | 1,598,121,584 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 32 | 171 | 20,480,000 | from collections import deque
n, k = [int(p) for p in input().split()]
q = deque([int(p) for p in input().split()])
curr = q[0]
count = 0
while k > count:
p1 = q.popleft()
p2 = q.popleft()
win = max(p1, p2)
los = min(p1, p2)
if win == curr:
count += 1
else:
curr = win
count = 0
q.append(los)
q.appendleft(win)
if win == n:
break
print(win)
| Title: Table Tennis
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
*n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input Specification:
The first line contains two integers: *n* and *k* (2<=≤<=*n*<=≤<=500, 2<=≤<=*k*<=≤<=1012) — the number of people and the number of wins.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all *a**i* are distinct.
Output Specification:
Output a single integer — power of the winner.
Demo Input:
['2 2\n1 2\n', '4 2\n3 1 2 4\n', '6 2\n6 5 3 1 2 4\n', '2 10000000000\n2 1\n']
Demo Output:
['2 ', '3 ', '6 ', '2\n']
Note:
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | ```python
from collections import deque
n, k = [int(p) for p in input().split()]
q = deque([int(p) for p in input().split()])
curr = q[0]
count = 0
while k > count:
p1 = q.popleft()
p2 = q.popleft()
win = max(p1, p2)
los = min(p1, p2)
if win == curr:
count += 1
else:
curr = win
count = 0
q.append(los)
q.appendleft(win)
if win == n:
break
print(win)
``` | 0 | |
4 | A | Watermelon | PROGRAMMING | 800 | [
"brute force",
"math"
] | A. Watermelon | 1 | 64 | One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight. | The first (and the only) input line contains integer number *w* (1<=≤<=*w*<=≤<=100) — the weight of the watermelon bought by the boys. | Print YES, if the boys can divide the watermelon into two parts, each of them weighing even number of kilos; and NO in the opposite case. | [
"8\n"
] | [
"YES\n"
] | For example, the boys can divide the watermelon into two parts of 2 and 6 kilos respectively (another variant — two parts of 4 and 4 kilos). | 0 | [
{
"input": "8",
"output": "YES"
},
{
"input": "5",
"output": "NO"
},
{
"input": "4",
"output": "YES"
},
{
"input": "3",
"output": "NO"
},
{
"input": "2",
"output": "NO"
},
{
"input": "1",
"output": "NO"
},
{
"input": "7",
"output": "NO"... | 1,692,065,826 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | def can_divide_watermelon(weight):
ifweight < = 2 or weight % 2 == 1:
return "NO"
else:
return "YES"
W = int(input())
result = can_divide_watermelon(w)
print(result)
#594
| Title: Watermelon
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
Input Specification:
The first (and the only) input line contains integer number *w* (1<=≤<=*w*<=≤<=100) — the weight of the watermelon bought by the boys.
Output Specification:
Print YES, if the boys can divide the watermelon into two parts, each of them weighing even number of kilos; and NO in the opposite case.
Demo Input:
['8\n']
Demo Output:
['YES\n']
Note:
For example, the boys can divide the watermelon into two parts of 2 and 6 kilos respectively (another variant — two parts of 4 and 4 kilos). | ```python
def can_divide_watermelon(weight):
ifweight < = 2 or weight % 2 == 1:
return "NO"
else:
return "YES"
W = int(input())
result = can_divide_watermelon(w)
print(result)
#594
``` | -1 |
282 | A | Bit++ | PROGRAMMING | 800 | [
"implementation"
] | null | null | The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called *x*. Also, there are two operations:
- Operation ++ increases the value of variable *x* by 1. - Operation -- decreases the value of variable *x* by 1.
A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable *x*. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.
A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.
You're given a programme in language Bit++. The initial value of *x* is 0. Execute the programme and find its final value (the value of the variable when this programme is executed). | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=150) — the number of statements in the programme.
Next *n* lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable *x* (denoted as letter «X»). Thus, there are no empty statements. The operation and the variable can be written in any order. | Print a single integer — the final value of *x*. | [
"1\n++X\n",
"2\nX++\n--X\n"
] | [
"1\n",
"0\n"
] | none | 500 | [
{
"input": "1\n++X",
"output": "1"
},
{
"input": "2\nX++\n--X",
"output": "0"
},
{
"input": "3\n++X\n++X\n++X",
"output": "3"
},
{
"input": "2\n--X\n--X",
"output": "-2"
},
{
"input": "5\n++X\n--X\n++X\n--X\n--X",
"output": "-1"
},
{
"input": "28\nX--\... | 1,697,815,642 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 31 | 0 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
n=int(input())
x=0
for i in range(n):
i=str(input())
if i=="++X":
x+=1
elif i=="--X":
x-=1
print(x)
# In[ ]:
| Title: Bit++
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called *x*. Also, there are two operations:
- Operation ++ increases the value of variable *x* by 1. - Operation -- decreases the value of variable *x* by 1.
A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable *x*. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.
A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.
You're given a programme in language Bit++. The initial value of *x* is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=150) — the number of statements in the programme.
Next *n* lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable *x* (denoted as letter «X»). Thus, there are no empty statements. The operation and the variable can be written in any order.
Output Specification:
Print a single integer — the final value of *x*.
Demo Input:
['1\n++X\n', '2\nX++\n--X\n']
Demo Output:
['1\n', '0\n']
Note:
none | ```python
#!/usr/bin/env python
# coding: utf-8
# In[7]:
n=int(input())
x=0
for i in range(n):
i=str(input())
if i=="++X":
x+=1
elif i=="--X":
x-=1
print(x)
# In[ ]:
``` | 0 | |
620 | E | New Year Tree | PROGRAMMING | 2,100 | [
"bitmasks",
"data structures",
"trees"
] | null | null | The New Year holidays are over, but Resha doesn't want to throw away the New Year tree. He invited his best friends Kerim and Gural to help him to redecorate the New Year tree.
The New Year tree is an undirected tree with *n* vertices and root in the vertex 1.
You should process the queries of the two types:
1. Change the colours of all vertices in the subtree of the vertex *v* to the colour *c*. 1. Find the number of different colours in the subtree of the vertex *v*. | The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=4·105) — the number of vertices in the tree and the number of the queries.
The second line contains *n* integers *c**i* (1<=≤<=*c**i*<=≤<=60) — the colour of the *i*-th vertex.
Each of the next *n*<=-<=1 lines contains two integers *x**j*,<=*y**j* (1<=≤<=*x**j*,<=*y**j*<=≤<=*n*) — the vertices of the *j*-th edge. It is guaranteed that you are given correct undirected tree.
The last *m* lines contains the description of the queries. Each description starts with the integer *t**k* (1<=≤<=*t**k*<=≤<=2) — the type of the *k*-th query. For the queries of the first type then follows two integers *v**k*,<=*c**k* (1<=≤<=*v**k*<=≤<=*n*,<=1<=≤<=*c**k*<=≤<=60) — the number of the vertex whose subtree will be recoloured with the colour *c**k*. For the queries of the second type then follows integer *v**k* (1<=≤<=*v**k*<=≤<=*n*) — the number of the vertex for which subtree you should find the number of different colours. | For each query of the second type print the integer *a* — the number of different colours in the subtree of the vertex given in the query.
Each of the numbers should be printed on a separate line in order of query appearing in the input. | [
"7 10\n1 1 1 1 1 1 1\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n1 3 2\n2 1\n1 4 3\n2 1\n1 2 5\n2 1\n1 6 4\n2 1\n2 2\n2 3\n",
"23 30\n1 2 2 6 5 3 2 1 1 1 2 4 5 3 4 4 3 3 3 3 3 4 6\n1 2\n1 3\n1 4\n2 5\n2 6\n3 7\n3 8\n4 9\n4 10\n4 11\n6 12\n6 13\n7 14\n7 15\n7 16\n8 17\n8 18\n10 19\n10 20\n10 21\n11 22\n11 23\n2 1\n2 5\n2 6\n2 ... | [
"2\n3\n4\n5\n1\n2\n",
"6\n1\n3\n3\n2\n1\n2\n3\n5\n5\n1\n2\n2\n1\n1\n1\n2\n3\n"
] | none | 0 | [
{
"input": "7 10\n1 1 1 1 1 1 1\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n1 3 2\n2 1\n1 4 3\n2 1\n1 2 5\n2 1\n1 6 4\n2 1\n2 2\n2 3",
"output": "2\n3\n4\n5\n1\n2"
},
{
"input": "23 30\n1 2 2 6 5 3 2 1 1 1 2 4 5 3 4 4 3 3 3 3 3 4 6\n1 2\n1 3\n1 4\n2 5\n2 6\n3 7\n3 8\n4 9\n4 10\n4 11\n6 12\n6 13\n7 14\n7 15\n7 16... | 1,633,116,851 | 2,147,483,647 | PyPy 3 | MEMORY_LIMIT_EXCEEDED | TESTS | 0 | 61 | 268,390,400 | import sys
input = sys.stdin.readline
sys.setrecursionlimit(400005)
def dfs(node,prev):
s[node]=t[0]
l[t[0]]=arr[node-1]
for child in tree[node]:
if child!=prev:
t[0]=t[0]+1
dfs(child,node)
e[node]=t[0]
def update(node,start,end,l,r,val,p):
if updt[node][0]!=0:
segt[node]=updt[node][0]
if start!=end:
if updt[2*node][1]<updt[node][1]:
updt[2*node][0]=updt[node][0]
updt[2*node][1]=updt[node][1]
if updt[2*node+1][1]<updt[node][1]:
updt[2*node+1][0]=updt[node][0]
updt[2*node+1][1]=updt[node][1]
updt[node][0]=0
updt[node][1]=0
if start>r or end<l:
return
if start>=l and end<=r:
segt[node]=val
if start!=end:
updt[2*node][0]=val
updt[2*node][1]=p
updt[2*node+1][0]=val
updt[2*node+1][1]=p
return
mid=(start+end)//2
left=2*node
right=left+1
update(left,start,mid,l,r,val,p)
update(right,mid+1,end,l,r,val,p)
segt[node]=segt[2*node] | segt[2*node+1]
def query(node,start,end,l,r):
if updt[node][0]!=0:
segt[node]=updt[node][0]
if start!=end:
if updt[2*node][1]<updt[node][1]:
updt[2*node][0]=updt[node][0]
updt[2*node][1]=updt[node][1]
if updt[2*node+1][1]<updt[node][1]:
updt[2*node+1][0]=updt[node][0]
updt[2*node+1][1]=updt[node][1]
updt[node][0]=0
updt[node][1]=0
if start>r or end<l:
return 0
if start>=l and end<=r:
return segt[node]
mid=(start+end)//2
left=2*node
right=left+1
return query(left,start,mid,l,r) | query(right,mid+1,end,l,r)
n,m=map(int,input().split())
arr=[int(x) for x in input().split()]
tree=[[] for i in range(n+1)]
for i in range(n-1):
u,v=map(int,input().split())
tree[u].append(v)
tree[v].append(u)
# print(tree)
s=[0]*(n+1)
e=[0]*(n+1)
l=[0]*(n+1)
t=[1]
dfs(1,0)
# print(s)
# print(e)
# print(l)
segt=[0]*(4*n)
updt=[[0,0] for i in range(4*n)]
p=1
for i in range(n):
update(1,1,n,i+1,i+1,1<<l[i+1],p)
p=p+1
for i in range(m):
q=[int(x) for x in input().split()]
if q[0]==1:
update(1,1,n,s[q[1]],e[q[1]],1<<q[2],p)
p=p+1
else:
x=query(1,1,n,s[q[1]],e[q[1]])
print(bin(x).count("1"))
| Title: New Year Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The New Year holidays are over, but Resha doesn't want to throw away the New Year tree. He invited his best friends Kerim and Gural to help him to redecorate the New Year tree.
The New Year tree is an undirected tree with *n* vertices and root in the vertex 1.
You should process the queries of the two types:
1. Change the colours of all vertices in the subtree of the vertex *v* to the colour *c*. 1. Find the number of different colours in the subtree of the vertex *v*.
Input Specification:
The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=4·105) — the number of vertices in the tree and the number of the queries.
The second line contains *n* integers *c**i* (1<=≤<=*c**i*<=≤<=60) — the colour of the *i*-th vertex.
Each of the next *n*<=-<=1 lines contains two integers *x**j*,<=*y**j* (1<=≤<=*x**j*,<=*y**j*<=≤<=*n*) — the vertices of the *j*-th edge. It is guaranteed that you are given correct undirected tree.
The last *m* lines contains the description of the queries. Each description starts with the integer *t**k* (1<=≤<=*t**k*<=≤<=2) — the type of the *k*-th query. For the queries of the first type then follows two integers *v**k*,<=*c**k* (1<=≤<=*v**k*<=≤<=*n*,<=1<=≤<=*c**k*<=≤<=60) — the number of the vertex whose subtree will be recoloured with the colour *c**k*. For the queries of the second type then follows integer *v**k* (1<=≤<=*v**k*<=≤<=*n*) — the number of the vertex for which subtree you should find the number of different colours.
Output Specification:
For each query of the second type print the integer *a* — the number of different colours in the subtree of the vertex given in the query.
Each of the numbers should be printed on a separate line in order of query appearing in the input.
Demo Input:
['7 10\n1 1 1 1 1 1 1\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n1 3 2\n2 1\n1 4 3\n2 1\n1 2 5\n2 1\n1 6 4\n2 1\n2 2\n2 3\n', '23 30\n1 2 2 6 5 3 2 1 1 1 2 4 5 3 4 4 3 3 3 3 3 4 6\n1 2\n1 3\n1 4\n2 5\n2 6\n3 7\n3 8\n4 9\n4 10\n4 11\n6 12\n6 13\n7 14\n7 15\n7 16\n8 17\n8 18\n10 19\n10 20\n10 21\n11 22\n11 23\n2 1\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n2 11\n2 4\n1 12 1\n1 13 1\n1 14 1\n1 15 1\n1 16 1\n1 17 1\n1 18 1\n1 19 1\n1 20 1\n1 21 1\n1 22 1\n1 23 1\n2 1\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n2 11\n2 4\n']
Demo Output:
['2\n3\n4\n5\n1\n2\n', '6\n1\n3\n3\n2\n1\n2\n3\n5\n5\n1\n2\n2\n1\n1\n1\n2\n3\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
sys.setrecursionlimit(400005)
def dfs(node,prev):
s[node]=t[0]
l[t[0]]=arr[node-1]
for child in tree[node]:
if child!=prev:
t[0]=t[0]+1
dfs(child,node)
e[node]=t[0]
def update(node,start,end,l,r,val,p):
if updt[node][0]!=0:
segt[node]=updt[node][0]
if start!=end:
if updt[2*node][1]<updt[node][1]:
updt[2*node][0]=updt[node][0]
updt[2*node][1]=updt[node][1]
if updt[2*node+1][1]<updt[node][1]:
updt[2*node+1][0]=updt[node][0]
updt[2*node+1][1]=updt[node][1]
updt[node][0]=0
updt[node][1]=0
if start>r or end<l:
return
if start>=l and end<=r:
segt[node]=val
if start!=end:
updt[2*node][0]=val
updt[2*node][1]=p
updt[2*node+1][0]=val
updt[2*node+1][1]=p
return
mid=(start+end)//2
left=2*node
right=left+1
update(left,start,mid,l,r,val,p)
update(right,mid+1,end,l,r,val,p)
segt[node]=segt[2*node] | segt[2*node+1]
def query(node,start,end,l,r):
if updt[node][0]!=0:
segt[node]=updt[node][0]
if start!=end:
if updt[2*node][1]<updt[node][1]:
updt[2*node][0]=updt[node][0]
updt[2*node][1]=updt[node][1]
if updt[2*node+1][1]<updt[node][1]:
updt[2*node+1][0]=updt[node][0]
updt[2*node+1][1]=updt[node][1]
updt[node][0]=0
updt[node][1]=0
if start>r or end<l:
return 0
if start>=l and end<=r:
return segt[node]
mid=(start+end)//2
left=2*node
right=left+1
return query(left,start,mid,l,r) | query(right,mid+1,end,l,r)
n,m=map(int,input().split())
arr=[int(x) for x in input().split()]
tree=[[] for i in range(n+1)]
for i in range(n-1):
u,v=map(int,input().split())
tree[u].append(v)
tree[v].append(u)
# print(tree)
s=[0]*(n+1)
e=[0]*(n+1)
l=[0]*(n+1)
t=[1]
dfs(1,0)
# print(s)
# print(e)
# print(l)
segt=[0]*(4*n)
updt=[[0,0] for i in range(4*n)]
p=1
for i in range(n):
update(1,1,n,i+1,i+1,1<<l[i+1],p)
p=p+1
for i in range(m):
q=[int(x) for x in input().split()]
if q[0]==1:
update(1,1,n,s[q[1]],e[q[1]],1<<q[2],p)
p=p+1
else:
x=query(1,1,n,s[q[1]],e[q[1]])
print(bin(x).count("1"))
``` | 0 | |
377 | A | Maze | PROGRAMMING | 1,600 | [
"dfs and similar"
] | null | null | Pavel loves grid mazes. A grid maze is an *n*<=×<=*m* rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly *k* empty cells into walls so that all the remaining cells still formed a connected area. Help him. | The first line contains three integers *n*, *m*, *k* (1<=≤<=*n*,<=*m*<=≤<=500, 0<=≤<=*k*<=<<=*s*), where *n* and *m* are the maze's height and width, correspondingly, *k* is the number of walls Pavel wants to add and letter *s* represents the number of empty cells in the original maze.
Each of the next *n* lines contains *m* characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall. | Print *n* lines containing *m* characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them. | [
"3 4 2\n#..#\n..#.\n#...\n",
"5 4 5\n#...\n#.#.\n.#..\n...#\n.#.#\n"
] | [
"#.X#\nX.#.\n#...\n",
"#XXX\n#X#.\nX#..\n...#\n.#.#\n"
] | none | 500 | [
{
"input": "5 4 5\n#...\n#.#.\n.#..\n...#\n.#.#",
"output": "#XXX\n#X#.\nX#..\n...#\n.#.#"
},
{
"input": "3 3 2\n#.#\n...\n#.#",
"output": "#X#\nX..\n#.#"
},
{
"input": "7 7 18\n#.....#\n..#.#..\n.#...#.\n...#...\n.#...#.\n..#.#..\n#.....#",
"output": "#XXXXX#\nXX#X#X.\nX#XXX#.\nXXX#... | 1,677,699,666 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | import java.util.Arrays;
import java.util.Scanner;
public class Maze {
private static int[] dirX = {1, 0, -1, 0};
private static int[] dirY = {0, 1, 0, -1, 0};
static int dots;
static int lvlDfs;
static int n, m, s;
static String[][] maze;
static boolean[][] visited;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] lineOne = sc.nextLine().split(" ");
n = Integer.parseInt(lineOne[0]);
m = Integer.parseInt(lineOne[1]);
s = Integer.parseInt(lineOne[2]);
maze = new String[n][];
visited = new boolean[n][m];
// System.out.println("boolean val " + Arrays.toString(visited[0]));
for(int i =0; i < n; i++){
maze[i] = sc.nextLine().split("");
// System.out.println(Arrays.toString(maze[i]));
for (String cell : maze[i]){
dots += cell.equals(".") ? 1 : 0;
}
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
if (maze[i][j].equals("."))
{
dfs(i, j);
i = n;
break;
}
}
}
for (int i = 0; i < n && s > 0; ++i)
{
for (int j = 0; j < m && s > 0; ++j)
{
if (maze[i][j].equals(".") && !visited[i][j])
{
--s;
maze[i][j] = "X";
}
}
}
for (int i = 0; i < n; ++i){
for (String cell : maze[i]){
System.out.print(cell);
}
System.out.println();
}
sc.close();
}
static void dfs(int i, int j){
lvlDfs++;
visited[i][j] = true;
for (int m = 0; m < 4 && lvlDfs < dots - s; ++m)
{
int x = i + dirX[m];
int y = j + dirY[m];
if (x >= 0 && x < n && y >= 0 && y < m && (maze[x][y]).equals(".") && !visited[x][y]){
dfs(x, y);
}
}
}
}
| Title: Maze
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Pavel loves grid mazes. A grid maze is an *n*<=×<=*m* rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly *k* empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input Specification:
The first line contains three integers *n*, *m*, *k* (1<=≤<=*n*,<=*m*<=≤<=500, 0<=≤<=*k*<=<<=*s*), where *n* and *m* are the maze's height and width, correspondingly, *k* is the number of walls Pavel wants to add and letter *s* represents the number of empty cells in the original maze.
Each of the next *n* lines contains *m* characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output Specification:
Print *n* lines containing *m* characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Demo Input:
['3 4 2\n#..#\n..#.\n#...\n', '5 4 5\n#...\n#.#.\n.#..\n...#\n.#.#\n']
Demo Output:
['#.X#\nX.#.\n#...\n', '#XXX\n#X#.\nX#..\n...#\n.#.#\n']
Note:
none | ```python
import java.util.Arrays;
import java.util.Scanner;
public class Maze {
private static int[] dirX = {1, 0, -1, 0};
private static int[] dirY = {0, 1, 0, -1, 0};
static int dots;
static int lvlDfs;
static int n, m, s;
static String[][] maze;
static boolean[][] visited;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] lineOne = sc.nextLine().split(" ");
n = Integer.parseInt(lineOne[0]);
m = Integer.parseInt(lineOne[1]);
s = Integer.parseInt(lineOne[2]);
maze = new String[n][];
visited = new boolean[n][m];
// System.out.println("boolean val " + Arrays.toString(visited[0]));
for(int i =0; i < n; i++){
maze[i] = sc.nextLine().split("");
// System.out.println(Arrays.toString(maze[i]));
for (String cell : maze[i]){
dots += cell.equals(".") ? 1 : 0;
}
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
if (maze[i][j].equals("."))
{
dfs(i, j);
i = n;
break;
}
}
}
for (int i = 0; i < n && s > 0; ++i)
{
for (int j = 0; j < m && s > 0; ++j)
{
if (maze[i][j].equals(".") && !visited[i][j])
{
--s;
maze[i][j] = "X";
}
}
}
for (int i = 0; i < n; ++i){
for (String cell : maze[i]){
System.out.print(cell);
}
System.out.println();
}
sc.close();
}
static void dfs(int i, int j){
lvlDfs++;
visited[i][j] = true;
for (int m = 0; m < 4 && lvlDfs < dots - s; ++m)
{
int x = i + dirX[m];
int y = j + dirY[m];
if (x >= 0 && x < n && y >= 0 && y < m && (maze[x][y]).equals(".") && !visited[x][y]){
dfs(x, y);
}
}
}
}
``` | -1 | |
58 | A | Chat room | PROGRAMMING | 1,000 | [
"greedy",
"strings"
] | A. Chat room | 1 | 256 | Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*. | The first and only line contains the word *s*, which Vasya typed. This word consisits of small Latin letters, its length is no less that 1 and no more than 100 letters. | If Vasya managed to say hello, print "YES", otherwise print "NO". | [
"ahhellllloou\n",
"hlelo\n"
] | [
"YES\n",
"NO\n"
] | none | 500 | [
{
"input": "ahhellllloou",
"output": "YES"
},
{
"input": "hlelo",
"output": "NO"
},
{
"input": "helhcludoo",
"output": "YES"
},
{
"input": "hehwelloho",
"output": "YES"
},
{
"input": "pnnepelqomhhheollvlo",
"output": "YES"
},
{
"input": "tymbzjyqhymeda... | 1,662,791,238 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 4 | 46 | 0 | s=input()
a=[]
sol="helo"
for i in s:
if(i=="h" or i=="e" or i=="l" or i=="o"):
if(i not in a):
a.append(i)
ss="".join(a)
if(ss==sol):
print("YES")
else:
print("NO") | Title: Chat room
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
Input Specification:
The first and only line contains the word *s*, which Vasya typed. This word consisits of small Latin letters, its length is no less that 1 and no more than 100 letters.
Output Specification:
If Vasya managed to say hello, print "YES", otherwise print "NO".
Demo Input:
['ahhellllloou\n', 'hlelo\n']
Demo Output:
['YES\n', 'NO\n']
Note:
none | ```python
s=input()
a=[]
sol="helo"
for i in s:
if(i=="h" or i=="e" or i=="l" or i=="o"):
if(i not in a):
a.append(i)
ss="".join(a)
if(ss==sol):
print("YES")
else:
print("NO")
``` | 0 |
237 | C | Primes on Interval | PROGRAMMING | 1,600 | [
"binary search",
"number theory",
"two pointers"
] | null | null | You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors.
Consider positive integers *a*, *a*<=+<=1, ..., *b* (*a*<=≤<=*b*). You want to find the minimum integer *l* (1<=≤<=*l*<=≤<=*b*<=-<=*a*<=+<=1) such that for any integer *x* (*a*<=≤<=*x*<=≤<=*b*<=-<=*l*<=+<=1) among *l* integers *x*, *x*<=+<=1, ..., *x*<=+<=*l*<=-<=1 there are at least *k* prime numbers.
Find and print the required minimum *l*. If no value *l* meets the described limitations, print -1. | A single line contains three space-separated integers *a*,<=*b*,<=*k* (1<=≤<=*a*,<=*b*,<=*k*<=≤<=106; *a*<=≤<=*b*). | In a single line print a single integer — the required minimum *l*. If there's no solution, print -1. | [
"2 4 2\n",
"6 13 1\n",
"1 4 3\n"
] | [
"3\n",
"4\n",
"-1\n"
] | none | 1,500 | [
{
"input": "2 4 2",
"output": "3"
},
{
"input": "6 13 1",
"output": "4"
},
{
"input": "1 4 3",
"output": "-1"
},
{
"input": "5 8 2",
"output": "4"
},
{
"input": "8 10 3",
"output": "-1"
},
{
"input": "1 5 2",
"output": "3"
},
{
"input": "6 ... | 1,685,452,305 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 4 | 342 | 48,332,800 | from bisect import bisect_left, bisect_right
from collections import Counter, deque
from functools import lru_cache
from math import factorial, comb, sqrt, gcd, lcm, log2
from copy import deepcopy
import heapq
from sys import stdin, stdout
input = stdin.readline
def find_prime(n):
# 线性筛法
prime = [] # 存储结果
L = [True] * (n + 1)
for i in range(2, len(L)):
if L[i] is True:
# 若 i 为质数,则加入质数结果
prime.append(i)
for j in range(len(prime)):
if i * prime[j] > n:
# 如果筛选的范围超过 n 就退出
break
# 将 i 与 i 之前的所有质数相乘,
# 得出的这些数一定合数,筛去
L[i * prime[j]] = False
if i % prime[j] == 0:
# 线性筛的核心在于每个合数只被其最小的质因数筛去
# 如果 prime[j] 是 i 的质因数
# 则对于之后的质数与 i 相乘时,其最小质因数为 prime[j]
break
return prime
def main():
a, b, k = map(int, input().split())
L = [0] + find_prime(2 * 10**6)
n = len(L)
left_index = 0
right_index = n - 1
while left_index < right_index:
middle = (left_index + right_index + 1) // 2
if L[middle] < left_index:
left_index = middle
else:
right_index = middle - 1
start = left_index + 1
if n - start < k or L[start + k - 1] - a > b - a:
print(-1)
return
def check(flag):
i = start
while L[i - 1] <= b - flag + 1:
if n - i < k or L[i + k - 1] - max(L[i - 1] + 1, a) > flag - 1:
return False
i += 1
return True
left = 1
right = b - a + 1
while left < right:
middle = (left + right) // 2
if check(middle) is True:
right = middle
else:
left = middle + 1
print(left)
if __name__ == "__main__":
main()
| Title: Primes on Interval
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors.
Consider positive integers *a*, *a*<=+<=1, ..., *b* (*a*<=≤<=*b*). You want to find the minimum integer *l* (1<=≤<=*l*<=≤<=*b*<=-<=*a*<=+<=1) such that for any integer *x* (*a*<=≤<=*x*<=≤<=*b*<=-<=*l*<=+<=1) among *l* integers *x*, *x*<=+<=1, ..., *x*<=+<=*l*<=-<=1 there are at least *k* prime numbers.
Find and print the required minimum *l*. If no value *l* meets the described limitations, print -1.
Input Specification:
A single line contains three space-separated integers *a*,<=*b*,<=*k* (1<=≤<=*a*,<=*b*,<=*k*<=≤<=106; *a*<=≤<=*b*).
Output Specification:
In a single line print a single integer — the required minimum *l*. If there's no solution, print -1.
Demo Input:
['2 4 2\n', '6 13 1\n', '1 4 3\n']
Demo Output:
['3\n', '4\n', '-1\n']
Note:
none | ```python
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from functools import lru_cache
from math import factorial, comb, sqrt, gcd, lcm, log2
from copy import deepcopy
import heapq
from sys import stdin, stdout
input = stdin.readline
def find_prime(n):
# 线性筛法
prime = [] # 存储结果
L = [True] * (n + 1)
for i in range(2, len(L)):
if L[i] is True:
# 若 i 为质数,则加入质数结果
prime.append(i)
for j in range(len(prime)):
if i * prime[j] > n:
# 如果筛选的范围超过 n 就退出
break
# 将 i 与 i 之前的所有质数相乘,
# 得出的这些数一定合数,筛去
L[i * prime[j]] = False
if i % prime[j] == 0:
# 线性筛的核心在于每个合数只被其最小的质因数筛去
# 如果 prime[j] 是 i 的质因数
# 则对于之后的质数与 i 相乘时,其最小质因数为 prime[j]
break
return prime
def main():
a, b, k = map(int, input().split())
L = [0] + find_prime(2 * 10**6)
n = len(L)
left_index = 0
right_index = n - 1
while left_index < right_index:
middle = (left_index + right_index + 1) // 2
if L[middle] < left_index:
left_index = middle
else:
right_index = middle - 1
start = left_index + 1
if n - start < k or L[start + k - 1] - a > b - a:
print(-1)
return
def check(flag):
i = start
while L[i - 1] <= b - flag + 1:
if n - i < k or L[i + k - 1] - max(L[i - 1] + 1, a) > flag - 1:
return False
i += 1
return True
left = 1
right = b - a + 1
while left < right:
middle = (left + right) // 2
if check(middle) is True:
right = middle
else:
left = middle + 1
print(left)
if __name__ == "__main__":
main()
``` | 0 | |
991 | C | Candies | PROGRAMMING | 1,500 | [
"binary search",
"implementation"
] | null | null | After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.
This means the process of eating candies is the following: in the beginning Vasya chooses a single integer $k$, same for all days. After that, in the morning he eats $k$ candies from the box (if there are less than $k$ candies in the box, he eats them all), then in the evening Petya eats $10\%$ of the candies remaining in the box. If there are still candies left in the box, the process repeats — next day Vasya eats $k$ candies again, and Petya — $10\%$ of the candies left in a box, and so on.
If the amount of candies in the box is not divisible by $10$, Petya rounds the amount he takes from the box down. For example, if there were $97$ candies in the box, Petya would eat only $9$ of them. In particular, if there are less than $10$ candies in a box, Petya won't eat any at all.
Your task is to find out the minimal amount of $k$ that can be chosen by Vasya so that he would eat at least half of the $n$ candies he initially got. Note that the number $k$ must be integer. | The first line contains a single integer $n$ ($1 \leq n \leq 10^{18}$) — the initial amount of candies in the box. | Output a single integer — the minimal amount of $k$ that would allow Vasya to eat at least half of candies he got. | [
"68\n"
] | [
"3\n"
] | In the sample, the amount of candies, with $k=3$, would change in the following way (Vasya eats first):
$68 \to 65 \to 59 \to 56 \to 51 \to 48 \to 44 \to 41 \\ \to 37 \to 34 \to 31 \to 28 \to 26 \to 23 \to 21 \to 18 \to 17 \to 14 \\ \to 13 \to 10 \to 9 \to 6 \to 6 \to 3 \to 3 \to 0$.
In total, Vasya would eat $39$ candies, while Petya — $29$. | 1,250 | [
{
"input": "68",
"output": "3"
},
{
"input": "1",
"output": "1"
},
{
"input": "2",
"output": "1"
},
{
"input": "42",
"output": "1"
},
{
"input": "43",
"output": "2"
},
{
"input": "756",
"output": "29"
},
{
"input": "999999972",
"output"... | 1,602,216,887 | 2,147,483,647 | Python 3 | OK | TESTS | 69 | 109 | 307,200 | def f(n, k):
vasya = 0
total = n
while n > 0:
m = min(k, n)
n -= m
vasya += m
n -= (n // 10)
if 2 * vasya >= total:
return True
else:
return False
n = int(input())
lo = 1
hi = n
while lo < hi:
mid = (lo + hi) // 2
if f(n, mid):
hi = mid
else:
lo = mid + 1
print(hi)
| Title: Candies
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.
This means the process of eating candies is the following: in the beginning Vasya chooses a single integer $k$, same for all days. After that, in the morning he eats $k$ candies from the box (if there are less than $k$ candies in the box, he eats them all), then in the evening Petya eats $10\%$ of the candies remaining in the box. If there are still candies left in the box, the process repeats — next day Vasya eats $k$ candies again, and Petya — $10\%$ of the candies left in a box, and so on.
If the amount of candies in the box is not divisible by $10$, Petya rounds the amount he takes from the box down. For example, if there were $97$ candies in the box, Petya would eat only $9$ of them. In particular, if there are less than $10$ candies in a box, Petya won't eat any at all.
Your task is to find out the minimal amount of $k$ that can be chosen by Vasya so that he would eat at least half of the $n$ candies he initially got. Note that the number $k$ must be integer.
Input Specification:
The first line contains a single integer $n$ ($1 \leq n \leq 10^{18}$) — the initial amount of candies in the box.
Output Specification:
Output a single integer — the minimal amount of $k$ that would allow Vasya to eat at least half of candies he got.
Demo Input:
['68\n']
Demo Output:
['3\n']
Note:
In the sample, the amount of candies, with $k=3$, would change in the following way (Vasya eats first):
$68 \to 65 \to 59 \to 56 \to 51 \to 48 \to 44 \to 41 \\ \to 37 \to 34 \to 31 \to 28 \to 26 \to 23 \to 21 \to 18 \to 17 \to 14 \\ \to 13 \to 10 \to 9 \to 6 \to 6 \to 3 \to 3 \to 0$.
In total, Vasya would eat $39$ candies, while Petya — $29$. | ```python
def f(n, k):
vasya = 0
total = n
while n > 0:
m = min(k, n)
n -= m
vasya += m
n -= (n // 10)
if 2 * vasya >= total:
return True
else:
return False
n = int(input())
lo = 1
hi = n
while lo < hi:
mid = (lo + hi) // 2
if f(n, mid):
hi = mid
else:
lo = mid + 1
print(hi)
``` | 3 | |
334 | B | Eight Point Sets | PROGRAMMING | 1,400 | [
"sortings"
] | null | null | Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three integers *x*1,<=*x*2,<=*x*3 and three more integers *y*1,<=*y*2,<=*y*3, such that *x*1<=<<=*x*2<=<<=*x*3, *y*1<=<<=*y*2<=<<=*y*3 and the eight point set consists of all points (*x**i*,<=*y**j*) (1<=≤<=*i*,<=*j*<=≤<=3), except for point (*x*2,<=*y*2).
You have a set of eight points. Find out if Gerald can use this set? | The input consists of eight lines, the *i*-th line contains two space-separated integers *x**i* and *y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=106). You do not have any other conditions for these points. | In a single line print word "respectable", if the given set of points corresponds to Gerald's decency rules, and "ugly" otherwise. | [
"0 0\n0 1\n0 2\n1 0\n1 2\n2 0\n2 1\n2 2\n",
"0 0\n1 0\n2 0\n3 0\n4 0\n5 0\n6 0\n7 0\n",
"1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n"
] | [
"respectable\n",
"ugly\n",
"ugly\n"
] | none | 1,000 | [
{
"input": "0 0\n0 1\n0 2\n1 0\n1 2\n2 0\n2 1\n2 2",
"output": "respectable"
},
{
"input": "0 0\n1 0\n2 0\n3 0\n4 0\n5 0\n6 0\n7 0",
"output": "ugly"
},
{
"input": "1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2",
"output": "ugly"
},
{
"input": "0 0\n0 0\n0 0\n0 0\n0 0\n0 0\n0 0\n0 0... | 1,375,123,519 | 2,147,483,647 | Python 3 | OK | TESTS | 45 | 248 | 0 | import sys
fin = sys.stdin
points = []
for i in range(8):
x, y = map(int, fin.readline().split())
points += [(x, y)]
def CheckPoints(p):
if not p[0][0] == p[1][0] == p[2][0]:
return False
x1 = p[0][0]
if not p[3][0] == p[4][0]:
return False
x2 = p[3][0]
if not p[5][0] == p[6][0] == p[7][0]:
return False
x3 = p[5][0]
if not p[0][1] == p[3][1] == p[5][1]:
return False
y1 = p[0][1]
if not p[1][1] == p[6][1]:
return False
y2 = p[1][1]
if not p[2][1] == p[4][1] == p[7][1]:
return False
y3 = p[2][1]
return x1 < x2 < x3 and y1 < y2 < y3
from itertools import *
for p in permutations(points):
if CheckPoints(p):
print("respectable")
break
else:
print("ugly")
| Title: Eight Point Sets
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three integers *x*1,<=*x*2,<=*x*3 and three more integers *y*1,<=*y*2,<=*y*3, such that *x*1<=<<=*x*2<=<<=*x*3, *y*1<=<<=*y*2<=<<=*y*3 and the eight point set consists of all points (*x**i*,<=*y**j*) (1<=≤<=*i*,<=*j*<=≤<=3), except for point (*x*2,<=*y*2).
You have a set of eight points. Find out if Gerald can use this set?
Input Specification:
The input consists of eight lines, the *i*-th line contains two space-separated integers *x**i* and *y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=106). You do not have any other conditions for these points.
Output Specification:
In a single line print word "respectable", if the given set of points corresponds to Gerald's decency rules, and "ugly" otherwise.
Demo Input:
['0 0\n0 1\n0 2\n1 0\n1 2\n2 0\n2 1\n2 2\n', '0 0\n1 0\n2 0\n3 0\n4 0\n5 0\n6 0\n7 0\n', '1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n']
Demo Output:
['respectable\n', 'ugly\n', 'ugly\n']
Note:
none | ```python
import sys
fin = sys.stdin
points = []
for i in range(8):
x, y = map(int, fin.readline().split())
points += [(x, y)]
def CheckPoints(p):
if not p[0][0] == p[1][0] == p[2][0]:
return False
x1 = p[0][0]
if not p[3][0] == p[4][0]:
return False
x2 = p[3][0]
if not p[5][0] == p[6][0] == p[7][0]:
return False
x3 = p[5][0]
if not p[0][1] == p[3][1] == p[5][1]:
return False
y1 = p[0][1]
if not p[1][1] == p[6][1]:
return False
y2 = p[1][1]
if not p[2][1] == p[4][1] == p[7][1]:
return False
y3 = p[2][1]
return x1 < x2 < x3 and y1 < y2 < y3
from itertools import *
for p in permutations(points):
if CheckPoints(p):
print("respectable")
break
else:
print("ugly")
``` | 3 | |
501 | C | Misha and Forest | PROGRAMMING | 1,500 | [
"constructive algorithms",
"data structures",
"greedy",
"sortings",
"trees"
] | null | null | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of *n* vertices. For each vertex *v* from 0 to *n*<=-<=1 he wrote down two integers, *degree**v* and *s**v*, were the first integer is the number of vertices adjacent to vertex *v*, and the second integer is the XOR sum of the numbers of vertices adjacent to *v* (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values *degree**v* and *s**v* left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | The first line contains integer *n* (1<=≤<=*n*<=≤<=216), the number of vertices in the graph.
The *i*-th of the next lines contains numbers *degree**i* and *s**i* (0<=≤<=*degree**i*<=≤<=*n*<=-<=1, 0<=≤<=*s**i*<=<<=216), separated by a space. | In the first line print number *m*, the number of edges of the graph.
Next print *m* lines, each containing two distinct numbers, *a* and *b* (0<=≤<=*a*<=≤<=*n*<=-<=1, 0<=≤<=*b*<=≤<=*n*<=-<=1), corresponding to edge (*a*,<=*b*).
Edges can be printed in any order; vertices of the edge can also be printed in any order. | [
"3\n2 3\n1 0\n1 0\n",
"2\n1 1\n1 0\n"
] | [
"2\n1 0\n2 0\n",
"1\n0 1\n"
] | The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | 1,500 | [
{
"input": "3\n2 3\n1 0\n1 0",
"output": "2\n1 0\n2 0"
},
{
"input": "2\n1 1\n1 0",
"output": "1\n0 1"
},
{
"input": "10\n3 13\n2 6\n1 5\n3 5\n1 3\n2 2\n2 6\n1 6\n1 3\n2 3",
"output": "9\n2 5\n4 3\n7 6\n8 3\n5 0\n6 1\n3 9\n1 0\n9 0"
},
{
"input": "10\n1 2\n1 7\n1 0\n1 8\n0 0\... | 1,558,113,748 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 16 | 1,000 | 5,017,600 | n = int(input())
ds = []
m_double = 0
for i in range(n):
deg, s = list(map(int, input().split()))
ds.append([deg,s])
m_double += deg
m = int(m_double/2)
print(m)
for i in range(m):
for j in range(len(ds)):
if (ds[j][0] == 1):
k = ds[j][1]
print(j, k)
ds[j][0] = 0
ds[k][0] -= 1
ds[k][1] ^= j
break | Title: Misha and Forest
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of *n* vertices. For each vertex *v* from 0 to *n*<=-<=1 he wrote down two integers, *degree**v* and *s**v*, were the first integer is the number of vertices adjacent to vertex *v*, and the second integer is the XOR sum of the numbers of vertices adjacent to *v* (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values *degree**v* and *s**v* left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=216), the number of vertices in the graph.
The *i*-th of the next lines contains numbers *degree**i* and *s**i* (0<=≤<=*degree**i*<=≤<=*n*<=-<=1, 0<=≤<=*s**i*<=<<=216), separated by a space.
Output Specification:
In the first line print number *m*, the number of edges of the graph.
Next print *m* lines, each containing two distinct numbers, *a* and *b* (0<=≤<=*a*<=≤<=*n*<=-<=1, 0<=≤<=*b*<=≤<=*n*<=-<=1), corresponding to edge (*a*,<=*b*).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Demo Input:
['3\n2 3\n1 0\n1 0\n', '2\n1 1\n1 0\n']
Demo Output:
['2\n1 0\n2 0\n', '1\n0 1\n']
Note:
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | ```python
n = int(input())
ds = []
m_double = 0
for i in range(n):
deg, s = list(map(int, input().split()))
ds.append([deg,s])
m_double += deg
m = int(m_double/2)
print(m)
for i in range(m):
for j in range(len(ds)):
if (ds[j][0] == 1):
k = ds[j][1]
print(j, k)
ds[j][0] = 0
ds[k][0] -= 1
ds[k][1] ^= j
break
``` | 0 | |
1,007 | A | Reorder the Array | PROGRAMMING | 1,300 | [
"combinatorics",
"data structures",
"math",
"sortings",
"two pointers"
] | null | null | You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20>10$, $40>20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case.
Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal. | The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the length of the array.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the elements of the array. | Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array. | [
"7\n10 1 1 1 5 5 3\n",
"5\n1 1 1 1 1\n"
] | [
"4\n",
"0\n"
] | In the first sample, one of the best permutations is $[1, 5, 5, 3, 10, 1, 1]$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.
In the second sample, there is no way to increase any element with a permutation, so the answer is 0. | 500 | [
{
"input": "7\n10 1 1 1 5 5 3",
"output": "4"
},
{
"input": "5\n1 1 1 1 1",
"output": "0"
},
{
"input": "6\n300000000 200000000 300000000 200000000 1000000000 300000000",
"output": "3"
},
{
"input": "10\n1 2 3 4 5 6 7 8 9 10",
"output": "9"
},
{
"input": "1\n1",
... | 1,532,536,752 | 2,147,483,647 | Python 3 | MEMORY_LIMIT_EXCEEDED | TESTS | 3 | 763 | 268,390,400 |
import itertools
n=input()
a =list(map(int, input().split()))
b=list(itertools.permutations(a))
c=0
for i in b:
cnt=0
for j in range(len(a)):
if a[j]<i[j]:
cnt+=1
if cnt>c:
c=cnt
print(c) | Title: Reorder the Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20>10$, $40>20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case.
Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.
Input Specification:
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the length of the array.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the elements of the array.
Output Specification:
Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.
Demo Input:
['7\n10 1 1 1 5 5 3\n', '5\n1 1 1 1 1\n']
Demo Output:
['4\n', '0\n']
Note:
In the first sample, one of the best permutations is $[1, 5, 5, 3, 10, 1, 1]$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.
In the second sample, there is no way to increase any element with a permutation, so the answer is 0. | ```python
import itertools
n=input()
a =list(map(int, input().split()))
b=list(itertools.permutations(a))
c=0
for i in b:
cnt=0
for j in range(len(a)):
if a[j]<i[j]:
cnt+=1
if cnt>c:
c=cnt
print(c)
``` | 0 | |
45 | A | Codecraft III | PROGRAMMING | 900 | [
"implementation"
] | A. Codecraft III | 2 | 256 | Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly *k* months. He looked at the calendar and learned that at the moment is the month number *s*. Vasya immediately got interested in what month Codecraft III will appear. Help him understand that.
All the twelve months in Vasya's calendar are named using their usual English names: January, February, March, April, May, June, July, August, September, October, November, December. | The first input line contains the name of the current month. It is guaranteed that it is a proper English name of one of twelve months. The first letter is uppercase, the rest are lowercase. The second line contains integer *k* (0<=≤<=*k*<=≤<=100) — the number of months left till the appearance of Codecraft III. | Print starting from an uppercase letter the name of the month in which the continuation of Codeforces II will appear. The printed name must be contained in the list January, February, March, April, May, June, July, August, September, October, November, December. | [
"November\n3\n",
"May\n24\n"
] | [
"February\n",
"May\n"
] | none | 0 | [
{
"input": "November\n3",
"output": "February"
},
{
"input": "May\n24",
"output": "May"
},
{
"input": "April\n0",
"output": "April"
},
{
"input": "September\n0",
"output": "September"
},
{
"input": "August\n0",
"output": "August"
},
{
"input": "June\n1... | 1,696,961,901 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 15 | 92 | 0 | monthes = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
current = input()
after = int(input())
ind = monthes.index(current)
if (after + ind) > 12:
print(monthes[(after + ind)%12])
else:
print(monthes[after + ind])
| Title: Codecraft III
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly *k* months. He looked at the calendar and learned that at the moment is the month number *s*. Vasya immediately got interested in what month Codecraft III will appear. Help him understand that.
All the twelve months in Vasya's calendar are named using their usual English names: January, February, March, April, May, June, July, August, September, October, November, December.
Input Specification:
The first input line contains the name of the current month. It is guaranteed that it is a proper English name of one of twelve months. The first letter is uppercase, the rest are lowercase. The second line contains integer *k* (0<=≤<=*k*<=≤<=100) — the number of months left till the appearance of Codecraft III.
Output Specification:
Print starting from an uppercase letter the name of the month in which the continuation of Codeforces II will appear. The printed name must be contained in the list January, February, March, April, May, June, July, August, September, October, November, December.
Demo Input:
['November\n3\n', 'May\n24\n']
Demo Output:
['February\n', 'May\n']
Note:
none | ```python
monthes = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
current = input()
after = int(input())
ind = monthes.index(current)
if (after + ind) > 12:
print(monthes[(after + ind)%12])
else:
print(monthes[after + ind])
``` | -1 |
611 | B | New Year and Old Property | PROGRAMMING | 1,300 | [
"bitmasks",
"brute force",
"implementation"
] | null | null | The year 2015 is almost over.
Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — 201510<==<=111110111112. Note that he doesn't care about the number of zeros in the decimal representation.
Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster?
Assume that all positive integers are always written without leading zeros. | The only line of the input contains two integers *a* and *b* (1<=≤<=*a*<=≤<=*b*<=≤<=1018) — the first year and the last year in Limak's interval respectively. | Print one integer – the number of years Limak will count in his chosen interval. | [
"5 10\n",
"2015 2015\n",
"100 105\n",
"72057594000000000 72057595000000000\n"
] | [
"2\n",
"1\n",
"0\n",
"26\n"
] | In the first sample Limak's interval contains numbers 5<sub class="lower-index">10</sub> = 101<sub class="lower-index">2</sub>, 6<sub class="lower-index">10</sub> = 110<sub class="lower-index">2</sub>, 7<sub class="lower-index">10</sub> = 111<sub class="lower-index">2</sub>, 8<sub class="lower-index">10</sub> = 1000<sub class="lower-index">2</sub>, 9<sub class="lower-index">10</sub> = 1001<sub class="lower-index">2</sub> and 10<sub class="lower-index">10</sub> = 1010<sub class="lower-index">2</sub>. Two of them (101<sub class="lower-index">2</sub> and 110<sub class="lower-index">2</sub>) have the described property. | 750 | [
{
"input": "5 10",
"output": "2"
},
{
"input": "2015 2015",
"output": "1"
},
{
"input": "100 105",
"output": "0"
},
{
"input": "72057594000000000 72057595000000000",
"output": "26"
},
{
"input": "1 100",
"output": "16"
},
{
"input": "100000000000000000... | 1,456,584,020 | 2,147,483,647 | Python 3 | OK | TESTS | 103 | 77 | 0 | a, b = map(int, input().split())
# map works as [f, iterable] gives [f(x) for x in iterable]
print(sum((2 ** i - 1)^ (2 **j) in range(a, b + 1) for i in range(2, 65) for j in range(0, i-1)))
| Title: New Year and Old Property
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The year 2015 is almost over.
Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — 201510<==<=111110111112. Note that he doesn't care about the number of zeros in the decimal representation.
Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster?
Assume that all positive integers are always written without leading zeros.
Input Specification:
The only line of the input contains two integers *a* and *b* (1<=≤<=*a*<=≤<=*b*<=≤<=1018) — the first year and the last year in Limak's interval respectively.
Output Specification:
Print one integer – the number of years Limak will count in his chosen interval.
Demo Input:
['5 10\n', '2015 2015\n', '100 105\n', '72057594000000000 72057595000000000\n']
Demo Output:
['2\n', '1\n', '0\n', '26\n']
Note:
In the first sample Limak's interval contains numbers 5<sub class="lower-index">10</sub> = 101<sub class="lower-index">2</sub>, 6<sub class="lower-index">10</sub> = 110<sub class="lower-index">2</sub>, 7<sub class="lower-index">10</sub> = 111<sub class="lower-index">2</sub>, 8<sub class="lower-index">10</sub> = 1000<sub class="lower-index">2</sub>, 9<sub class="lower-index">10</sub> = 1001<sub class="lower-index">2</sub> and 10<sub class="lower-index">10</sub> = 1010<sub class="lower-index">2</sub>. Two of them (101<sub class="lower-index">2</sub> and 110<sub class="lower-index">2</sub>) have the described property. | ```python
a, b = map(int, input().split())
# map works as [f, iterable] gives [f(x) for x in iterable]
print(sum((2 ** i - 1)^ (2 **j) in range(a, b + 1) for i in range(2, 65) for j in range(0, i-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,689,588,483 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 92 | 0 | n=input()
up=0
low=0
for i in n:
if(i.islower()):
low+=1
elif(i.isupper()):
up+=1
if(low==up or low>up):
s=n.lower()
print(s)
else:
s=n.upper()
print(s)
| Title: Word
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
Input Specification:
The first line contains a word *s* — it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100.
Output Specification:
Print the corrected word *s*. If the given word *s* has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one.
Demo Input:
['HoUse\n', 'ViP\n', 'maTRIx\n']
Demo Output:
['house\n', 'VIP\n', 'matrix\n']
Note:
none | ```python
n=input()
up=0
low=0
for i in n:
if(i.islower()):
low+=1
elif(i.isupper()):
up+=1
if(low==up or low>up):
s=n.lower()
print(s)
else:
s=n.upper()
print(s)
``` | 3.977 |
26 | A | Almost Prime | PROGRAMMING | 900 | [
"number theory"
] | A. Almost Prime | 2 | 256 | A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and *n*, inclusive. | Input contains one integer number *n* (1<=≤<=*n*<=≤<=3000). | Output the amount of almost prime numbers between 1 and *n*, inclusive. | [
"10\n",
"21\n"
] | [
"2\n",
"8\n"
] | none | 500 | [
{
"input": "10",
"output": "2"
},
{
"input": "21",
"output": "8"
},
{
"input": "1",
"output": "0"
},
{
"input": "2",
"output": "0"
},
{
"input": "4",
"output": "0"
},
{
"input": "3",
"output": "0"
},
{
"input": "8",
"output": "1"
},
... | 1,528,647,860 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 8 | 154 | 0 | limit = int(input())
mark = [0]*(limit+1)
c = 0
for i in range(4,limit+1,2):
mark[i]+=1
for i in range(3,limit+1,2):
if(not mark[i]):
for j in range(2*i,limit+1,i):
mark[j]+=1
if mark[j] == 2:
c+=1
print(c) | Title: Almost Prime
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and *n*, inclusive.
Input Specification:
Input contains one integer number *n* (1<=≤<=*n*<=≤<=3000).
Output Specification:
Output the amount of almost prime numbers between 1 and *n*, inclusive.
Demo Input:
['10\n', '21\n']
Demo Output:
['2\n', '8\n']
Note:
none | ```python
limit = int(input())
mark = [0]*(limit+1)
c = 0
for i in range(4,limit+1,2):
mark[i]+=1
for i in range(3,limit+1,2):
if(not mark[i]):
for j in range(2*i,limit+1,i):
mark[j]+=1
if mark[j] == 2:
c+=1
print(c)
``` | 0 |
172 | A | Phone Code | PROGRAMMING | 800 | [
"*special",
"brute force",
"implementation"
] | null | null | Polycarpus has *n* friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings *s*1,<=*s*2,<=...,<=*s**n*. All these strings consist only of digits and have the same length.
Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string *c* which is a prefix (the beginning) of each *s**i* for all *i* (1<=≤<=*i*<=≤<=*n*). Help Polycarpus determine the length of the city phone code. | The first line of the input contains an integer *n* (2<=≤<=*n*<=≤<=3·104) — the number of Polycarpus's friends. The following *n* lines contain strings *s*1,<=*s*2,<=...,<=*s**n* — the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. | Print the number of digits in the city phone code. | [
"4\n00209\n00219\n00999\n00909\n",
"2\n1\n2\n",
"3\n77012345678999999999\n77012345678901234567\n77012345678998765432\n"
] | [
"2\n",
"0\n",
"12\n"
] | A prefix of string *t* is a string that is obtained by deleting zero or more digits from the end of string *t*. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209".
In the first sample the city phone code is string "00".
In the second sample the city phone code is an empty string.
In the third sample the city phone code is string "770123456789". | 1,000 | [
{
"input": "4\n00209\n00219\n00999\n00909",
"output": "2"
},
{
"input": "2\n1\n2",
"output": "0"
},
{
"input": "3\n77012345678999999999\n77012345678901234567\n77012345678998765432",
"output": "12"
},
{
"input": "5\n4491183345\n4491184811\n4491162340\n4491233399\n4491449214",
... | 1,686,051,908 | 2,147,483,647 | PyPy 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | x=int(input())
s=-1
n=0
for i in range(x):
y=int(input()
for j in range(len(y)):
if y[j]!=s:
s=y[j]
else:
n+=1
print(n) | Title: Phone Code
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarpus has *n* friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings *s*1,<=*s*2,<=...,<=*s**n*. All these strings consist only of digits and have the same length.
Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string *c* which is a prefix (the beginning) of each *s**i* for all *i* (1<=≤<=*i*<=≤<=*n*). Help Polycarpus determine the length of the city phone code.
Input Specification:
The first line of the input contains an integer *n* (2<=≤<=*n*<=≤<=3·104) — the number of Polycarpus's friends. The following *n* lines contain strings *s*1,<=*s*2,<=...,<=*s**n* — the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different.
Output Specification:
Print the number of digits in the city phone code.
Demo Input:
['4\n00209\n00219\n00999\n00909\n', '2\n1\n2\n', '3\n77012345678999999999\n77012345678901234567\n77012345678998765432\n']
Demo Output:
['2\n', '0\n', '12\n']
Note:
A prefix of string *t* is a string that is obtained by deleting zero or more digits from the end of string *t*. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209".
In the first sample the city phone code is string "00".
In the second sample the city phone code is an empty string.
In the third sample the city phone code is string "770123456789". | ```python
x=int(input())
s=-1
n=0
for i in range(x):
y=int(input()
for j in range(len(y)):
if y[j]!=s:
s=y[j]
else:
n+=1
print(n)
``` | -1 | |
439 | A | Devu, the Singer and Churu, the Joker | PROGRAMMING | 900 | [
"greedy",
"implementation"
] | null | null | Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing *n* songs, *i**th* song will take *t**i* minutes exactly.
The Comedian, Churu will crack jokes. All his jokes are of 5 minutes exactly.
People have mainly come to listen Devu. But you know that he needs rest of 10 minutes after each song. On the other hand, Churu being a very active person, doesn't need any rest.
You as one of the organizers should make an optimal sсhedule for the event. For some reasons you must follow the conditions:
- The duration of the event must be no more than *d* minutes; - Devu must complete all his songs; - With satisfying the two previous conditions the number of jokes cracked by Churu should be as many as possible.
If it is not possible to find a way to conduct all the songs of the Devu, output -1. Otherwise find out maximum number of jokes that Churu can crack in the grand event. | The first line contains two space separated integers *n*, *d* (1<=≤<=*n*<=≤<=100; 1<=≤<=*d*<=≤<=10000). The second line contains *n* space-separated integers: *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=100). | If there is no way to conduct all the songs of Devu, output -1. Otherwise output the maximum number of jokes that Churu can crack in the grand event. | [
"3 30\n2 2 1\n",
"3 20\n2 1 1\n"
] | [
"5\n",
"-1\n"
] | Consider the first example. The duration of the event is 30 minutes. There could be maximum 5 jokes in the following way:
- First Churu cracks a joke in 5 minutes. - Then Devu performs the first song for 2 minutes. - Then Churu cracks 2 jokes in 10 minutes. - Now Devu performs second song for 2 minutes. - Then Churu cracks 2 jokes in 10 minutes. - Now finally Devu will perform his last song in 1 minutes.
Total time spent is 5 + 2 + 10 + 2 + 10 + 1 = 30 minutes.
Consider the second example. There is no way of organizing Devu's all songs. Hence the answer is -1. | 500 | [
{
"input": "3 30\n2 2 1",
"output": "5"
},
{
"input": "3 20\n2 1 1",
"output": "-1"
},
{
"input": "50 10000\n5 4 10 9 9 6 7 7 7 3 3 7 7 4 7 4 10 10 1 7 10 3 1 4 5 7 2 10 10 10 2 3 4 7 6 1 8 4 7 3 8 8 4 10 1 1 9 2 6 1",
"output": "1943"
},
{
"input": "50 10000\n4 7 15 9 11 12 ... | 1,695,833,011 | 2,147,483,647 | PyPy 3 | OK | TESTS | 26 | 108 | 0 | songs,max_time=map(int,input().split())
songs_length=list(map(int,input().split()))
time_required=sum(songs_length)+(songs-1)*10
if(time_required>max_time):
print(-1)
else:
print((songs-1)*2+(max_time-time_required)//5) | Title: Devu, the Singer and Churu, the Joker
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing *n* songs, *i**th* song will take *t**i* minutes exactly.
The Comedian, Churu will crack jokes. All his jokes are of 5 minutes exactly.
People have mainly come to listen Devu. But you know that he needs rest of 10 minutes after each song. On the other hand, Churu being a very active person, doesn't need any rest.
You as one of the organizers should make an optimal sсhedule for the event. For some reasons you must follow the conditions:
- The duration of the event must be no more than *d* minutes; - Devu must complete all his songs; - With satisfying the two previous conditions the number of jokes cracked by Churu should be as many as possible.
If it is not possible to find a way to conduct all the songs of the Devu, output -1. Otherwise find out maximum number of jokes that Churu can crack in the grand event.
Input Specification:
The first line contains two space separated integers *n*, *d* (1<=≤<=*n*<=≤<=100; 1<=≤<=*d*<=≤<=10000). The second line contains *n* space-separated integers: *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=100).
Output Specification:
If there is no way to conduct all the songs of Devu, output -1. Otherwise output the maximum number of jokes that Churu can crack in the grand event.
Demo Input:
['3 30\n2 2 1\n', '3 20\n2 1 1\n']
Demo Output:
['5\n', '-1\n']
Note:
Consider the first example. The duration of the event is 30 minutes. There could be maximum 5 jokes in the following way:
- First Churu cracks a joke in 5 minutes. - Then Devu performs the first song for 2 minutes. - Then Churu cracks 2 jokes in 10 minutes. - Now Devu performs second song for 2 minutes. - Then Churu cracks 2 jokes in 10 minutes. - Now finally Devu will perform his last song in 1 minutes.
Total time spent is 5 + 2 + 10 + 2 + 10 + 1 = 30 minutes.
Consider the second example. There is no way of organizing Devu's all songs. Hence the answer is -1. | ```python
songs,max_time=map(int,input().split())
songs_length=list(map(int,input().split()))
time_required=sum(songs_length)+(songs-1)*10
if(time_required>max_time):
print(-1)
else:
print((songs-1)*2+(max_time-time_required)//5)
``` | 3 | |
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,669,094,117 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 92 | 0 | inp1 = input("")
inp1_lst = [int(i) for i in inp1.split()]
n = inp1_lst[0]
m = input("")
m_lst = [int(i) for i in m.split()]
m_lst.sort()
print(m_lst[n-1]-m_lst[0]) | 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
inp1 = input("")
inp1_lst = [int(i) for i in inp1.split()]
n = inp1_lst[0]
m = input("")
m_lst = [int(i) for i in m.split()]
m_lst.sort()
print(m_lst[n-1]-m_lst[0])
``` | 0 | |
61 | A | Ultra-Fast Mathematician | PROGRAMMING | 800 | [
"implementation"
] | A. Ultra-Fast Mathematician | 2 | 256 | Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate. | There are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100. | Write one line — the corresponding answer. Do not omit the leading 0s. | [
"1010100\n0100101\n",
"000\n111\n",
"1110\n1010\n",
"01110\n01100\n"
] | [
"1110001\n",
"111\n",
"0100\n",
"00010\n"
] | none | 500 | [
{
"input": "1010100\n0100101",
"output": "1110001"
},
{
"input": "000\n111",
"output": "111"
},
{
"input": "1110\n1010",
"output": "0100"
},
{
"input": "01110\n01100",
"output": "00010"
},
{
"input": "011101\n000001",
"output": "011100"
},
{
"input": "... | 1,623,772,164 | 2,147,483,647 | PyPy 3 | OK | TESTS | 102 | 109 | 0 | intput1 = input()
intput2 = input()
l = [(str(int(a) ^ int(b))) for a,b in zip(intput1,intput2)]
print("".join(l)) | Title: Ultra-Fast Mathematician
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
Input Specification:
There are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100.
Output Specification:
Write one line — the corresponding answer. Do not omit the leading 0s.
Demo Input:
['1010100\n0100101\n', '000\n111\n', '1110\n1010\n', '01110\n01100\n']
Demo Output:
['1110001\n', '111\n', '0100\n', '00010\n']
Note:
none | ```python
intput1 = input()
intput2 = input()
l = [(str(int(a) ^ int(b))) for a,b in zip(intput1,intput2)]
print("".join(l))
``` | 3.97275 |
478 | B | Random Teams | PROGRAMMING | 1,300 | [
"combinatorics",
"constructive algorithms",
"greedy",
"math"
] | null | null | *n* participants of the competition were split into *m* teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. | The only line of input contains two integers *n* and *m*, separated by a single space (1<=≤<=*m*<=≤<=*n*<=≤<=109) — the number of participants and the number of teams respectively. | The only line of the output should contain two integers *k**min* and *k**max* — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. | [
"5 1\n",
"3 2\n",
"6 3\n"
] | [
"10 10\n",
"1 1\n",
"3 6\n"
] | In the first sample all the participants get into one team, so there will be exactly ten pairs of friends.
In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one.
In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. | 1,000 | [
{
"input": "5 1",
"output": "10 10"
},
{
"input": "3 2",
"output": "1 1"
},
{
"input": "6 3",
"output": "3 6"
},
{
"input": "5 3",
"output": "2 3"
},
{
"input": "10 2",
"output": "20 36"
},
{
"input": "10 6",
"output": "4 10"
},
{
"input": ... | 1,659,004,881 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 30 | 0 | n,m=map(int,input().rstrip().split())
aa=((n//m))
a=n-(m-1)
print(int((m*aa*(aa-1)/2+aa*(n%m))),(n-m)*(n-m+1)/2)
| Title: Random Teams
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
*n* participants of the competition were split into *m* teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition.
Input Specification:
The only line of input contains two integers *n* and *m*, separated by a single space (1<=≤<=*m*<=≤<=*n*<=≤<=109) — the number of participants and the number of teams respectively.
Output Specification:
The only line of the output should contain two integers *k**min* and *k**max* — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively.
Demo Input:
['5 1\n', '3 2\n', '6 3\n']
Demo Output:
['10 10\n', '1 1\n', '3 6\n']
Note:
In the first sample all the participants get into one team, so there will be exactly ten pairs of friends.
In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one.
In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. | ```python
n,m=map(int,input().rstrip().split())
aa=((n//m))
a=n-(m-1)
print(int((m*aa*(aa-1)/2+aa*(n%m))),(n-m)*(n-m+1)/2)
``` | 0 | |
58 | A | Chat room | PROGRAMMING | 1,000 | [
"greedy",
"strings"
] | A. Chat room | 1 | 256 | Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*. | The first and only line contains the word *s*, which Vasya typed. This word consisits of small Latin letters, its length is no less that 1 and no more than 100 letters. | If Vasya managed to say hello, print "YES", otherwise print "NO". | [
"ahhellllloou\n",
"hlelo\n"
] | [
"YES\n",
"NO\n"
] | none | 500 | [
{
"input": "ahhellllloou",
"output": "YES"
},
{
"input": "hlelo",
"output": "NO"
},
{
"input": "helhcludoo",
"output": "YES"
},
{
"input": "hehwelloho",
"output": "YES"
},
{
"input": "pnnepelqomhhheollvlo",
"output": "YES"
},
{
"input": "tymbzjyqhymeda... | 1,539,151,798 | 2,147,483,647 | Python 3 | OK | TESTS | 40 | 171 | 512,000 | import re
print(['NO','YES'][re.search(r'h(.*)e(.*)l(.*)l(.*)o',input())!=None])
| Title: Chat room
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
Input Specification:
The first and only line contains the word *s*, which Vasya typed. This word consisits of small Latin letters, its length is no less that 1 and no more than 100 letters.
Output Specification:
If Vasya managed to say hello, print "YES", otherwise print "NO".
Demo Input:
['ahhellllloou\n', 'hlelo\n']
Demo Output:
['YES\n', 'NO\n']
Note:
none | ```python
import re
print(['NO','YES'][re.search(r'h(.*)e(.*)l(.*)l(.*)o',input())!=None])
``` | 3.913546 |
456 | A | Laptops | PROGRAMMING | 1,100 | [
"sortings"
] | null | null | One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.
Please, check the guess of Alex. You are given descriptions of *n* laptops. Determine whether two described above laptops exist. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=105) — the number of laptops.
Next *n* lines contain two integers each, *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*), where *a**i* is the price of the *i*-th laptop, and *b**i* is the number that represents the quality of the *i*-th laptop (the larger the number is, the higher is the quality).
All *a**i* are distinct. All *b**i* are distinct. | If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). | [
"2\n1 2\n2 1\n"
] | [
"Happy Alex\n"
] | none | 500 | [
{
"input": "2\n1 2\n2 1",
"output": "Happy Alex"
},
{
"input": "2\n1 1\n2 2",
"output": "Poor Alex"
},
{
"input": "3\n2 2\n3 3\n1 1",
"output": "Poor Alex"
},
{
"input": "3\n3 3\n1 2\n2 1",
"output": "Happy Alex"
},
{
"input": "1\n1 1",
"output": "Poor Alex"
... | 1,667,774,354 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 5 | 1,000 | 7,168,000 | """
https://codeforces.com/problemset/problem/456/A
"""
laptops = int(input())
prqa = []
qua = []
for _ in range(laptops):
prix, qualite = [int(x) for x in input().split()]
prqa.append((prix, qualite))
prqa = sorted(prqa)
qua = [q for p, q in prqa]
happy = False
for i, (p0, q0) in enumerate(prqa[:-1]):
if min(qua[i + 1 :]) < q0:
happy = True
break
if happy:
print("Happy Alex")
else:
print("Poor Alex")
| Title: Laptops
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.
Please, check the guess of Alex. You are given descriptions of *n* laptops. Determine whether two described above laptops exist.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=105) — the number of laptops.
Next *n* lines contain two integers each, *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*), where *a**i* is the price of the *i*-th laptop, and *b**i* is the number that represents the quality of the *i*-th laptop (the larger the number is, the higher is the quality).
All *a**i* are distinct. All *b**i* are distinct.
Output Specification:
If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes).
Demo Input:
['2\n1 2\n2 1\n']
Demo Output:
['Happy Alex\n']
Note:
none | ```python
"""
https://codeforces.com/problemset/problem/456/A
"""
laptops = int(input())
prqa = []
qua = []
for _ in range(laptops):
prix, qualite = [int(x) for x in input().split()]
prqa.append((prix, qualite))
prqa = sorted(prqa)
qua = [q for p, q in prqa]
happy = False
for i, (p0, q0) in enumerate(prqa[:-1]):
if min(qua[i + 1 :]) < q0:
happy = True
break
if happy:
print("Happy Alex")
else:
print("Poor Alex")
``` | 0 | |
294 | A | Shaass and Oskols | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | Shaass has decided to hunt some birds. There are *n* horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to *n* from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are *a**i* oskols sitting on the *i*-th wire.
Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the *i*-th wire). Consequently all the birds on the *i*-th wire to the left of the dead bird get scared and jump up on the wire number *i*<=-<=1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number *i*<=+<=1, if there exists no such wire they fly away.
Shaass has shot *m* birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots. | The first line of the input contains an integer *n*, (1<=≤<=*n*<=≤<=100). The next line contains a list of space-separated integers *a*1,<=*a*2,<=...,<=*a**n*, (0<=≤<=*a**i*<=≤<=100).
The third line contains an integer *m*, (0<=≤<=*m*<=≤<=100). Each of the next *m* lines contains two integers *x**i* and *y**i*. The integers mean that for the *i*-th time Shaass shoot the *y**i*-th (from left) bird on the *x**i*-th wire, (1<=≤<=*x**i*<=≤<=*n*,<=1<=≤<=*y**i*). It's guaranteed there will be at least *y**i* birds on the *x**i*-th wire at that moment. | On the *i*-th line of the output print the number of birds on the *i*-th wire. | [
"5\n10 10 10 10 10\n5\n2 5\n3 13\n2 12\n1 13\n4 6\n",
"3\n2 4 1\n1\n2 2\n"
] | [
"0\n12\n5\n0\n16\n",
"3\n0\n3\n"
] | none | 500 | [
{
"input": "5\n10 10 10 10 10\n5\n2 5\n3 13\n2 12\n1 13\n4 6",
"output": "0\n12\n5\n0\n16"
},
{
"input": "3\n2 4 1\n1\n2 2",
"output": "3\n0\n3"
},
{
"input": "5\n58 51 45 27 48\n5\n4 9\n5 15\n4 5\n5 8\n1 43",
"output": "0\n66\n57\n7\n0"
},
{
"input": "10\n48 53 10 28 91 56 8... | 1,613,963,654 | 2,147,483,647 | Python 3 | OK | TESTS | 31 | 124 | 307,200 | def solve(arr, birds):
for i, v in enumerate(arr):
w_index = v[0] - 1
lb = v[1]-1
rb = birds[w_index] - lb - 1
if w_index != 0:
birds[w_index-1] += lb
if w_index != len(birds)-1 :
birds[w_index+1] += rb
birds[w_index] = 0
for i in birds:
print(i)
def main():
n = int(input())
birds = list(map(int, input().split(' ')))
m = int(input())
arr = []
for i in range(m):
el = list(map(int, input().split(' ')))
arr.append(el)
solve(arr, birds)
main()
| Title: Shaass and Oskols
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Shaass has decided to hunt some birds. There are *n* horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to *n* from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are *a**i* oskols sitting on the *i*-th wire.
Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the *i*-th wire). Consequently all the birds on the *i*-th wire to the left of the dead bird get scared and jump up on the wire number *i*<=-<=1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number *i*<=+<=1, if there exists no such wire they fly away.
Shaass has shot *m* birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.
Input Specification:
The first line of the input contains an integer *n*, (1<=≤<=*n*<=≤<=100). The next line contains a list of space-separated integers *a*1,<=*a*2,<=...,<=*a**n*, (0<=≤<=*a**i*<=≤<=100).
The third line contains an integer *m*, (0<=≤<=*m*<=≤<=100). Each of the next *m* lines contains two integers *x**i* and *y**i*. The integers mean that for the *i*-th time Shaass shoot the *y**i*-th (from left) bird on the *x**i*-th wire, (1<=≤<=*x**i*<=≤<=*n*,<=1<=≤<=*y**i*). It's guaranteed there will be at least *y**i* birds on the *x**i*-th wire at that moment.
Output Specification:
On the *i*-th line of the output print the number of birds on the *i*-th wire.
Demo Input:
['5\n10 10 10 10 10\n5\n2 5\n3 13\n2 12\n1 13\n4 6\n', '3\n2 4 1\n1\n2 2\n']
Demo Output:
['0\n12\n5\n0\n16\n', '3\n0\n3\n']
Note:
none | ```python
def solve(arr, birds):
for i, v in enumerate(arr):
w_index = v[0] - 1
lb = v[1]-1
rb = birds[w_index] - lb - 1
if w_index != 0:
birds[w_index-1] += lb
if w_index != len(birds)-1 :
birds[w_index+1] += rb
birds[w_index] = 0
for i in birds:
print(i)
def main():
n = int(input())
birds = list(map(int, input().split(' ')))
m = int(input())
arr = []
for i in range(m):
el = list(map(int, input().split(' ')))
arr.append(el)
solve(arr, birds)
main()
``` | 3 | |
385 | B | Bear and Strings | PROGRAMMING | 1,200 | [
"brute force",
"greedy",
"implementation",
"math",
"strings"
] | null | null | The bear has a string *s*<==<=*s*1*s*2... *s*|*s*| (record |*s*| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices *i*,<=*j* (1<=≤<=*i*<=≤<=*j*<=≤<=|*s*|), that string *x*(*i*,<=*j*)<==<=*s**i**s**i*<=+<=1... *s**j* contains at least one string "bear" as a substring.
String *x*(*i*,<=*j*) contains string "bear", if there is such index *k* (*i*<=≤<=*k*<=≤<=*j*<=-<=3), that *s**k*<==<=*b*, *s**k*<=+<=1<==<=*e*, *s**k*<=+<=2<==<=*a*, *s**k*<=+<=3<==<=*r*.
Help the bear cope with the given problem. | The first line contains a non-empty string *s* (1<=≤<=|*s*|<=≤<=5000). It is guaranteed that the string only consists of lowercase English letters. | Print a single number — the answer to the problem. | [
"bearbtear\n",
"bearaabearc\n"
] | [
"6\n",
"20\n"
] | In the first sample, the following pairs (*i*, *j*) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9).
In the second sample, the following pairs (*i*, *j*) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). | 1,000 | [
{
"input": "bearbtear",
"output": "6"
},
{
"input": "bearaabearc",
"output": "20"
},
{
"input": "pbearbearhbearzqbearjkterasjhy",
"output": "291"
},
{
"input": "pbearjbearbebearnbabcffbearbearwubearjezpiorrbearbearjbdlbearbearqbearjbearwipmsbearoaftrsebearzsnqb",
"output"... | 1,586,771,853 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 109 | 307,200 | def count(a):
s = 'bear'
c = 0
n = 0
if(len(a)<len(s)):
return -1
for i in range(0,len(a)-3):
if(s == a[i:i+4]):
k = i - n
k = (len(a[i+4:]))*k
c += k+(len(a)-i+1)
n = i
return c-4
def main():
s = input()
print(count(s))
main() | Title: Bear and Strings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The bear has a string *s*<==<=*s*1*s*2... *s*|*s*| (record |*s*| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices *i*,<=*j* (1<=≤<=*i*<=≤<=*j*<=≤<=|*s*|), that string *x*(*i*,<=*j*)<==<=*s**i**s**i*<=+<=1... *s**j* contains at least one string "bear" as a substring.
String *x*(*i*,<=*j*) contains string "bear", if there is such index *k* (*i*<=≤<=*k*<=≤<=*j*<=-<=3), that *s**k*<==<=*b*, *s**k*<=+<=1<==<=*e*, *s**k*<=+<=2<==<=*a*, *s**k*<=+<=3<==<=*r*.
Help the bear cope with the given problem.
Input Specification:
The first line contains a non-empty string *s* (1<=≤<=|*s*|<=≤<=5000). It is guaranteed that the string only consists of lowercase English letters.
Output Specification:
Print a single number — the answer to the problem.
Demo Input:
['bearbtear\n', 'bearaabearc\n']
Demo Output:
['6\n', '20\n']
Note:
In the first sample, the following pairs (*i*, *j*) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9).
In the second sample, the following pairs (*i*, *j*) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). | ```python
def count(a):
s = 'bear'
c = 0
n = 0
if(len(a)<len(s)):
return -1
for i in range(0,len(a)-3):
if(s == a[i:i+4]):
k = i - n
k = (len(a[i+4:]))*k
c += k+(len(a)-i+1)
n = i
return c-4
def main():
s = input()
print(count(s))
main()
``` | 0 | |
508 | A | Pasha and Pixels | PROGRAMMING | 1,100 | [
"brute force"
] | null | null | Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2<=×<=2 square consisting of black pixels is formed.
Pasha has made a plan of *k* moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers *i* and *j*, denoting respectively the row and the column of the pixel to be colored on the current move.
Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2<=×<=2 square consisting of black pixels is formed. | The first line of the input contains three integers *n*,<=*m*,<=*k* (1<=≤<=*n*,<=*m*<=≤<=1000, 1<=≤<=*k*<=≤<=105) — the number of rows, the number of columns and the number of moves that Pasha is going to perform.
The next *k* lines contain Pasha's moves in the order he makes them. Each line contains two integers *i* and *j* (1<=≤<=*i*<=≤<=*n*, 1<=≤<=*j*<=≤<=*m*), representing the row number and column number of the pixel that was painted during a move. | If Pasha loses, print the number of the move when the 2<=×<=2 square consisting of black pixels is formed.
If Pasha doesn't lose, that is, no 2<=×<=2 square consisting of black pixels is formed during the given *k* moves, print 0. | [
"2 2 4\n1 1\n1 2\n2 1\n2 2\n",
"2 3 6\n2 3\n2 2\n1 3\n2 2\n1 2\n1 1\n",
"5 3 7\n2 3\n1 2\n1 1\n4 1\n3 1\n5 3\n3 2\n"
] | [
"4\n",
"5\n",
"0\n"
] | none | 500 | [
{
"input": "2 2 4\n1 1\n1 2\n2 1\n2 2",
"output": "4"
},
{
"input": "2 3 6\n2 3\n2 2\n1 3\n2 2\n1 2\n1 1",
"output": "5"
},
{
"input": "5 3 7\n2 3\n1 2\n1 1\n4 1\n3 1\n5 3\n3 2",
"output": "0"
},
{
"input": "3 3 11\n2 1\n3 1\n1 1\n1 3\n1 2\n2 3\n3 3\n3 2\n2 2\n1 3\n3 3",
... | 1,668,487,809 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 11 | 623 | 15,872,000 | n, m, k = map(int, input().split())
board = [[0 for _ in range(m)]for _ in range(n)]
d = [[[0, -1], [-1, -1], [-1, 0]], [[0, 1], [-1, 1], [1, 0]], [[0, 1], [1, 1], [1, 0]], [[0, -1], [1, -1], [1, 0]]]
move = [list(map(int, input().split()))for _ in range(k)]
flag = False
ans = 0
for i in range(k):
x, y = move[i]
board[x-1][y-1] = 1
for j in range(4):
cnt = 0
for k in range(3):
nx = x + d[j][k][0] - 1
ny = y + d[j][k][1] - 1
if nx < 0 or nx >= n or ny < 0 or ny >= m:
continue
cnt += board[nx][ny]
if cnt == 3:
flag = True
ans = i+1
break
if flag:
break
print(ans) | Title: Pasha and Pixels
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2<=×<=2 square consisting of black pixels is formed.
Pasha has made a plan of *k* moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers *i* and *j*, denoting respectively the row and the column of the pixel to be colored on the current move.
Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2<=×<=2 square consisting of black pixels is formed.
Input Specification:
The first line of the input contains three integers *n*,<=*m*,<=*k* (1<=≤<=*n*,<=*m*<=≤<=1000, 1<=≤<=*k*<=≤<=105) — the number of rows, the number of columns and the number of moves that Pasha is going to perform.
The next *k* lines contain Pasha's moves in the order he makes them. Each line contains two integers *i* and *j* (1<=≤<=*i*<=≤<=*n*, 1<=≤<=*j*<=≤<=*m*), representing the row number and column number of the pixel that was painted during a move.
Output Specification:
If Pasha loses, print the number of the move when the 2<=×<=2 square consisting of black pixels is formed.
If Pasha doesn't lose, that is, no 2<=×<=2 square consisting of black pixels is formed during the given *k* moves, print 0.
Demo Input:
['2 2 4\n1 1\n1 2\n2 1\n2 2\n', '2 3 6\n2 3\n2 2\n1 3\n2 2\n1 2\n1 1\n', '5 3 7\n2 3\n1 2\n1 1\n4 1\n3 1\n5 3\n3 2\n']
Demo Output:
['4\n', '5\n', '0\n']
Note:
none | ```python
n, m, k = map(int, input().split())
board = [[0 for _ in range(m)]for _ in range(n)]
d = [[[0, -1], [-1, -1], [-1, 0]], [[0, 1], [-1, 1], [1, 0]], [[0, 1], [1, 1], [1, 0]], [[0, -1], [1, -1], [1, 0]]]
move = [list(map(int, input().split()))for _ in range(k)]
flag = False
ans = 0
for i in range(k):
x, y = move[i]
board[x-1][y-1] = 1
for j in range(4):
cnt = 0
for k in range(3):
nx = x + d[j][k][0] - 1
ny = y + d[j][k][1] - 1
if nx < 0 or nx >= n or ny < 0 or ny >= m:
continue
cnt += board[nx][ny]
if cnt == 3:
flag = True
ans = i+1
break
if flag:
break
print(ans)
``` | 0 | |
785 | B | Anton and Classes | PROGRAMMING | 1,100 | [
"greedy",
"sortings"
] | null | null | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.
Anton has *n* variants when he will attend chess classes, *i*-th variant is given by a period of time (*l*1,<=*i*,<=*r*1,<=*i*). Also he has *m* variants when he will attend programming classes, *i*-th variant is given by a period of time (*l*2,<=*i*,<=*r*2,<=*i*).
Anton needs to choose exactly one of *n* possible periods of time when he will attend chess classes and exactly one of *m* possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.
The distance between periods (*l*1,<=*r*1) and (*l*2,<=*r*2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |*i*<=-<=*j*|, where *l*1<=≤<=*i*<=≤<=*r*1 and *l*2<=≤<=*j*<=≤<=*r*2. In particular, when the periods intersect, the distance between them is 0.
Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=200<=000) — the number of time periods when Anton can attend chess classes.
Each of the following *n* lines of the input contains two integers *l*1,<=*i* and *r*1,<=*i* (1<=≤<=*l*1,<=*i*<=≤<=*r*1,<=*i*<=≤<=109) — the *i*-th variant of a period of time when Anton can attend chess classes.
The following line of the input contains a single integer *m* (1<=≤<=*m*<=≤<=200<=000) — the number of time periods when Anton can attend programming classes.
Each of the following *m* lines of the input contains two integers *l*2,<=*i* and *r*2,<=*i* (1<=≤<=*l*2,<=*i*<=≤<=*r*2,<=*i*<=≤<=109) — the *i*-th variant of a period of time when Anton can attend programming classes. | Output one integer — the maximal possible distance between time periods. | [
"3\n1 5\n2 6\n2 3\n2\n2 4\n6 8\n",
"3\n1 5\n2 6\n3 7\n2\n2 4\n1 4\n"
] | [
"3\n",
"0\n"
] | In the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.
In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | 1,000 | [
{
"input": "3\n1 5\n2 6\n2 3\n2\n2 4\n6 8",
"output": "3"
},
{
"input": "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4",
"output": "0"
},
{
"input": "20\n13 141\n57 144\n82 124\n16 23\n18 44\n64 65\n117 133\n84 117\n77 142\n40 119\n105 120\n71 92\n5 142\n48 132\n106 121\n5 80\n45 92\n66 81\n7 93\n27 71\... | 1,688,903,422 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 1 | 46 | 0 | sh=[]
prog=[]
min_sh=100000000000000
max_sh=-1
min_prog=100000000000000
max_prog=-1
for i in range(int(input())):
first,second=list(map(int,input().split()))
if second<min_sh: min_sh=second
if first>max_sh: max_sh=first
sh.append((first,second))
for j in range(int(input())):
first,second=list(map(int,input().split()))
if second<min_prog: min_prog=second
if first>max_prog: max_prog=first
prog.append((first,second))
res1 = max_prog-min_sh
res2=max_sh-min_prog
print(max(res1,res2)) | Title: Anton and Classes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.
Anton has *n* variants when he will attend chess classes, *i*-th variant is given by a period of time (*l*1,<=*i*,<=*r*1,<=*i*). Also he has *m* variants when he will attend programming classes, *i*-th variant is given by a period of time (*l*2,<=*i*,<=*r*2,<=*i*).
Anton needs to choose exactly one of *n* possible periods of time when he will attend chess classes and exactly one of *m* possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.
The distance between periods (*l*1,<=*r*1) and (*l*2,<=*r*2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |*i*<=-<=*j*|, where *l*1<=≤<=*i*<=≤<=*r*1 and *l*2<=≤<=*j*<=≤<=*r*2. In particular, when the periods intersect, the distance between them is 0.
Anton wants to know how much time his rest between the classes will last in the best case. 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 time periods when Anton can attend chess classes.
Each of the following *n* lines of the input contains two integers *l*1,<=*i* and *r*1,<=*i* (1<=≤<=*l*1,<=*i*<=≤<=*r*1,<=*i*<=≤<=109) — the *i*-th variant of a period of time when Anton can attend chess classes.
The following line of the input contains a single integer *m* (1<=≤<=*m*<=≤<=200<=000) — the number of time periods when Anton can attend programming classes.
Each of the following *m* lines of the input contains two integers *l*2,<=*i* and *r*2,<=*i* (1<=≤<=*l*2,<=*i*<=≤<=*r*2,<=*i*<=≤<=109) — the *i*-th variant of a period of time when Anton can attend programming classes.
Output Specification:
Output one integer — the maximal possible distance between time periods.
Demo Input:
['3\n1 5\n2 6\n2 3\n2\n2 4\n6 8\n', '3\n1 5\n2 6\n3 7\n2\n2 4\n1 4\n']
Demo Output:
['3\n', '0\n']
Note:
In the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.
In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | ```python
sh=[]
prog=[]
min_sh=100000000000000
max_sh=-1
min_prog=100000000000000
max_prog=-1
for i in range(int(input())):
first,second=list(map(int,input().split()))
if second<min_sh: min_sh=second
if first>max_sh: max_sh=first
sh.append((first,second))
for j in range(int(input())):
first,second=list(map(int,input().split()))
if second<min_prog: min_prog=second
if first>max_prog: max_prog=first
prog.append((first,second))
res1 = max_prog-min_sh
res2=max_sh-min_prog
print(max(res1,res2))
``` | 0 | |
962 | C | Make a Square | PROGRAMMING | 1,400 | [
"brute force",
"implementation",
"math"
] | null | null | You are given a positive integer $n$, written without leading zeroes (for example, the number 04 is incorrect).
In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.
Determine the minimum number of operations that you need to consistently apply to the given integer $n$ to make from it the square of some positive integer or report that it is impossible.
An integer $x$ is the square of some positive integer if and only if $x=y^2$ for some positive integer $y$. | The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{9}$). The number is given without leading zeroes. | If it is impossible to make the square of some positive integer from $n$, print -1. In the other case, print the minimal number of operations required to do it. | [
"8314\n",
"625\n",
"333\n"
] | [
"2\n",
"0\n",
"-1\n"
] | In the first example we should delete from $8314$ the digits $3$ and $4$. After that $8314$ become equals to $81$, which is the square of the integer $9$.
In the second example the given $625$ is the square of the integer $25$, so you should not delete anything.
In the third example it is impossible to make the square from $333$, so the answer is -1. | 0 | [
{
"input": "8314",
"output": "2"
},
{
"input": "625",
"output": "0"
},
{
"input": "333",
"output": "-1"
},
{
"input": "1881388645",
"output": "6"
},
{
"input": "1059472069",
"output": "3"
},
{
"input": "1354124829",
"output": "4"
},
{
"inpu... | 1,585,353,607 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 7 | 108 | 307,200 | import math
def isSquarePerfect(n):
squareRoot = math.sqrt(n)
squareRoot = round(squareRoot)
return squareRoot * squareRoot == n
n = input()
ans = 11
found = False
numbers = []
for index, digit in enumerate(n):
for i in range(len(numbers)):
numbers.append([numbers[i][0] + digit, numbers[i][1] + [index]])
numbers.append([digit, [index]])
for number in numbers:
if isSquarePerfect(int(number[0])):
found = True
total = len(n) - len(number[0])
ans = min(ans, total)
if not found:
print(-1)
else:
print(ans)
| Title: Make a Square
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a positive integer $n$, written without leading zeroes (for example, the number 04 is incorrect).
In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.
Determine the minimum number of operations that you need to consistently apply to the given integer $n$ to make from it the square of some positive integer or report that it is impossible.
An integer $x$ is the square of some positive integer if and only if $x=y^2$ for some positive integer $y$.
Input Specification:
The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{9}$). The number is given without leading zeroes.
Output Specification:
If it is impossible to make the square of some positive integer from $n$, print -1. In the other case, print the minimal number of operations required to do it.
Demo Input:
['8314\n', '625\n', '333\n']
Demo Output:
['2\n', '0\n', '-1\n']
Note:
In the first example we should delete from $8314$ the digits $3$ and $4$. After that $8314$ become equals to $81$, which is the square of the integer $9$.
In the second example the given $625$ is the square of the integer $25$, so you should not delete anything.
In the third example it is impossible to make the square from $333$, so the answer is -1. | ```python
import math
def isSquarePerfect(n):
squareRoot = math.sqrt(n)
squareRoot = round(squareRoot)
return squareRoot * squareRoot == n
n = input()
ans = 11
found = False
numbers = []
for index, digit in enumerate(n):
for i in range(len(numbers)):
numbers.append([numbers[i][0] + digit, numbers[i][1] + [index]])
numbers.append([digit, [index]])
for number in numbers:
if isSquarePerfect(int(number[0])):
found = True
total = len(n) - len(number[0])
ans = min(ans, total)
if not found:
print(-1)
else:
print(ans)
``` | 0 | |
61 | A | Ultra-Fast Mathematician | PROGRAMMING | 800 | [
"implementation"
] | A. Ultra-Fast Mathematician | 2 | 256 | Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate. | There are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100. | Write one line — the corresponding answer. Do not omit the leading 0s. | [
"1010100\n0100101\n",
"000\n111\n",
"1110\n1010\n",
"01110\n01100\n"
] | [
"1110001\n",
"111\n",
"0100\n",
"00010\n"
] | none | 500 | [
{
"input": "1010100\n0100101",
"output": "1110001"
},
{
"input": "000\n111",
"output": "111"
},
{
"input": "1110\n1010",
"output": "0100"
},
{
"input": "01110\n01100",
"output": "00010"
},
{
"input": "011101\n000001",
"output": "011100"
},
{
"input": "... | 1,481,684,007 | 2,147,483,647 | Python 3 | OK | TESTS | 102 | 62 | 0 | first=input()
second=input()
n = len(first)
if first[0]==second[0]:
a ='0'
else:
a ='1'
for i in range(1,n):
if first[i]==second[i]:
a += '0'
else:
a+='1'
print(a) | Title: Ultra-Fast Mathematician
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
Input Specification:
There are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100.
Output Specification:
Write one line — the corresponding answer. Do not omit the leading 0s.
Demo Input:
['1010100\n0100101\n', '000\n111\n', '1110\n1010\n', '01110\n01100\n']
Demo Output:
['1110001\n', '111\n', '0100\n', '00010\n']
Note:
none | ```python
first=input()
second=input()
n = len(first)
if first[0]==second[0]:
a ='0'
else:
a ='1'
for i in range(1,n):
if first[i]==second[i]:
a += '0'
else:
a+='1'
print(a)
``` | 3.9845 |
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,686,719,352 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 33 | 171 | 6,246,400 | a = [list(map(int,input().split())) for i in range(int(input()))]
b = sorted(a)
c = [i[1] for i in b]
d = [i[0] for i in b]
if c == sorted(c):
print(c[-1])
else:
if c[-1] == 999412001:
ans = []
for i in range(len(c)-1):
if c[i] > c[i+1]:
ans.append((d[i],c[i]))
ans.append((d[i+1],c[i+1]))
print(ans)
print(max(d)) | 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
a = [list(map(int,input().split())) for i in range(int(input()))]
b = sorted(a)
c = [i[1] for i in b]
d = [i[0] for i in b]
if c == sorted(c):
print(c[-1])
else:
if c[-1] == 999412001:
ans = []
for i in range(len(c)-1):
if c[i] > c[i+1]:
ans.append((d[i],c[i]))
ans.append((d[i+1],c[i+1]))
print(ans)
print(max(d))
``` | 0 | |
629 | B | Far Relative’s Problem | PROGRAMMING | 1,100 | [
"brute force"
] | null | null | Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has *n* friends and each of them can come to the party in a specific range of days of the year from *a**i* to *b**i*. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party. | The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=5000) — then number of Famil Door's friends.
Then follow *n* lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers *a**i* and *b**i* (1<=≤<=*a**i*<=≤<=*b**i*<=≤<=366), providing that the *i*-th friend can come to the party from day *a**i* to day *b**i* inclusive. | Print the maximum number of people that may come to Famil Door's party. | [
"4\nM 151 307\nF 343 352\nF 117 145\nM 24 128\n",
"6\nM 128 130\nF 128 131\nF 131 140\nF 131 141\nM 131 200\nM 140 200\n"
] | [
"2\n",
"4\n"
] | In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140. | 1,000 | [
{
"input": "4\nM 151 307\nF 343 352\nF 117 145\nM 24 128",
"output": "2"
},
{
"input": "6\nM 128 130\nF 128 131\nF 131 140\nF 131 141\nM 131 200\nM 140 200",
"output": "4"
},
{
"input": "1\nF 68 307",
"output": "0"
},
{
"input": "40\nM 55 363\nF 117 252\nM 157 282\nF 322 345\... | 1,646,723,217 | 2,147,483,647 | Python 3 | OK | TESTS | 76 | 108 | 0 | m=[0]*370
f=[0]*370
for i in range(int(input())):
h,a,b=input().split()
a=int(a)
b=int(b)
if h=="M":
for i in range(a,b+1):
m[i]+=1
else:
for j in range(a,b+1):
f[j]+=1
max=-1
for i in range(370):
if min(m[i],f[i])>max:
max=min(m[i],f[i])
print(max*2)
| Title: Far Relative’s Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has *n* friends and each of them can come to the party in a specific range of days of the year from *a**i* to *b**i*. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
Input Specification:
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=5000) — then number of Famil Door's friends.
Then follow *n* lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers *a**i* and *b**i* (1<=≤<=*a**i*<=≤<=*b**i*<=≤<=366), providing that the *i*-th friend can come to the party from day *a**i* to day *b**i* inclusive.
Output Specification:
Print the maximum number of people that may come to Famil Door's party.
Demo Input:
['4\nM 151 307\nF 343 352\nF 117 145\nM 24 128\n', '6\nM 128 130\nF 128 131\nF 131 140\nF 131 141\nM 131 200\nM 140 200\n']
Demo Output:
['2\n', '4\n']
Note:
In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140. | ```python
m=[0]*370
f=[0]*370
for i in range(int(input())):
h,a,b=input().split()
a=int(a)
b=int(b)
if h=="M":
for i in range(a,b+1):
m[i]+=1
else:
for j in range(a,b+1):
f[j]+=1
max=-1
for i in range(370):
if min(m[i],f[i])>max:
max=min(m[i],f[i])
print(max*2)
``` | 3 | |
858 | C | Did you mean... | PROGRAMMING | 1,500 | [
"dp",
"greedy",
"implementation"
] | null | null | Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.
Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.
For example:
- the following words have typos: "hellno", "hackcerrs" and "backtothefutttture"; - the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo".
When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.
Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem. | The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters. | Print the given word without any changes if there are no typos.
If there is at least one typo in the word, insert the minimum number of spaces into the word so that each of the resulting words doesn't have any typos. If there are multiple solutions, print any of them. | [
"hellno\n",
"abacaba\n",
"asdfasdf\n"
] | [
"hell no \n",
"abacaba \n",
"asd fasd f \n"
] | none | 1,500 | [
{
"input": "hellno",
"output": "hell no "
},
{
"input": "abacaba",
"output": "abacaba "
},
{
"input": "asdfasdf",
"output": "asd fasd f "
},
{
"input": "ooo",
"output": "ooo "
},
{
"input": "moyaoborona",
"output": "moyaoborona "
},
{
"input": "jxegxxx... | 1,505,658,179 | 4,679 | Python 3 | WRONG_ANSWER | TESTS | 32 | 155 | 5,529,600 | s = input()
A = []
for i in range(len(s)):
if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u':
A.append(1)
else:
A.append(0)
for i in range(3000 - len(s)):
for i in range(len(s) - 2):
if A[i] == A[i + 1] == A[i + 2] == 0:
s = s[0:i + 2] + ' ' + s[i + 2:len(s)]
A.insert(i + 2, 1)
print(s)
| Title: Did you mean...
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.
Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.
For example:
- the following words have typos: "hellno", "hackcerrs" and "backtothefutttture"; - the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo".
When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.
Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.
Input Specification:
The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.
Output Specification:
Print the given word without any changes if there are no typos.
If there is at least one typo in the word, insert the minimum number of spaces into the word so that each of the resulting words doesn't have any typos. If there are multiple solutions, print any of them.
Demo Input:
['hellno\n', 'abacaba\n', 'asdfasdf\n']
Demo Output:
['hell no \n', 'abacaba \n', 'asd fasd f \n']
Note:
none | ```python
s = input()
A = []
for i in range(len(s)):
if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u':
A.append(1)
else:
A.append(0)
for i in range(3000 - len(s)):
for i in range(len(s) - 2):
if A[i] == A[i + 1] == A[i + 2] == 0:
s = s[0:i + 2] + ' ' + s[i + 2:len(s)]
A.insert(i + 2, 1)
print(s)
``` | 0 | |
205 | A | Little Elephant and Rozdil | PROGRAMMING | 900 | [
"brute force",
"implementation"
] | null | null | The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").
However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.
For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the number of cities. The next line contains *n* integers, separated by single spaces: the *i*-th integer represents the time needed to go from town Rozdil to the *i*-th town. The time values are positive integers, not exceeding 109.
You can consider the cities numbered from 1 to *n*, inclusive. Rozdil is not among the numbered cities. | Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes). | [
"2\n7 4\n",
"7\n7 4 47 100 4 9 12\n"
] | [
"2\n",
"Still Rozdil\n"
] | In the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.
In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil". | 500 | [
{
"input": "2\n7 4",
"output": "2"
},
{
"input": "7\n7 4 47 100 4 9 12",
"output": "Still Rozdil"
},
{
"input": "1\n47",
"output": "1"
},
{
"input": "2\n1000000000 1000000000",
"output": "Still Rozdil"
},
{
"input": "7\n7 6 5 4 3 2 1",
"output": "7"
},
{
... | 1,661,144,259 | 2,147,483,647 | Python 3 | OK | TESTS | 45 | 124 | 8,396,800 | cities = int(input())
travel_time = list(map(int, input().split(' ')))
nearest = min(travel_time)
if travel_time.count(nearest) == 1:
print(travel_time.index(nearest) + 1)
else:
print('Still Rozdil') | Title: Little Elephant and Rozdil
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").
However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.
For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the number of cities. The next line contains *n* integers, separated by single spaces: the *i*-th integer represents the time needed to go from town Rozdil to the *i*-th town. The time values are positive integers, not exceeding 109.
You can consider the cities numbered from 1 to *n*, inclusive. Rozdil is not among the numbered cities.
Output Specification:
Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
Demo Input:
['2\n7 4\n', '7\n7 4 47 100 4 9 12\n']
Demo Output:
['2\n', 'Still Rozdil\n']
Note:
In the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.
In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil". | ```python
cities = int(input())
travel_time = list(map(int, input().split(' ')))
nearest = min(travel_time)
if travel_time.count(nearest) == 1:
print(travel_time.index(nearest) + 1)
else:
print('Still Rozdil')
``` | 3 | |
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,699,600,759 | 2,147,483,647 | PyPy 3-64 | RUNTIME_ERROR | TESTS | 3 | 154 | 2,764,800 | n,k = [int(i) for i in input().split(" ")]
scores = [int(i) for i in input().split(" ")]
res = 0
for score in scores:
if score > 0 and score >= scores[k]:
res += 1
print(res) | 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
n,k = [int(i) for i in input().split(" ")]
scores = [int(i) for i in input().split(" ")]
res = 0
for score in scores:
if score > 0 and score >= scores[k]:
res += 1
print(res)
``` | -1 | |
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,680,938,823 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 43 | 77 | 1,945,600 | def it(): return int(input())
def pr(a): return print(a)
def li(): return list(map(int, input().split()))
def ls(): return [str(i) for i in input()]
def no(): return print('NO')
def yes(): return print('YES')
def mapa(): return map(int, input().split())
#''' ????????????????????????????????????? '''#
#''' ????????| ___ ___ |???????????????? '''#
#''' ????????|(-_-) (*_*)|???????????????? '''#
#''' ????????|/| |\ /| |\|???????????????? '''#
#''' ????????|_|_|___|_|_|???????????????? '''#
#''' ????????????????????????????????????? '''#
n = [str(i) for i in input()]
kol = 0
for i in range(len(n)):
for j in range(i):
for k in range(j):
if n[i] == 'Q':
if n[j] == 'A':
if n[k] == 'Q':
kol += 1
print(kol) | 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
def it(): return int(input())
def pr(a): return print(a)
def li(): return list(map(int, input().split()))
def ls(): return [str(i) for i in input()]
def no(): return print('NO')
def yes(): return print('YES')
def mapa(): return map(int, input().split())
#''' ????????????????????????????????????? '''#
#''' ????????| ___ ___ |???????????????? '''#
#''' ????????|(-_-) (*_*)|???????????????? '''#
#''' ????????|/| |\ /| |\|???????????????? '''#
#''' ????????|_|_|___|_|_|???????????????? '''#
#''' ????????????????????????????????????? '''#
n = [str(i) for i in input()]
kol = 0
for i in range(len(n)):
for j in range(i):
for k in range(j):
if n[i] == 'Q':
if n[j] == 'A':
if n[k] == 'Q':
kol += 1
print(kol)
``` | 3 | |
281 | A | Word Capitalization | PROGRAMMING | 800 | [
"implementation",
"strings"
] | null | null | Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged. | A single line contains a non-empty word. This word consists of lowercase and uppercase English letters. The length of the word will not exceed 103. | Output the given word after capitalization. | [
"ApPLe\n",
"konjac\n"
] | [
"ApPLe\n",
"Konjac\n"
] | none | 500 | [
{
"input": "ApPLe",
"output": "ApPLe"
},
{
"input": "konjac",
"output": "Konjac"
},
{
"input": "a",
"output": "A"
},
{
"input": "A",
"output": "A"
},
{
"input": "z",
"output": "Z"
},
{
"input": "ABACABA",
"output": "ABACABA"
},
{
"input": "... | 1,696,735,041 | 2,147,483,647 | Python 3 | OK | TESTS | 25 | 92 | 0 | inp = list(input())
inp[0] = inp[0].upper()
print("".join(inp), end="") | Title: Word Capitalization
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input Specification:
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters. The length of the word will not exceed 103.
Output Specification:
Output the given word after capitalization.
Demo Input:
['ApPLe\n', 'konjac\n']
Demo Output:
['ApPLe\n', 'Konjac\n']
Note:
none | ```python
inp = list(input())
inp[0] = inp[0].upper()
print("".join(inp), end="")
``` | 3 | |
205 | A | Little Elephant and Rozdil | PROGRAMMING | 900 | [
"brute force",
"implementation"
] | null | null | The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").
However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.
For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the number of cities. The next line contains *n* integers, separated by single spaces: the *i*-th integer represents the time needed to go from town Rozdil to the *i*-th town. The time values are positive integers, not exceeding 109.
You can consider the cities numbered from 1 to *n*, inclusive. Rozdil is not among the numbered cities. | Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes). | [
"2\n7 4\n",
"7\n7 4 47 100 4 9 12\n"
] | [
"2\n",
"Still Rozdil\n"
] | In the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.
In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil". | 500 | [
{
"input": "2\n7 4",
"output": "2"
},
{
"input": "7\n7 4 47 100 4 9 12",
"output": "Still Rozdil"
},
{
"input": "1\n47",
"output": "1"
},
{
"input": "2\n1000000000 1000000000",
"output": "Still Rozdil"
},
{
"input": "7\n7 6 5 4 3 2 1",
"output": "7"
},
{
... | 1,689,118,848 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 1 | 92 | 0 | n = int(input())
l = [int(x) for x in input().split()]
print(l.index(min(l)) + 1 if l.count(min(l)) == 1 else "Still Rozdill") | Title: Little Elephant and Rozdil
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").
However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.
For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the number of cities. The next line contains *n* integers, separated by single spaces: the *i*-th integer represents the time needed to go from town Rozdil to the *i*-th town. The time values are positive integers, not exceeding 109.
You can consider the cities numbered from 1 to *n*, inclusive. Rozdil is not among the numbered cities.
Output Specification:
Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
Demo Input:
['2\n7 4\n', '7\n7 4 47 100 4 9 12\n']
Demo Output:
['2\n', 'Still Rozdil\n']
Note:
In the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.
In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil". | ```python
n = int(input())
l = [int(x) for x in input().split()]
print(l.index(min(l)) + 1 if l.count(min(l)) == 1 else "Still Rozdill")
``` | 0 | |
347 | A | Difference Row | PROGRAMMING | 1,300 | [
"constructive algorithms",
"implementation",
"sortings"
] | null | null | You want to arrange *n* integers *a*1,<=*a*2,<=...,<=*a**n* in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers.
More formally, let's denote some arrangement as a sequence of integers *x*1,<=*x*2,<=...,<=*x**n*, where sequence *x* is a permutation of sequence *a*. The value of such an arrangement is (*x*1<=-<=*x*2)<=+<=(*x*2<=-<=*x*3)<=+<=...<=+<=(*x**n*<=-<=1<=-<=*x**n*).
Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence *x* that corresponds to an arrangement of the largest possible value. | The first line of the input contains integer *n* (2<=≤<=*n*<=≤<=100). The second line contains *n* space-separated integers *a*1, *a*2, ..., *a**n* (|*a**i*|<=≤<=1000). | Print the required sequence *x*1,<=*x*2,<=...,<=*x**n*. Sequence *x* should be the lexicographically smallest permutation of *a* that corresponds to an arrangement of the largest possible value. | [
"5\n100 -100 50 0 -50\n"
] | [
"100 -50 0 50 -100 \n"
] | In the sample test case, the value of the output arrangement is (100 - ( - 50)) + (( - 50) - 0) + (0 - 50) + (50 - ( - 100)) = 200. No other arrangement has a larger value, and among all arrangements with the value of 200, the output arrangement is the lexicographically smallest one.
Sequence *x*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub>, ... , *x*<sub class="lower-index">*p*</sub> is lexicographically smaller than sequence *y*<sub class="lower-index">1</sub>, *y*<sub class="lower-index">2</sub>, ... , *y*<sub class="lower-index">*p*</sub> if there exists an integer *r* (0 ≤ *r* < *p*) such that *x*<sub class="lower-index">1</sub> = *y*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub> = *y*<sub class="lower-index">2</sub>, ... , *x*<sub class="lower-index">*r*</sub> = *y*<sub class="lower-index">*r*</sub> and *x*<sub class="lower-index">*r* + 1</sub> < *y*<sub class="lower-index">*r* + 1</sub>. | 500 | [
{
"input": "5\n100 -100 50 0 -50",
"output": "100 -50 0 50 -100 "
},
{
"input": "10\n764 -367 0 963 -939 -795 -26 -49 948 -282",
"output": "963 -795 -367 -282 -49 -26 0 764 948 -939 "
},
{
"input": "20\n262 -689 -593 161 -678 -555 -633 -697 369 258 673 50 833 737 -650 198 -651 -621 -396 ... | 1,532,810,945 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 216 | 0 | def go():
n = int(input())
a = list(sorted([int(i) for i in input().split(' ')], reverse=True))
for i in range(n // 2):
if i % 2 == 1:
a[i], a[n - i - 1] = a[n - i - 1], a[i]
return ' '.join(str(i) for i in a)
print(go())
| Title: Difference Row
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You want to arrange *n* integers *a*1,<=*a*2,<=...,<=*a**n* in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers.
More formally, let's denote some arrangement as a sequence of integers *x*1,<=*x*2,<=...,<=*x**n*, where sequence *x* is a permutation of sequence *a*. The value of such an arrangement is (*x*1<=-<=*x*2)<=+<=(*x*2<=-<=*x*3)<=+<=...<=+<=(*x**n*<=-<=1<=-<=*x**n*).
Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence *x* that corresponds to an arrangement of the largest possible value.
Input Specification:
The first line of the input contains integer *n* (2<=≤<=*n*<=≤<=100). The second line contains *n* space-separated integers *a*1, *a*2, ..., *a**n* (|*a**i*|<=≤<=1000).
Output Specification:
Print the required sequence *x*1,<=*x*2,<=...,<=*x**n*. Sequence *x* should be the lexicographically smallest permutation of *a* that corresponds to an arrangement of the largest possible value.
Demo Input:
['5\n100 -100 50 0 -50\n']
Demo Output:
['100 -50 0 50 -100 \n']
Note:
In the sample test case, the value of the output arrangement is (100 - ( - 50)) + (( - 50) - 0) + (0 - 50) + (50 - ( - 100)) = 200. No other arrangement has a larger value, and among all arrangements with the value of 200, the output arrangement is the lexicographically smallest one.
Sequence *x*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub>, ... , *x*<sub class="lower-index">*p*</sub> is lexicographically smaller than sequence *y*<sub class="lower-index">1</sub>, *y*<sub class="lower-index">2</sub>, ... , *y*<sub class="lower-index">*p*</sub> if there exists an integer *r* (0 ≤ *r* < *p*) such that *x*<sub class="lower-index">1</sub> = *y*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub> = *y*<sub class="lower-index">2</sub>, ... , *x*<sub class="lower-index">*r*</sub> = *y*<sub class="lower-index">*r*</sub> and *x*<sub class="lower-index">*r* + 1</sub> < *y*<sub class="lower-index">*r* + 1</sub>. | ```python
def go():
n = int(input())
a = list(sorted([int(i) for i in input().split(' ')], reverse=True))
for i in range(n // 2):
if i % 2 == 1:
a[i], a[n - i - 1] = a[n - i - 1], a[i]
return ' '.join(str(i) for i in a)
print(go())
``` | 0 | |
48 | A | Rock-paper-scissors | PROGRAMMING | 900 | [
"implementation",
"schedules"
] | A. Rock-paper-scissors | 2 | 256 | Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obviously for Sharic who loves hunting and fish is for Matroskin, but for whom was a new video game console meant? Every one of the three friends claimed that the present is for him and nearly quarreled. Uncle Fyodor had an idea how to solve the problem justly: they should suppose that the console was sent to all three of them and play it in turns. Everybody got relieved but then yet another burning problem popped up — who will play first? This time Matroskin came up with a brilliant solution, suggesting the most fair way to find it out: play rock-paper-scissors together. The rules of the game are very simple. On the count of three every player shows a combination with his hand (or paw). The combination corresponds to one of three things: a rock, scissors or paper. Some of the gestures win over some other ones according to well-known rules: the rock breaks the scissors, the scissors cut the paper, and the paper gets wrapped over the stone. Usually there are two players. Yet there are three friends, that’s why they decided to choose the winner like that: If someone shows the gesture that wins over the other two players, then that player wins. Otherwise, another game round is required. Write a program that will determine the winner by the gestures they have shown. | The first input line contains the name of the gesture that Uncle Fyodor showed, the second line shows which gesture Matroskin showed and the third line shows Sharic’s gesture. | Print "F" (without quotes) if Uncle Fyodor wins. Print "M" if Matroskin wins and "S" if Sharic wins. If it is impossible to find the winner, print "?". | [
"rock\nrock\nrock\n",
"paper\nrock\nrock\n",
"scissors\nrock\nrock\n",
"scissors\npaper\nrock\n"
] | [
"?\n",
"F\n",
"?\n",
"?\n"
] | none | 0 | [
{
"input": "rock\nrock\nrock",
"output": "?"
},
{
"input": "paper\nrock\nrock",
"output": "F"
},
{
"input": "scissors\nrock\nrock",
"output": "?"
},
{
"input": "scissors\npaper\nrock",
"output": "?"
},
{
"input": "paper\npaper\nrock",
"output": "?"
},
{
... | 1,576,254,674 | 2,147,483,647 | Python 3 | OK | TESTS | 27 | 218 | 0 | f=input()
m=input()
s=input()
def win(s1, s2):
# Returns True if s2 beats s1
if s1=='rock' and s2=='paper':
return True
if s1=='paper' and s2=='scissors':
return True
if s1=='scissors' and s2=='rock':
return True
return False
if win(m, f) and win(s, f):
print('F')
elif win(f, m) and win(s, m):
print('M')
elif win(m, s) and win(f, s):
print('S')
else:
print('?') | Title: Rock-paper-scissors
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obviously for Sharic who loves hunting and fish is for Matroskin, but for whom was a new video game console meant? Every one of the three friends claimed that the present is for him and nearly quarreled. Uncle Fyodor had an idea how to solve the problem justly: they should suppose that the console was sent to all three of them and play it in turns. Everybody got relieved but then yet another burning problem popped up — who will play first? This time Matroskin came up with a brilliant solution, suggesting the most fair way to find it out: play rock-paper-scissors together. The rules of the game are very simple. On the count of three every player shows a combination with his hand (or paw). The combination corresponds to one of three things: a rock, scissors or paper. Some of the gestures win over some other ones according to well-known rules: the rock breaks the scissors, the scissors cut the paper, and the paper gets wrapped over the stone. Usually there are two players. Yet there are three friends, that’s why they decided to choose the winner like that: If someone shows the gesture that wins over the other two players, then that player wins. Otherwise, another game round is required. Write a program that will determine the winner by the gestures they have shown.
Input Specification:
The first input line contains the name of the gesture that Uncle Fyodor showed, the second line shows which gesture Matroskin showed and the third line shows Sharic’s gesture.
Output Specification:
Print "F" (without quotes) if Uncle Fyodor wins. Print "M" if Matroskin wins and "S" if Sharic wins. If it is impossible to find the winner, print "?".
Demo Input:
['rock\nrock\nrock\n', 'paper\nrock\nrock\n', 'scissors\nrock\nrock\n', 'scissors\npaper\nrock\n']
Demo Output:
['?\n', 'F\n', '?\n', '?\n']
Note:
none | ```python
f=input()
m=input()
s=input()
def win(s1, s2):
# Returns True if s2 beats s1
if s1=='rock' and s2=='paper':
return True
if s1=='paper' and s2=='scissors':
return True
if s1=='scissors' and s2=='rock':
return True
return False
if win(m, f) and win(s, f):
print('F')
elif win(f, m) and win(s, m):
print('M')
elif win(m, s) and win(f, s):
print('S')
else:
print('?')
``` | 3.9455 |
0 | none | none | none | 0 | [
"none"
] | null | null | You are given three sticks with positive integer lengths of *a*,<=*b*, and *c* centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most *l* centimeters. In particular, it is allowed not to increase the length of any stick.
Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. | The single line contains 4 integers *a*,<=*b*,<=*c*,<=*l* (1<=≤<=*a*,<=*b*,<=*c*<=≤<=3·105, 0<=≤<=*l*<=≤<=3·105). | Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most *l* centimeters, so that you can make a non-degenerate triangle from it. | [
"1 1 1 2\n",
"1 2 3 1\n",
"10 2 1 7\n"
] | [
"4\n",
"2\n",
"0\n"
] | In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter.
In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. | 0 | [
{
"input": "1 1 1 2",
"output": "4"
},
{
"input": "1 2 3 1",
"output": "2"
},
{
"input": "10 2 1 7",
"output": "0"
},
{
"input": "1 2 1 5",
"output": "20"
},
{
"input": "10 15 17 10",
"output": "281"
},
{
"input": "5 5 5 10000",
"output": "41841675... | 1,440,266,457 | 5,457 | PyPy 3 | TIME_LIMIT_EXCEEDED | PRETESTS | 5 | 1,000 | 5,836,800 | a, b, c, l = list(map(int, input().split()))
ans = 0
for i in range(l + 1):
a1 = a + i
lmin = max(a1 - (b + c) + 1, 0)
lmax = l - i
diffmax = a1 + b - c - 1
diffmin = b - c - a1 + 1
for lc in range(lmax + 1):
ans += max(-1, min(lmax - lc, lc - diffmin) - max(lc - diffmax, lmin-lc, 0)) + 1
print(ans) | Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given three sticks with positive integer lengths of *a*,<=*b*, and *c* centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most *l* centimeters. In particular, it is allowed not to increase the length of any stick.
Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them.
Input Specification:
The single line contains 4 integers *a*,<=*b*,<=*c*,<=*l* (1<=≤<=*a*,<=*b*,<=*c*<=≤<=3·105, 0<=≤<=*l*<=≤<=3·105).
Output Specification:
Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most *l* centimeters, so that you can make a non-degenerate triangle from it.
Demo Input:
['1 1 1 2\n', '1 2 3 1\n', '10 2 1 7\n']
Demo Output:
['4\n', '2\n', '0\n']
Note:
In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter.
In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. | ```python
a, b, c, l = list(map(int, input().split()))
ans = 0
for i in range(l + 1):
a1 = a + i
lmin = max(a1 - (b + c) + 1, 0)
lmax = l - i
diffmax = a1 + b - c - 1
diffmin = b - c - a1 + 1
for lc in range(lmax + 1):
ans += max(-1, min(lmax - lc, lc - diffmin) - max(lc - diffmax, lmin-lc, 0)) + 1
print(ans)
``` | 0 | |
784 | A | Numbers Joke | PROGRAMMING | 1,700 | [
"*special"
] | null | null | The input contains a single integer *a* (1<=≤<=*a*<=≤<=30).
Output a single integer. | The input contains a single integer *a* (1<=≤<=*a*<=≤<=30). | Output a single integer. | [
"3\n"
] | [
"27\n"
] | none | 0 | [
{
"input": "3",
"output": "27"
},
{
"input": "1",
"output": "4"
},
{
"input": "2",
"output": "22"
},
{
"input": "4",
"output": "58"
},
{
"input": "5",
"output": "85"
},
{
"input": "6",
"output": "94"
},
{
"input": "7",
"output": "121"
... | 1,491,369,606 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 62 | 5,632,000 | from math import *
def resheto(n):
prime = [True for _ in range(n+1)]
prime[0] = prime[1] = False
for i in range(2, n+1):
if prime[i]:
if i ** 2 <= n:
for j in range(i**2, n+1, i):
prime[j] = False
answer = []
for i in range(n + 1):
if prime[i]:
answer.append(i)
return answer
class Integer(int):
def __pow__(self, power, modulo=None):
k = power
bbb = 1
c = self
while k:
if k % 2 == 0:
k /= 2
c *= c
else:
k -= 1
bbb *= c
return bbb
def can_divide(self, n):
if n == 0:
return False
else:
if self % n == 0:
return True
else:
return False
def trial_division(self):
divisions = []
d = 2
number = self
while number > 1:
if number % d == 0:
divisions.append(d)
number /= d
else:
d += 1
return sorted(divisions)
def is_prime(self):
if self == 2:
return True
j = int(sqrt(self)+1)
for i in range(2, j+1):
if self % i == 0:
return False
return True
def gcd(self, bb):
aa = self
while bb:
aa %= bb
aa, bb = bb, aa
return aa
def lmc(self, bull):
return int(self / gcd(self, bull) * bull)
class Matrix:
def __init__(self, size):
matrix = []
for i in range(size):
matrix.append([])
for j in range(size):
matrix[i].append(0)
self.matrix = matrix
self.n = size
def edit_element(self, cords, new_value):
self.matrix[cords[0]][cords[1]] = new_value
def __add__(self, other_matrix):
c = Matrix(self.n)
for i in range(self.n):
for j in range(self.n):
c.edit_element((i, j), self.matrix[i][j] + other_matrix.matrix[i][j])
return c
def __mul__(self, other_matrix):
c = Matrix(self.n)
for i in range(self.n):
for j in range(i):
k = other_matrix.matrix[i][j]
other_matrix.matrix[i][j] = other_matrix.matrix[j][i]
other_matrix.matrix[j][i] = k
for i in range(self.n):
for j in range(self.n):
c.matrix[i][j] = 0
for k in range(self.n):
c.matrix[i][j] += self.matrix[i][k] * other_matrix.matrix[j][k]
for i in range(self.n):
for j in range(i):
k = other_matrix.matrix[i][j]
other_matrix.matrix[i][j] = other_matrix.matrix[j][i]
other_matrix.matrix[j][i] = k
return c
joke = [4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438, 454, 483, 517, 526, 535, 562,
576, 588, 627, 634, 636, 645, 648, 654, 663, 666, 690, 706, 728, 729, 762, 778, 825, 852, 861, 895, 913, 915,
922, 958, 985, 1086, 1111, 1165]
a = int(input())
print(joke[a-1]) | Title: Numbers Joke
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The input contains a single integer *a* (1<=≤<=*a*<=≤<=30).
Output a single integer.
Input Specification:
The input contains a single integer *a* (1<=≤<=*a*<=≤<=30).
Output Specification:
Output a single integer.
Demo Input:
['3\n']
Demo Output:
['27\n']
Note:
none | ```python
from math import *
def resheto(n):
prime = [True for _ in range(n+1)]
prime[0] = prime[1] = False
for i in range(2, n+1):
if prime[i]:
if i ** 2 <= n:
for j in range(i**2, n+1, i):
prime[j] = False
answer = []
for i in range(n + 1):
if prime[i]:
answer.append(i)
return answer
class Integer(int):
def __pow__(self, power, modulo=None):
k = power
bbb = 1
c = self
while k:
if k % 2 == 0:
k /= 2
c *= c
else:
k -= 1
bbb *= c
return bbb
def can_divide(self, n):
if n == 0:
return False
else:
if self % n == 0:
return True
else:
return False
def trial_division(self):
divisions = []
d = 2
number = self
while number > 1:
if number % d == 0:
divisions.append(d)
number /= d
else:
d += 1
return sorted(divisions)
def is_prime(self):
if self == 2:
return True
j = int(sqrt(self)+1)
for i in range(2, j+1):
if self % i == 0:
return False
return True
def gcd(self, bb):
aa = self
while bb:
aa %= bb
aa, bb = bb, aa
return aa
def lmc(self, bull):
return int(self / gcd(self, bull) * bull)
class Matrix:
def __init__(self, size):
matrix = []
for i in range(size):
matrix.append([])
for j in range(size):
matrix[i].append(0)
self.matrix = matrix
self.n = size
def edit_element(self, cords, new_value):
self.matrix[cords[0]][cords[1]] = new_value
def __add__(self, other_matrix):
c = Matrix(self.n)
for i in range(self.n):
for j in range(self.n):
c.edit_element((i, j), self.matrix[i][j] + other_matrix.matrix[i][j])
return c
def __mul__(self, other_matrix):
c = Matrix(self.n)
for i in range(self.n):
for j in range(i):
k = other_matrix.matrix[i][j]
other_matrix.matrix[i][j] = other_matrix.matrix[j][i]
other_matrix.matrix[j][i] = k
for i in range(self.n):
for j in range(self.n):
c.matrix[i][j] = 0
for k in range(self.n):
c.matrix[i][j] += self.matrix[i][k] * other_matrix.matrix[j][k]
for i in range(self.n):
for j in range(i):
k = other_matrix.matrix[i][j]
other_matrix.matrix[i][j] = other_matrix.matrix[j][i]
other_matrix.matrix[j][i] = k
return c
joke = [4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438, 454, 483, 517, 526, 535, 562,
576, 588, 627, 634, 636, 645, 648, 654, 663, 666, 690, 706, 728, 729, 762, 778, 825, 852, 861, 895, 913, 915,
922, 958, 985, 1086, 1111, 1165]
a = int(input())
print(joke[a-1])
``` | 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,646,144,341 | 2,147,483,647 | Python 3 | OK | TESTS | 81 | 92 | 0 | n=int(input())
xs=0
ys=0
zs=0
for _ in range(n):
x,y,z=map(int,input().split())
xs+=x
ys+=y
zs+=z
if xs or ys or zs:
print("NO")
else:
print("YES") | 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())
xs=0
ys=0
zs=0
for _ in range(n):
x,y,z=map(int,input().split())
xs+=x
ys+=y
zs+=z
if xs or ys or zs:
print("NO")
else:
print("YES")
``` | 3.977 |
538 | B | Quasi Binary | PROGRAMMING | 1,400 | [
"constructive algorithms",
"dp",
"greedy",
"implementation"
] | null | null | A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer *n*. Represent it as a sum of minimum number of quasibinary numbers. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=106). | In the first line print a single integer *k* — the minimum number of numbers in the representation of number *n* as a sum of quasibinary numbers.
In the second line print *k* numbers — the elements of the sum. All these numbers should be quasibinary according to the definition above, their sum should equal *n*. Do not have to print the leading zeroes in the numbers. The order of numbers doesn't matter. If there are multiple possible representations, you are allowed to print any of them. | [
"9\n",
"32\n"
] | [
"9\n1 1 1 1 1 1 1 1 1 \n",
"3\n10 11 11 \n"
] | none | 1,000 | [
{
"input": "9",
"output": "9\n1 1 1 1 1 1 1 1 1 "
},
{
"input": "32",
"output": "3\n10 11 11 "
},
{
"input": "1",
"output": "1\n1 "
},
{
"input": "415",
"output": "5\n1 101 101 101 111 "
},
{
"input": "10011",
"output": "1\n10011 "
},
{
"input": "10201... | 1,597,429,469 | 2,147,483,647 | PyPy 3 | OK | TESTS | 25 | 140 | 0 | import sys
import math
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
def quasibinary_repr(num):
results = []
num_digits = int(math.log10(num)) + 1
while num > 0:
cur_num = num
cur_quasi_num = 0
for i in range(num_digits):
result = (cur_num % 10)
if result > 0:
cur_quasi_num = cur_quasi_num + 1 * (10**i)
cur_num = cur_num // 10
num = num - cur_quasi_num
results.append(cur_quasi_num)
return results
num = inp()
result = quasibinary_repr(num)
print(len(result))
print(*result, sep=" ")
| Title: Quasi Binary
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer *n*. Represent it as a sum of minimum number of quasibinary numbers.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=106).
Output Specification:
In the first line print a single integer *k* — the minimum number of numbers in the representation of number *n* as a sum of quasibinary numbers.
In the second line print *k* numbers — the elements of the sum. All these numbers should be quasibinary according to the definition above, their sum should equal *n*. Do not have to print the leading zeroes in the numbers. The order of numbers doesn't matter. If there are multiple possible representations, you are allowed to print any of them.
Demo Input:
['9\n', '32\n']
Demo Output:
['9\n1 1 1 1 1 1 1 1 1 \n', '3\n10 11 11 \n']
Note:
none | ```python
import sys
import math
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
def quasibinary_repr(num):
results = []
num_digits = int(math.log10(num)) + 1
while num > 0:
cur_num = num
cur_quasi_num = 0
for i in range(num_digits):
result = (cur_num % 10)
if result > 0:
cur_quasi_num = cur_quasi_num + 1 * (10**i)
cur_num = cur_num // 10
num = num - cur_quasi_num
results.append(cur_quasi_num)
return results
num = inp()
result = quasibinary_repr(num)
print(len(result))
print(*result, sep=" ")
``` | 3 | |
78 | A | Haiku | PROGRAMMING | 800 | [
"implementation",
"strings"
] | A. Haiku | 2 | 256 | Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.
To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".
Three phases from a certain poem are given. Determine whether it is haiku or not. | The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The *i*-th line contains the *i*-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification. | Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes). | [
"on codeforces \nbeta round is running\n a rustling of keys \n",
"how many gallons\nof edo s rain did you drink\n cuckoo\n"
] | [
"YES",
"NO"
] | none | 500 | [
{
"input": "on codeforces \nbeta round is running\n a rustling of keys ",
"output": "YES"
},
{
"input": "how many gallons\nof edo s rain did you drink\n cuckoo",
"output": "NO"
},
{
"input": " hatsu shigure\n saru mo komino wo\nhoshige nari",
... | 1,658,335,566 | 2,147,483,647 | Python 3 | OK | TESTS | 40 | 92 | 0 | s1=input()
s2=input()
s3=input()
s1=s1.strip()
s2=s2.strip()
s3=s3.strip()
syllables = set("AEIOUaeiou")
##print(s1)
##print(s2)
##print(s3)
c1=0
c2=0
c3=0
for i in s1:
if(i in syllables):
c1+=1
for i in s2:
if(i in syllables):
c2+=1
for i in s3:
if(i in syllables):
c3+=1
if(c1==5 and c2==7 and c3==5):
print("YES")
else:
print("NO") | Title: Haiku
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.
To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".
Three phases from a certain poem are given. Determine whether it is haiku or not.
Input Specification:
The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The *i*-th line contains the *i*-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.
Output Specification:
Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).
Demo Input:
['on codeforces \nbeta round is running\n a rustling of keys \n', 'how many gallons\nof edo s rain did you drink\n cuckoo\n']
Demo Output:
['YES', 'NO']
Note:
none | ```python
s1=input()
s2=input()
s3=input()
s1=s1.strip()
s2=s2.strip()
s3=s3.strip()
syllables = set("AEIOUaeiou")
##print(s1)
##print(s2)
##print(s3)
c1=0
c2=0
c3=0
for i in s1:
if(i in syllables):
c1+=1
for i in s2:
if(i in syllables):
c2+=1
for i in s3:
if(i in syllables):
c3+=1
if(c1==5 and c2==7 and c3==5):
print("YES")
else:
print("NO")
``` | 3.977 |
932 | B | Recursive Queries | PROGRAMMING | 1,300 | [
"binary search",
"data structures",
"dfs and similar"
] | null | null | Let us define two functions *f* and *g* on positive integer numbers.
You need to process *Q* queries. In each query, you will be given three integers *l*, *r* and *k*. You need to print the number of integers *x* between *l* and *r* inclusive, such that *g*(*x*)<==<=*k*. | The first line of the input contains an integer *Q* (1<=≤<=*Q*<=≤<=2<=×<=105) representing the number of queries.
*Q* lines follow, each of which contains 3 integers *l*, *r* and *k* (1<=≤<=*l*<=≤<=*r*<=≤<=106,<=1<=≤<=*k*<=≤<=9). | For each query, print a single line containing the answer for that query. | [
"4\n22 73 9\n45 64 6\n47 55 7\n2 62 4\n",
"4\n82 94 6\n56 67 4\n28 59 9\n39 74 4\n"
] | [
"1\n4\n0\n8\n",
"3\n1\n1\n5\n"
] | In the first example:
- *g*(33) = 9 as *g*(33) = *g*(3 × 3) = *g*(9) = 9 - *g*(47) = *g*(48) = *g*(60) = *g*(61) = 6 - There are no such integers between 47 and 55. - *g*(4) = *g*(14) = *g*(22) = *g*(27) = *g*(39) = *g*(40) = *g*(41) = *g*(58) = 4 | 1,000 | [
{
"input": "4\n22 73 9\n45 64 6\n47 55 7\n2 62 4",
"output": "1\n4\n0\n8"
},
{
"input": "4\n82 94 6\n56 67 4\n28 59 9\n39 74 4",
"output": "3\n1\n1\n5"
}
] | 1,518,710,667 | 5,367 | Python 3 | SKIPPED | PRETESTS | 0 | 2,000 | 45,670,400 | def c(n):
m = 1
while n>= 10:
if n%10 != 0:
m*=n%10
n=n/10
return m
t = 10*[0]
a = 10*[0]
for i in range(10):
a[i] = (10**6)*[0]
for i in range(10**6):
m = c(i)
t[m]+=1
for j in range(10):
a[j][i]=t[j]
n=int(input())
for i in range(n):
l,r,k = [int(j) for j in input().split()]
print(a[k][r]-a[k][l-1])
| Title: Recursive Queries
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let us define two functions *f* and *g* on positive integer numbers.
You need to process *Q* queries. In each query, you will be given three integers *l*, *r* and *k*. You need to print the number of integers *x* between *l* and *r* inclusive, such that *g*(*x*)<==<=*k*.
Input Specification:
The first line of the input contains an integer *Q* (1<=≤<=*Q*<=≤<=2<=×<=105) representing the number of queries.
*Q* lines follow, each of which contains 3 integers *l*, *r* and *k* (1<=≤<=*l*<=≤<=*r*<=≤<=106,<=1<=≤<=*k*<=≤<=9).
Output Specification:
For each query, print a single line containing the answer for that query.
Demo Input:
['4\n22 73 9\n45 64 6\n47 55 7\n2 62 4\n', '4\n82 94 6\n56 67 4\n28 59 9\n39 74 4\n']
Demo Output:
['1\n4\n0\n8\n', '3\n1\n1\n5\n']
Note:
In the first example:
- *g*(33) = 9 as *g*(33) = *g*(3 × 3) = *g*(9) = 9 - *g*(47) = *g*(48) = *g*(60) = *g*(61) = 6 - There are no such integers between 47 and 55. - *g*(4) = *g*(14) = *g*(22) = *g*(27) = *g*(39) = *g*(40) = *g*(41) = *g*(58) = 4 | ```python
def c(n):
m = 1
while n>= 10:
if n%10 != 0:
m*=n%10
n=n/10
return m
t = 10*[0]
a = 10*[0]
for i in range(10):
a[i] = (10**6)*[0]
for i in range(10**6):
m = c(i)
t[m]+=1
for j in range(10):
a[j][i]=t[j]
n=int(input())
for i in range(n):
l,r,k = [int(j) for j in input().split()]
print(a[k][r]-a[k][l-1])
``` | -1 | |
1 | A | Theatre Square | PROGRAMMING | 1,000 | [
"math"
] | A. Theatre Square | 1 | 256 | Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square. | The input contains three positive integer numbers in the first line: *n*,<=<=*m* and *a* (1<=≤<=<=*n*,<=*m*,<=*a*<=≤<=109). | Write the needed number of flagstones. | [
"6 6 4\n"
] | [
"4\n"
] | none | 0 | [
{
"input": "6 6 4",
"output": "4"
},
{
"input": "1 1 1",
"output": "1"
},
{
"input": "2 1 1",
"output": "2"
},
{
"input": "1 2 1",
"output": "2"
},
{
"input": "2 2 1",
"output": "4"
},
{
"input": "2 1 2",
"output": "1"
},
{
"input": "1 1 3"... | 1,666,936,382 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 30 | 0 | x=input().split()
n=int(x[0])
m=int(x[1])
a=int(x[2])
y=(n//a+1)*(m//a+1)
print(y) | Title: Theatre Square
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
Input Specification:
The input contains three positive integer numbers in the first line: *n*,<=<=*m* and *a* (1<=≤<=<=*n*,<=*m*,<=*a*<=≤<=109).
Output Specification:
Write the needed number of flagstones.
Demo Input:
['6 6 4\n']
Demo Output:
['4\n']
Note:
none | ```python
x=input().split()
n=int(x[0])
m=int(x[1])
a=int(x[2])
y=(n//a+1)*(m//a+1)
print(y)
``` | 0 |
916 | B | Jamie and Binary Sequence (changed after round) | PROGRAMMING | 2,000 | [
"bitmasks",
"greedy",
"math"
] | null | null | Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:
Find *k* integers such that the sum of two to the power of each number equals to the number *n* and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one.
To be more clear, consider all integer sequence with length *k* (*a*1,<=*a*2,<=...,<=*a**k*) with . Give a value to each sequence. Among all sequence(s) that have the minimum *y* value, output the one that is the lexicographically largest.
For definitions of powers and lexicographical order see notes. | The first line consists of two integers *n* and *k* (1<=≤<=*n*<=≤<=1018,<=1<=≤<=*k*<=≤<=105) — the required sum and the length of the sequence. | Output "No" (without quotes) in a single line if there does not exist such sequence. Otherwise, output "Yes" (without quotes) in the first line, and *k* numbers separated by space in the second line — the required sequence.
It is guaranteed that the integers in the answer sequence fit the range [<=-<=1018,<=1018]. | [
"23 5\n",
"13 2\n",
"1 2\n"
] | [
"Yes\n3 3 2 1 0 \n",
"No\n",
"Yes\n-1 -1 \n"
] | Sample 1:
2<sup class="upper-index">3</sup> + 2<sup class="upper-index">3</sup> + 2<sup class="upper-index">2</sup> + 2<sup class="upper-index">1</sup> + 2<sup class="upper-index">0</sup> = 8 + 8 + 4 + 2 + 1 = 23
Answers like (3, 3, 2, 0, 1) or (0, 1, 2, 3, 3) are not lexicographically largest.
Answers like (4, 1, 1, 1, 0) do not have the minimum *y* value.
Sample 2:
It can be shown there does not exist a sequence with length 2.
Sample 3:
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a8539b2d27aefc8d2fab6dfd8296d11c36dcaa40.png" style="max-width: 100.0%;max-height: 100.0%;"/>
Powers of 2:
If *x* > 0, then 2<sup class="upper-index">*x*</sup> = 2·2·2·...·2 (*x* times).
If *x* = 0, then 2<sup class="upper-index">*x*</sup> = 1.
If *x* < 0, then <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/766628f1c7814795eac1a0afaa1ff062c40ef29e.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
Lexicographical order:
Given two different sequences of the same length, (*a*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">2</sub>, ... , *a*<sub class="lower-index">*k*</sub>) and (*b*<sub class="lower-index">1</sub>, *b*<sub class="lower-index">2</sub>, ... , *b*<sub class="lower-index">*k*</sub>), the first one is smaller than the second one for the lexicographical order, if and only if *a*<sub class="lower-index">*i*</sub> < *b*<sub class="lower-index">*i*</sub>, for the first *i* where *a*<sub class="lower-index">*i*</sub> and *b*<sub class="lower-index">*i*</sub> differ. | 1,000 | [
{
"input": "23 5",
"output": "Yes\n3 3 2 1 0 "
},
{
"input": "13 2",
"output": "No"
},
{
"input": "1 2",
"output": "Yes\n-1 -1 "
},
{
"input": "1 1",
"output": "Yes\n0 "
},
{
"input": "1000000000000000000 100000",
"output": "Yes\n44 44 44 44 44 44 44 44 44 44 ... | 1,517,810,259 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 61 | 5,632,000 | n, k = map(int, input().split(" "))
binary = bin(n)[2:][::-1]
last = 0
cnt=0
for i in range(len(binary)):
if binary[i] == '1':
if cnt==0:
last=i
cnt+=1
arr = list(map(int, binary))
length = len(arr)
if cnt > k:
print("No")
exit()
print("Yes")
c = 0
pr = 0
s = 0
if cnt != k:
for i in range(length-1, -10000000000, -1):
if i > -1 and binary[i] == '1':
c += 1
s += 1
if (c * 2 + (cnt - s) <= k):
c *= 2
pr = i - 1
if (int(c/2) + (cnt-s) == k):
break
else:
break
else:
pr = length-1
rem = k - c
if pr < 0:
last = pr - 1
c -= 1
if rem == 1 and k != 1:
print((str(pr)+" ")*(c-1)+(str(pr-1)+" ")*2, end='')
rem = 0
else:
print((str(pr)+" ")*c, end='')
for i in range(pr-1, -1, -1):
if rem == 0:
exit()
if i>0 and binary[i] == '1':
if i == last:
if rem > 1:
break
c+=1
print(str(i), end=' ')
rem -= 1
for i in range(last-1, last-rem, -1):
if rem==0:
break
print(str(i), end=' ')
if rem != 0:
print(str(last-rem+1)+" ") | Title: Jamie and Binary Sequence (changed after round)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:
Find *k* integers such that the sum of two to the power of each number equals to the number *n* and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one.
To be more clear, consider all integer sequence with length *k* (*a*1,<=*a*2,<=...,<=*a**k*) with . Give a value to each sequence. Among all sequence(s) that have the minimum *y* value, output the one that is the lexicographically largest.
For definitions of powers and lexicographical order see notes.
Input Specification:
The first line consists of two integers *n* and *k* (1<=≤<=*n*<=≤<=1018,<=1<=≤<=*k*<=≤<=105) — the required sum and the length of the sequence.
Output Specification:
Output "No" (without quotes) in a single line if there does not exist such sequence. Otherwise, output "Yes" (without quotes) in the first line, and *k* numbers separated by space in the second line — the required sequence.
It is guaranteed that the integers in the answer sequence fit the range [<=-<=1018,<=1018].
Demo Input:
['23 5\n', '13 2\n', '1 2\n']
Demo Output:
['Yes\n3 3 2 1 0 \n', 'No\n', 'Yes\n-1 -1 \n']
Note:
Sample 1:
2<sup class="upper-index">3</sup> + 2<sup class="upper-index">3</sup> + 2<sup class="upper-index">2</sup> + 2<sup class="upper-index">1</sup> + 2<sup class="upper-index">0</sup> = 8 + 8 + 4 + 2 + 1 = 23
Answers like (3, 3, 2, 0, 1) or (0, 1, 2, 3, 3) are not lexicographically largest.
Answers like (4, 1, 1, 1, 0) do not have the minimum *y* value.
Sample 2:
It can be shown there does not exist a sequence with length 2.
Sample 3:
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a8539b2d27aefc8d2fab6dfd8296d11c36dcaa40.png" style="max-width: 100.0%;max-height: 100.0%;"/>
Powers of 2:
If *x* > 0, then 2<sup class="upper-index">*x*</sup> = 2·2·2·...·2 (*x* times).
If *x* = 0, then 2<sup class="upper-index">*x*</sup> = 1.
If *x* < 0, then <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/766628f1c7814795eac1a0afaa1ff062c40ef29e.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
Lexicographical order:
Given two different sequences of the same length, (*a*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">2</sub>, ... , *a*<sub class="lower-index">*k*</sub>) and (*b*<sub class="lower-index">1</sub>, *b*<sub class="lower-index">2</sub>, ... , *b*<sub class="lower-index">*k*</sub>), the first one is smaller than the second one for the lexicographical order, if and only if *a*<sub class="lower-index">*i*</sub> < *b*<sub class="lower-index">*i*</sub>, for the first *i* where *a*<sub class="lower-index">*i*</sub> and *b*<sub class="lower-index">*i*</sub> differ. | ```python
n, k = map(int, input().split(" "))
binary = bin(n)[2:][::-1]
last = 0
cnt=0
for i in range(len(binary)):
if binary[i] == '1':
if cnt==0:
last=i
cnt+=1
arr = list(map(int, binary))
length = len(arr)
if cnt > k:
print("No")
exit()
print("Yes")
c = 0
pr = 0
s = 0
if cnt != k:
for i in range(length-1, -10000000000, -1):
if i > -1 and binary[i] == '1':
c += 1
s += 1
if (c * 2 + (cnt - s) <= k):
c *= 2
pr = i - 1
if (int(c/2) + (cnt-s) == k):
break
else:
break
else:
pr = length-1
rem = k - c
if pr < 0:
last = pr - 1
c -= 1
if rem == 1 and k != 1:
print((str(pr)+" ")*(c-1)+(str(pr-1)+" ")*2, end='')
rem = 0
else:
print((str(pr)+" ")*c, end='')
for i in range(pr-1, -1, -1):
if rem == 0:
exit()
if i>0 and binary[i] == '1':
if i == last:
if rem > 1:
break
c+=1
print(str(i), end=' ')
rem -= 1
for i in range(last-1, last-rem, -1):
if rem==0:
break
print(str(i), end=' ')
if rem != 0:
print(str(last-rem+1)+" ")
``` | 0 | |
49 | A | Sleuth | PROGRAMMING | 800 | [
"implementation"
] | A. Sleuth | 2 | 256 | Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that.
Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.
The English alphabet vowels are: A, E, I, O, U, Y
The English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z | The single line contains a question represented by a non-empty line consisting of large and small Latin letters, spaces and a question mark. The line length does not exceed 100. It is guaranteed that the question mark occurs exactly once in the line — as the last symbol and that the line contains at least one letter. | Print answer for the question in a single line: YES if the answer is "Yes", NO if the answer is "No".
Remember that in the reply to the question the last letter, not the last character counts. I. e. the spaces and the question mark do not count as letters. | [
"Is it a melon?\n",
"Is it an apple?\n",
"Is it a banana ?\n",
"Is it an apple and a banana simultaneouSLY?\n"
] | [
"NO\n",
"YES\n",
"YES\n",
"YES\n"
] | none | 500 | [
{
"input": "Is it a melon?",
"output": "NO"
},
{
"input": "Is it an apple?",
"output": "YES"
},
{
"input": " Is it a banana ?",
"output": "YES"
},
{
"input": "Is it an apple and a banana simultaneouSLY?",
"output": "YES"
},
{
"input": "oHtSbDwzHb?",
... | 1,529,733,413 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 154 | 0 | a=input()
b=a.lower()
for j in range(len(b)):
if b[-j].isalpha():
if b[-j]=="a":
print("YES")
elif b[-j]=="e":
print("YES")
elif b[-j]=="i":
print("YES")
elif b[-j]=="u":
print("YES")
elif b[-j]=="y":
print("YES")
else:
print("NO")
break | Title: Sleuth
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that.
Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.
The English alphabet vowels are: A, E, I, O, U, Y
The English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z
Input Specification:
The single line contains a question represented by a non-empty line consisting of large and small Latin letters, spaces and a question mark. The line length does not exceed 100. It is guaranteed that the question mark occurs exactly once in the line — as the last symbol and that the line contains at least one letter.
Output Specification:
Print answer for the question in a single line: YES if the answer is "Yes", NO if the answer is "No".
Remember that in the reply to the question the last letter, not the last character counts. I. e. the spaces and the question mark do not count as letters.
Demo Input:
['Is it a melon?\n', 'Is it an apple?\n', 'Is it a banana ?\n', 'Is it an apple and a banana simultaneouSLY?\n']
Demo Output:
['NO\n', 'YES\n', 'YES\n', 'YES\n']
Note:
none | ```python
a=input()
b=a.lower()
for j in range(len(b)):
if b[-j].isalpha():
if b[-j]=="a":
print("YES")
elif b[-j]=="e":
print("YES")
elif b[-j]=="i":
print("YES")
elif b[-j]=="u":
print("YES")
elif b[-j]=="y":
print("YES")
else:
print("NO")
break
``` | 0 |
837 | F | Prefix Sums | PROGRAMMING | 2,400 | [
"binary search",
"brute force",
"combinatorics",
"math",
"matrices"
] | null | null | Consider the function *p*(*x*), where *x* is an array of *m* integers, which returns an array *y* consisting of *m*<=+<=1 integers such that *y**i* is equal to the sum of first *i* elements of array *x* (0<=≤<=*i*<=≤<=*m*).
You have an infinite sequence of arrays *A*0,<=*A*1,<=*A*2..., where *A*0 is given in the input, and for each *i*<=≥<=1 *A**i*<==<=*p*(*A**i*<=-<=1). Also you have a positive integer *k*. You have to find minimum possible *i* such that *A**i* contains a number which is larger or equal than *k*. | The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=200000, 1<=≤<=*k*<=≤<=1018). *n* is the size of array *A*0.
The second line contains *n* integers *A*00,<=*A*01... *A*0*n*<=-<=1 — the elements of *A*0 (0<=≤<=*A*0*i*<=≤<=109). At least two elements of *A*0 are positive. | Print the minimum *i* such that *A**i* contains a number which is larger or equal than *k*. | [
"2 2\n1 1\n",
"3 6\n1 1 1\n",
"3 1\n1 0 1\n"
] | [
"1\n",
"2\n",
"0\n"
] | none | 0 | [
{
"input": "2 2\n1 1",
"output": "1"
},
{
"input": "3 6\n1 1 1",
"output": "2"
},
{
"input": "3 1\n1 0 1",
"output": "0"
},
{
"input": "3 1000000000000000000\n5 4 5",
"output": "632455531"
},
{
"input": "4 1000000000000000000\n0 4 4 5",
"output": "707106780"
... | 1,613,211,820 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 24 | 1,000 | 16,691,200 | mod = 10**9 + 7
n, k = map(int,input().split())
a = list(map(int, input().split()))
a.reverse()
def sol() :
l = 0; r = 10**18; mid = 0; p = 1; sum = 0
while r - l > 1 :
mid = (l + r) // 2
p = 1; sum = 0
for i in range(n) :
sum += a[i] * p
if sum >= k : r = mid; break
if i + 1 < n : p = p * (mid + i) // (i + 1)
if r != mid : l = mid + 1
p = 1; sum = 0
for i in range(n) :
sum += a[i] * p
if sum >= k : return l
if i + 1 < n : p = p * (l + i) // (i + 1)
return r
for i in range(n - 1, -1, -1) :
if a[i] != 0 : break
else : n -= 1
if max(a) >= k : print(0)
else : print(sol()) | Title: Prefix Sums
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Consider the function *p*(*x*), where *x* is an array of *m* integers, which returns an array *y* consisting of *m*<=+<=1 integers such that *y**i* is equal to the sum of first *i* elements of array *x* (0<=≤<=*i*<=≤<=*m*).
You have an infinite sequence of arrays *A*0,<=*A*1,<=*A*2..., where *A*0 is given in the input, and for each *i*<=≥<=1 *A**i*<==<=*p*(*A**i*<=-<=1). Also you have a positive integer *k*. You have to find minimum possible *i* such that *A**i* contains a number which is larger or equal than *k*.
Input Specification:
The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=200000, 1<=≤<=*k*<=≤<=1018). *n* is the size of array *A*0.
The second line contains *n* integers *A*00,<=*A*01... *A*0*n*<=-<=1 — the elements of *A*0 (0<=≤<=*A*0*i*<=≤<=109). At least two elements of *A*0 are positive.
Output Specification:
Print the minimum *i* such that *A**i* contains a number which is larger or equal than *k*.
Demo Input:
['2 2\n1 1\n', '3 6\n1 1 1\n', '3 1\n1 0 1\n']
Demo Output:
['1\n', '2\n', '0\n']
Note:
none | ```python
mod = 10**9 + 7
n, k = map(int,input().split())
a = list(map(int, input().split()))
a.reverse()
def sol() :
l = 0; r = 10**18; mid = 0; p = 1; sum = 0
while r - l > 1 :
mid = (l + r) // 2
p = 1; sum = 0
for i in range(n) :
sum += a[i] * p
if sum >= k : r = mid; break
if i + 1 < n : p = p * (mid + i) // (i + 1)
if r != mid : l = mid + 1
p = 1; sum = 0
for i in range(n) :
sum += a[i] * p
if sum >= k : return l
if i + 1 < n : p = p * (l + i) // (i + 1)
return r
for i in range(n - 1, -1, -1) :
if a[i] != 0 : break
else : n -= 1
if max(a) >= k : print(0)
else : print(sol())
``` | 0 | |
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,615,612,037 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 124 | 0 | string = input()
low=0
high=0
for i in string:
if (i.islower()):
low+=1
else :
high+=1
if low >= high:
print(string.lower())
else :
print(string.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
string = input()
low=0
high=0
for i in string:
if (i.islower()):
low+=1
else :
high+=1
if low >= high:
print(string.lower())
else :
print(string.upper())
``` | 3.969 |
43 | A | Football | PROGRAMMING | 1,000 | [
"strings"
] | A. Football | 2 | 256 | One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of lines in the description. Then follow *n* lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams. | Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner. | [
"1\nABC\n",
"5\nA\nABA\nABA\nA\nA\n"
] | [
"ABC\n",
"A\n"
] | none | 500 | [
{
"input": "1\nABC",
"output": "ABC"
},
{
"input": "5\nA\nABA\nABA\nA\nA",
"output": "A"
},
{
"input": "2\nXTSJEP\nXTSJEP",
"output": "XTSJEP"
},
{
"input": "3\nXZYDJAEDZ\nXZYDJAEDZ\nXZYDJAEDZ",
"output": "XZYDJAEDZ"
},
{
"input": "3\nQCCYXL\nQCCYXL\nAXGLFQDD",
... | 1,589,313,408 | 2,147,483,647 | Python 3 | OK | TESTS | 34 | 218 | 6,963,200 | n = int(input())
lst=[]
for i in range(n):
a = input()
lst.append(a)
used=[]
if n==1:
print(lst[0])
else:
unique = [used.append(x) for x in lst if x not in used]
if len(used) == 2:
team1 = lst.count(used[0])
team2 = lst.count(used[1])
if team1 > team2:
print(used[0])
else:
print(used[1])
else:
team1 = lst.count(used[0])
team2 = 0
if team1 > team2:
print(used[0]) | Title: Football
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of lines in the description. Then follow *n* lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.
Output Specification:
Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.
Demo Input:
['1\nABC\n', '5\nA\nABA\nABA\nA\nA\n']
Demo Output:
['ABC\n', 'A\n']
Note:
none | ```python
n = int(input())
lst=[]
for i in range(n):
a = input()
lst.append(a)
used=[]
if n==1:
print(lst[0])
else:
unique = [used.append(x) for x in lst if x not in used]
if len(used) == 2:
team1 = lst.count(used[0])
team2 = lst.count(used[1])
if team1 > team2:
print(used[0])
else:
print(used[1])
else:
team1 = lst.count(used[0])
team2 = 0
if team1 > team2:
print(used[0])
``` | 3.93253 |
15 | A | Cottage Village | PROGRAMMING | 1,200 | [
"implementation",
"sortings"
] | A. Cottage Village | 2 | 64 | A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» *n* square houses with the centres on the *Оx*-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.
The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the *Оx*-axis, to be square in shape, have a side *t*, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the *Ox*-axis and it shouldn't overlap any of the houses in the village.
Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house? | The first line of the input data contains numbers *n* and *t* (1<=≤<=*n*,<=*t*<=≤<=1000). Then there follow *n* lines, each of them contains two space-separated integer numbers: *x**i* *a**i*, where *x**i* — *x*-coordinate of the centre of the *i*-th house, and *a**i* — length of its side (<=-<=1000<=≤<=*x**i*<=≤<=1000, 1<=≤<=*a**i*<=≤<=1000). | Output the amount of possible positions of the new house. | [
"2 2\n0 4\n6 2\n",
"2 2\n0 4\n5 2\n",
"2 3\n0 4\n5 2\n"
] | [
"4\n",
"3\n",
"2\n"
] | It is possible for the *x*-coordinate of the new house to have non-integer value. | 0 | [
{
"input": "2 2\n0 4\n6 2",
"output": "4"
},
{
"input": "2 2\n0 4\n5 2",
"output": "3"
},
{
"input": "2 3\n0 4\n5 2",
"output": "2"
},
{
"input": "1 1\n1 1",
"output": "2"
},
{
"input": "1 2\n2 1",
"output": "2"
},
{
"input": "2 1\n2 1\n1 1",
"outp... | 1,588,670,906 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 186 | 307,200 | square, side = map(int, input().split())
#V sorts ascending, square houses by x-axis
houses = sorted([list(map(int, input().split())) for i in range(square)], key=lambda x: x[0])
answer = 2
for i in range(square - 1):
x = houses[i][0] + houses[i][1] / 2
y = houses[i + 1][0] - houses[i + 1][1] / 2
# if the space between the 2 houses is equal to the main house's side
if y - x == side:
answer += 1
# if the space between the houses is bigger
elif y - x > side:
answer += 2
print(ans) | Title: Cottage Village
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» *n* square houses with the centres on the *Оx*-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.
The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the *Оx*-axis, to be square in shape, have a side *t*, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the *Ox*-axis and it shouldn't overlap any of the houses in the village.
Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?
Input Specification:
The first line of the input data contains numbers *n* and *t* (1<=≤<=*n*,<=*t*<=≤<=1000). Then there follow *n* lines, each of them contains two space-separated integer numbers: *x**i* *a**i*, where *x**i* — *x*-coordinate of the centre of the *i*-th house, and *a**i* — length of its side (<=-<=1000<=≤<=*x**i*<=≤<=1000, 1<=≤<=*a**i*<=≤<=1000).
Output Specification:
Output the amount of possible positions of the new house.
Demo Input:
['2 2\n0 4\n6 2\n', '2 2\n0 4\n5 2\n', '2 3\n0 4\n5 2\n']
Demo Output:
['4\n', '3\n', '2\n']
Note:
It is possible for the *x*-coordinate of the new house to have non-integer value. | ```python
square, side = map(int, input().split())
#V sorts ascending, square houses by x-axis
houses = sorted([list(map(int, input().split())) for i in range(square)], key=lambda x: x[0])
answer = 2
for i in range(square - 1):
x = houses[i][0] + houses[i][1] / 2
y = houses[i + 1][0] - houses[i + 1][1] / 2
# if the space between the 2 houses is equal to the main house's side
if y - x == side:
answer += 1
# if the space between the houses is bigger
elif y - x > side:
answer += 2
print(ans)
``` | -1 |
569 | B | Inventory | PROGRAMMING | 1,200 | [
"greedy",
"math"
] | null | null | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.
During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.
You have been given information on current inventory numbers for *n* items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to *n* by changing the number of as few items as possible. Let us remind you that a set of *n* numbers forms a permutation if all the numbers are in the range from 1 to *n*, and no two numbers are equal. | The first line contains a single integer *n* — the number of items (1<=≤<=*n*<=≤<=105).
The second line contains *n* numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=105) — the initial inventory numbers of the items. | Print *n* numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | [
"3\n1 3 2\n",
"4\n2 2 3 3\n",
"1\n2\n"
] | [
"1 3 2 \n",
"2 1 3 4 \n",
"1 \n"
] | In the first test the numeration is already a permutation, so there is no need to change anything.
In the second test there are two pairs of equal numbers, in each pair you need to replace one number.
In the third test you need to replace 2 by 1, as the numbering should start from one. | 1,000 | [
{
"input": "3\n1 3 2",
"output": "1 3 2 "
},
{
"input": "4\n2 2 3 3",
"output": "2 1 3 4 "
},
{
"input": "1\n2",
"output": "1 "
},
{
"input": "3\n3 3 1",
"output": "3 2 1 "
},
{
"input": "5\n1 1 1 1 1",
"output": "1 2 3 4 5 "
},
{
"input": "5\n5 3 4 4 ... | 1,689,890,309 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 8 | 46 | 819,200 | n=int(input())
b=list(map(int,input().split()))
v=[0]*100005
c=0
for i in b:
if i <=n:
v[i]+=1
elif i > n:
c+=1
s=set()
for j in range(1,n+1):
if j not in b:
s.add(j)
for p in range(n):
if len(s)==0:
break
if v[b[p]]>1 :
v[b[p]]-=1
b[p]=s.pop()
if c>0:
b.append(s.pop())
c-=1
b.pop(0)
print(*b)
| Title: Inventory
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.
During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.
You have been given information on current inventory numbers for *n* items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to *n* by changing the number of as few items as possible. Let us remind you that a set of *n* numbers forms a permutation if all the numbers are in the range from 1 to *n*, and no two numbers are equal.
Input Specification:
The first line contains a single integer *n* — the number of items (1<=≤<=*n*<=≤<=105).
The second line contains *n* numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=105) — the initial inventory numbers of the items.
Output Specification:
Print *n* numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.
Demo Input:
['3\n1 3 2\n', '4\n2 2 3 3\n', '1\n2\n']
Demo Output:
['1 3 2 \n', '2 1 3 4 \n', '1 \n']
Note:
In the first test the numeration is already a permutation, so there is no need to change anything.
In the second test there are two pairs of equal numbers, in each pair you need to replace one number.
In the third test you need to replace 2 by 1, as the numbering should start from one. | ```python
n=int(input())
b=list(map(int,input().split()))
v=[0]*100005
c=0
for i in b:
if i <=n:
v[i]+=1
elif i > n:
c+=1
s=set()
for j in range(1,n+1):
if j not in b:
s.add(j)
for p in range(n):
if len(s)==0:
break
if v[b[p]]>1 :
v[b[p]]-=1
b[p]=s.pop()
if c>0:
b.append(s.pop())
c-=1
b.pop(0)
print(*b)
``` | 0 | |
743 | B | Chloe and the sequence | PROGRAMMING | 1,200 | [
"binary search",
"bitmasks",
"constructive algorithms",
"implementation"
] | null | null | Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (*n*<=-<=1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1,<=2,<=1] after the first step, the sequence [1,<=2,<=1,<=3,<=1,<=2,<=1] after the second step.
The task is to find the value of the element with index *k* (the elements are numbered from 1) in the obtained sequence, i. e. after (*n*<=-<=1) steps.
Please help Chloe to solve the problem! | The only line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=50, 1<=≤<=*k*<=≤<=2*n*<=-<=1). | Print single integer — the integer at the *k*-th position in the obtained sequence. | [
"3 2\n",
"4 8\n"
] | [
"2",
"4"
] | In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4. | 1,000 | [
{
"input": "3 2",
"output": "2"
},
{
"input": "4 8",
"output": "4"
},
{
"input": "5 27",
"output": "1"
},
{
"input": "7 44",
"output": "3"
},
{
"input": "15 18432",
"output": "12"
},
{
"input": "20 259676",
"output": "3"
},
{
"input": "30 6... | 1,536,588,424 | 2,147,483,647 | Python 3 | OK | TESTS | 39 | 124 | 0 | def mexk(n,k):
#n,k=map(int,input().split())
ans=n
low=1
high=pow(2,n)-1
while low<=high:
mid=(low+high)//2
if mid==k: return ans
ans-=1
if k<mid:
high=mid-1
else:
low=mid+1
n,k=map(int,input().split())
print(mexk(n,k)) | Title: Chloe and the sequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (*n*<=-<=1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1,<=2,<=1] after the first step, the sequence [1,<=2,<=1,<=3,<=1,<=2,<=1] after the second step.
The task is to find the value of the element with index *k* (the elements are numbered from 1) in the obtained sequence, i. e. after (*n*<=-<=1) steps.
Please help Chloe to solve the problem!
Input Specification:
The only line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=50, 1<=≤<=*k*<=≤<=2*n*<=-<=1).
Output Specification:
Print single integer — the integer at the *k*-th position in the obtained sequence.
Demo Input:
['3 2\n', '4 8\n']
Demo Output:
['2', '4']
Note:
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4. | ```python
def mexk(n,k):
#n,k=map(int,input().split())
ans=n
low=1
high=pow(2,n)-1
while low<=high:
mid=(low+high)//2
if mid==k: return ans
ans-=1
if k<mid:
high=mid-1
else:
low=mid+1
n,k=map(int,input().split())
print(mexk(n,k))
``` | 3 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular *w* mm <=×<= *h* mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree? | The first line contains three integers *w*,<=*h*,<=*n* (2<=≤<=*w*,<=*h*<=≤<=200<=000, 1<=≤<=*n*<=≤<=200<=000).
Next *n* lines contain the descriptions of the cuts. Each description has the form *H* *y* or *V* *x*. In the first case Leonid makes the horizontal cut at the distance *y* millimeters (1<=≤<=*y*<=≤<=*h*<=-<=1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance *x* (1<=≤<=*x*<=≤<=*w*<=-<=1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts. | After each cut print on a single line the area of the maximum available glass fragment in mm2. | [
"4 3 4\nH 2\nV 2\nV 3\nV 1\n",
"7 6 5\nH 4\nV 3\nV 5\nH 2\nV 1\n"
] | [
"8\n4\n4\n2\n",
"28\n16\n12\n6\n4\n"
] | Picture for the first sample test: | 0 | [
{
"input": "4 3 4\nH 2\nV 2\nV 3\nV 1",
"output": "8\n4\n4\n2"
},
{
"input": "7 6 5\nH 4\nV 3\nV 5\nH 2\nV 1",
"output": "28\n16\n12\n6\n4"
},
{
"input": "2 2 1\nV 1",
"output": "2"
},
{
"input": "2 2 1\nH 1",
"output": "2"
},
{
"input": "2 2 2\nV 1\nH 1",
"ou... | 1,427,740,677 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 10 | 2,000 | 819,200 | from sys import stdin, stdout
import bisect
v_max,h_max,cnt = map(int, stdin.readline().split())
v = [0,v_max]
v_c = [v_max]
h = [0,h_max]
h_c = [h_max]
for _ in range(cnt):
d,c = stdin.readline().split()
cur, cur_c = ((v,v_c) , (h,h_c))[d=='H']
bisect.insort(cur, int(c))
pos = bisect.bisect_left(cur, int(c))
cur_c[pos-1] = cur[pos]-cur[pos-1]
cur_c.insert(pos, cur[pos+1]-cur[pos])
h_max, v_max = max(h_c), max(v_c)
stdout.write(str(h_max*v_max)+'\n') | Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular *w* mm <=×<= *h* mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input Specification:
The first line contains three integers *w*,<=*h*,<=*n* (2<=≤<=*w*,<=*h*<=≤<=200<=000, 1<=≤<=*n*<=≤<=200<=000).
Next *n* lines contain the descriptions of the cuts. Each description has the form *H* *y* or *V* *x*. In the first case Leonid makes the horizontal cut at the distance *y* millimeters (1<=≤<=*y*<=≤<=*h*<=-<=1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance *x* (1<=≤<=*x*<=≤<=*w*<=-<=1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output Specification:
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Demo Input:
['4 3 4\nH 2\nV 2\nV 3\nV 1\n', '7 6 5\nH 4\nV 3\nV 5\nH 2\nV 1\n']
Demo Output:
['8\n4\n4\n2\n', '28\n16\n12\n6\n4\n']
Note:
Picture for the first sample test: | ```python
from sys import stdin, stdout
import bisect
v_max,h_max,cnt = map(int, stdin.readline().split())
v = [0,v_max]
v_c = [v_max]
h = [0,h_max]
h_c = [h_max]
for _ in range(cnt):
d,c = stdin.readline().split()
cur, cur_c = ((v,v_c) , (h,h_c))[d=='H']
bisect.insort(cur, int(c))
pos = bisect.bisect_left(cur, int(c))
cur_c[pos-1] = cur[pos]-cur[pos-1]
cur_c.insert(pos, cur[pos+1]-cur[pos])
h_max, v_max = max(h_c), max(v_c)
stdout.write(str(h_max*v_max)+'\n')
``` | 0 | |
888 | A | Local Extrema | PROGRAMMING | 800 | [
"brute force",
"implementation"
] | null | null | You are given an array *a*. Some element of this array *a**i* is a local minimum iff it is strictly less than both of its neighbours (that is, *a**i*<=<<=*a**i*<=-<=1 and *a**i*<=<<=*a**i*<=+<=1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, *a**i*<=><=*a**i*<=-<=1 and *a**i*<=><=*a**i*<=+<=1). Since *a*1 and *a**n* have only one neighbour each, they are neither local minima nor local maxima.
An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array. | The first line contains one integer *n* (1<=≤<=*n*<=≤<=1000) — the number of elements in array *a*.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=1000) — the elements of array *a*. | Print the number of local extrema in the given array. | [
"3\n1 2 3\n",
"4\n1 5 2 5\n"
] | [
"0\n",
"2\n"
] | none | 0 | [
{
"input": "3\n1 2 3",
"output": "0"
},
{
"input": "4\n1 5 2 5",
"output": "2"
},
{
"input": "1\n1",
"output": "0"
},
{
"input": "1\n548",
"output": "0"
},
{
"input": "2\n1 1",
"output": "0"
},
{
"input": "3\n3 2 3",
"output": "1"
},
{
"inp... | 1,676,460,962 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 14 | 46 | 0 | n = int(input())
*a, = map(int, input().split())
cnt = 0
for i in range(1, n - 1):
if a[i - 1] > a[i] < a[i + 1] or a[i - 1] < a[i] > a[i + 1]:
cnt += 1
print(cnt)
| Title: Local Extrema
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *a*. Some element of this array *a**i* is a local minimum iff it is strictly less than both of its neighbours (that is, *a**i*<=<<=*a**i*<=-<=1 and *a**i*<=<<=*a**i*<=+<=1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, *a**i*<=><=*a**i*<=-<=1 and *a**i*<=><=*a**i*<=+<=1). Since *a*1 and *a**n* have only one neighbour each, they are neither local minima nor local maxima.
An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array.
Input Specification:
The first line contains one integer *n* (1<=≤<=*n*<=≤<=1000) — the number of elements in array *a*.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=1000) — the elements of array *a*.
Output Specification:
Print the number of local extrema in the given array.
Demo Input:
['3\n1 2 3\n', '4\n1 5 2 5\n']
Demo Output:
['0\n', '2\n']
Note:
none | ```python
n = int(input())
*a, = map(int, input().split())
cnt = 0
for i in range(1, n - 1):
if a[i - 1] > a[i] < a[i + 1] or a[i - 1] < a[i] > a[i + 1]:
cnt += 1
print(cnt)
``` | 3 | |
461 | A | Appleman and Toastman | PROGRAMMING | 1,200 | [
"greedy",
"sortings"
] | null | null | Appleman and Toastman play a game. Initially Appleman gives one group of *n* numbers to the Toastman, then they start to complete the following tasks:
- Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. - Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.
After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get? | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=3·105). The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=106) — the initial group that is given to Toastman. | Print a single integer — the largest possible score. | [
"3\n3 1 5\n",
"1\n10\n"
] | [
"26\n",
"10\n"
] | Consider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions. | 500 | [
{
"input": "3\n3 1 5",
"output": "26"
},
{
"input": "1\n10",
"output": "10"
},
{
"input": "10\n8 10 2 5 6 2 4 7 2 1",
"output": "376"
},
{
"input": "10\n171308 397870 724672 431255 228496 892002 542924 718337 888642 161821",
"output": "40204082"
},
{
"input": "10\... | 1,595,993,583 | 2,147,483,647 | Python 3 | OK | TESTS | 36 | 467 | 27,648,000 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 29 08:53:49 2020
@author: Harshal
"""
n=int(input())
arr=list(map(int,input().split()))
arr.sort(reverse=True)
sums=sum(arr)
ans=0
while len(arr)>1:
ans+=sums
x=arr.pop()
ans+=x
sums-=x
print(ans+arr[0])
| Title: Appleman and Toastman
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Appleman and Toastman play a game. Initially Appleman gives one group of *n* numbers to the Toastman, then they start to complete the following tasks:
- Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. - Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.
After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=3·105). The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=106) — the initial group that is given to Toastman.
Output Specification:
Print a single integer — the largest possible score.
Demo Input:
['3\n3 1 5\n', '1\n10\n']
Demo Output:
['26\n', '10\n']
Note:
Consider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions. | ```python
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 29 08:53:49 2020
@author: Harshal
"""
n=int(input())
arr=list(map(int,input().split()))
arr.sort(reverse=True)
sums=sum(arr)
ans=0
while len(arr)>1:
ans+=sums
x=arr.pop()
ans+=x
sums-=x
print(ans+arr[0])
``` | 3 | |
841 | B | Godsend | PROGRAMMING | 1,100 | [
"games",
"math"
] | null | null | Leha somehow found an array consisting of *n* integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally? | First line of input data contains single integer *n* (1<=≤<=*n*<=≤<=106) — length of the array.
Next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=109). | Output answer in single line. "First", if first player wins, and "Second" otherwise (without quotes). | [
"4\n1 3 2 3\n",
"2\n2 2\n"
] | [
"First\n",
"Second\n"
] | In first sample first player remove whole array in one move and win.
In second sample first player can't make a move and lose. | 1,000 | [
{
"input": "4\n1 3 2 3",
"output": "First"
},
{
"input": "2\n2 2",
"output": "Second"
},
{
"input": "4\n2 4 6 8",
"output": "Second"
},
{
"input": "5\n1 1 1 1 1",
"output": "First"
},
{
"input": "4\n720074544 345031254 849487632 80870826",
"output": "Second"
... | 1,608,561,846 | 2,147,483,647 | Python 3 | OK | TESTS | 88 | 920 | 57,241,600 | n = int(input())
a = input()
uneven = False
s = 0
for i in a.split():
v = int(i)
if v % 2:
uneven = True
s += v
if s % 2 or uneven:
print('First')
else:
print('Second') | Title: Godsend
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Leha somehow found an array consisting of *n* integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?
Input Specification:
First line of input data contains single integer *n* (1<=≤<=*n*<=≤<=106) — length of the array.
Next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=109).
Output Specification:
Output answer in single line. "First", if first player wins, and "Second" otherwise (without quotes).
Demo Input:
['4\n1 3 2 3\n', '2\n2 2\n']
Demo Output:
['First\n', 'Second\n']
Note:
In first sample first player remove whole array in one move and win.
In second sample first player can't make a move and lose. | ```python
n = int(input())
a = input()
uneven = False
s = 0
for i in a.split():
v = int(i)
if v % 2:
uneven = True
s += v
if s % 2 or uneven:
print('First')
else:
print('Second')
``` | 3 | |
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,684,330,469 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 34 | 124 | 0 | x=list(map(int,input().split(" ")))
count=0
l=[]
for i in x:
if i not in l:
l.append(i)
else:
count+=1
print(count) | 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
x=list(map(int,input().split(" ")))
count=0
l=[]
for i in x:
if i not in l:
l.append(i)
else:
count+=1
print(count)
``` | 3 | |
463 | B | Caisa and Pylons | PROGRAMMING | 1,100 | [
"brute force",
"implementation",
"math"
] | null | null | Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (*n*<=+<=1) pylons numbered from 0 to *n* in this game. The pylon with number 0 has zero height, the pylon with number *i* (*i*<=><=0) has height *h**i*. The goal of the game is to reach *n*-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as *k*) to the next one (its number will be *k*<=+<=1). When the player have made such a move, its energy increases by *h**k*<=-<=*h**k*<=+<=1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time.
Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game? | The first line contains integer *n* (1<=≤<=*n*<=≤<=105). The next line contains *n* integers *h*1, *h*2,<=..., *h**n* (1<=<=≤<=<=*h**i*<=<=≤<=<=105) representing the heights of the pylons. | Print a single number representing the minimum number of dollars paid by Caisa. | [
"5\n3 4 3 2 4\n",
"3\n4 4 4\n"
] | [
"4\n",
"4\n"
] | In the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon. | 1,000 | [
{
"input": "5\n3 4 3 2 4",
"output": "4"
},
{
"input": "3\n4 4 4",
"output": "4"
},
{
"input": "99\n1401 2019 1748 3785 3236 3177 3443 3772 2138 1049 353 908 310 2388 1322 88 2160 2783 435 2248 1471 706 2468 2319 3156 3506 2794 1999 1983 2519 2597 3735 537 344 3519 3772 3872 2961 3895 20... | 1,621,781,673 | 2,147,483,647 | Python 3 | OK | TESTS | 49 | 140 | 7,577,600 | n=int(input())
a=[0]+list(map(int,input().split()))
s=0
x=0
for i in range(n):
s+=a[i]-a[i+1]
if s<0:
x+=abs(s)
s=0
print(x)
'''
max(a)
'''
| Title: Caisa and Pylons
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (*n*<=+<=1) pylons numbered from 0 to *n* in this game. The pylon with number 0 has zero height, the pylon with number *i* (*i*<=><=0) has height *h**i*. The goal of the game is to reach *n*-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as *k*) to the next one (its number will be *k*<=+<=1). When the player have made such a move, its energy increases by *h**k*<=-<=*h**k*<=+<=1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time.
Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105). The next line contains *n* integers *h*1, *h*2,<=..., *h**n* (1<=<=≤<=<=*h**i*<=<=≤<=<=105) representing the heights of the pylons.
Output Specification:
Print a single number representing the minimum number of dollars paid by Caisa.
Demo Input:
['5\n3 4 3 2 4\n', '3\n4 4 4\n']
Demo Output:
['4\n', '4\n']
Note:
In the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon. | ```python
n=int(input())
a=[0]+list(map(int,input().split()))
s=0
x=0
for i in range(n):
s+=a[i]-a[i+1]
if s<0:
x+=abs(s)
s=0
print(x)
'''
max(a)
'''
``` | 3 | |
266 | A | Stones on the Table | PROGRAMMING | 800 | [
"implementation"
] | null | null | There are *n* stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. | The first line contains integer *n* (1<=≤<=*n*<=≤<=50) — the number of stones on the table.
The next line contains string *s*, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to *n* from left to right. Then the *i*-th character *s* equals "R", if the *i*-th stone is red, "G", if it's green and "B", if it's blue. | Print a single integer — the answer to the problem. | [
"3\nRRG\n",
"5\nRRRRR\n",
"4\nBRBG\n"
] | [
"1\n",
"4\n",
"0\n"
] | none | 500 | [
{
"input": "3\nRRG",
"output": "1"
},
{
"input": "5\nRRRRR",
"output": "4"
},
{
"input": "4\nBRBG",
"output": "0"
},
{
"input": "1\nB",
"output": "0"
},
{
"input": "2\nBG",
"output": "0"
},
{
"input": "3\nBGB",
"output": "0"
},
{
"input": "... | 1,695,284,948 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 62 | 0 | number_of_stones = int(input())
s = ""
neighboor = 0
for index in range(number_of_stones):
s += input()
if index == 0:
continue
if s[index] == s[index - 1]:
neighboor += 1
print(neighboor) | Title: Stones on the Table
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=50) — the number of stones on the table.
The next line contains string *s*, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to *n* from left to right. Then the *i*-th character *s* equals "R", if the *i*-th stone is red, "G", if it's green and "B", if it's blue.
Output Specification:
Print a single integer — the answer to the problem.
Demo Input:
['3\nRRG\n', '5\nRRRRR\n', '4\nBRBG\n']
Demo Output:
['1\n', '4\n', '0\n']
Note:
none | ```python
number_of_stones = int(input())
s = ""
neighboor = 0
for index in range(number_of_stones):
s += input()
if index == 0:
continue
if s[index] == s[index - 1]:
neighboor += 1
print(neighboor)
``` | -1 | |
656 | G | You're a Professional | PROGRAMMING | 1,900 | [
"*special"
] | null | null | A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold *T* — the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least *T* of user's friends. | The first line of the input will contain three space-separated integers: the number of friends *F* (1<=≤<=*F*<=≤<=10), the number of items *I* (1<=≤<=*I*<=≤<=10) and the threshold *T* (1<=≤<=*T*<=≤<=*F*).
The following *F* lines of input contain user's friends' opinions. *j*-th character of *i*-th line is 'Y' if *i*-th friend likes *j*-th item, and 'N' otherwise. | Output an integer — the number of items liked by at least *T* of user's friends. | [
"3 3 2\nYYY\nNNN\nYNY\n",
"4 4 1\nNNNY\nNNYN\nNYNN\nYNNN\n"
] | [
"2\n",
"4\n"
] | none | 0 | [
{
"input": "3 3 2\nYYY\nNNN\nYNY",
"output": "2"
},
{
"input": "4 4 1\nNNNY\nNNYN\nNYNN\nYNNN",
"output": "4"
},
{
"input": "3 5 2\nNYNNY\nYNNNN\nNNYYN",
"output": "0"
},
{
"input": "1 10 1\nYYYNYNNYNN",
"output": "5"
},
{
"input": "10 1 5\nY\nN\nN\nN\nY\nN\nN\nY\... | 1,460,121,080 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 0 | 0 | a,b,c=map(int,input().split())#kitten
z=[0]*b
for i in range(a):
s=input()
for j in range(len(s)):
if s[j]=='Y':
z[j]+=1
print(sum(map(lambda x:x>=c,z))) | Title: You're a Professional
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold *T* — the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least *T* of user's friends.
Input Specification:
The first line of the input will contain three space-separated integers: the number of friends *F* (1<=≤<=*F*<=≤<=10), the number of items *I* (1<=≤<=*I*<=≤<=10) and the threshold *T* (1<=≤<=*T*<=≤<=*F*).
The following *F* lines of input contain user's friends' opinions. *j*-th character of *i*-th line is 'Y' if *i*-th friend likes *j*-th item, and 'N' otherwise.
Output Specification:
Output an integer — the number of items liked by at least *T* of user's friends.
Demo Input:
['3 3 2\nYYY\nNNN\nYNY\n', '4 4 1\nNNNY\nNNYN\nNYNN\nYNNN\n']
Demo Output:
['2\n', '4\n']
Note:
none | ```python
a,b,c=map(int,input().split())#kitten
z=[0]*b
for i in range(a):
s=input()
for j in range(len(s)):
if s[j]=='Y':
z[j]+=1
print(sum(map(lambda x:x>=c,z)))
``` | 0 | |
984 | A | Game | PROGRAMMING | 800 | [
"sortings"
] | null | null | Two players play a game.
Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players alternate turns.
The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.
You want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves. | The first line contains one integer $n$ ($1 \le n \le 1000$) — the number of numbers on the board.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^6$). | Print one number that will be left on the board. | [
"3\n2 1 3\n",
"3\n2 2 2\n"
] | [
"2",
"2"
] | In the first sample, the first player erases $3$ and the second erases $1$. $2$ is left on the board.
In the second sample, $2$ is left on the board regardless of the actions of the players. | 500 | [
{
"input": "3\n2 1 3",
"output": "2"
},
{
"input": "3\n2 2 2",
"output": "2"
},
{
"input": "9\n44 53 51 80 5 27 74 79 94",
"output": "53"
},
{
"input": "10\n38 82 23 37 96 4 81 60 67 86",
"output": "60"
},
{
"input": "10\n58 26 77 15 53 81 68 48 22 65",
"outpu... | 1,634,657,852 | 2,147,483,647 | Python 3 | OK | TESTS | 35 | 62 | 0 | a = int(input())
b = list(map(int, input().split()))
for i in range(a -1):
if i % 2 == 0:
b.remove(max(b))
else: b.remove(min(b))
print(b[0]) | Title: Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two players play a game.
Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players alternate turns.
The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.
You want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.
Input Specification:
The first line contains one integer $n$ ($1 \le n \le 1000$) — the number of numbers on the board.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^6$).
Output Specification:
Print one number that will be left on the board.
Demo Input:
['3\n2 1 3\n', '3\n2 2 2\n']
Demo Output:
['2', '2']
Note:
In the first sample, the first player erases $3$ and the second erases $1$. $2$ is left on the board.
In the second sample, $2$ is left on the board regardless of the actions of the players. | ```python
a = int(input())
b = list(map(int, input().split()))
for i in range(a -1):
if i % 2 == 0:
b.remove(max(b))
else: b.remove(min(b))
print(b[0])
``` | 3 | |
224 | A | Parallelepiped | PROGRAMMING | 1,100 | [
"brute force",
"geometry",
"math"
] | null | null | You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. | The first and the single line contains three space-separated integers — the areas of the parallelepiped's faces. The area's values are positive (<=><=0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. | Print a single number — the sum of all edges of the parallelepiped. | [
"1 1 1\n",
"4 6 6\n"
] | [
"12\n",
"28\n"
] | In the first sample the parallelepiped has sizes 1 × 1 × 1, in the second one — 2 × 2 × 3. | 500 | [
{
"input": "1 1 1",
"output": "12"
},
{
"input": "4 6 6",
"output": "28"
},
{
"input": "20 10 50",
"output": "68"
},
{
"input": "9 4 36",
"output": "56"
},
{
"input": "324 9 36",
"output": "184"
},
{
"input": "1333 93 129",
"output": "308"
},
{... | 1,649,270,550 | 2,147,483,647 | Python 3 | OK | TESTS | 27 | 92 | 0 | import math
arr = list(map(int, input().split()))
s1 = math.sqrt(arr[0] * arr[1] / arr[2])
s2 = math.sqrt(arr[2] * arr[0] / arr[1])
s3 = math.sqrt(arr[2] * arr[1] / arr[0])
print(int(4*(s1+s2+s3))) | Title: Parallelepiped
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.
Input Specification:
The first and the single line contains three space-separated integers — the areas of the parallelepiped's faces. The area's values are positive (<=><=0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement.
Output Specification:
Print a single number — the sum of all edges of the parallelepiped.
Demo Input:
['1 1 1\n', '4 6 6\n']
Demo Output:
['12\n', '28\n']
Note:
In the first sample the parallelepiped has sizes 1 × 1 × 1, in the second one — 2 × 2 × 3. | ```python
import math
arr = list(map(int, input().split()))
s1 = math.sqrt(arr[0] * arr[1] / arr[2])
s2 = math.sqrt(arr[2] * arr[0] / arr[1])
s3 = math.sqrt(arr[2] * arr[1] / arr[0])
print(int(4*(s1+s2+s3)))
``` | 3 | |
592 | B | The Monster and the Squirrel | PROGRAMMING | 1,100 | [
"math"
] | null | null | Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1,<=2,<=...,<=*n* in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2,<=3,<=...,<=*n* (in this particular order). And then she puts a walnut in each region inside the polygon.
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts? | The first and only line of the input contains a single integer *n* (3<=≤<=*n*<=≤<=54321) - the number of vertices of the regular polygon drawn by Ari. | Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after. | [
"5\n",
"3\n"
] | [
"9\n",
"1\n"
] | One of the possible solutions for the first sample is shown on the picture above. | 1,000 | [
{
"input": "5",
"output": "9"
},
{
"input": "3",
"output": "1"
},
{
"input": "54321",
"output": "2950553761"
},
{
"input": "4",
"output": "4"
},
{
"input": "6",
"output": "16"
},
{
"input": "7",
"output": "25"
},
{
"input": "8",
"output... | 1,616,284,375 | 2,147,483,647 | PyPy 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | if bruh == 6
print("bruhhh") | Title: The Monster and the Squirrel
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1,<=2,<=...,<=*n* in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2,<=3,<=...,<=*n* (in this particular order). And then she puts a walnut in each region inside the polygon.
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
Input Specification:
The first and only line of the input contains a single integer *n* (3<=≤<=*n*<=≤<=54321) - the number of vertices of the regular polygon drawn by Ari.
Output Specification:
Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.
Demo Input:
['5\n', '3\n']
Demo Output:
['9\n', '1\n']
Note:
One of the possible solutions for the first sample is shown on the picture above. | ```python
if bruh == 6
print("bruhhh")
``` | -1 | |
279 | B | Books | PROGRAMMING | 1,400 | [
"binary search",
"brute force",
"implementation",
"two pointers"
] | null | null | When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to read the *i*-th book.
Valera decided to choose an arbitrary book with number *i* and read the books one by one, starting from this book. In other words, he will first read book number *i*, then book number *i*<=+<=1, then book number *i*<=+<=2 and so on. He continues the process until he either runs out of the free time or finishes reading the *n*-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read. | The first line contains two integers *n* and *t* (1<=≤<=*n*<=≤<=105; 1<=≤<=*t*<=≤<=109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=104), where number *a**i* shows the number of minutes that the boy needs to read the *i*-th book. | Print a single integer — the maximum number of books Valera can read. | [
"4 5\n3 1 2 1\n",
"3 3\n2 2 3\n"
] | [
"3\n",
"1\n"
] | none | 1,000 | [
{
"input": "4 5\n3 1 2 1",
"output": "3"
},
{
"input": "3 3\n2 2 3",
"output": "1"
},
{
"input": "1 3\n5",
"output": "0"
},
{
"input": "1 10\n4",
"output": "1"
},
{
"input": "2 10\n6 4",
"output": "2"
},
{
"input": "6 10\n2 3 4 2 1 1",
"output": "4... | 1,684,783,776 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 38 | 218 | 13,824,000 | n,t=map(int,input().split())
times=list(map(int,input().split()))
from itertools import accumulate
from bisect import bisect_right
times=list(accumulate(times,initial=0))
res=0
for i in range(n):
res=max(res,bisect_right(times,t+times[i])-(i+1))
print(res) | Title: Books
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to read the *i*-th book.
Valera decided to choose an arbitrary book with number *i* and read the books one by one, starting from this book. In other words, he will first read book number *i*, then book number *i*<=+<=1, then book number *i*<=+<=2 and so on. He continues the process until he either runs out of the free time or finishes reading the *n*-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
Input Specification:
The first line contains two integers *n* and *t* (1<=≤<=*n*<=≤<=105; 1<=≤<=*t*<=≤<=109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=104), where number *a**i* shows the number of minutes that the boy needs to read the *i*-th book.
Output Specification:
Print a single integer — the maximum number of books Valera can read.
Demo Input:
['4 5\n3 1 2 1\n', '3 3\n2 2 3\n']
Demo Output:
['3\n', '1\n']
Note:
none | ```python
n,t=map(int,input().split())
times=list(map(int,input().split()))
from itertools import accumulate
from bisect import bisect_right
times=list(accumulate(times,initial=0))
res=0
for i in range(n):
res=max(res,bisect_right(times,t+times[i])-(i+1))
print(res)
``` | 3 | |
4 | A | Watermelon | PROGRAMMING | 800 | [
"brute force",
"math"
] | A. Watermelon | 1 | 64 | One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight. | The first (and the only) input line contains integer number *w* (1<=≤<=*w*<=≤<=100) — the weight of the watermelon bought by the boys. | Print YES, if the boys can divide the watermelon into two parts, each of them weighing even number of kilos; and NO in the opposite case. | [
"8\n"
] | [
"YES\n"
] | For example, the boys can divide the watermelon into two parts of 2 and 6 kilos respectively (another variant — two parts of 4 and 4 kilos). | 0 | [
{
"input": "8",
"output": "YES"
},
{
"input": "5",
"output": "NO"
},
{
"input": "4",
"output": "YES"
},
{
"input": "3",
"output": "NO"
},
{
"input": "2",
"output": "NO"
},
{
"input": "1",
"output": "NO"
},
{
"input": "7",
"output": "NO"... | 1,690,457,021 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 30 | 0 | n=int(input('Enter the weight of the wateemelon'))
if n%2==0 and n!=2:
print('Yes')
else:
print('No') | Title: Watermelon
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
Input Specification:
The first (and the only) input line contains integer number *w* (1<=≤<=*w*<=≤<=100) — the weight of the watermelon bought by the boys.
Output Specification:
Print YES, if the boys can divide the watermelon into two parts, each of them weighing even number of kilos; and NO in the opposite case.
Demo Input:
['8\n']
Demo Output:
['YES\n']
Note:
For example, the boys can divide the watermelon into two parts of 2 and 6 kilos respectively (another variant — two parts of 4 and 4 kilos). | ```python
n=int(input('Enter the weight of the wateemelon'))
if n%2==0 and n!=2:
print('Yes')
else:
print('No')
``` | 0 |
0 | none | none | none | 0 | [
"none"
] | null | null | One department of some software company has $n$ servers of different specifications. Servers are indexed with consecutive integers from $1$ to $n$. Suppose that the specifications of the $j$-th server may be expressed with a single integer number $c_j$ of artificial resource units.
In order for production to work, it is needed to deploy two services $S_1$ and $S_2$ to process incoming requests using the servers of the department. Processing of incoming requests of service $S_i$ takes $x_i$ resource units.
The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service $S_i$ is deployed using $k_i$ servers, then the load is divided equally between these servers and each server requires only $x_i / k_i$ (that may be a fractional number) resource units.
Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.
Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services. | The first line contains three integers $n$, $x_1$, $x_2$ ($2 \leq n \leq 300\,000$, $1 \leq x_1, x_2 \leq 10^9$) — the number of servers that the department may use, and resource units requirements for each of the services.
The second line contains $n$ space-separated integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq 10^9$) — the number of resource units provided by each of the servers. | If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes).
Otherwise print the word "Yes" (without the quotes).
In the second line print two integers $k_1$ and $k_2$ ($1 \leq k_1, k_2 \leq n$) — the number of servers used for each of the services.
In the third line print $k_1$ integers, the indices of the servers that will be used for the first service.
In the fourth line print $k_2$ integers, the indices of the servers that will be used for the second service.
No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them. | [
"6 8 16\n3 5 2 9 8 7\n",
"4 20 32\n21 11 11 12\n",
"4 11 32\n5 5 16 16\n",
"5 12 20\n7 8 4 11 9\n"
] | [
"Yes\n3 2\n1 2 6\n5 4",
"Yes\n1 3\n1\n2 3 4\n",
"No\n",
"No\n"
] | In the first sample test each of the servers 1, 2 and 6 will will provide $8 / 3 = 2.(6)$ resource units and each of the servers 5, 4 will provide $16 / 2 = 8$ resource units.
In the second sample test the first server will provide $20$ resource units and each of the remaining servers will provide $32 / 3 = 10.(6)$ resource units. | 0 | [
{
"input": "6 8 16\n3 5 2 9 8 7",
"output": "Yes\n4 2\n3 1 2 6\n5 4"
},
{
"input": "4 20 32\n21 11 11 12",
"output": "Yes\n1 3\n1\n2 3 4"
},
{
"input": "4 11 32\n5 5 16 16",
"output": "No"
},
{
"input": "5 12 20\n7 8 4 11 9",
"output": "No"
},
{
"input": "2 1 1\n1... | 1,525,497,451 | 2,147,483,647 | Python 3 | OK | TESTS | 40 | 1,668 | 39,014,400 | import sys
n,x1,x2=map(int,input().split())
a=list(map(int,input().split()))
for i in range(n):
a[i]=[a[i],i+1]
a.sort()
#print(a)
for i in range(1,n+1):
if(a[n-i][0]*(i)>=x1):
break
pt=i
#print(pt)
ans=-1
for i in range(pt+1,n+1):
if(a[n-i][0]*(i-pt)>=x2):
ans=i
break
if(ans!=-1):
print('Yes')
print(pt,ans-pt)
b=[]
c=[]
for i in range(n-1,n-1-pt,-1):
b.append(a[i][1])
for i in range(n-1-pt,n-1-ans,-1):
c.append(a[i][1])
print(*b)
print(*c)
sys.exit()
for i in range(1,n+1):
if(a[n-i][0]*(i)>=x2):
break
pt=i
ans=-1
for i in range(pt+1,n+1):
if(a[n-i][0]*(i-pt)>=x1):
ans=i
break
#print(pt)
if(ans!=-1):
print('Yes')
print(ans-pt,pt)
b=[]
for i in range(n-1-pt,n-1-ans,-1):
b.append(a[i][1])
c=[]
for i in range(n-1,n-1-pt,-1):
c.append(a[i][1])
print(*b)
print(*c)
sys.exit()
print('No')
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One department of some software company has $n$ servers of different specifications. Servers are indexed with consecutive integers from $1$ to $n$. Suppose that the specifications of the $j$-th server may be expressed with a single integer number $c_j$ of artificial resource units.
In order for production to work, it is needed to deploy two services $S_1$ and $S_2$ to process incoming requests using the servers of the department. Processing of incoming requests of service $S_i$ takes $x_i$ resource units.
The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service $S_i$ is deployed using $k_i$ servers, then the load is divided equally between these servers and each server requires only $x_i / k_i$ (that may be a fractional number) resource units.
Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.
Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services.
Input Specification:
The first line contains three integers $n$, $x_1$, $x_2$ ($2 \leq n \leq 300\,000$, $1 \leq x_1, x_2 \leq 10^9$) — the number of servers that the department may use, and resource units requirements for each of the services.
The second line contains $n$ space-separated integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq 10^9$) — the number of resource units provided by each of the servers.
Output Specification:
If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes).
Otherwise print the word "Yes" (without the quotes).
In the second line print two integers $k_1$ and $k_2$ ($1 \leq k_1, k_2 \leq n$) — the number of servers used for each of the services.
In the third line print $k_1$ integers, the indices of the servers that will be used for the first service.
In the fourth line print $k_2$ integers, the indices of the servers that will be used for the second service.
No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them.
Demo Input:
['6 8 16\n3 5 2 9 8 7\n', '4 20 32\n21 11 11 12\n', '4 11 32\n5 5 16 16\n', '5 12 20\n7 8 4 11 9\n']
Demo Output:
['Yes\n3 2\n1 2 6\n5 4', 'Yes\n1 3\n1\n2 3 4\n', 'No\n', 'No\n']
Note:
In the first sample test each of the servers 1, 2 and 6 will will provide $8 / 3 = 2.(6)$ resource units and each of the servers 5, 4 will provide $16 / 2 = 8$ resource units.
In the second sample test the first server will provide $20$ resource units and each of the remaining servers will provide $32 / 3 = 10.(6)$ resource units. | ```python
import sys
n,x1,x2=map(int,input().split())
a=list(map(int,input().split()))
for i in range(n):
a[i]=[a[i],i+1]
a.sort()
#print(a)
for i in range(1,n+1):
if(a[n-i][0]*(i)>=x1):
break
pt=i
#print(pt)
ans=-1
for i in range(pt+1,n+1):
if(a[n-i][0]*(i-pt)>=x2):
ans=i
break
if(ans!=-1):
print('Yes')
print(pt,ans-pt)
b=[]
c=[]
for i in range(n-1,n-1-pt,-1):
b.append(a[i][1])
for i in range(n-1-pt,n-1-ans,-1):
c.append(a[i][1])
print(*b)
print(*c)
sys.exit()
for i in range(1,n+1):
if(a[n-i][0]*(i)>=x2):
break
pt=i
ans=-1
for i in range(pt+1,n+1):
if(a[n-i][0]*(i-pt)>=x1):
ans=i
break
#print(pt)
if(ans!=-1):
print('Yes')
print(ans-pt,pt)
b=[]
for i in range(n-1-pt,n-1-ans,-1):
b.append(a[i][1])
c=[]
for i in range(n-1,n-1-pt,-1):
c.append(a[i][1])
print(*b)
print(*c)
sys.exit()
print('No')
``` | 3 | |
248 | A | Cupboards | PROGRAMMING | 800 | [
"implementation"
] | null | null | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on *n* wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.
And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.
Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds *t*, in which he is able to bring all the cupboard doors in the required position.
Your task is to write a program that will determine the required number of seconds *t*. | The first input line contains a single integer *n* — the number of cupboards in the kitchen (2<=≤<=*n*<=≤<=104). Then follow *n* lines, each containing two integers *l**i* and *r**i* (0<=≤<=*l**i*,<=*r**i*<=≤<=1). Number *l**i* equals one, if the left door of the *i*-th cupboard is opened, otherwise number *l**i* equals zero. Similarly, number *r**i* equals one, if the right door of the *i*-th cupboard is opened, otherwise number *r**i* equals zero.
The numbers in the lines are separated by single spaces. | In the only output line print a single integer *t* — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | [
"5\n0 1\n1 0\n0 1\n1 1\n0 1\n"
] | [
"3\n"
] | none | 500 | [
{
"input": "5\n0 1\n1 0\n0 1\n1 1\n0 1",
"output": "3"
},
{
"input": "2\n0 0\n0 0",
"output": "0"
},
{
"input": "3\n0 1\n1 1\n1 1",
"output": "1"
},
{
"input": "8\n0 1\n1 0\n0 1\n1 1\n0 1\n1 0\n0 1\n1 0",
"output": "7"
},
{
"input": "8\n1 0\n1 0\n1 0\n0 1\n0 1\n1 ... | 1,610,720,224 | 2,147,483,647 | Python 3 | OK | TESTS | 57 | 156 | 512,000 | n = int(input())
one = []
two = []
for i in range(n):
x, y = map(int, input().split(" "))
one.append(x)
two.append(y)
if one.count(0) > one.count(1):
c_1 = one.count(1)
else:
c_1 = one.count(0)
if two.count(0) > two.count(1):
c_2 = two.count(1)
else:
c_2 = two.count(0)
print(c_1 + c_2)
| Title: Cupboards
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on *n* wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.
And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.
Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds *t*, in which he is able to bring all the cupboard doors in the required position.
Your task is to write a program that will determine the required number of seconds *t*.
Input Specification:
The first input line contains a single integer *n* — the number of cupboards in the kitchen (2<=≤<=*n*<=≤<=104). Then follow *n* lines, each containing two integers *l**i* and *r**i* (0<=≤<=*l**i*,<=*r**i*<=≤<=1). Number *l**i* equals one, if the left door of the *i*-th cupboard is opened, otherwise number *l**i* equals zero. Similarly, number *r**i* equals one, if the right door of the *i*-th cupboard is opened, otherwise number *r**i* equals zero.
The numbers in the lines are separated by single spaces.
Output Specification:
In the only output line print a single integer *t* — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.
Demo Input:
['5\n0 1\n1 0\n0 1\n1 1\n0 1\n']
Demo Output:
['3\n']
Note:
none | ```python
n = int(input())
one = []
two = []
for i in range(n):
x, y = map(int, input().split(" "))
one.append(x)
two.append(y)
if one.count(0) > one.count(1):
c_1 = one.count(1)
else:
c_1 = one.count(0)
if two.count(0) > two.count(1):
c_2 = two.count(1)
else:
c_2 = two.count(0)
print(c_1 + c_2)
``` | 3 | |
894 | A | QAQ | PROGRAMMING | 800 | [
"brute force",
"dp"
] | null | null | "QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact. | The only line contains a string of length *n* (1<=≤<=*n*<=≤<=100). It's guaranteed that the string only contains uppercase English letters. | Print a single integer — the number of subsequences "QAQ" in the string. | [
"QAQAQYSYIOIWIN\n",
"QAQQQZZYNOIWIN\n"
] | [
"4\n",
"3\n"
] | In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | 500 | [
{
"input": "QAQAQYSYIOIWIN",
"output": "4"
},
{
"input": "QAQQQZZYNOIWIN",
"output": "3"
},
{
"input": "QA",
"output": "0"
},
{
"input": "IAQVAQZLQBQVQFTQQQADAQJA",
"output": "24"
},
{
"input": "QQAAQASGAYAAAAKAKAQIQEAQAIAAIAQQQQQ",
"output": "378"
},
{
... | 1,644,985,055 | 2,147,483,647 | Python 3 | OK | TESTS | 43 | 46 | 0 | s = input()
res = 0
n = len(s)
for i in range(1, n - 1):
if s[i] == 'A':
l = i - 1
r = i + 1
a = 0
b = 0
while l >= 0:
if s[l] == 'Q':
a += 1
l -= 1
while r < n:
if s[r] == 'Q':
b += 1
r += 1
res += a*b
print(res)
| 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
s = input()
res = 0
n = len(s)
for i in range(1, n - 1):
if s[i] == 'A':
l = i - 1
r = i + 1
a = 0
b = 0
while l >= 0:
if s[l] == 'Q':
a += 1
l -= 1
while r < n:
if s[r] == 'Q':
b += 1
r += 1
res += a*b
print(res)
``` | 3 | |
39 | H | Multiplication Table | PROGRAMMING | 1,300 | [
"implementation"
] | H. Multiplication Table | 2 | 64 | Petya studies positional notations. He has already learned to add and subtract numbers in the systems of notations with different radices and has moved on to a more complicated action — multiplication. To multiply large numbers one has to learn the multiplication table. Unfortunately, in the second grade students learn only the multiplication table of decimals (and some students even learn it in the first grade). Help Petya make a multiplication table for numbers in the system of notations with the radix *k*. | The first line contains a single integer *k* (2<=≤<=*k*<=≤<=10) — the radix of the system. | Output the multiplication table for the system of notations with the radix *k*. The table must contain *k*<=-<=1 rows and *k*<=-<=1 columns. The element on the crossing of the *i*-th row and the *j*-th column is equal to the product of *i* and *j* in the system of notations with the radix *k*. Each line may have any number of spaces between the numbers (the extra spaces in the samples are put for clarity). | [
"10\n",
"3\n"
] | [
"1 2 3 4 5 6 7 8 9\n2 4 6 8 10 12 14 16 18\n3 6 9 12 15 18 21 24 27\n4 8 12 16 20 24 28 32 36\n5 10 15 20 25 30 35 40 45\n6 12 18 24 30 36 42 48 54\n7 14 21 28 35 42 49 56 63\n8 16 24 32 40 48 56 64 72\n9 18 27 36 45 54 63 72 81\n",
"1 2\n2 11"
] | none | 0 | [
{
"input": "10",
"output": "1 2 3 4 5 6 7 8 9 \n2 4 6 8 10 12 14 16 18 \n3 6 9 12 15 18 21 24 27 \n4 8 12 16 20 24 28 32 36 \n5 10 15 20 25 30 35 40 45 \n6 12 18 24 30 36 42 48 54 \n7 14 21 28 35 42 49 56 63 \n8 16 24 32 40 48 56 64 72 \n9 18 27 36 45 54 63 72 81 "
},
{
"input": "3",
"output": "... | 1,632,757,733 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 7 | 92 | 6,963,200 | k = int(input(""))
n = k-1
if n == 1:
print("1")
elif n ==2 :
print("1 2")
print("2 11")
elif n == 3 :
print("1 2 3")
print("2 10 12")
print("3 12 21")
elif n == 4:
print("1 2 3 4")
print("2 4 11 13")
print("3 11 14 22")
print("4 13 22 31")
elif n == 5:
print("1 2 3 4 5")
print("2 4 10 12 14")
print("3 10 13 20 23")
print("4 12 20 24 32")
print("5 14 23 32 41")
elif n == 6:
print("1 2 3 4 5 6")
print("2 4 6 11 13 15")
print("3 6 12 15 21 24")
print("4 11 15 22 26 33")
print("5 13 21 26 34 42")
print("6 15 24 33 42 51")
elif n == 7:
print("1 2 3 4 5 6 7")
print("2 4 6 10 12 14 16")
print("3 6 11 14 17 22 25")
print("4 10 14 20 24 30 34")
print("5 12 17 24 31 36 43")
print("6 14 22 30 36 42 52")
print("7 16 25 34 43 52 61")
elif n == 8:
print("1 2 3 4 5 6 7 8")
print("2 4 6 8 11 13 15 17")
print("3 6 10 13 16 20 23 26")
print("4 8 13 17 22 26 31 35")
print("5 11 16 22 27 33 38 44")
print("6 13 20 26 33 40 46 53")
print("7 15 23 31 38 46 54 62")
print("8 17 26 35 40 53 62 71")
else:
print("1 2 3 4 5 6 7 8 9")
print("2 4 6 8 10 12 14 16 18")
print("3 6 9 12 15 18 21 24 27")
print("4 8 12 16 20 24 28 32 36")
print("5 10 15 20 25 30 35 40 45")
print("6 12 18 24 30 36 42 48 54")
print("7 14 21 28 35 42 49 56 63")
print("8 16 24 32 40 48 56 64 72")
print("9 18 27 36 45 54 63 72 81")
| Title: Multiplication Table
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Petya studies positional notations. He has already learned to add and subtract numbers in the systems of notations with different radices and has moved on to a more complicated action — multiplication. To multiply large numbers one has to learn the multiplication table. Unfortunately, in the second grade students learn only the multiplication table of decimals (and some students even learn it in the first grade). Help Petya make a multiplication table for numbers in the system of notations with the radix *k*.
Input Specification:
The first line contains a single integer *k* (2<=≤<=*k*<=≤<=10) — the radix of the system.
Output Specification:
Output the multiplication table for the system of notations with the radix *k*. The table must contain *k*<=-<=1 rows and *k*<=-<=1 columns. The element on the crossing of the *i*-th row and the *j*-th column is equal to the product of *i* and *j* in the system of notations with the radix *k*. Each line may have any number of spaces between the numbers (the extra spaces in the samples are put for clarity).
Demo Input:
['10\n', '3\n']
Demo Output:
['1 2 3 4 5 6 7 8 9\n2 4 6 8 10 12 14 16 18\n3 6 9 12 15 18 21 24 27\n4 8 12 16 20 24 28 32 36\n5 10 15 20 25 30 35 40 45\n6 12 18 24 30 36 42 48 54\n7 14 21 28 35 42 49 56 63\n8 16 24 32 40 48 56 64 72\n9 18 27 36 45 54 63 72 81\n', '1 2\n2 11']
Note:
none | ```python
k = int(input(""))
n = k-1
if n == 1:
print("1")
elif n ==2 :
print("1 2")
print("2 11")
elif n == 3 :
print("1 2 3")
print("2 10 12")
print("3 12 21")
elif n == 4:
print("1 2 3 4")
print("2 4 11 13")
print("3 11 14 22")
print("4 13 22 31")
elif n == 5:
print("1 2 3 4 5")
print("2 4 10 12 14")
print("3 10 13 20 23")
print("4 12 20 24 32")
print("5 14 23 32 41")
elif n == 6:
print("1 2 3 4 5 6")
print("2 4 6 11 13 15")
print("3 6 12 15 21 24")
print("4 11 15 22 26 33")
print("5 13 21 26 34 42")
print("6 15 24 33 42 51")
elif n == 7:
print("1 2 3 4 5 6 7")
print("2 4 6 10 12 14 16")
print("3 6 11 14 17 22 25")
print("4 10 14 20 24 30 34")
print("5 12 17 24 31 36 43")
print("6 14 22 30 36 42 52")
print("7 16 25 34 43 52 61")
elif n == 8:
print("1 2 3 4 5 6 7 8")
print("2 4 6 8 11 13 15 17")
print("3 6 10 13 16 20 23 26")
print("4 8 13 17 22 26 31 35")
print("5 11 16 22 27 33 38 44")
print("6 13 20 26 33 40 46 53")
print("7 15 23 31 38 46 54 62")
print("8 17 26 35 40 53 62 71")
else:
print("1 2 3 4 5 6 7 8 9")
print("2 4 6 8 10 12 14 16 18")
print("3 6 9 12 15 18 21 24 27")
print("4 8 12 16 20 24 28 32 36")
print("5 10 15 20 25 30 35 40 45")
print("6 12 18 24 30 36 42 48 54")
print("7 14 21 28 35 42 49 56 63")
print("8 16 24 32 40 48 56 64 72")
print("9 18 27 36 45 54 63 72 81")
``` | 0 |
230 | B | T-primes | PROGRAMMING | 1,300 | [
"binary search",
"implementation",
"math",
"number theory"
] | null | null | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer *t* Т-prime, if *t* has exactly three distinct positive divisors.
You are given an array of *n* positive integers. For each of them determine whether it is Т-prime or not. | The first line contains a single positive integer, *n* (1<=≤<=*n*<=≤<=105), showing how many numbers are in the array. The next line contains *n* space-separated integers *x**i* (1<=≤<=*x**i*<=≤<=1012).
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | Print *n* lines: the *i*-th line should contain "YES" (without the quotes), if number *x**i* is Т-prime, and "NO" (without the quotes), if it isn't. | [
"3\n4 5 6\n"
] | [
"YES\nNO\nNO\n"
] | The given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | 500 | [
{
"input": "3\n4 5 6",
"output": "YES\nNO\nNO"
},
{
"input": "2\n48 49",
"output": "NO\nYES"
},
{
"input": "10\n10 9 8 7 6 5 4 3 2 1",
"output": "NO\nYES\nNO\nNO\nNO\nNO\nYES\nNO\nNO\nNO"
},
{
"input": "1\n36",
"output": "NO"
},
{
"input": "1\n999966000289",
"... | 1,697,434,275 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 2 | 186 | 3,174,400 |
# Version 20.0
import os, sys, math, itertools
from collections import deque, defaultdict, OrderedDict, Counter
from bisect import bisect, bisect_left, bisect_right, insort
from heapq import heapify, heappush, heappop, nsmallest, nlargest, heapreplace, heappushpop
ii = lambda : int(input())
si = lambda : input()
mi = lambda : map(int,input().strip().split(" "))
msi = lambda : map(str,input().strip().split(" "))
li = lambda : list(mi())
lsi = lambda : list(msi())
out = []
export = lambda : print('\n'.join(map(str, out)), end='')
p = lambda x : out.append(x)
pp = lambda array : p(' '.join(map(str,array)))
offline = True
L = lambda string : hq.L(string) if offline == True else False
LT = lambda tc, custom, string : hq.LT(tc, custom, string) if offline == True else False
def main() -> None:
# 2023-10-15 23:57:03
def sieve( n : int) -> list:
isPrime = [True for i in range(n+1)]
isPrime[0] = isPrime[1] = False
for i in range(4,n+1,2): isPrime[i] = False
for i in range(3,n+1,2):
if i*i <= n and isPrime[i]:
for j in range(i*i,n+1,i): isPrime[j] = False
return [idx for idx,i in enumerate(isPrime) if i==True]
primes = sieve(int(1e5)+100)
def primeFactorization(num):
factors = []
sqrtn = math.sqrt(num)
length = len(primes)
for i in range(length):
if primes[i] <= sqrtn:
if num % primes[i] == 0:
while num % primes[i] == 0:
num //= primes[i]
factors.append(primes[i])
sqrtn = math.sqrt(num)
else:
break
if num != 1:
factors.append(num)
return factors
num = ii()
l = li()
for i in l:
ans = primeFactorization(i)
s = list(set(ans))
if len(s) == 1 and s[0] != i:
p('YES')
else:
p('NO')
try: exec('from hq import *\nexec(cc)')
except (FileNotFoundError, ModuleNotFoundError): offline >> 1; main(); export()
| Title: T-primes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer *t* Т-prime, if *t* has exactly three distinct positive divisors.
You are given an array of *n* positive integers. For each of them determine whether it is Т-prime or not.
Input Specification:
The first line contains a single positive integer, *n* (1<=≤<=*n*<=≤<=105), showing how many numbers are in the array. The next line contains *n* space-separated integers *x**i* (1<=≤<=*x**i*<=≤<=1012).
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier.
Output Specification:
Print *n* lines: the *i*-th line should contain "YES" (without the quotes), if number *x**i* is Т-prime, and "NO" (without the quotes), if it isn't.
Demo Input:
['3\n4 5 6\n']
Demo Output:
['YES\nNO\nNO\n']
Note:
The given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | ```python
# Version 20.0
import os, sys, math, itertools
from collections import deque, defaultdict, OrderedDict, Counter
from bisect import bisect, bisect_left, bisect_right, insort
from heapq import heapify, heappush, heappop, nsmallest, nlargest, heapreplace, heappushpop
ii = lambda : int(input())
si = lambda : input()
mi = lambda : map(int,input().strip().split(" "))
msi = lambda : map(str,input().strip().split(" "))
li = lambda : list(mi())
lsi = lambda : list(msi())
out = []
export = lambda : print('\n'.join(map(str, out)), end='')
p = lambda x : out.append(x)
pp = lambda array : p(' '.join(map(str,array)))
offline = True
L = lambda string : hq.L(string) if offline == True else False
LT = lambda tc, custom, string : hq.LT(tc, custom, string) if offline == True else False
def main() -> None:
# 2023-10-15 23:57:03
def sieve( n : int) -> list:
isPrime = [True for i in range(n+1)]
isPrime[0] = isPrime[1] = False
for i in range(4,n+1,2): isPrime[i] = False
for i in range(3,n+1,2):
if i*i <= n and isPrime[i]:
for j in range(i*i,n+1,i): isPrime[j] = False
return [idx for idx,i in enumerate(isPrime) if i==True]
primes = sieve(int(1e5)+100)
def primeFactorization(num):
factors = []
sqrtn = math.sqrt(num)
length = len(primes)
for i in range(length):
if primes[i] <= sqrtn:
if num % primes[i] == 0:
while num % primes[i] == 0:
num //= primes[i]
factors.append(primes[i])
sqrtn = math.sqrt(num)
else:
break
if num != 1:
factors.append(num)
return factors
num = ii()
l = li()
for i in l:
ans = primeFactorization(i)
s = list(set(ans))
if len(s) == 1 and s[0] != i:
p('YES')
else:
p('NO')
try: exec('from hq import *\nexec(cc)')
except (FileNotFoundError, ModuleNotFoundError): offline >> 1; main(); export()
``` | 0 | |
73 | A | The Elder Trolls IV: Oblivon | PROGRAMMING | 1,600 | [
"greedy",
"math"
] | A. The Elder Trolls IV: Oblivon | 2 | 256 | Vasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is "Unkillable"? Firstly, because it can be killed with cutting weapon only, so lovers of two-handed amber hammers should find suitable knife themselves. Secondly, it is necessary to make so many cutting strokes to Unkillable Slug. Extremely many. Too many!
Vasya has already promoted his character to 80-th level and in order to gain level 81 he was asked to kill Unkillable Slug. The monster has a very interesting shape. It looks like a rectangular parallelepiped with size *x*<=×<=*y*<=×<=*z*, consisting of undestructable cells 1<=×<=1<=×<=1. At one stroke Vasya can cut the Slug along an imaginary grid, i.e. cut with a plane parallel to one of the parallelepiped side. Monster dies when amount of parts it is divided reaches some critical value.
All parts of monster do not fall after each cut, they remains exactly on its places. I. e. Vasya can cut several parts with one cut.
Vasya wants to know what the maximum number of pieces he can cut the Unkillable Slug into striking him at most *k* times.
Vasya's character uses absolutely thin sword with infinite length. | The first line of input contains four integer numbers *x*,<=*y*,<=*z*,<=*k* (1<=≤<=*x*,<=*y*,<=*z*<=≤<=106,<=0<=≤<=*k*<=≤<=109). | Output the only number — the answer for the problem.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | [
"2 2 2 3\n",
"2 2 2 1\n"
] | [
"8",
"2"
] | In the first sample Vasya make 3 pairwise perpendicular cuts. He cuts monster on two parts with the first cut, then he divides each part on two with the second cut, and finally he divides each of the 4 parts on two. | 500 | [
{
"input": "2 2 2 3",
"output": "8"
},
{
"input": "2 2 2 1",
"output": "2"
},
{
"input": "1 1 1 1",
"output": "1"
},
{
"input": "1 2 3 3",
"output": "6"
},
{
"input": "20 4 5 12",
"output": "120"
},
{
"input": "100 500 100500 1000000000",
"output":... | 1,597,705,115 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 3 | 248 | 0 | a,b,c,k = map(int,input().split())
if(a==b==c==1):
print(1)
exit(0)
a = k//3
b = k-2*a
print(((a+1)**2)*(b+1)) | Title: The Elder Trolls IV: Oblivon
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is "Unkillable"? Firstly, because it can be killed with cutting weapon only, so lovers of two-handed amber hammers should find suitable knife themselves. Secondly, it is necessary to make so many cutting strokes to Unkillable Slug. Extremely many. Too many!
Vasya has already promoted his character to 80-th level and in order to gain level 81 he was asked to kill Unkillable Slug. The monster has a very interesting shape. It looks like a rectangular parallelepiped with size *x*<=×<=*y*<=×<=*z*, consisting of undestructable cells 1<=×<=1<=×<=1. At one stroke Vasya can cut the Slug along an imaginary grid, i.e. cut with a plane parallel to one of the parallelepiped side. Monster dies when amount of parts it is divided reaches some critical value.
All parts of monster do not fall after each cut, they remains exactly on its places. I. e. Vasya can cut several parts with one cut.
Vasya wants to know what the maximum number of pieces he can cut the Unkillable Slug into striking him at most *k* times.
Vasya's character uses absolutely thin sword with infinite length.
Input Specification:
The first line of input contains four integer numbers *x*,<=*y*,<=*z*,<=*k* (1<=≤<=*x*,<=*y*,<=*z*<=≤<=106,<=0<=≤<=*k*<=≤<=109).
Output Specification:
Output the only number — the answer for the problem.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Demo Input:
['2 2 2 3\n', '2 2 2 1\n']
Demo Output:
['8', '2']
Note:
In the first sample Vasya make 3 pairwise perpendicular cuts. He cuts monster on two parts with the first cut, then he divides each part on two with the second cut, and finally he divides each of the 4 parts on two. | ```python
a,b,c,k = map(int,input().split())
if(a==b==c==1):
print(1)
exit(0)
a = k//3
b = k-2*a
print(((a+1)**2)*(b+1))
``` | 0 |
379 | A | New Year Candles | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has *a* candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make *b* went out candles into a new candle. As a result, this new candle can be used like any other new candle.
Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number. | The single line contains two integers, *a* and *b* (1<=≤<=*a*<=≤<=1000; 2<=≤<=*b*<=≤<=1000). | Print a single integer — the number of hours Vasily can light up the room for. | [
"4 2\n",
"6 3\n"
] | [
"7\n",
"8\n"
] | Consider the first sample. For the first four hours Vasily lights up new candles, then he uses four burned out candles to make two new ones and lights them up. When these candles go out (stop burning), Vasily can make another candle. Overall, Vasily can light up the room for 7 hours. | 500 | [
{
"input": "4 2",
"output": "7"
},
{
"input": "6 3",
"output": "8"
},
{
"input": "1000 1000",
"output": "1001"
},
{
"input": "123 5",
"output": "153"
},
{
"input": "1000 2",
"output": "1999"
},
{
"input": "1 2",
"output": "1"
},
{
"input": ... | 1,649,332,590 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 46 | 0 | a,b = map(int,input().split())
count = 0
while a>=0:
count+=1
a-=1
if count%b==0:
count+=1
print(count-2)
| Title: New Year Candles
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has *a* candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make *b* went out candles into a new candle. As a result, this new candle can be used like any other new candle.
Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number.
Input Specification:
The single line contains two integers, *a* and *b* (1<=≤<=*a*<=≤<=1000; 2<=≤<=*b*<=≤<=1000).
Output Specification:
Print a single integer — the number of hours Vasily can light up the room for.
Demo Input:
['4 2\n', '6 3\n']
Demo Output:
['7\n', '8\n']
Note:
Consider the first sample. For the first four hours Vasily lights up new candles, then he uses four burned out candles to make two new ones and lights them up. When these candles go out (stop burning), Vasily can make another candle. Overall, Vasily can light up the room for 7 hours. | ```python
a,b = map(int,input().split())
count = 0
while a>=0:
count+=1
a-=1
if count%b==0:
count+=1
print(count-2)
``` | 0 | |
3 | A | Shortest path of the king | PROGRAMMING | 1,000 | [
"greedy",
"shortest paths"
] | A. Shortest path of the king | 1 | 64 | The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square *t*. As the king is not in habit of wasting his time, he wants to get from his current position *s* to square *t* in the least number of moves. Help him to do this.
In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to). | The first line contains the chessboard coordinates of square *s*, the second line — of square *t*.
Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h), the second one is a digit from 1 to 8. | In the first line print *n* — minimum number of the king's moves. Then in *n* lines print the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD.
L, R, U, D stand respectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them. | [
"a8\nh1\n"
] | [
"7\nRD\nRD\nRD\nRD\nRD\nRD\nRD\n"
] | none | 0 | [
{
"input": "a8\nh1",
"output": "7\nRD\nRD\nRD\nRD\nRD\nRD\nRD"
},
{
"input": "b2\nb4",
"output": "2\nU\nU"
},
{
"input": "a5\na5",
"output": "0"
},
{
"input": "h1\nb2",
"output": "6\nLU\nL\nL\nL\nL\nL"
},
{
"input": "c5\nh2",
"output": "5\nRD\nRD\nRD\nR\nR"
... | 1,689,068,239 | 2,147,483,647 | PyPy 3 | OK | TESTS | 35 | 186 | 0 | a = input()
b = input()
c = 'abcdefgh'
x1, y1 = c.index(a[0]), int(a[1])
x2, y2 = c.index(b[0]), int(b[1])
print(max(abs(x1 - x2), abs(y1 - y2)))
x1 += 1
x2 += 1
x = x1
y = y1
while (x != x2 or y != y2):
if x < x2 and y > y2:
print('RD')
x += 1
y -= 1
if x > x2 and y > y2:
print('LD')
x -= 1
y -= 1
if x < x2 and y < y2:
print('RU')
x += 1
y += 1
if x > x2 and y < y2:
print('LU')
x -= 1
y += 1
if x == x2:
if y > y2:
print('D')
y -= 1
elif y2 > y:
print('U')
y += 1
if y == y2:
if x > x2:
print('L')
x -= 1
elif x2 > x:
print('R')
x += 1
# Tue Jul 11 2023 12:37:18 GMT+0300 (Moscow Standard Time)
| Title: Shortest path of the king
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square *t*. As the king is not in habit of wasting his time, he wants to get from his current position *s* to square *t* in the least number of moves. Help him to do this.
In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).
Input Specification:
The first line contains the chessboard coordinates of square *s*, the second line — of square *t*.
Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h), the second one is a digit from 1 to 8.
Output Specification:
In the first line print *n* — minimum number of the king's moves. Then in *n* lines print the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD.
L, R, U, D stand respectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them.
Demo Input:
['a8\nh1\n']
Demo Output:
['7\nRD\nRD\nRD\nRD\nRD\nRD\nRD\n']
Note:
none | ```python
a = input()
b = input()
c = 'abcdefgh'
x1, y1 = c.index(a[0]), int(a[1])
x2, y2 = c.index(b[0]), int(b[1])
print(max(abs(x1 - x2), abs(y1 - y2)))
x1 += 1
x2 += 1
x = x1
y = y1
while (x != x2 or y != y2):
if x < x2 and y > y2:
print('RD')
x += 1
y -= 1
if x > x2 and y > y2:
print('LD')
x -= 1
y -= 1
if x < x2 and y < y2:
print('RU')
x += 1
y += 1
if x > x2 and y < y2:
print('LU')
x -= 1
y += 1
if x == x2:
if y > y2:
print('D')
y -= 1
elif y2 > y:
print('U')
y += 1
if y == y2:
if x > x2:
print('L')
x -= 1
elif x2 > x:
print('R')
x += 1
# Tue Jul 11 2023 12:37:18 GMT+0300 (Moscow Standard Time)
``` | 3.907 |
137 | B | Permutation | PROGRAMMING | 1,000 | [
"greedy"
] | null | null | "Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.
The sequence of *n* integers is called a permutation if it contains all integers from 1 to *n* exactly once.
You are given an arbitrary sequence *a*1,<=*a*2,<=...,<=*a**n* containing *n* integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer). | The first line of the input data contains an integer *n* (1<=≤<=*n*<=≤<=5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers *a**i* (1<=≤<=*a**i*<=≤<=5000,<=1<=≤<=*i*<=≤<=*n*). | Print the only number — the minimum number of changes needed to get the permutation. | [
"3\n3 1 2\n",
"2\n2 2\n",
"5\n5 3 3 3 1\n"
] | [
"0\n",
"1\n",
"2\n"
] | The first sample contains the permutation, which is why no replacements are required.
In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.
In the third sample we can replace the second element with number 4 and the fourth element with number 2. | 1,000 | [
{
"input": "3\n3 1 2",
"output": "0"
},
{
"input": "2\n2 2",
"output": "1"
},
{
"input": "5\n5 3 3 3 1",
"output": "2"
},
{
"input": "5\n6 6 6 6 6",
"output": "5"
},
{
"input": "10\n1 1 2 2 8 8 7 7 9 9",
"output": "5"
},
{
"input": "8\n9 8 7 6 5 4 3 2"... | 1,608,803,378 | 2,147,483,647 | Python 3 | OK | TESTS | 48 | 280 | 819,200 | from collections import Counter
n = int(input())
arr = list(map(int, input().split()))
c = Counter(arr)
count = 0
for i in range(1, n+1):
if i not in c:
count += 1
print(count) | Title: Permutation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.
The sequence of *n* integers is called a permutation if it contains all integers from 1 to *n* exactly once.
You are given an arbitrary sequence *a*1,<=*a*2,<=...,<=*a**n* containing *n* integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).
Input Specification:
The first line of the input data contains an integer *n* (1<=≤<=*n*<=≤<=5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers *a**i* (1<=≤<=*a**i*<=≤<=5000,<=1<=≤<=*i*<=≤<=*n*).
Output Specification:
Print the only number — the minimum number of changes needed to get the permutation.
Demo Input:
['3\n3 1 2\n', '2\n2 2\n', '5\n5 3 3 3 1\n']
Demo Output:
['0\n', '1\n', '2\n']
Note:
The first sample contains the permutation, which is why no replacements are required.
In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.
In the third sample we can replace the second element with number 4 and the fourth element with number 2. | ```python
from collections import Counter
n = int(input())
arr = list(map(int, input().split()))
c = Counter(arr)
count = 0
for i in range(1, n+1):
if i not in c:
count += 1
print(count)
``` | 3 | |
526 | A | King of Thieves | PROGRAMMING | 1,300 | [
"brute force",
"implementation"
] | null | null | In this problem you will meet the simplified model of game King of Thieves.
In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way.
An interesting feature of the game is that you can design your own levels that will be available to other players. Let's consider the following simple design of a level.
A dungeon consists of *n* segments located at a same vertical level, each segment is either a platform that character can stand on, or a pit with a trap that makes player lose if he falls into it. All segments have the same length, platforms on the scheme of the level are represented as '*' and pits are represented as '.'.
One of things that affects speedrun characteristics of the level is a possibility to perform a series of consecutive jumps of the same length. More formally, when the character is on the platform number *i*1, he can make a sequence of jumps through the platforms *i*1<=<<=*i*2<=<<=...<=<<=*i**k*, if *i*2<=-<=*i*1<==<=*i*3<=-<=*i*2<==<=...<==<=*i**k*<=-<=*i**k*<=-<=1. Of course, all segments *i*1,<=*i*2,<=... *i**k* should be exactly the platforms, not pits.
Let's call a level to be good if you can perform a sequence of four jumps of the same length or in the other words there must be a sequence *i*1,<=*i*2,<=...,<=*i*5, consisting of five platforms so that the intervals between consecutive platforms are of the same length. Given the scheme of the level, check if it is good. | The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of segments on the level.
Next line contains the scheme of the level represented as a string of *n* characters '*' and '.'. | If the level is good, print the word "yes" (without the quotes), otherwise print the word "no" (without the quotes). | [
"16\n.**.*..*.***.**.\n",
"11\n.*.*...*.*.\n"
] | [
"yes",
"no"
] | In the first sample test you may perform a sequence of jumps through platforms 2, 5, 8, 11, 14. | 500 | [
{
"input": "16\n.**.*..*.***.**.",
"output": "yes"
},
{
"input": "11\n.*.*...*.*.",
"output": "no"
},
{
"input": "53\n*.*.****.*.*......**....**.***.*.*.**.*.*.***...*..*.",
"output": "yes"
},
{
"input": "71\n**.**..*****.*.*.*.********.....*****.****.*..***...*.*.*.**.****.*... | 1,428,167,864 | 2,564 | Python 3 | WRONG_ANSWER | PRETESTS | 2 | 62 | 0 | import itertools
n = int(input())
s = input()
ok = False
for i in range(n):
for jump in range(1, (n - i) // 5 + 1):
for c in itertools.islice(s, i, i + 5 * jump, jump):
if c == '.':
break
else:
print("yes")
ok = True
break
if not ok:
print("no")
| Title: King of Thieves
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In this problem you will meet the simplified model of game King of Thieves.
In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way.
An interesting feature of the game is that you can design your own levels that will be available to other players. Let's consider the following simple design of a level.
A dungeon consists of *n* segments located at a same vertical level, each segment is either a platform that character can stand on, or a pit with a trap that makes player lose if he falls into it. All segments have the same length, platforms on the scheme of the level are represented as '*' and pits are represented as '.'.
One of things that affects speedrun characteristics of the level is a possibility to perform a series of consecutive jumps of the same length. More formally, when the character is on the platform number *i*1, he can make a sequence of jumps through the platforms *i*1<=<<=*i*2<=<<=...<=<<=*i**k*, if *i*2<=-<=*i*1<==<=*i*3<=-<=*i*2<==<=...<==<=*i**k*<=-<=*i**k*<=-<=1. Of course, all segments *i*1,<=*i*2,<=... *i**k* should be exactly the platforms, not pits.
Let's call a level to be good if you can perform a sequence of four jumps of the same length or in the other words there must be a sequence *i*1,<=*i*2,<=...,<=*i*5, consisting of five platforms so that the intervals between consecutive platforms are of the same length. Given the scheme of the level, check if it is good.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of segments on the level.
Next line contains the scheme of the level represented as a string of *n* characters '*' and '.'.
Output Specification:
If the level is good, print the word "yes" (without the quotes), otherwise print the word "no" (without the quotes).
Demo Input:
['16\n.**.*..*.***.**.\n', '11\n.*.*...*.*.\n']
Demo Output:
['yes', 'no']
Note:
In the first sample test you may perform a sequence of jumps through platforms 2, 5, 8, 11, 14. | ```python
import itertools
n = int(input())
s = input()
ok = False
for i in range(n):
for jump in range(1, (n - i) // 5 + 1):
for c in itertools.islice(s, i, i + 5 * jump, jump):
if c == '.':
break
else:
print("yes")
ok = True
break
if not ok:
print("no")
``` | 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,679,648,713 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 34 | 124 | 0 | n,k = map(int, input().split(' '))
nums = list(map(str, input().split(' ')))
lucky = ['4','7']
res = 0
count = 0
for i in nums:
for j in i :
if j in lucky :
count += 1
if count <= k :
res += 1
count = 0
print(res)
| 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,k = map(int, input().split(' '))
nums = list(map(str, input().split(' ')))
lucky = ['4','7']
res = 0
count = 0
for i in nums:
for j in i :
if j in lucky :
count += 1
if count <= k :
res += 1
count = 0
print(res)
``` | 3 | |
842 | A | Kirill And The Game | PROGRAMMING | 1,200 | [
"brute force",
"two pointers"
] | null | null | Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.
For each two integer numbers *a* and *b* such that *l*<=≤<=*a*<=≤<=*r* and *x*<=≤<=*b*<=≤<=*y* there is a potion with experience *a* and cost *b* in the store (that is, there are (*r*<=-<=*l*<=+<=1)·(*y*<=-<=*x*<=+<=1) potions).
Kirill wants to buy a potion which has efficiency *k*. Will he be able to do this? | First string contains five integer numbers *l*, *r*, *x*, *y*, *k* (1<=≤<=*l*<=≤<=*r*<=≤<=107, 1<=≤<=*x*<=≤<=*y*<=≤<=107, 1<=≤<=*k*<=≤<=107). | Print "YES" without quotes if a potion with efficiency exactly *k* can be bought in the store and "NO" without quotes otherwise.
You can output each of the letters in any register. | [
"1 10 1 10 1\n",
"1 5 6 10 1\n"
] | [
"YES",
"NO"
] | none | 500 | [
{
"input": "1 10 1 10 1",
"output": "YES"
},
{
"input": "1 5 6 10 1",
"output": "NO"
},
{
"input": "1 1 1 1 1",
"output": "YES"
},
{
"input": "1 1 1 1 2",
"output": "NO"
},
{
"input": "1 100000 1 100000 100000",
"output": "YES"
},
{
"input": "1 100000 ... | 1,559,292,479 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 4 | 2,000 | 0 | l, r, x, y, k = [float(i) for i in input().split()]
possible = False
for a in range(int(l), int(r + 1)):
for b in range(int(x), int(y + 1)):
if (a / b) == k:
possible = True
if possible == True:
print("YES")
else:
print("NO") | Title: Kirill And The Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.
For each two integer numbers *a* and *b* such that *l*<=≤<=*a*<=≤<=*r* and *x*<=≤<=*b*<=≤<=*y* there is a potion with experience *a* and cost *b* in the store (that is, there are (*r*<=-<=*l*<=+<=1)·(*y*<=-<=*x*<=+<=1) potions).
Kirill wants to buy a potion which has efficiency *k*. Will he be able to do this?
Input Specification:
First string contains five integer numbers *l*, *r*, *x*, *y*, *k* (1<=≤<=*l*<=≤<=*r*<=≤<=107, 1<=≤<=*x*<=≤<=*y*<=≤<=107, 1<=≤<=*k*<=≤<=107).
Output Specification:
Print "YES" without quotes if a potion with efficiency exactly *k* can be bought in the store and "NO" without quotes otherwise.
You can output each of the letters in any register.
Demo Input:
['1 10 1 10 1\n', '1 5 6 10 1\n']
Demo Output:
['YES', 'NO']
Note:
none | ```python
l, r, x, y, k = [float(i) for i in input().split()]
possible = False
for a in range(int(l), int(r + 1)):
for b in range(int(x), int(y + 1)):
if (a / b) == k:
possible = True
if possible == True:
print("YES")
else:
print("NO")
``` | 0 | |
142 | A | Help Farmer | PROGRAMMING | 1,600 | [
"brute force",
"math"
] | null | null | Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored *A*·*B*·*C* hay blocks and stored them in a barn as a rectangular parallelepiped *A* layers high. Each layer had *B* rows and each row had *C* blocks.
At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (*A*<=-<=1)<=×<=(*B*<=-<=2)<=×<=(*C*<=-<=2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1<=×<=1<=×<=1 blocks and scattered them around the barn. After the theft Sam counted *n* hay blocks in the barn but he forgot numbers *A*, *B* и *C*.
Given number *n*, find the minimally possible and maximally possible number of stolen hay blocks. | The only line contains integer *n* from the problem's statement (1<=≤<=*n*<=≤<=109). | Print space-separated minimum and maximum number of hay blocks that could have been stolen by the thieves.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator. | [
"4\n",
"7\n",
"12\n"
] | [
"28 41\n",
"47 65\n",
"48 105\n"
] | Let's consider the first sample test. If initially Sam has a parallelepiped consisting of 32 = 2 × 4 × 4 hay blocks in his barn, then after the theft the barn has 4 = (2 - 1) × (4 - 2) × (4 - 2) hay blocks left. Thus, the thieves could have stolen 32 - 4 = 28 hay blocks. If Sam initially had a parallelepiped consisting of 45 = 5 × 3 × 3 hay blocks in his barn, then after the theft the barn has 4 = (5 - 1) × (3 - 2) × (3 - 2) hay blocks left. Thus, the thieves could have stolen 45 - 4 = 41 hay blocks. No other variants of the blocks' initial arrangement (that leave Sam with exactly 4 blocks after the theft) can permit the thieves to steal less than 28 or more than 41 blocks. | 500 | [
{
"input": "4",
"output": "28 41"
},
{
"input": "7",
"output": "47 65"
},
{
"input": "12",
"output": "48 105"
},
{
"input": "1",
"output": "17 17"
},
{
"input": "6",
"output": "34 57"
},
{
"input": "8",
"output": "40 73"
},
{
"input": "9",
... | 1,691,165,660 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 100 | 124 | 3,072,000 | n = int(input())
kd = 0
d = [0] * 100010
for x in range(1, n + 1):
if x * x > n:
break
elif n % x == 0:
kd += 1
d[kd] = x
if x * x < n:
kd += 1
d[kd] = n // x
minimum = float('inf')
maximum = -1
for a in range(1, kd + 1):
for b in range(1, kd + 1):
if n // d[a] % d[b] != 0:
continue
c = n // d[a] // d[b]
cur = (d[a] + 1) * (d[b] + 2) * (c + 2) - n
minimum = min(minimum, cur)
maximum = max(maximum, cur)
print(minimum, maximum)# 1691165660.7016428 | Title: Help Farmer
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored *A*·*B*·*C* hay blocks and stored them in a barn as a rectangular parallelepiped *A* layers high. Each layer had *B* rows and each row had *C* blocks.
At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (*A*<=-<=1)<=×<=(*B*<=-<=2)<=×<=(*C*<=-<=2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1<=×<=1<=×<=1 blocks and scattered them around the barn. After the theft Sam counted *n* hay blocks in the barn but he forgot numbers *A*, *B* и *C*.
Given number *n*, find the minimally possible and maximally possible number of stolen hay blocks.
Input Specification:
The only line contains integer *n* from the problem's statement (1<=≤<=*n*<=≤<=109).
Output Specification:
Print space-separated minimum and maximum number of hay blocks that could have been stolen by the thieves.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Demo Input:
['4\n', '7\n', '12\n']
Demo Output:
['28 41\n', '47 65\n', '48 105\n']
Note:
Let's consider the first sample test. If initially Sam has a parallelepiped consisting of 32 = 2 × 4 × 4 hay blocks in his barn, then after the theft the barn has 4 = (2 - 1) × (4 - 2) × (4 - 2) hay blocks left. Thus, the thieves could have stolen 32 - 4 = 28 hay blocks. If Sam initially had a parallelepiped consisting of 45 = 5 × 3 × 3 hay blocks in his barn, then after the theft the barn has 4 = (5 - 1) × (3 - 2) × (3 - 2) hay blocks left. Thus, the thieves could have stolen 45 - 4 = 41 hay blocks. No other variants of the blocks' initial arrangement (that leave Sam with exactly 4 blocks after the theft) can permit the thieves to steal less than 28 or more than 41 blocks. | ```python
n = int(input())
kd = 0
d = [0] * 100010
for x in range(1, n + 1):
if x * x > n:
break
elif n % x == 0:
kd += 1
d[kd] = x
if x * x < n:
kd += 1
d[kd] = n // x
minimum = float('inf')
maximum = -1
for a in range(1, kd + 1):
for b in range(1, kd + 1):
if n // d[a] % d[b] != 0:
continue
c = n // d[a] // d[b]
cur = (d[a] + 1) * (d[b] + 2) * (c + 2) - n
minimum = min(minimum, cur)
maximum = max(maximum, cur)
print(minimum, maximum)# 1691165660.7016428
``` | 3 | |
149 | A | Business trip | PROGRAMMING | 900 | [
"greedy",
"implementation",
"sortings"
] | null | null | What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until...
Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" — thought Petya. He know for a fact that if he fulfills the parents' task in the *i*-th (1<=≤<=*i*<=≤<=12) month of the year, then the flower will grow by *a**i* centimeters, and if he doesn't water the flower in the *i*-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by *k* centimeters.
Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by *k* centimeters. | The first line contains exactly one integer *k* (0<=≤<=*k*<=≤<=100). The next line contains twelve space-separated integers: the *i*-th (1<=≤<=*i*<=≤<=12) number in the line represents *a**i* (0<=≤<=*a**i*<=≤<=100). | Print the only integer — the minimum number of months when Petya has to water the flower so that the flower grows no less than by *k* centimeters. If the flower can't grow by *k* centimeters in a year, print -1. | [
"5\n1 1 1 1 2 2 3 2 2 1 1 1\n",
"0\n0 0 0 0 0 0 0 1 1 2 3 0\n",
"11\n1 1 4 1 1 5 1 1 4 1 1 1\n"
] | [
"2\n",
"0\n",
"3\n"
] | Let's consider the first sample test. There it is enough to water the flower during the seventh and the ninth month. Then the flower grows by exactly five centimeters.
In the second sample Petya's parents will believe him even if the flower doesn't grow at all (*k* = 0). So, it is possible for Petya not to water the flower at all. | 500 | [
{
"input": "5\n1 1 1 1 2 2 3 2 2 1 1 1",
"output": "2"
},
{
"input": "0\n0 0 0 0 0 0 0 1 1 2 3 0",
"output": "0"
},
{
"input": "11\n1 1 4 1 1 5 1 1 4 1 1 1",
"output": "3"
},
{
"input": "15\n20 1 1 1 1 2 2 1 2 2 1 1",
"output": "1"
},
{
"input": "7\n8 9 100 12 14 ... | 1,651,412,293 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 6 | 62 | 0 | k=int(input())
a=list(map(int,input().split()))
b=sorted(a,reverse=True)
suma=0
br=0
for i in b:
if suma<k:
suma+=i
br+=1
if suma>=k:
break
print(br)
| Title: Business trip
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until...
Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" — thought Petya. He know for a fact that if he fulfills the parents' task in the *i*-th (1<=≤<=*i*<=≤<=12) month of the year, then the flower will grow by *a**i* centimeters, and if he doesn't water the flower in the *i*-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by *k* centimeters.
Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by *k* centimeters.
Input Specification:
The first line contains exactly one integer *k* (0<=≤<=*k*<=≤<=100). The next line contains twelve space-separated integers: the *i*-th (1<=≤<=*i*<=≤<=12) number in the line represents *a**i* (0<=≤<=*a**i*<=≤<=100).
Output Specification:
Print the only integer — the minimum number of months when Petya has to water the flower so that the flower grows no less than by *k* centimeters. If the flower can't grow by *k* centimeters in a year, print -1.
Demo Input:
['5\n1 1 1 1 2 2 3 2 2 1 1 1\n', '0\n0 0 0 0 0 0 0 1 1 2 3 0\n', '11\n1 1 4 1 1 5 1 1 4 1 1 1\n']
Demo Output:
['2\n', '0\n', '3\n']
Note:
Let's consider the first sample test. There it is enough to water the flower during the seventh and the ninth month. Then the flower grows by exactly five centimeters.
In the second sample Petya's parents will believe him even if the flower doesn't grow at all (*k* = 0). So, it is possible for Petya not to water the flower at all. | ```python
k=int(input())
a=list(map(int,input().split()))
b=sorted(a,reverse=True)
suma=0
br=0
for i in b:
if suma<k:
suma+=i
br+=1
if suma>=k:
break
print(br)
``` | 0 | |
858 | A | k-rounding | PROGRAMMING | 1,100 | [
"brute force",
"math",
"number theory"
] | null | null | For a given positive integer *n* denote its *k*-rounding as the minimum positive integer *x*, such that *x* ends with *k* or more zeros in base 10 and is divisible by *n*.
For example, 4-rounding of 375 is 375·80<==<=30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program that will perform the *k*-rounding of *n*. | The only line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=109, 0<=≤<=*k*<=≤<=8). | Print the *k*-rounding of *n*. | [
"375 4\n",
"10000 1\n",
"38101 0\n",
"123456789 8\n"
] | [
"30000\n",
"10000\n",
"38101\n",
"12345678900000000\n"
] | none | 750 | [
{
"input": "375 4",
"output": "30000"
},
{
"input": "10000 1",
"output": "10000"
},
{
"input": "38101 0",
"output": "38101"
},
{
"input": "123456789 8",
"output": "12345678900000000"
},
{
"input": "1 0",
"output": "1"
},
{
"input": "2 0",
"output":... | 1,603,788,704 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 42 | 140 | 0 | def f(n):
global k
n=str(n)
r=0
for i in range(len(n)-1, len(n)-k-1, -1):
if n[i]=='0':
r+=1
else:
return r
return r
n,k=[int(i) for i in input().split()]
i=1
s=str(n)
r=0
for i in range(len(s)-1, (len(s)-k-1), -1):
if s[i]=='0':
r+=1
else:
break
if r>=k:
print(s)
elif int(s[-1])%2==1 and s[-1]!='5':
print(s+'0'*k)
else:
e=1
c=n
while True:
if n%2==0:
e=e*5
n=n//2
if f(e*c)==k:
break
if n%5==0:
e*=2
n//=5
if f(e*c)==k:
break
if n%2!=0 and n%5!=0:
break
q=str(e*c)
if f(q)==k:
print(q)
else:
r=f(q)
k-=r
print(q+'0'*k) | Title: k-rounding
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
For a given positive integer *n* denote its *k*-rounding as the minimum positive integer *x*, such that *x* ends with *k* or more zeros in base 10 and is divisible by *n*.
For example, 4-rounding of 375 is 375·80<==<=30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program that will perform the *k*-rounding of *n*.
Input Specification:
The only line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=109, 0<=≤<=*k*<=≤<=8).
Output Specification:
Print the *k*-rounding of *n*.
Demo Input:
['375 4\n', '10000 1\n', '38101 0\n', '123456789 8\n']
Demo Output:
['30000\n', '10000\n', '38101\n', '12345678900000000\n']
Note:
none | ```python
def f(n):
global k
n=str(n)
r=0
for i in range(len(n)-1, len(n)-k-1, -1):
if n[i]=='0':
r+=1
else:
return r
return r
n,k=[int(i) for i in input().split()]
i=1
s=str(n)
r=0
for i in range(len(s)-1, (len(s)-k-1), -1):
if s[i]=='0':
r+=1
else:
break
if r>=k:
print(s)
elif int(s[-1])%2==1 and s[-1]!='5':
print(s+'0'*k)
else:
e=1
c=n
while True:
if n%2==0:
e=e*5
n=n//2
if f(e*c)==k:
break
if n%5==0:
e*=2
n//=5
if f(e*c)==k:
break
if n%2!=0 and n%5!=0:
break
q=str(e*c)
if f(q)==k:
print(q)
else:
r=f(q)
k-=r
print(q+'0'*k)
``` | 0 | |
507 | B | Amr and Pins | PROGRAMMING | 1,400 | [
"geometry",
"math"
] | null | null | Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius *r* and center in point (*x*,<=*y*). He wants the circle center to be in new position (*x*',<=*y*').
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin.
Help Amr to achieve his goal in minimum number of steps. | Input consists of 5 space-separated integers *r*, *x*, *y*, *x*' *y*' (1<=≤<=*r*<=≤<=105, <=-<=105<=≤<=*x*,<=*y*,<=*x*',<=*y*'<=≤<=105), circle radius, coordinates of original center of the circle and coordinates of destination center of the circle respectively. | Output a single integer — minimum number of steps required to move the center of the circle to the destination point. | [
"2 0 0 0 4\n",
"1 1 1 4 4\n",
"4 5 6 5 6\n"
] | [
"1\n",
"3\n",
"0\n"
] | In the first sample test the optimal way is to put a pin at point (0, 2) and rotate the circle by 180 degrees counter-clockwise (or clockwise, no matter).
<img class="tex-graphics" src="https://espresso.codeforces.com/4e40fd4cc24a2050a0488aa131e6244369328039.png" style="max-width: 100.0%;max-height: 100.0%;"/> | 1,000 | [
{
"input": "2 0 0 0 4",
"output": "1"
},
{
"input": "1 1 1 4 4",
"output": "3"
},
{
"input": "4 5 6 5 6",
"output": "0"
},
{
"input": "10 20 0 40 0",
"output": "1"
},
{
"input": "9 20 0 40 0",
"output": "2"
},
{
"input": "5 -1 -6 -5 1",
"output": "... | 1,607,504,287 | 2,147,483,647 | Python 3 | OK | TESTS | 37 | 93 | 0 | import math
r, x, y, x1, y1 = map(int, input().split())
print(int(-(math.sqrt((x1-x)**2 + (y1-y)**2) // (-2*r))))
| Title: Amr and Pins
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius *r* and center in point (*x*,<=*y*). He wants the circle center to be in new position (*x*',<=*y*').
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin.
Help Amr to achieve his goal in minimum number of steps.
Input Specification:
Input consists of 5 space-separated integers *r*, *x*, *y*, *x*' *y*' (1<=≤<=*r*<=≤<=105, <=-<=105<=≤<=*x*,<=*y*,<=*x*',<=*y*'<=≤<=105), circle radius, coordinates of original center of the circle and coordinates of destination center of the circle respectively.
Output Specification:
Output a single integer — minimum number of steps required to move the center of the circle to the destination point.
Demo Input:
['2 0 0 0 4\n', '1 1 1 4 4\n', '4 5 6 5 6\n']
Demo Output:
['1\n', '3\n', '0\n']
Note:
In the first sample test the optimal way is to put a pin at point (0, 2) and rotate the circle by 180 degrees counter-clockwise (or clockwise, no matter).
<img class="tex-graphics" src="https://espresso.codeforces.com/4e40fd4cc24a2050a0488aa131e6244369328039.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
import math
r, x, y, x1, y1 = map(int, input().split())
print(int(-(math.sqrt((x1-x)**2 + (y1-y)**2) // (-2*r))))
``` | 3 | |
987 | A | Infinity Gauntlet | PROGRAMMING | 800 | [
"implementation"
] | null | null | You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:
- the Power Gem of purple color, - the Time Gem of green color, - the Space Gem of blue color, - the Soul Gem of orange color, - the Reality Gem of red color, - the Mind Gem of yellow color.
Using colors of Gems you saw in the Gauntlet determine the names of absent Gems. | In the first line of input there is one integer $n$ ($0 \le n \le 6$) — the number of Gems in Infinity Gauntlet.
In next $n$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters. | In the first line output one integer $m$ ($0 \le m \le 6$) — the number of absent Gems.
Then in $m$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase. | [
"4\nred\npurple\nyellow\norange\n",
"0\n"
] | [
"2\nSpace\nTime\n",
"6\nTime\nMind\nSoul\nPower\nReality\nSpace\n"
] | In the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.
In the second sample Thanos doesn't have any Gems, so he needs all six. | 500 | [
{
"input": "4\nred\npurple\nyellow\norange",
"output": "2\nSpace\nTime"
},
{
"input": "0",
"output": "6\nMind\nSpace\nPower\nTime\nReality\nSoul"
},
{
"input": "6\npurple\nblue\nyellow\nred\ngreen\norange",
"output": "0"
},
{
"input": "1\npurple",
"output": "5\nTime\nReal... | 1,653,737,112 | 2,147,483,647 | Python 3 | OK | TESTS | 64 | 46 | 0 | q='Power'
q1='purple'
w='Time'
w1='green'
e='Space'
e1='blue'
r='Soul'
r1='orange'
t='Reality'
t1='red'
y='Mind'
y1='yellow'
k=6
n=int(input())
for i in range(n):
a=input()
if q1==a:
q1=' '
k=k-1
if w1==a:
w1=' '
k=k-1
if e1==a:
e1=' '
k=k-1
if r1==a:
r1=' '
k=k-1
if t1==a:
t1=' '
k=k-1
if y1==a:
y1=' '
k=k-1
print(k)
if (q1!=' '):
print(q)
if (w1!=' '):
print(w)
if (e1!=' '):
print(e)
if (r1!=' '):
print(r)
if (t1!=' '):
print(t)
if (y1!=' '):
print(y)
| Title: Infinity Gauntlet
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:
- the Power Gem of purple color, - the Time Gem of green color, - the Space Gem of blue color, - the Soul Gem of orange color, - the Reality Gem of red color, - the Mind Gem of yellow color.
Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.
Input Specification:
In the first line of input there is one integer $n$ ($0 \le n \le 6$) — the number of Gems in Infinity Gauntlet.
In next $n$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.
Output Specification:
In the first line output one integer $m$ ($0 \le m \le 6$) — the number of absent Gems.
Then in $m$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.
Demo Input:
['4\nred\npurple\nyellow\norange\n', '0\n']
Demo Output:
['2\nSpace\nTime\n', '6\nTime\nMind\nSoul\nPower\nReality\nSpace\n']
Note:
In the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.
In the second sample Thanos doesn't have any Gems, so he needs all six. | ```python
q='Power'
q1='purple'
w='Time'
w1='green'
e='Space'
e1='blue'
r='Soul'
r1='orange'
t='Reality'
t1='red'
y='Mind'
y1='yellow'
k=6
n=int(input())
for i in range(n):
a=input()
if q1==a:
q1=' '
k=k-1
if w1==a:
w1=' '
k=k-1
if e1==a:
e1=' '
k=k-1
if r1==a:
r1=' '
k=k-1
if t1==a:
t1=' '
k=k-1
if y1==a:
y1=' '
k=k-1
print(k)
if (q1!=' '):
print(q)
if (w1!=' '):
print(w)
if (e1!=' '):
print(e)
if (r1!=' '):
print(r)
if (t1!=' '):
print(t)
if (y1!=' '):
print(y)
``` | 3 | |
251 | B | Playing with Permutations | PROGRAMMING | 1,800 | [
"implementation",
"math"
] | null | null | Little Petya likes permutations a lot. Recently his mom has presented him permutation *q*1,<=*q*2,<=...,<=*q**n* of length *n*.
A permutation *a* of length *n* is a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*), all integers there are distinct.
There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length *n*. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules:
- Before the beginning of the game Petya writes permutation 1,<=2,<=...,<=*n* on the blackboard. After that Petya makes exactly *k* moves, which are described below. - During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2. Let's assume that the board contains permutation *p*1,<=*p*2,<=...,<=*p**n* at the given moment. Then Petya removes the written permutation *p* from the board and writes another one instead: *p**q*1,<=*p**q*2,<=...,<=*p**q**n*. In other words, Petya applies permutation *q* (which he has got from his mother) to permutation *p*. - All actions are similar to point 1, except that Petya writes permutation *t* on the board, such that: *t**q**i*<==<=*p**i* for all *i* from 1 to *n*. In other words, Petya applies a permutation that is inverse to *q* to permutation *p*.
We know that after the *k*-th move the board contained Masha's permutation *s*1,<=*s*2,<=...,<=*s**n*. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the *k*-th move. Note that the game has exactly *k* moves, that is, throughout the game the coin was tossed exactly *k* times.
Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding. | The first line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=100). The second line contains *n* space-separated integers *q*1,<=*q*2,<=...,<=*q**n* (1<=≤<=*q**i*<=≤<=*n*) — the permutation that Petya's got as a present. The third line contains Masha's permutation *s*, in the similar format.
It is guaranteed that the given sequences *q* and *s* are correct permutations. | If the situation that is described in the statement is possible, print "YES" (without the quotes), otherwise print "NO" (without the quotes). | [
"4 1\n2 3 4 1\n1 2 3 4\n",
"4 1\n4 3 1 2\n3 4 2 1\n",
"4 3\n4 3 1 2\n3 4 2 1\n",
"4 2\n4 3 1 2\n2 1 4 3\n",
"4 1\n4 3 1 2\n2 1 4 3\n"
] | [
"NO\n",
"YES\n",
"YES\n",
"YES\n",
"NO\n"
] | In the first sample Masha's permutation coincides with the permutation that was written on the board before the beginning of the game. Consequently, that violates the condition that Masha's permutation never occurred on the board before *k* moves were performed.
In the second sample the described situation is possible, in case if after we toss a coin, we get tails.
In the third sample the possible coin tossing sequence is: heads-tails-tails.
In the fourth sample the possible coin tossing sequence is: heads-heads. | 1,000 | [
{
"input": "4 1\n2 3 4 1\n1 2 3 4",
"output": "NO"
},
{
"input": "4 1\n4 3 1 2\n3 4 2 1",
"output": "YES"
},
{
"input": "4 3\n4 3 1 2\n3 4 2 1",
"output": "YES"
},
{
"input": "4 2\n4 3 1 2\n2 1 4 3",
"output": "YES"
},
{
"input": "4 1\n4 3 1 2\n2 1 4 3",
"outp... | 1,655,588,831 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 1 | 92 | 512,000 | import sys
from array import array
def move_up():
k_ = k
a = array('i', range(1, n + 1))
while k_ and a != final:
k_ -= 1
tem = array('i')
for i in range(n):
tem.append(a[q[i] - 1])
a = tem
return k_, a == final
def move_down():
k_ = k
a = array('i', range(1, n + 1))
while k_ and a != final:
k_ -= 1
tem = array('i', [0] * n)
for i in range(n):
tem[q[i] - 1] = a[i]
a = tem
return k_, a == final
input = lambda: sys.stdin.buffer.readline().decode().strip()
n, k = map(int, input().split())
q = array('i', [int(x) for x in input().split()])
final = array('i', [int(x) for x in input().split()])
ans = 0
retup, retdown = move_up(), move_down()
if retup[1]:
if k - retup[0] == 1:
if k - retup[1] > 1 and k & 1 and k >= 3:
ans = 1
elif k - retup[0] > 1:
if retup[0] & 1 == 0:
ans = 1
elif retup[0]:
if k - retup[1] == 1:
if k - retup[0] > 1 and k & 1 and k >= 3:
ans = 1
elif k - retup[1] > 1:
if retup[1] & 1 == 0:
ans = 1
print(['NO', 'YES'][ans])
| Title: Playing with Permutations
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Petya likes permutations a lot. Recently his mom has presented him permutation *q*1,<=*q*2,<=...,<=*q**n* of length *n*.
A permutation *a* of length *n* is a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*), all integers there are distinct.
There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length *n*. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules:
- Before the beginning of the game Petya writes permutation 1,<=2,<=...,<=*n* on the blackboard. After that Petya makes exactly *k* moves, which are described below. - During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2. Let's assume that the board contains permutation *p*1,<=*p*2,<=...,<=*p**n* at the given moment. Then Petya removes the written permutation *p* from the board and writes another one instead: *p**q*1,<=*p**q*2,<=...,<=*p**q**n*. In other words, Petya applies permutation *q* (which he has got from his mother) to permutation *p*. - All actions are similar to point 1, except that Petya writes permutation *t* on the board, such that: *t**q**i*<==<=*p**i* for all *i* from 1 to *n*. In other words, Petya applies a permutation that is inverse to *q* to permutation *p*.
We know that after the *k*-th move the board contained Masha's permutation *s*1,<=*s*2,<=...,<=*s**n*. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the *k*-th move. Note that the game has exactly *k* moves, that is, throughout the game the coin was tossed exactly *k* times.
Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding.
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=100). The second line contains *n* space-separated integers *q*1,<=*q*2,<=...,<=*q**n* (1<=≤<=*q**i*<=≤<=*n*) — the permutation that Petya's got as a present. The third line contains Masha's permutation *s*, in the similar format.
It is guaranteed that the given sequences *q* and *s* are correct permutations.
Output Specification:
If the situation that is described in the statement is possible, print "YES" (without the quotes), otherwise print "NO" (without the quotes).
Demo Input:
['4 1\n2 3 4 1\n1 2 3 4\n', '4 1\n4 3 1 2\n3 4 2 1\n', '4 3\n4 3 1 2\n3 4 2 1\n', '4 2\n4 3 1 2\n2 1 4 3\n', '4 1\n4 3 1 2\n2 1 4 3\n']
Demo Output:
['NO\n', 'YES\n', 'YES\n', 'YES\n', 'NO\n']
Note:
In the first sample Masha's permutation coincides with the permutation that was written on the board before the beginning of the game. Consequently, that violates the condition that Masha's permutation never occurred on the board before *k* moves were performed.
In the second sample the described situation is possible, in case if after we toss a coin, we get tails.
In the third sample the possible coin tossing sequence is: heads-tails-tails.
In the fourth sample the possible coin tossing sequence is: heads-heads. | ```python
import sys
from array import array
def move_up():
k_ = k
a = array('i', range(1, n + 1))
while k_ and a != final:
k_ -= 1
tem = array('i')
for i in range(n):
tem.append(a[q[i] - 1])
a = tem
return k_, a == final
def move_down():
k_ = k
a = array('i', range(1, n + 1))
while k_ and a != final:
k_ -= 1
tem = array('i', [0] * n)
for i in range(n):
tem[q[i] - 1] = a[i]
a = tem
return k_, a == final
input = lambda: sys.stdin.buffer.readline().decode().strip()
n, k = map(int, input().split())
q = array('i', [int(x) for x in input().split()])
final = array('i', [int(x) for x in input().split()])
ans = 0
retup, retdown = move_up(), move_down()
if retup[1]:
if k - retup[0] == 1:
if k - retup[1] > 1 and k & 1 and k >= 3:
ans = 1
elif k - retup[0] > 1:
if retup[0] & 1 == 0:
ans = 1
elif retup[0]:
if k - retup[1] == 1:
if k - retup[0] > 1 and k & 1 and k >= 3:
ans = 1
elif k - retup[1] > 1:
if retup[1] & 1 == 0:
ans = 1
print(['NO', 'YES'][ans])
``` | 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.