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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
304 | B | Calendar | PROGRAMMING | 1,300 | [
"brute force",
"implementation"
] | null | null | Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows:
Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year.
In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February.
Look at the sample to understand what borders are included in the aswer. | The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900<=≤<=*yyyy*<=≤<=2038 and yyyy:mm:dd is a legal date). | Print a single integer — the answer to the problem. | [
"1900:01:01\n2038:12:31\n",
"1996:03:09\n1991:11:12\n"
] | [
"50768\n",
"1579\n"
] | none | 1,000 | [
{
"input": "1900:01:01\n2038:12:31",
"output": "50768"
},
{
"input": "1996:03:09\n1991:11:12",
"output": "1579"
},
{
"input": "1999:12:31\n2000:02:29",
"output": "60"
},
{
"input": "1903:09:27\n1988:06:15",
"output": "30943"
},
{
"input": "1913:11:14\n1901:05:11",... | 1,693,685,709 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 30 | 92 | 0 | from sys import stdin
def input(): return stdin.readline()[:-1]
def ili(): return list(map(int, input().split()))
y1,m1,d1=map(int, input().split(':'))
y2,m2,d2=map(int, input().split(':'))
days = 0
if y1*100000+m1*100+d1 > y2*100000+m2*100+d2:
# print("hererheoroe")
y1, y2 = y2, y1
m1, m2 = m2, m1
d1, d2 = d2, d1
for i in range(y1+1,y2):
if (i%4 == 0 and i%100 != 0) or i%400 == 0:
days += 366
continue
days += 365
for l in range(1, m2+1):
if l == m2:
# print("hello")
days += d2
break
if l == 1 or l == 3 or l == 5 or l == 7 or l == 8 or l == 10 or l == 12:
days += 31
elif l == 4 or l == 6 or l == 9 or l == 11:
days += 30
elif l == 2:
days += 28
if (y2%4 == 0 and y2%100 != 0) or y2%400 == 0:
days += 1
days += 365
if (y1%4 == 0 and y1%100 != 0) or y1%400 == 0:
days += 1
# print(f"y2 is {y2}")
for l in range(1, m1+1):
if l == m1:
days -= d1
break
if l == 1 or l == 3 or l == 5 or l == 7 or l == 8 or l == 10 or l == 12:
days -= 31
elif l == 4 or l == 6 or l == 9 or l == 11:
days -= 30
elif l == 2:
days -= 28
if (y1%4 == 0 and y1%100 != 0) or y1%400 == 0:
# print("hellomoto")
days -= 1
print(days)
| Title: Calendar
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows:
Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year.
In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February.
Look at the sample to understand what borders are included in the aswer.
Input Specification:
The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900<=≤<=*yyyy*<=≤<=2038 and yyyy:mm:dd is a legal date).
Output Specification:
Print a single integer — the answer to the problem.
Demo Input:
['1900:01:01\n2038:12:31\n', '1996:03:09\n1991:11:12\n']
Demo Output:
['50768\n', '1579\n']
Note:
none | ```python
from sys import stdin
def input(): return stdin.readline()[:-1]
def ili(): return list(map(int, input().split()))
y1,m1,d1=map(int, input().split(':'))
y2,m2,d2=map(int, input().split(':'))
days = 0
if y1*100000+m1*100+d1 > y2*100000+m2*100+d2:
# print("hererheoroe")
y1, y2 = y2, y1
m1, m2 = m2, m1
d1, d2 = d2, d1
for i in range(y1+1,y2):
if (i%4 == 0 and i%100 != 0) or i%400 == 0:
days += 366
continue
days += 365
for l in range(1, m2+1):
if l == m2:
# print("hello")
days += d2
break
if l == 1 or l == 3 or l == 5 or l == 7 or l == 8 or l == 10 or l == 12:
days += 31
elif l == 4 or l == 6 or l == 9 or l == 11:
days += 30
elif l == 2:
days += 28
if (y2%4 == 0 and y2%100 != 0) or y2%400 == 0:
days += 1
days += 365
if (y1%4 == 0 and y1%100 != 0) or y1%400 == 0:
days += 1
# print(f"y2 is {y2}")
for l in range(1, m1+1):
if l == m1:
days -= d1
break
if l == 1 or l == 3 or l == 5 or l == 7 or l == 8 or l == 10 or l == 12:
days -= 31
elif l == 4 or l == 6 or l == 9 or l == 11:
days -= 30
elif l == 2:
days -= 28
if (y1%4 == 0 and y1%100 != 0) or y1%400 == 0:
# print("hellomoto")
days -= 1
print(days)
``` | 0 | |
729 | B | Spotlights | PROGRAMMING | 1,200 | [
"dp",
"implementation"
] | null | null | Theater stage is a rectangular field of size *n*<=×<=*m*. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.
A position is good if two conditions hold:
- there is no actor in the cell the spotlight is placed to; - there is at least one actor in the direction the spotlight projects.
Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ. | The first line contains two positive integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and the number of columns in the plan.
The next *n* lines contain *m* integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan. | Print one integer — the number of good positions for placing the spotlight. | [
"2 4\n0 1 0 0\n1 0 1 0\n",
"4 4\n0 0 0 0\n1 0 0 1\n0 1 1 0\n0 1 0 0\n"
] | [
"9\n",
"20\n"
] | In the first example the following positions are good:
1. the (1, 1) cell and right direction; 1. the (1, 1) cell and down direction; 1. the (1, 3) cell and left direction; 1. the (1, 3) cell and down direction; 1. the (1, 4) cell and left direction; 1. the (2, 2) cell and left direction; 1. the (2, 2) cell and up direction; 1. the (2, 2) and right direction; 1. the (2, 4) cell and left direction.
Therefore, there are 9 good positions in this example. | 1,000 | [
{
"input": "2 4\n0 1 0 0\n1 0 1 0",
"output": "9"
},
{
"input": "4 4\n0 0 0 0\n1 0 0 1\n0 1 1 0\n0 1 0 0",
"output": "20"
},
{
"input": "1 5\n1 1 0 0 0",
"output": "3"
},
{
"input": "2 10\n0 0 0 0 0 0 0 1 0 0\n1 0 0 0 0 0 0 0 0 0",
"output": "20"
},
{
"input": "3 ... | 1,479,636,225 | 3,525 | Python 3 | TIME_LIMIT_EXCEEDED | PRETESTS | 6 | 1,000 | 5,734,400 | n, m = map(int, input().split())
A = []
ans = 0
B = [0 for i in range(m)]
for i in range(n):
line = list(map(int, input().split()))
res = 0
for j in range(m):
if line[j] == 1:
res = 1
B[j] = 1
if line[j] == 0 and res == 1:
ans += 1
if line[j] == 0 and B[j] == 1:
ans += 1
res = 0
for j in range(m - 1, -1, -1):
if line[j] == 1:
res = 1
if line[j] == 0 and res == 1:
ans += 1
A.append(line)
B = [0 for i in range(m)]
for i in range(n - 1, -1, -1):
line = A[i]
for j in range(m):
if line[j] == 1:
B[j] = 1
if line[j] == 0 and B[j] == 1:
ans += 1
print(ans) | Title: Spotlights
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Theater stage is a rectangular field of size *n*<=×<=*m*. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.
A position is good if two conditions hold:
- there is no actor in the cell the spotlight is placed to; - there is at least one actor in the direction the spotlight projects.
Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.
Input Specification:
The first line contains two positive integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and the number of columns in the plan.
The next *n* lines contain *m* integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.
Output Specification:
Print one integer — the number of good positions for placing the spotlight.
Demo Input:
['2 4\n0 1 0 0\n1 0 1 0\n', '4 4\n0 0 0 0\n1 0 0 1\n0 1 1 0\n0 1 0 0\n']
Demo Output:
['9\n', '20\n']
Note:
In the first example the following positions are good:
1. the (1, 1) cell and right direction; 1. the (1, 1) cell and down direction; 1. the (1, 3) cell and left direction; 1. the (1, 3) cell and down direction; 1. the (1, 4) cell and left direction; 1. the (2, 2) cell and left direction; 1. the (2, 2) cell and up direction; 1. the (2, 2) and right direction; 1. the (2, 4) cell and left direction.
Therefore, there are 9 good positions in this example. | ```python
n, m = map(int, input().split())
A = []
ans = 0
B = [0 for i in range(m)]
for i in range(n):
line = list(map(int, input().split()))
res = 0
for j in range(m):
if line[j] == 1:
res = 1
B[j] = 1
if line[j] == 0 and res == 1:
ans += 1
if line[j] == 0 and B[j] == 1:
ans += 1
res = 0
for j in range(m - 1, -1, -1):
if line[j] == 1:
res = 1
if line[j] == 0 and res == 1:
ans += 1
A.append(line)
B = [0 for i in range(m)]
for i in range(n - 1, -1, -1):
line = A[i]
for j in range(m):
if line[j] == 1:
B[j] = 1
if line[j] == 0 and B[j] == 1:
ans += 1
print(ans)
``` | 0 | |
765 | B | Code obfuscation | PROGRAMMING | 1,100 | [
"greedy",
"implementation",
"strings"
] | null | null | Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol *a*, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with *b*, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation. | In the only line of input there is a string *S* of lowercase English letters (1<=≤<=|*S*|<=≤<=500) — the identifiers of a program with removed whitespace characters. | If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO". | [
"abacaba\n",
"jinotega\n"
] | [
"YES\n",
"NO\n"
] | In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
- replace all occurences of number with a, the result would be "a string a character a string a",- replace all occurences of string with b, the result would be "a b a character a b a",- replace all occurences of character with c, the result would be "a b a c a b a",- all identifiers have been replaced, thus the obfuscation is finished. | 1,000 | [
{
"input": "abacaba",
"output": "YES"
},
{
"input": "jinotega",
"output": "NO"
},
{
"input": "aaaaaaaaaaa",
"output": "YES"
},
{
"input": "aba",
"output": "YES"
},
{
"input": "bab",
"output": "NO"
},
{
"input": "a",
"output": "YES"
},
{
"in... | 1,611,752,338 | 2,147,483,647 | PyPy 3 | OK | TESTS | 59 | 156 | 2,355,200 | import string
obf = [x for x in input()]
obf = [x for i, x in enumerate(obf) if x not in obf[:i]]
n = len(obf)
letters = list(string.ascii_lowercase)
letters = letters[:n]
if obf == letters:
print('Yes')
else:
print('No')
| Title: Code obfuscation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol *a*, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with *b*, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input Specification:
In the only line of input there is a string *S* of lowercase English letters (1<=≤<=|*S*|<=≤<=500) — the identifiers of a program with removed whitespace characters.
Output Specification:
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Demo Input:
['abacaba\n', 'jinotega\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
- replace all occurences of number with a, the result would be "a string a character a string a",- replace all occurences of string with b, the result would be "a b a character a b a",- replace all occurences of character with c, the result would be "a b a c a b a",- all identifiers have been replaced, thus the obfuscation is finished. | ```python
import string
obf = [x for x in input()]
obf = [x for i, x in enumerate(obf) if x not in obf[:i]]
n = len(obf)
letters = list(string.ascii_lowercase)
letters = letters[:n]
if obf == letters:
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,690,500,517 | 2,147,483,647 | Python 3 | OK | TESTS | 20 | 46 | 0 | n=int(input())
x=1
l=[]
while x!=n+1:
w=input("")
l.append(w)
x+=1
y=0
m=[]
for y in range (n):
v=l[y]
p=len(v)-2
if len(v)>10:
a=v[0]+str(p)+v[len(v)-1]
m.append(a)
else:
m.append(v)
p=0
while p!=len(m):
print(m[p])
p+=1
| 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())
x=1
l=[]
while x!=n+1:
w=input("")
l.append(w)
x+=1
y=0
m=[]
for y in range (n):
v=l[y]
p=len(v)-2
if len(v)>10:
a=v[0]+str(p)+v[len(v)-1]
m.append(a)
else:
m.append(v)
p=0
while p!=len(m):
print(m[p])
p+=1
``` | 3.977 |
300 | B | Coach | PROGRAMMING | 1,500 | [
"brute force",
"dfs and similar",
"graphs"
] | null | null | A programming coach has *n* students to teach. We know that *n* is divisible by 3. Let's assume that all students are numbered from 1 to *n*, inclusive.
Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the *i*-th student wants to be on the same team with the *j*-th one, then the *j*-th student wants to be on the same team with the *i*-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the *i*-th student wants to be on the same team with the *j*-th, then the *i*-th and the *j*-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.
Help the coach and divide the teams the way he wants. | The first line of the input contains integers *n* and *m* (3<=≤<=*n*<=≤<=48, . Then follow *m* lines, each contains a pair of integers *a**i*,<=*b**i* (1<=≤<=*a**i*<=<<=*b**i*<=≤<=*n*) — the pair *a**i*,<=*b**i* means that students with numbers *a**i* and *b**i* want to be on the same team.
It is guaranteed that *n* is divisible by 3. It is guaranteed that each pair *a**i*,<=*b**i* occurs in the input at most once. | If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers *x**i*, *y**i*, *z**i* (1<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=*n*) — the *i*-th team.
If there are multiple answers, you are allowed to print any of them. | [
"3 0\n",
"6 4\n1 2\n2 3\n3 4\n5 6\n",
"3 3\n1 2\n2 3\n1 3\n"
] | [
"3 2 1 \n",
"-1\n",
"3 2 1 \n"
] | none | 1,000 | [
{
"input": "3 0",
"output": "3 2 1 "
},
{
"input": "6 4\n1 2\n2 3\n3 4\n5 6",
"output": "-1"
},
{
"input": "3 3\n1 2\n2 3\n1 3",
"output": "3 2 1 "
},
{
"input": "6 3\n1 2\n3 4\n5 6",
"output": "-1"
},
{
"input": "15 9\n1 4\n1 6\n2 7\n2 11\n4 6\n5 12\n7 11\n9 14\n... | 1,598,850,955 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 4 | 278 | 20,172,800 | n, m = map(int, input().split())
ans = []
temp = set()
if m == 0:
for x in range(n // 3):
print(n, n - 1, n - 2)
n -= 3
else:
for x in range(m):
z, y = map(int, input().split())
if len(temp) < 3:
temp.add(z)
temp.add(y)
else:
if z not in temp or y not in temp:
print(-1)
exit()
else:
ans.append(temp)
temp = set()
for x in ans:
print(*x)
| Title: Coach
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A programming coach has *n* students to teach. We know that *n* is divisible by 3. Let's assume that all students are numbered from 1 to *n*, inclusive.
Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the *i*-th student wants to be on the same team with the *j*-th one, then the *j*-th student wants to be on the same team with the *i*-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the *i*-th student wants to be on the same team with the *j*-th, then the *i*-th and the *j*-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.
Help the coach and divide the teams the way he wants.
Input Specification:
The first line of the input contains integers *n* and *m* (3<=≤<=*n*<=≤<=48, . Then follow *m* lines, each contains a pair of integers *a**i*,<=*b**i* (1<=≤<=*a**i*<=<<=*b**i*<=≤<=*n*) — the pair *a**i*,<=*b**i* means that students with numbers *a**i* and *b**i* want to be on the same team.
It is guaranteed that *n* is divisible by 3. It is guaranteed that each pair *a**i*,<=*b**i* occurs in the input at most once.
Output Specification:
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers *x**i*, *y**i*, *z**i* (1<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=*n*) — the *i*-th team.
If there are multiple answers, you are allowed to print any of them.
Demo Input:
['3 0\n', '6 4\n1 2\n2 3\n3 4\n5 6\n', '3 3\n1 2\n2 3\n1 3\n']
Demo Output:
['3 2 1 \n', '-1\n', '3 2 1 \n']
Note:
none | ```python
n, m = map(int, input().split())
ans = []
temp = set()
if m == 0:
for x in range(n // 3):
print(n, n - 1, n - 2)
n -= 3
else:
for x in range(m):
z, y = map(int, input().split())
if len(temp) < 3:
temp.add(z)
temp.add(y)
else:
if z not in temp or y not in temp:
print(-1)
exit()
else:
ans.append(temp)
temp = set()
for x in ans:
print(*x)
``` | 0 | |
1,009 | B | Minimum Ternary String | PROGRAMMING | 1,400 | [
"greedy",
"implementation"
] | null | null | You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
- "010210" $\rightarrow$ "100210"; - "010210" $\rightarrow$ "001210"; - "010210" $\rightarrow$ "010120"; - "010210" $\rightarrow$ "010201".
Note than you cannot swap "02" $\rightarrow$ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String $a$ is lexicographically less than string $b$ (if strings $a$ and $b$ have the same length) if there exists some position $i$ ($1 \le i \le |a|$, where $|s|$ is the length of the string $s$) such that for every $j < i$ holds $a_j = b_j$, and $a_i < b_i$. | The first line of the input contains the string $s$ consisting only of characters '0', '1' and '2', its length is between $1$ and $10^5$ (inclusive). | Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero). | [
"100210\n",
"11222121\n",
"20\n"
] | [
"001120\n",
"11112222\n",
"20\n"
] | none | 0 | [
{
"input": "100210",
"output": "001120"
},
{
"input": "11222121",
"output": "11112222"
},
{
"input": "20",
"output": "20"
},
{
"input": "1002",
"output": "0012"
},
{
"input": "10",
"output": "01"
},
{
"input": "000021",
"output": "000012"
},
{
... | 1,531,780,820 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 77 | 0 | word = input()
count_ones = 0
cur_word = ''
for c in word:
if int(c)==1:
count_ones += 1
if int(c)!=1:
cur_word = cur_word + c
res = ''
found = 0
for c in cur_word:
if c==2 and found==0:
found = 1
for i in range(count_ones):
res += '1'
else:
res += c
if found==0:
for i in range(count_ones):
res += '1'
print(res)
| Title: Minimum Ternary String
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
- "010210" $\rightarrow$ "100210"; - "010210" $\rightarrow$ "001210"; - "010210" $\rightarrow$ "010120"; - "010210" $\rightarrow$ "010201".
Note than you cannot swap "02" $\rightarrow$ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String $a$ is lexicographically less than string $b$ (if strings $a$ and $b$ have the same length) if there exists some position $i$ ($1 \le i \le |a|$, where $|s|$ is the length of the string $s$) such that for every $j < i$ holds $a_j = b_j$, and $a_i < b_i$.
Input Specification:
The first line of the input contains the string $s$ consisting only of characters '0', '1' and '2', its length is between $1$ and $10^5$ (inclusive).
Output Specification:
Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Demo Input:
['100210\n', '11222121\n', '20\n']
Demo Output:
['001120\n', '11112222\n', '20\n']
Note:
none | ```python
word = input()
count_ones = 0
cur_word = ''
for c in word:
if int(c)==1:
count_ones += 1
if int(c)!=1:
cur_word = cur_word + c
res = ''
found = 0
for c in cur_word:
if c==2 and found==0:
found = 1
for i in range(count_ones):
res += '1'
else:
res += c
if found==0:
for i in range(count_ones):
res += '1'
print(res)
``` | 0 | |
227 | B | Effective Approach | PROGRAMMING | 1,100 | [
"implementation"
] | null | null | Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.
According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.
Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to *n*) and ending with the *n*-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the *n*-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.
To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to *n*, and generated *m* queries of the form: find element with value *b**i* in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.
But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute. | The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements in the array. The second line contains *n* distinct space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — the elements of array.
The third line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of queries. The last line contains *m* space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=*n*) — the search queries. Note that the queries can repeat. | Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. | [
"2\n1 2\n1\n1\n",
"2\n2 1\n1\n1\n",
"3\n3 1 2\n3\n1 2 3\n"
] | [
"1 2\n",
"2 1\n",
"6 6\n"
] | In the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).
In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element). | 1,000 | [
{
"input": "2\n1 2\n1\n1",
"output": "1 2"
},
{
"input": "2\n2 1\n1\n1",
"output": "2 1"
},
{
"input": "3\n3 1 2\n3\n1 2 3",
"output": "6 6"
},
{
"input": "9\n2 9 3 1 6 4 7 8 5\n9\n5 1 5 2 8 4 4 4 5",
"output": "58 32"
},
{
"input": "10\n3 10 9 2 7 6 5 8 4 1\n1\n4... | 1,664,063,741 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 5 | 2,000 | 6,656,000 | n=int(input())
s=list(map(int,input().split()))
m=int(input())
mm=list(map(int,input().split()))
s2=s.copy()
s2.reverse()
v=0
p=0
for i in mm:
v+=s.index(i)+1
p+=s2.index(i)+1
print(v,p) | Title: Effective Approach
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.
According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.
Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to *n*) and ending with the *n*-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the *n*-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.
To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to *n*, and generated *m* queries of the form: find element with value *b**i* in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.
But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements in the array. The second line contains *n* distinct space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — the elements of array.
The third line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of queries. The last line contains *m* space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=*n*) — the search queries. Note that the queries can repeat.
Output Specification:
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Demo Input:
['2\n1 2\n1\n1\n', '2\n2 1\n1\n1\n', '3\n3 1 2\n3\n1 2 3\n']
Demo Output:
['1 2\n', '2 1\n', '6 6\n']
Note:
In the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).
In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element). | ```python
n=int(input())
s=list(map(int,input().split()))
m=int(input())
mm=list(map(int,input().split()))
s2=s.copy()
s2.reverse()
v=0
p=0
for i in mm:
v+=s.index(i)+1
p+=s2.index(i)+1
print(v,p)
``` | 0 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are *n* members, numbered 1 through *n*. *m* pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes. | The first line of the input contain two integers *n* and *m* (3<=≤<=*n*<=≤<=150<=000, ) — the number of members and the number of pairs of members that are friends.
The *i*-th of the next *m* lines contains two distinct integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*). Members *a**i* and *b**i* are friends with each other. No pair of members will appear more than once in the input. | If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes). | [
"4 3\n1 3\n3 4\n1 4\n",
"4 4\n3 1\n2 3\n3 4\n1 2\n",
"10 4\n4 3\n5 10\n8 9\n1 2\n",
"3 2\n1 2\n2 3\n"
] | [
"YES\n",
"NO\n",
"YES\n",
"NO\n"
] | The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not. | 0 | [
{
"input": "4 3\n1 3\n3 4\n1 4",
"output": "YES"
},
{
"input": "4 4\n3 1\n2 3\n3 4\n1 2",
"output": "NO"
},
{
"input": "10 4\n4 3\n5 10\n8 9\n1 2",
"output": "YES"
},
{
"input": "3 2\n1 2\n2 3",
"output": "NO"
},
{
"input": "3 0",
"output": "YES"
},
{
... | 1,694,384,729 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 5 | 31 | 0 | def dfs(ver, par, amigos, visitados):
visitados[ver] = True
for vecino in amigos[ver]:
if not visitados[vecino]:
dfs(vecino, par, amigos, visitados)
else:
if par != vecino:
return False
return True
def es_red_racional(n, m, relaciones):
amigos = [[] for _ in range(n)]
for a, b in relaciones:
amigos[a - 1].append(b - 1)
amigos[b - 1].append(a - 1)
visitados = [False] * n
for i in range(n):
if not visitados[i]:
if not dfs(i, -1, amigos, visitados):
return "NO"
return "YES"
# Lectura de entrada
n, m = map(int, input().split())
relaciones = []
for _ in range(m):
a, b = map(int, input().split())
relaciones.append((a, b))
# Verificación y salida
resultado = es_red_racional(n, m, relaciones)
print(resultado)
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are *n* members, numbered 1 through *n*. *m* pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input Specification:
The first line of the input contain two integers *n* and *m* (3<=≤<=*n*<=≤<=150<=000, ) — the number of members and the number of pairs of members that are friends.
The *i*-th of the next *m* lines contains two distinct integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*). Members *a**i* and *b**i* are friends with each other. No pair of members will appear more than once in the input.
Output Specification:
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Demo Input:
['4 3\n1 3\n3 4\n1 4\n', '4 4\n3 1\n2 3\n3 4\n1 2\n', '10 4\n4 3\n5 10\n8 9\n1 2\n', '3 2\n1 2\n2 3\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n', 'NO\n']
Note:
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not. | ```python
def dfs(ver, par, amigos, visitados):
visitados[ver] = True
for vecino in amigos[ver]:
if not visitados[vecino]:
dfs(vecino, par, amigos, visitados)
else:
if par != vecino:
return False
return True
def es_red_racional(n, m, relaciones):
amigos = [[] for _ in range(n)]
for a, b in relaciones:
amigos[a - 1].append(b - 1)
amigos[b - 1].append(a - 1)
visitados = [False] * n
for i in range(n):
if not visitados[i]:
if not dfs(i, -1, amigos, visitados):
return "NO"
return "YES"
# Lectura de entrada
n, m = map(int, input().split())
relaciones = []
for _ in range(m):
a, b = map(int, input().split())
relaciones.append((a, b))
# Verificación y salida
resultado = es_red_racional(n, m, relaciones)
print(resultado)
``` | 0 | |
522 | D | Closest Equals | PROGRAMMING | 2,000 | [
"*special",
"data structures"
] | null | null | You are given sequence *a*1,<=*a*2,<=...,<=*a**n* and *m* queries *l**j*,<=*r**j* (1<=≤<=*l**j*<=≤<=*r**j*<=≤<=*n*). For each query you need to print the minimum distance between such pair of elements *a**x* and *a**y* (*x*<=≠<=*y*), that:
- both indexes of the elements lie within range [*l**j*,<=*r**j*], that is, *l**j*<=≤<=*x*,<=*y*<=≤<=*r**j*; - the values of the elements are equal, that is *a**x*<==<=*a**y*.
The text above understands distance as |*x*<=-<=*y*|. | The first line of the input contains a pair of integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=5·105) — the length of the sequence and the number of queries, correspondingly.
The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≤<=*a**i*<=≤<=109).
Next *m* lines contain the queries, one per line. Each query is given by a pair of numbers *l**j*,<=*r**j* (1<=≤<=*l**j*<=≤<=*r**j*<=≤<=*n*) — the indexes of the query range limits. | Print *m* integers — the answers to each query. If there is no valid match for some query, please print -1 as an answer to this query. | [
"5 3\n1 1 2 3 2\n1 5\n2 4\n3 5\n",
"6 5\n1 2 1 3 2 3\n4 6\n1 3\n2 5\n2 4\n1 6\n"
] | [
"1\n-1\n2\n",
"2\n2\n3\n-1\n2\n"
] | none | 2,000 | [
{
"input": "5 3\n1 1 2 3 2\n1 5\n2 4\n3 5",
"output": "1\n-1\n2"
},
{
"input": "6 5\n1 2 1 3 2 3\n4 6\n1 3\n2 5\n2 4\n1 6",
"output": "2\n2\n3\n-1\n2"
},
{
"input": "10 6\n2 2 1 5 6 4 9 8 5 4\n1 2\n1 10\n2 10\n2 9\n5 5\n2 8",
"output": "1\n1\n4\n5\n-1\n-1"
},
{
"input": "1 1\... | 1,630,624,811 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 2 | 108 | 20,172,800 | def find1(X, l, r):
m = len(X)
if r < X[0]:
return float('inf')
if X[-1] < l:
return float('inf')
if l <= X[0]:
left_point = 0
else:
s = 0
e = m-1
while s+1 < e:
mid = (s+e)//2
if X[mid] > l:
s, e = mid, e
else:
s, e = s, mid
left_point = e
if X[-1] <= r:
right_point = m-1
else:
s = 0
e = m-1
while s+1 < e:
mid = (s+e)//2
if X[mid] <= r:
s, e = mid, e
else:
s, e = s, mid
right_point = s
if left_point==right_point:
return float('inf')
return X[right_point]-X[left_point]
def process(A, Q):
d = {}
n = len(A)
answer = []
for i in range(n):
x = A[i]
if x not in d:
d[x] = []
d[x].append(i)
for l, r in Q:
my_min = float('inf')
for x in d:
my_min = min(my_min, find1(d[x], l-1, r-1))
if my_min==float('inf'):
answer.append(-1)
else:
answer.append(my_min)
return answer
n, m = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
Q = []
for i in range(m):
l, r = [int(x) for x in input().split()]
Q.append([l, r])
answer = process(A, Q)
for x in answer:
print(x) | Title: Closest Equals
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given sequence *a*1,<=*a*2,<=...,<=*a**n* and *m* queries *l**j*,<=*r**j* (1<=≤<=*l**j*<=≤<=*r**j*<=≤<=*n*). For each query you need to print the minimum distance between such pair of elements *a**x* and *a**y* (*x*<=≠<=*y*), that:
- both indexes of the elements lie within range [*l**j*,<=*r**j*], that is, *l**j*<=≤<=*x*,<=*y*<=≤<=*r**j*; - the values of the elements are equal, that is *a**x*<==<=*a**y*.
The text above understands distance as |*x*<=-<=*y*|.
Input Specification:
The first line of the input contains a pair of integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=5·105) — the length of the sequence and the number of queries, correspondingly.
The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≤<=*a**i*<=≤<=109).
Next *m* lines contain the queries, one per line. Each query is given by a pair of numbers *l**j*,<=*r**j* (1<=≤<=*l**j*<=≤<=*r**j*<=≤<=*n*) — the indexes of the query range limits.
Output Specification:
Print *m* integers — the answers to each query. If there is no valid match for some query, please print -1 as an answer to this query.
Demo Input:
['5 3\n1 1 2 3 2\n1 5\n2 4\n3 5\n', '6 5\n1 2 1 3 2 3\n4 6\n1 3\n2 5\n2 4\n1 6\n']
Demo Output:
['1\n-1\n2\n', '2\n2\n3\n-1\n2\n']
Note:
none | ```python
def find1(X, l, r):
m = len(X)
if r < X[0]:
return float('inf')
if X[-1] < l:
return float('inf')
if l <= X[0]:
left_point = 0
else:
s = 0
e = m-1
while s+1 < e:
mid = (s+e)//2
if X[mid] > l:
s, e = mid, e
else:
s, e = s, mid
left_point = e
if X[-1] <= r:
right_point = m-1
else:
s = 0
e = m-1
while s+1 < e:
mid = (s+e)//2
if X[mid] <= r:
s, e = mid, e
else:
s, e = s, mid
right_point = s
if left_point==right_point:
return float('inf')
return X[right_point]-X[left_point]
def process(A, Q):
d = {}
n = len(A)
answer = []
for i in range(n):
x = A[i]
if x not in d:
d[x] = []
d[x].append(i)
for l, r in Q:
my_min = float('inf')
for x in d:
my_min = min(my_min, find1(d[x], l-1, r-1))
if my_min==float('inf'):
answer.append(-1)
else:
answer.append(my_min)
return answer
n, m = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
Q = []
for i in range(m):
l, r = [int(x) for x in input().split()]
Q.append([l, r])
answer = process(A, Q)
for x in answer:
print(x)
``` | 0 | |
920 | E | Connected Components? | PROGRAMMING | 2,100 | [
"data structures",
"dfs and similar",
"dsu",
"graphs"
] | null | null | You are given an undirected graph consisting of *n* vertices and edges. Instead of giving you the edges that exist in the graph, we give you *m* unordered pairs (*x*,<=*y*) such that there is no edge between *x* and *y*, and if some pair of vertices is not listed in the input, then there is an edge between these vertices.
You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices *X* such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to *X* violates this rule. | The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=200000, ).
Then *m* lines follow, each containing a pair of integers *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*, *x*<=≠<=*y*) denoting that there is no edge between *x* and *y*. Each pair is listed at most once; (*x*,<=*y*) and (*y*,<=*x*) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. | Firstly print *k* — the number of connected components in this graph.
Then print *k* integers — the sizes of components. You should output these integers in non-descending order. | [
"5 5\n1 2\n3 4\n3 2\n4 2\n2 5\n"
] | [
"2\n1 4 "
] | none | 0 | [
{
"input": "5 5\n1 2\n3 4\n3 2\n4 2\n2 5",
"output": "2\n1 4 "
},
{
"input": "8 15\n2 1\n4 5\n2 4\n3 4\n2 5\n3 5\n2 6\n3 6\n5 6\n4 6\n2 7\n3 8\n2 8\n3 7\n6 7",
"output": "1\n8 "
},
{
"input": "12 58\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 10\n1 11\n1 12\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n... | 1,618,877,066 | 2,147,483,647 | PyPy 3 | MEMORY_LIMIT_EXCEEDED | TESTS | 8 | 2,292 | 268,390,400 | import sys
input = sys.stdin.buffer.readline
n,m = map(int,input().split())
adj = [set() for i in range(n+1)]
for i in range(m):
x,y = map(int,input().split())
adj[x].add(y)
adj[y].add(x)
unpaired = set([i for i in range(1,n+1)])
comps = []
vis = [0]*(n+1)
for i in range(1,n+1):
if not vis[i]:
comps.append(0)
s = [i]
while s:
c = s[-1]
if not vis[c]:
comps[-1] += 1
vis[c] = 1
unpaired.remove(c)
for ne in unpaired:
if ne not in adj[c]:
s.append(ne)
else:
s.pop()
print(len(comps))
print(*sorted(comps)) | Title: Connected Components?
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an undirected graph consisting of *n* vertices and edges. Instead of giving you the edges that exist in the graph, we give you *m* unordered pairs (*x*,<=*y*) such that there is no edge between *x* and *y*, and if some pair of vertices is not listed in the input, then there is an edge between these vertices.
You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices *X* such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to *X* violates this rule.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=200000, ).
Then *m* lines follow, each containing a pair of integers *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*, *x*<=≠<=*y*) denoting that there is no edge between *x* and *y*. Each pair is listed at most once; (*x*,<=*y*) and (*y*,<=*x*) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices.
Output Specification:
Firstly print *k* — the number of connected components in this graph.
Then print *k* integers — the sizes of components. You should output these integers in non-descending order.
Demo Input:
['5 5\n1 2\n3 4\n3 2\n4 2\n2 5\n']
Demo Output:
['2\n1 4 ']
Note:
none | ```python
import sys
input = sys.stdin.buffer.readline
n,m = map(int,input().split())
adj = [set() for i in range(n+1)]
for i in range(m):
x,y = map(int,input().split())
adj[x].add(y)
adj[y].add(x)
unpaired = set([i for i in range(1,n+1)])
comps = []
vis = [0]*(n+1)
for i in range(1,n+1):
if not vis[i]:
comps.append(0)
s = [i]
while s:
c = s[-1]
if not vis[c]:
comps[-1] += 1
vis[c] = 1
unpaired.remove(c)
for ne in unpaired:
if ne not in adj[c]:
s.append(ne)
else:
s.pop()
print(len(comps))
print(*sorted(comps))
``` | 0 | |
678 | C | Joty and Chocolate | PROGRAMMING | 1,600 | [
"implementation",
"math",
"number theory"
] | null | null | Little Joty has got a task to do. She has a line of *n* tiles indexed from 1 to *n*. She has to paint them in a strange pattern.
An unpainted tile should be painted Red if it's index is divisible by *a* and an unpainted tile should be painted Blue if it's index is divisible by *b*. So the tile with the number divisible by *a* and *b* can be either painted Red or Blue.
After her painting is done, she will get *p* chocolates for each tile that is painted Red and *q* chocolates for each tile that is painted Blue.
Note that she can paint tiles in any order she wants.
Given the required information, find the maximum number of chocolates Joty can get. | The only line contains five integers *n*, *a*, *b*, *p* and *q* (1<=≤<=*n*,<=*a*,<=*b*,<=*p*,<=*q*<=≤<=109). | Print the only integer *s* — the maximum number of chocolates Joty can get.
Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type. | [
"5 2 3 12 15\n",
"20 2 3 3 5\n"
] | [
"39\n",
"51\n"
] | none | 0 | [
{
"input": "5 2 3 12 15",
"output": "39"
},
{
"input": "20 2 3 3 5",
"output": "51"
},
{
"input": "1 1 1 1 1",
"output": "1"
},
{
"input": "1 2 2 2 2",
"output": "0"
},
{
"input": "2 1 3 3 3",
"output": "6"
},
{
"input": "3 1 1 3 3",
"output": "9"
... | 1,630,367,829 | 2,147,483,647 | PyPy 3 | OK | TESTS | 185 | 109 | 20,172,800 | from sys import stdin, stdout
def read():
return stdin.readline().rstrip()
def read_int():
return int(read())
def read_ints():
return list(map(int, read().split()))
def gcd(x,y):
while y>0:
x,y=y,x%y
return x
def solve():
n,a,b,p,q=read_ints()
print((n//a)*p + (n//b)*q - (n//(a*b//gcd(a,b)))*min(p,q))
solve()
| Title: Joty and Chocolate
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Joty has got a task to do. She has a line of *n* tiles indexed from 1 to *n*. She has to paint them in a strange pattern.
An unpainted tile should be painted Red if it's index is divisible by *a* and an unpainted tile should be painted Blue if it's index is divisible by *b*. So the tile with the number divisible by *a* and *b* can be either painted Red or Blue.
After her painting is done, she will get *p* chocolates for each tile that is painted Red and *q* chocolates for each tile that is painted Blue.
Note that she can paint tiles in any order she wants.
Given the required information, find the maximum number of chocolates Joty can get.
Input Specification:
The only line contains five integers *n*, *a*, *b*, *p* and *q* (1<=≤<=*n*,<=*a*,<=*b*,<=*p*,<=*q*<=≤<=109).
Output Specification:
Print the only integer *s* — the maximum number of chocolates Joty can get.
Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.
Demo Input:
['5 2 3 12 15\n', '20 2 3 3 5\n']
Demo Output:
['39\n', '51\n']
Note:
none | ```python
from sys import stdin, stdout
def read():
return stdin.readline().rstrip()
def read_int():
return int(read())
def read_ints():
return list(map(int, read().split()))
def gcd(x,y):
while y>0:
x,y=y,x%y
return x
def solve():
n,a,b,p,q=read_ints()
print((n//a)*p + (n//b)*q - (n//(a*b//gcd(a,b)))*min(p,q))
solve()
``` | 3 | |
514 | A | Chewbaсca and Number | PROGRAMMING | 1,200 | [
"greedy",
"implementation"
] | null | null | Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*.
Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero. | The first line contains a single integer *x* (1<=≤<=*x*<=≤<=1018) — the number that Luke Skywalker gave to Chewbacca. | Print the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes. | [
"27\n",
"4545\n"
] | [
"22\n",
"4444\n"
] | none | 500 | [
{
"input": "27",
"output": "22"
},
{
"input": "4545",
"output": "4444"
},
{
"input": "1",
"output": "1"
},
{
"input": "9",
"output": "9"
},
{
"input": "8772",
"output": "1222"
},
{
"input": "81",
"output": "11"
},
{
"input": "71723447",
... | 1,683,287,065 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 7 | 77 | 0 | import math
n=int(input())
t=n
num=0
i=0
while t:
temp=t%10
temp=min(temp, 9-temp)
num+=((temp)*pow(10, i))
i+=1
t=int(t/10)
if num==0: print(n)
else: print(num)
| Title: Chewbaсca and Number
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*.
Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.
Input Specification:
The first line contains a single integer *x* (1<=≤<=*x*<=≤<=1018) — the number that Luke Skywalker gave to Chewbacca.
Output Specification:
Print the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes.
Demo Input:
['27\n', '4545\n']
Demo Output:
['22\n', '4444\n']
Note:
none | ```python
import math
n=int(input())
t=n
num=0
i=0
while t:
temp=t%10
temp=min(temp, 9-temp)
num+=((temp)*pow(10, i))
i+=1
t=int(t/10)
if num==0: print(n)
else: print(num)
``` | 0 | |
237 | A | Free Cash | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | Valera runs a 24/7 fast food cafe. He magically learned that next day *n* people will visit his cafe. For each person we know the arrival time: the *i*-th person comes exactly at *h**i* hours *m**i* minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.
Valera is very greedy, so he wants to serve all *n* customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe.
Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105), that is the number of cafe visitors.
Each of the following *n* lines has two space-separated integers *h**i* and *m**i* (0<=≤<=*h**i*<=≤<=23; 0<=≤<=*m**i*<=≤<=59), representing the time when the *i*-th person comes into the cafe.
Note that the time is given in the chronological order. All time is given within one 24-hour period. | Print a single integer — the minimum number of cashes, needed to serve all clients next day. | [
"4\n8 0\n8 10\n8 10\n8 45\n",
"3\n0 12\n10 11\n22 22\n"
] | [
"2\n",
"1\n"
] | In the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.
In the second sample all visitors will come in different times, so it will be enough one cash. | 500 | [
{
"input": "4\n8 0\n8 10\n8 10\n8 45",
"output": "2"
},
{
"input": "3\n0 12\n10 11\n22 22",
"output": "1"
},
{
"input": "5\n12 8\n15 27\n15 27\n16 2\n19 52",
"output": "2"
},
{
"input": "7\n5 6\n7 34\n7 34\n7 34\n12 29\n15 19\n20 23",
"output": "3"
},
{
"input": "... | 1,674,650,753 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 5 | 62 | 0 | s=[[],[]]
for _ in range(int(input())):
a,b=map(int,input().split())
if b in s[0]: s[1][0]+=1
else: s[1].append(1)
s[0].append(b)
print(max(s[1])) | Title: Free Cash
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Valera runs a 24/7 fast food cafe. He magically learned that next day *n* people will visit his cafe. For each person we know the arrival time: the *i*-th person comes exactly at *h**i* hours *m**i* minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.
Valera is very greedy, so he wants to serve all *n* customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe.
Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105), that is the number of cafe visitors.
Each of the following *n* lines has two space-separated integers *h**i* and *m**i* (0<=≤<=*h**i*<=≤<=23; 0<=≤<=*m**i*<=≤<=59), representing the time when the *i*-th person comes into the cafe.
Note that the time is given in the chronological order. All time is given within one 24-hour period.
Output Specification:
Print a single integer — the minimum number of cashes, needed to serve all clients next day.
Demo Input:
['4\n8 0\n8 10\n8 10\n8 45\n', '3\n0 12\n10 11\n22 22\n']
Demo Output:
['2\n', '1\n']
Note:
In the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.
In the second sample all visitors will come in different times, so it will be enough one cash. | ```python
s=[[],[]]
for _ in range(int(input())):
a,b=map(int,input().split())
if b in s[0]: s[1][0]+=1
else: s[1].append(1)
s[0].append(b)
print(max(s[1]))
``` | 0 | |
545 | C | Woodcutters | PROGRAMMING | 1,500 | [
"dp",
"greedy"
] | null | null | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.
There are *n* trees located along the road at points with coordinates *x*1,<=*x*2,<=...,<=*x**n*. Each tree has its height *h**i*. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [*x**i*<=-<=*h**i*,<=*x**i*] or [*x**i*;*x**i*<=+<=*h**i*]. The tree that is not cut down occupies a single point with coordinate *x**i*. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of trees.
Next *n* lines contain pairs of integers *x**i*,<=*h**i* (1<=≤<=*x**i*,<=*h**i*<=≤<=109) — the coordinate and the height of the *і*-th tree.
The pairs are given in the order of ascending *x**i*. No two trees are located at the point with the same coordinate. | Print a single number — the maximum number of trees that you can cut down by the given rules. | [
"5\n1 2\n2 1\n5 10\n10 9\n19 1\n",
"5\n1 2\n2 1\n5 10\n10 9\n20 1\n"
] | [
"3\n",
"4\n"
] | In the first sample you can fell the trees like that:
- fell the 1-st tree to the left — now it occupies segment [ - 1;1] - fell the 2-nd tree to the right — now it occupies segment [2;3] - leave the 3-rd tree — it occupies point 5 - leave the 4-th tree — it occupies point 10 - fell the 5-th tree to the right — now it occupies segment [19;20]
In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | 1,750 | [
{
"input": "5\n1 2\n2 1\n5 10\n10 9\n19 1",
"output": "3"
},
{
"input": "5\n1 2\n2 1\n5 10\n10 9\n20 1",
"output": "4"
},
{
"input": "4\n10 4\n15 1\n19 3\n20 1",
"output": "4"
},
{
"input": "35\n1 7\n3 11\n6 12\n7 6\n8 5\n9 11\n15 3\n16 10\n22 2\n23 3\n25 7\n27 3\n34 5\n35 10... | 1,697,646,809 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 2 | 31 | 102,400 | e = int(input())
x = [0] * (e+1)
h = [0] * (e+1)
gp = [[0] * 5 for _ in range(e +1)]
for i in range(1, e+1):
x[i], h[i] = map(int, input().split())
if e== 1:
print(1)
exit(0)
if x[1] + h[1] < x[2]:
dp[1][2] = 1
gp[1][1] = 1
for i in range(2,e+1):
p1 =gp[i-1][0]
p2 = gp[i-1][1]
p3 =gp[i-1][2]
gp[i][0] = max(p1, p2, p3)
if x[i] - x[i-1] > h[i] + h[i-1]:
gp[i][1] =gp[i][0] + 1
elif x[i] - x[i-1] > h[i]:
gp[i][1] = 1 + max(p1, p2)
if i+1 <= e and x[i+1] - x[i] > h[i]:
gp[i][2] = 1 + gp[i][0]
if i ==e:
gp[i][2] = 1 + gp[i][0]
print(max(gp[e][2], gp[e][0], gp[e][1])) | Title: Woodcutters
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.
There are *n* trees located along the road at points with coordinates *x*1,<=*x*2,<=...,<=*x**n*. Each tree has its height *h**i*. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [*x**i*<=-<=*h**i*,<=*x**i*] or [*x**i*;*x**i*<=+<=*h**i*]. The tree that is not cut down occupies a single point with coordinate *x**i*. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of trees.
Next *n* lines contain pairs of integers *x**i*,<=*h**i* (1<=≤<=*x**i*,<=*h**i*<=≤<=109) — the coordinate and the height of the *і*-th tree.
The pairs are given in the order of ascending *x**i*. No two trees are located at the point with the same coordinate.
Output Specification:
Print a single number — the maximum number of trees that you can cut down by the given rules.
Demo Input:
['5\n1 2\n2 1\n5 10\n10 9\n19 1\n', '5\n1 2\n2 1\n5 10\n10 9\n20 1\n']
Demo Output:
['3\n', '4\n']
Note:
In the first sample you can fell the trees like that:
- fell the 1-st tree to the left — now it occupies segment [ - 1;1] - fell the 2-nd tree to the right — now it occupies segment [2;3] - leave the 3-rd tree — it occupies point 5 - leave the 4-th tree — it occupies point 10 - fell the 5-th tree to the right — now it occupies segment [19;20]
In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | ```python
e = int(input())
x = [0] * (e+1)
h = [0] * (e+1)
gp = [[0] * 5 for _ in range(e +1)]
for i in range(1, e+1):
x[i], h[i] = map(int, input().split())
if e== 1:
print(1)
exit(0)
if x[1] + h[1] < x[2]:
dp[1][2] = 1
gp[1][1] = 1
for i in range(2,e+1):
p1 =gp[i-1][0]
p2 = gp[i-1][1]
p3 =gp[i-1][2]
gp[i][0] = max(p1, p2, p3)
if x[i] - x[i-1] > h[i] + h[i-1]:
gp[i][1] =gp[i][0] + 1
elif x[i] - x[i-1] > h[i]:
gp[i][1] = 1 + max(p1, p2)
if i+1 <= e and x[i+1] - x[i] > h[i]:
gp[i][2] = 1 + gp[i][0]
if i ==e:
gp[i][2] = 1 + gp[i][0]
print(max(gp[e][2], gp[e][0], gp[e][1]))
``` | -1 | |
272 | A | Dima and Friends | PROGRAMMING | 1,000 | [
"implementation",
"math"
] | null | null | Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.
For example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place.
Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima. | The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of Dima's friends. Dima himself isn't considered to be his own friend. The second line contains *n* positive integers, not exceeding 5, representing, how many fingers the Dima's friends will show.
The numbers in the lines are separated by a single space. | In a single line print the answer to the problem. | [
"1\n1\n",
"1\n2\n",
"2\n3 5\n"
] | [
"3\n",
"2\n",
"3\n"
] | In the first sample Dima can show 1, 3 or 5 fingers. If Dima shows 3 fingers, then the counting-out will go like that: Dima, his friend, Dima, his friend.
In the second sample Dima can show 2 or 4 fingers. | 500 | [
{
"input": "1\n1",
"output": "3"
},
{
"input": "1\n2",
"output": "2"
},
{
"input": "2\n3 5",
"output": "3"
},
{
"input": "2\n3 5",
"output": "3"
},
{
"input": "1\n5",
"output": "3"
},
{
"input": "5\n4 4 3 5 1",
"output": "4"
},
{
"input": "... | 1,499,926,848 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 124 | 5,529,600 | n = int(input())
string = input()
a = sum(list(map(int, string.split())))
b = 0
for x in range(1, 6):
if (a + x) % (n + 1) != 1:
b += 1
print(b) | Title: Dima and Friends
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.
For example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place.
Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of Dima's friends. Dima himself isn't considered to be his own friend. The second line contains *n* positive integers, not exceeding 5, representing, how many fingers the Dima's friends will show.
The numbers in the lines are separated by a single space.
Output Specification:
In a single line print the answer to the problem.
Demo Input:
['1\n1\n', '1\n2\n', '2\n3 5\n']
Demo Output:
['3\n', '2\n', '3\n']
Note:
In the first sample Dima can show 1, 3 or 5 fingers. If Dima shows 3 fingers, then the counting-out will go like that: Dima, his friend, Dima, his friend.
In the second sample Dima can show 2 or 4 fingers. | ```python
n = int(input())
string = input()
a = sum(list(map(int, string.split())))
b = 0
for x in range(1, 6):
if (a + x) % (n + 1) != 1:
b += 1
print(b)
``` | 3 | |
0 | none | none | none | 0 | [
"none"
] | null | null | A factory produces thimbles in bulk. Typically, it can produce up to *a* thimbles a day. However, some of the machinery is defective, so it can currently only produce *b* thimbles each day. The factory intends to choose a *k*-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of *a* thimbles per day after the *k* days are complete.
Initially, no orders are pending. The factory receives updates of the form *d**i*, *a**i*, indicating that *a**i* new orders have been placed for the *d**i*-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.
As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day *p**i*. Help the owner answer his questions. | The first line contains five integers *n*, *k*, *a*, *b*, and *q* (1<=≤<=*k*<=≤<=*n*<=≤<=200<=000, 1<=≤<=*b*<=<<=*a*<=≤<=10 000, 1<=≤<=*q*<=≤<=200<=000) — the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively.
The next *q* lines contain the descriptions of the queries. Each query is of one of the following two forms:
- 1 *d**i* *a**i* (1<=≤<=*d**i*<=≤<=*n*, 1<=≤<=*a**i*<=≤<=10 000), representing an update of *a**i* orders on day *d**i*, or - 2 *p**i* (1<=≤<=*p**i*<=≤<=*n*<=-<=*k*<=+<=1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day *p**i*?
It's guaranteed that the input will contain at least one query of the second type. | For each query of the second type, print a line containing a single integer — the maximum number of orders that the factory can fill over all *n* days. | [
"5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3\n",
"5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2\n"
] | [
"3\n6\n4\n",
"7\n1\n"
] | Consider the first sample.
We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.
For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.
For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders. | 0 | [
{
"input": "5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3",
"output": "3\n6\n4"
},
{
"input": "5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2",
"output": "7\n1"
},
{
"input": "1 1 2 1 1\n2 1",
"output": "0"
}
] | 1,456,685,835 | 2,835 | PyPy 3 | WRONG_ANSWER | PRETESTS | 0 | 93 | 0 | n, k, a, b, q = map(int, input().split())
g1 = [0] * (n + 1)
g2 = [0] * (n + 1)
p = []
for i in range(q):
s = input().split()
if len(s) == 3:
h, d = int(s[1]), int(s[2])
g1[h] += d
g2[h] += d
else:
p.append(int(s[1]))
sum = 0
for i in range(n + 1):
sum += min(g1[i], b)
g1[i] = sum
sum = 0
for i in range(n + 1):
sum += min(g2[i], a)
g2[i] = sum
for i in range(len(p)):
sum1 = g1[p[i] - 1] - g1[0]
sum2 = g2[-1] - g2[p[i] + k - 1]
print(sum1 + sum2)
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A factory produces thimbles in bulk. Typically, it can produce up to *a* thimbles a day. However, some of the machinery is defective, so it can currently only produce *b* thimbles each day. The factory intends to choose a *k*-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of *a* thimbles per day after the *k* days are complete.
Initially, no orders are pending. The factory receives updates of the form *d**i*, *a**i*, indicating that *a**i* new orders have been placed for the *d**i*-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.
As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day *p**i*. Help the owner answer his questions.
Input Specification:
The first line contains five integers *n*, *k*, *a*, *b*, and *q* (1<=≤<=*k*<=≤<=*n*<=≤<=200<=000, 1<=≤<=*b*<=<<=*a*<=≤<=10 000, 1<=≤<=*q*<=≤<=200<=000) — the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively.
The next *q* lines contain the descriptions of the queries. Each query is of one of the following two forms:
- 1 *d**i* *a**i* (1<=≤<=*d**i*<=≤<=*n*, 1<=≤<=*a**i*<=≤<=10 000), representing an update of *a**i* orders on day *d**i*, or - 2 *p**i* (1<=≤<=*p**i*<=≤<=*n*<=-<=*k*<=+<=1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day *p**i*?
It's guaranteed that the input will contain at least one query of the second type.
Output Specification:
For each query of the second type, print a line containing a single integer — the maximum number of orders that the factory can fill over all *n* days.
Demo Input:
['5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3\n', '5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2\n']
Demo Output:
['3\n6\n4\n', '7\n1\n']
Note:
Consider the first sample.
We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.
For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.
For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders. | ```python
n, k, a, b, q = map(int, input().split())
g1 = [0] * (n + 1)
g2 = [0] * (n + 1)
p = []
for i in range(q):
s = input().split()
if len(s) == 3:
h, d = int(s[1]), int(s[2])
g1[h] += d
g2[h] += d
else:
p.append(int(s[1]))
sum = 0
for i in range(n + 1):
sum += min(g1[i], b)
g1[i] = sum
sum = 0
for i in range(n + 1):
sum += min(g2[i], a)
g2[i] = sum
for i in range(len(p)):
sum1 = g1[p[i] - 1] - g1[0]
sum2 = g2[-1] - g2[p[i] + k - 1]
print(sum1 + sum2)
``` | 0 | |
909 | B | Segments | PROGRAMMING | 1,300 | [
"constructive algorithms",
"math"
] | null | null | You are given an integer *N*. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and *N*, inclusive; there will be of them.
You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endpoints though). You can not move the segments to a different location on the coordinate axis.
Find the minimal number of layers you have to use for the given *N*. | The only input line contains a single integer *N* (1<=≤<=*N*<=≤<=100). | Output a single integer - the minimal number of layers required to draw the segments for the given *N*. | [
"2\n",
"3\n",
"4\n"
] | [
"2\n",
"4\n",
"6\n"
] | As an example, here are the segments and their optimal arrangement into layers for *N* = 4. | 1,000 | [
{
"input": "2",
"output": "2"
},
{
"input": "3",
"output": "4"
},
{
"input": "4",
"output": "6"
},
{
"input": "21",
"output": "121"
},
{
"input": "100",
"output": "2550"
},
{
"input": "1",
"output": "1"
},
{
"input": "5",
"output": "9"
... | 1,592,654,649 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 93 | 0 | for i in range(1):
n=int(input())
s=0
for i in range(1,n+1):
s=i+s
print(s)
x=s/2
if x>int(x):
print(int(x)+1)
else:
print(int(x))
| Title: Segments
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an integer *N*. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and *N*, inclusive; there will be of them.
You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endpoints though). You can not move the segments to a different location on the coordinate axis.
Find the minimal number of layers you have to use for the given *N*.
Input Specification:
The only input line contains a single integer *N* (1<=≤<=*N*<=≤<=100).
Output Specification:
Output a single integer - the minimal number of layers required to draw the segments for the given *N*.
Demo Input:
['2\n', '3\n', '4\n']
Demo Output:
['2\n', '4\n', '6\n']
Note:
As an example, here are the segments and their optimal arrangement into layers for *N* = 4. | ```python
for i in range(1):
n=int(input())
s=0
for i in range(1,n+1):
s=i+s
print(s)
x=s/2
if x>int(x):
print(int(x)+1)
else:
print(int(x))
``` | 0 | |
769 | D | k-Interesting Pairs Of Integers | PROGRAMMING | 1,700 | [
"*special",
"bitmasks",
"brute force",
"meet-in-the-middle"
] | null | null | Vasya has the sequence consisting of *n* integers. Vasya consider the pair of integers *x* and *y* k-interesting, if their binary representation differs from each other exactly in *k* bits. For example, if *k*<==<=2, the pair of integers *x*<==<=5 and *y*<==<=3 is k-interesting, because their binary representation *x*=101 and *y*=011 differs exactly in two bits.
Vasya wants to know how many pairs of indexes (*i*, *j*) are in his sequence so that *i*<=<<=*j* and the pair of integers *a**i* and *a**j* is k-interesting. Your task is to help Vasya and determine this number. | The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=105, 0<=≤<=*k*<=≤<=14) — the number of integers in Vasya's sequence and the number of bits in which integers in k-interesting pair should differ.
The second line contains the sequence *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=104), which Vasya has. | Print the number of pairs (*i*, *j*) so that *i*<=<<=*j* and the pair of integers *a**i* and *a**j* is k-interesting. | [
"4 1\n0 3 2 1\n",
"6 0\n200 100 100 100 200 200\n"
] | [
"4\n",
"6\n"
] | In the first test there are 4 k-interesting pairs:
- (1, 3), - (1, 4), - (2, 3), - (2, 4).
In the second test *k* = 0. Consequently, integers in any k-interesting pair should be equal to themselves. Thus, for the second test there are 6 k-interesting pairs:
- (1, 5), - (1, 6), - (2, 3), - (2, 4), - (3, 4), - (5, 6). | 2,000 | [
{
"input": "4 1\n0 3 2 1",
"output": "4"
},
{
"input": "6 0\n200 100 100 100 200 200",
"output": "6"
},
{
"input": "2 0\n1 1",
"output": "1"
},
{
"input": "2 0\n0 0",
"output": "1"
},
{
"input": "2 0\n10000 10000",
"output": "1"
},
{
"input": "2 0\n0 1... | 1,488,640,245 | 11,445 | Python 3 | WRONG_ANSWER | PRETESTS | 6 | 62 | 4,915,200 | def pr(a,b):
a = str(a)
b = str(b)
if len(a)>len(b):
k = len(a) - len(b)
for i in range(len(b),0):
for j in range(len(a),0):
if a-b == j-i and b[i] != a[j]:
k+=1
else:
k = len(b) - len(a)
for i in range(len(a),0):
for j in range(len(b),0):
if b-a == j-i and a[i] != b[j]:
k+=1
return k
def main():
n,m = map(int,input().split())
arr = list(map(int,input().split()))
for i in range(n):
k = 1
b = 0
while (arr[i]!=0):
b += arr[i] % 2 * k
arr[i] //= 2
k *= 10
arr[i] = b
q = 0
for i in range(n):
for j in range(i+1,n):
p = pr(arr[i],arr[j])
if p == m:
q+=1;
print(q)
main() | Title: k-Interesting Pairs Of Integers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has the sequence consisting of *n* integers. Vasya consider the pair of integers *x* and *y* k-interesting, if their binary representation differs from each other exactly in *k* bits. For example, if *k*<==<=2, the pair of integers *x*<==<=5 and *y*<==<=3 is k-interesting, because their binary representation *x*=101 and *y*=011 differs exactly in two bits.
Vasya wants to know how many pairs of indexes (*i*, *j*) are in his sequence so that *i*<=<<=*j* and the pair of integers *a**i* and *a**j* is k-interesting. Your task is to help Vasya and determine this number.
Input Specification:
The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=105, 0<=≤<=*k*<=≤<=14) — the number of integers in Vasya's sequence and the number of bits in which integers in k-interesting pair should differ.
The second line contains the sequence *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=104), which Vasya has.
Output Specification:
Print the number of pairs (*i*, *j*) so that *i*<=<<=*j* and the pair of integers *a**i* and *a**j* is k-interesting.
Demo Input:
['4 1\n0 3 2 1\n', '6 0\n200 100 100 100 200 200\n']
Demo Output:
['4\n', '6\n']
Note:
In the first test there are 4 k-interesting pairs:
- (1, 3), - (1, 4), - (2, 3), - (2, 4).
In the second test *k* = 0. Consequently, integers in any k-interesting pair should be equal to themselves. Thus, for the second test there are 6 k-interesting pairs:
- (1, 5), - (1, 6), - (2, 3), - (2, 4), - (3, 4), - (5, 6). | ```python
def pr(a,b):
a = str(a)
b = str(b)
if len(a)>len(b):
k = len(a) - len(b)
for i in range(len(b),0):
for j in range(len(a),0):
if a-b == j-i and b[i] != a[j]:
k+=1
else:
k = len(b) - len(a)
for i in range(len(a),0):
for j in range(len(b),0):
if b-a == j-i and a[i] != b[j]:
k+=1
return k
def main():
n,m = map(int,input().split())
arr = list(map(int,input().split()))
for i in range(n):
k = 1
b = 0
while (arr[i]!=0):
b += arr[i] % 2 * k
arr[i] //= 2
k *= 10
arr[i] = b
q = 0
for i in range(n):
for j in range(i+1,n):
p = pr(arr[i],arr[j])
if p == m:
q+=1;
print(q)
main()
``` | 0 | |
363 | B | Fence | PROGRAMMING | 1,100 | [
"brute force",
"dp"
] | null | null | There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights.
Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly *k* consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such *k* consecutive planks that the sum of their heights is minimal possible.
Write the program that finds the indexes of *k* consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic). | The first line of the input contains integers *n* and *k* (1<=≤<=*n*<=≤<=1.5·105,<=1<=≤<=*k*<=≤<=*n*) — the number of planks in the fence and the width of the hole for the piano. The second line contains the sequence of integers *h*1,<=*h*2,<=...,<=*h**n* (1<=≤<=*h**i*<=≤<=100), where *h**i* is the height of the *i*-th plank of the fence. | Print such integer *j* that the sum of the heights of planks *j*, *j*<=+<=1, ..., *j*<=+<=*k*<=-<=1 is the minimum possible. If there are multiple such *j*'s, print any of them. | [
"7 3\n1 2 6 1 1 7 1\n"
] | [
"3\n"
] | In the sample, your task is to find three consecutive planks with the minimum sum of heights. In the given case three planks with indexes 3, 4 and 5 have the required attribute, their total height is 8. | 1,000 | [
{
"input": "7 3\n1 2 6 1 1 7 1",
"output": "3"
},
{
"input": "1 1\n100",
"output": "1"
},
{
"input": "2 1\n10 20",
"output": "1"
},
{
"input": "10 5\n1 2 3 1 2 2 3 1 4 5",
"output": "1"
},
{
"input": "10 2\n3 1 4 1 4 6 2 1 4 6",
"output": "7"
},
{
"inp... | 1,688,494,412 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 51 | 93 | 17,612,800 | from sys import stdin, stdout
def input():
return stdin.readline().strip()
def print(string):
return stdout.write(str(string) + "\n")
def main():
n, k = map(int, input().split())
h = [int(x) for x in input().split()]
dp = [None] * n
dp[0] = sum(h[:k])
smallest_i = 0
for i in range(n-k):
dp[i+1] = dp[i] - h[i] + h[i+k]
if dp[i+1] < dp[smallest_i]:
smallest_i = i+1
print(smallest_i+1)
if __name__ == "__main__":
main()
| Title: Fence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights.
Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly *k* consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such *k* consecutive planks that the sum of their heights is minimal possible.
Write the program that finds the indexes of *k* consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).
Input Specification:
The first line of the input contains integers *n* and *k* (1<=≤<=*n*<=≤<=1.5·105,<=1<=≤<=*k*<=≤<=*n*) — the number of planks in the fence and the width of the hole for the piano. The second line contains the sequence of integers *h*1,<=*h*2,<=...,<=*h**n* (1<=≤<=*h**i*<=≤<=100), where *h**i* is the height of the *i*-th plank of the fence.
Output Specification:
Print such integer *j* that the sum of the heights of planks *j*, *j*<=+<=1, ..., *j*<=+<=*k*<=-<=1 is the minimum possible. If there are multiple such *j*'s, print any of them.
Demo Input:
['7 3\n1 2 6 1 1 7 1\n']
Demo Output:
['3\n']
Note:
In the sample, your task is to find three consecutive planks with the minimum sum of heights. In the given case three planks with indexes 3, 4 and 5 have the required attribute, their total height is 8. | ```python
from sys import stdin, stdout
def input():
return stdin.readline().strip()
def print(string):
return stdout.write(str(string) + "\n")
def main():
n, k = map(int, input().split())
h = [int(x) for x in input().split()]
dp = [None] * n
dp[0] = sum(h[:k])
smallest_i = 0
for i in range(n-k):
dp[i+1] = dp[i] - h[i] + h[i+k]
if dp[i+1] < dp[smallest_i]:
smallest_i = i+1
print(smallest_i+1)
if __name__ == "__main__":
main()
``` | 3 | |
716 | A | Crazy Computer | PROGRAMMING | 800 | [
"implementation"
] | null | null | ZS the Coder is coding on a crazy computer. If you don't type in a word for a *c* consecutive seconds, everything you typed disappear!
More formally, if you typed a word at second *a* and then the next word at second *b*, then if *b*<=-<=*a*<=≤<=*c*, just the new word is appended to other words on the screen. If *b*<=-<=*a*<=><=*c*, then everything on the screen disappears and after that the word you have typed appears on the screen.
For example, if *c*<==<=5 and you typed words at seconds 1,<=3,<=8,<=14,<=19,<=20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.
You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything. | The first line contains two integers *n* and *c* (1<=≤<=*n*<=≤<=100<=000,<=1<=≤<=*c*<=≤<=109) — the number of words ZS the Coder typed and the crazy computer delay respectively.
The next line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t*1<=<<=*t*2<=<<=...<=<<=*t**n*<=≤<=109), where *t**i* denotes the second when ZS the Coder typed the *i*-th word. | Print a single positive integer, the number of words that remain on the screen after all *n* words was typed, in other words, at the second *t**n*. | [
"6 5\n1 3 8 14 19 20\n",
"6 1\n1 3 5 7 9 10\n"
] | [
"3",
"2"
] | The first sample is already explained in the problem statement.
For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 > 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1. | 500 | [
{
"input": "6 5\n1 3 8 14 19 20",
"output": "3"
},
{
"input": "6 1\n1 3 5 7 9 10",
"output": "2"
},
{
"input": "1 1\n1000000000",
"output": "1"
},
{
"input": "5 5\n1 7 12 13 14",
"output": "4"
},
{
"input": "2 1000000000\n1 1000000000",
"output": "2"
},
{
... | 1,568,221,442 | 2,147,483,647 | PyPy 3 | OK | TESTS | 81 | 249 | 11,366,400 | n,c=map(int,input().split())
s=1
l=list(map(int,input().split()))
a=l[0]
b=0
for i in range(1,len(l)):
b=l[i]
if(b-a<=c):
s+=1
else:
s=1
a=l[i]
print(str(s),end="")
| Title: Crazy Computer
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
ZS the Coder is coding on a crazy computer. If you don't type in a word for a *c* consecutive seconds, everything you typed disappear!
More formally, if you typed a word at second *a* and then the next word at second *b*, then if *b*<=-<=*a*<=≤<=*c*, just the new word is appended to other words on the screen. If *b*<=-<=*a*<=><=*c*, then everything on the screen disappears and after that the word you have typed appears on the screen.
For example, if *c*<==<=5 and you typed words at seconds 1,<=3,<=8,<=14,<=19,<=20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.
You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
Input Specification:
The first line contains two integers *n* and *c* (1<=≤<=*n*<=≤<=100<=000,<=1<=≤<=*c*<=≤<=109) — the number of words ZS the Coder typed and the crazy computer delay respectively.
The next line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t*1<=<<=*t*2<=<<=...<=<<=*t**n*<=≤<=109), where *t**i* denotes the second when ZS the Coder typed the *i*-th word.
Output Specification:
Print a single positive integer, the number of words that remain on the screen after all *n* words was typed, in other words, at the second *t**n*.
Demo Input:
['6 5\n1 3 8 14 19 20\n', '6 1\n1 3 5 7 9 10\n']
Demo Output:
['3', '2']
Note:
The first sample is already explained in the problem statement.
For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 > 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1. | ```python
n,c=map(int,input().split())
s=1
l=list(map(int,input().split()))
a=l[0]
b=0
for i in range(1,len(l)):
b=l[i]
if(b-a<=c):
s+=1
else:
s=1
a=l[i]
print(str(s),end="")
``` | 3 | |
770 | A | New Password | PROGRAMMING | 800 | [
"*special",
"implementation"
] | null | null | Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.
Innokentiy decides that new password should satisfy the following conditions:
- the length of the password must be equal to *n*, - the password should consist only of lowercase Latin letters, - the number of distinct symbols in the password must be equal to *k*, - any two consecutive symbols in the password must be distinct.
Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions. | The first line contains two positive integers *n* and *k* (2<=≤<=*n*<=≤<=100, 2<=≤<=*k*<=≤<=*min*(*n*,<=26)) — the length of the password and the number of distinct symbols in it.
Pay attention that a desired new password always exists. | Print any password which satisfies all conditions given by Innokentiy. | [
"4 3\n",
"6 6\n",
"5 2\n"
] | [
"java\n",
"python\n",
"phphp\n"
] | In the first test there is one of the appropriate new passwords — java, because its length is equal to 4 and 3 distinct lowercase letters a, j and v are used in it.
In the second test there is one of the appropriate new passwords — python, because its length is equal to 6 and it consists of 6 distinct lowercase letters.
In the third test there is one of the appropriate new passwords — phphp, because its length is equal to 5 and 2 distinct lowercase letters p and h are used in it.
Pay attention the condition that no two identical symbols are consecutive is correct for all appropriate passwords in tests. | 500 | [
{
"input": "4 3",
"output": "abca"
},
{
"input": "6 6",
"output": "abcdef"
},
{
"input": "5 2",
"output": "ababa"
},
{
"input": "3 2",
"output": "aba"
},
{
"input": "10 2",
"output": "ababababab"
},
{
"input": "26 13",
"output": "abcdefghijklmabcde... | 1,650,487,800 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 31 | 409,600 | import random
import string
alpha ='abcdefghijklmnopqrstuvwxyz'
x = int(input())
c = int(input())
password = ''
for i in range(0,c):
password +=alpha[i]
for i in range(c,x):
password+= password[i-c]
print(password)
| Title: New Password
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.
Innokentiy decides that new password should satisfy the following conditions:
- the length of the password must be equal to *n*, - the password should consist only of lowercase Latin letters, - the number of distinct symbols in the password must be equal to *k*, - any two consecutive symbols in the password must be distinct.
Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions.
Input Specification:
The first line contains two positive integers *n* and *k* (2<=≤<=*n*<=≤<=100, 2<=≤<=*k*<=≤<=*min*(*n*,<=26)) — the length of the password and the number of distinct symbols in it.
Pay attention that a desired new password always exists.
Output Specification:
Print any password which satisfies all conditions given by Innokentiy.
Demo Input:
['4 3\n', '6 6\n', '5 2\n']
Demo Output:
['java\n', 'python\n', 'phphp\n']
Note:
In the first test there is one of the appropriate new passwords — java, because its length is equal to 4 and 3 distinct lowercase letters a, j and v are used in it.
In the second test there is one of the appropriate new passwords — python, because its length is equal to 6 and it consists of 6 distinct lowercase letters.
In the third test there is one of the appropriate new passwords — phphp, because its length is equal to 5 and 2 distinct lowercase letters p and h are used in it.
Pay attention the condition that no two identical symbols are consecutive is correct for all appropriate passwords in tests. | ```python
import random
import string
alpha ='abcdefghijklmnopqrstuvwxyz'
x = int(input())
c = int(input())
password = ''
for i in range(0,c):
password +=alpha[i]
for i in range(c,x):
password+= password[i-c]
print(password)
``` | -1 | |
515 | C | Drazil and Factorial | PROGRAMMING | 1,400 | [
"greedy",
"math",
"sortings"
] | null | null | Drazil is playing a math game with Varda.
Let's define for positive integer *x* as a product of factorials of its digits. For example, .
First, they choose a decimal number *a* consisting of *n* digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number *x* satisfying following two conditions:
1. *x* doesn't contain neither digit 0 nor digit 1.
2. = .
Help friends find such number. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=15) — the number of digits in *a*.
The second line contains *n* digits of *a*. There is at least one digit in *a* that is larger than 1. Number *a* may possibly contain leading zeroes. | Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation. | [
"4\n1234\n",
"3\n555\n"
] | [
"33222\n",
"555\n"
] | In the first case, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f5a4207f23215fddce977ab5ea9e9d2e7578fb52.png" style="max-width: 100.0%;max-height: 100.0%;"/> | 1,000 | [
{
"input": "4\n1234",
"output": "33222"
},
{
"input": "3\n555",
"output": "555"
},
{
"input": "15\n012345781234578",
"output": "7777553333222222222222"
},
{
"input": "1\n8",
"output": "7222"
},
{
"input": "10\n1413472614",
"output": "75333332222222"
},
{
... | 1,602,596,428 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 0 | 108 | 0 | n=int(input())
digits=list(map(int,input()))
print(digits)
countfact={2:0,3:0,5:0,7:0}
def fact(n):
mydict={2:0,3:0,5:0,7:0}
factor=[i for i in range(1,n+1)]
for val in factor:
if val==2:
mydict[2]+=1
elif val==3:
mydict[3]+=1
elif val==4:
mydict[2]+=2
elif val==5:
mydict[5]+=1
elif val==6:
mydict[3]+=1
mydict[2]+=1
elif val==7:
mydict[7]+=1
elif val==8:
mydict[2]+=3
elif val==9:
mydict[3]+=2
return mydict
for digit in digits:
tmp=fact(digit)
for key in tmp.keys():
countfact[key]+=tmp[key]
while countfact[2]!=0:
if countfact[7]!=0:
tmp=fact(7)
print("7",end="")
for key in tmp.keys():
countfact[key]-=tmp[key]
elif countfact[5]!=0:
tmp=fact(5)
print("5",end="")
for key in tmp.keys():
countfact[key]-=tmp[key]
elif countfact[3]!=0:
tmp=fact(3)
print("3",end="")
for key in tmp.keys():
countfact[key]-=tmp[key]
elif countfact[2]!=0:
tmp=fact(2)
print("2",end="")
for key in tmp.keys():
countfact[key]-=tmp[key]
| Title: Drazil and Factorial
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Drazil is playing a math game with Varda.
Let's define for positive integer *x* as a product of factorials of its digits. For example, .
First, they choose a decimal number *a* consisting of *n* digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number *x* satisfying following two conditions:
1. *x* doesn't contain neither digit 0 nor digit 1.
2. = .
Help friends find such number.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=15) — the number of digits in *a*.
The second line contains *n* digits of *a*. There is at least one digit in *a* that is larger than 1. Number *a* may possibly contain leading zeroes.
Output Specification:
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Demo Input:
['4\n1234\n', '3\n555\n']
Demo Output:
['33222\n', '555\n']
Note:
In the first case, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f5a4207f23215fddce977ab5ea9e9d2e7578fb52.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
n=int(input())
digits=list(map(int,input()))
print(digits)
countfact={2:0,3:0,5:0,7:0}
def fact(n):
mydict={2:0,3:0,5:0,7:0}
factor=[i for i in range(1,n+1)]
for val in factor:
if val==2:
mydict[2]+=1
elif val==3:
mydict[3]+=1
elif val==4:
mydict[2]+=2
elif val==5:
mydict[5]+=1
elif val==6:
mydict[3]+=1
mydict[2]+=1
elif val==7:
mydict[7]+=1
elif val==8:
mydict[2]+=3
elif val==9:
mydict[3]+=2
return mydict
for digit in digits:
tmp=fact(digit)
for key in tmp.keys():
countfact[key]+=tmp[key]
while countfact[2]!=0:
if countfact[7]!=0:
tmp=fact(7)
print("7",end="")
for key in tmp.keys():
countfact[key]-=tmp[key]
elif countfact[5]!=0:
tmp=fact(5)
print("5",end="")
for key in tmp.keys():
countfact[key]-=tmp[key]
elif countfact[3]!=0:
tmp=fact(3)
print("3",end="")
for key in tmp.keys():
countfact[key]-=tmp[key]
elif countfact[2]!=0:
tmp=fact(2)
print("2",end="")
for key in tmp.keys():
countfact[key]-=tmp[key]
``` | 0 | |
19 | D | Points | PROGRAMMING | 2,800 | [
"data structures"
] | D. Points | 2 | 256 | Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point (0,<=0) is located in the bottom-left corner, *Ox* axis is directed right, *Oy* axis is directed up. Pete gives Bob requests of three types:
- add x y — on the sheet of paper Bob marks a point with coordinates (*x*,<=*y*). For each request of this type it's guaranteed that point (*x*,<=*y*) is not yet marked on Bob's sheet at the time of the request. - remove x y — on the sheet of paper Bob erases the previously marked point with coordinates (*x*,<=*y*). For each request of this type it's guaranteed that point (*x*,<=*y*) is already marked on Bob's sheet at the time of the request. - find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point (*x*,<=*y*). Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete.
Bob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to 2·105, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please! | The first input line contains number *n* (1<=≤<=*n*<=≤<=2·105) — amount of requests. Then there follow *n* lines — descriptions of the requests. add x y describes the request to add a point, remove x y — the request to erase a point, find x y — the request to find the bottom-left point. All the coordinates in the input file are non-negative and don't exceed 109. | For each request of type find x y output in a separate line the answer to it — coordinates of the bottommost among the leftmost marked points, lying strictly above and to the right of point (*x*,<=*y*). If there are no points strictly above and to the right of point (*x*,<=*y*), output -1. | [
"7\nadd 1 1\nadd 3 4\nfind 0 0\nremove 1 1\nfind 0 0\nadd 1 1\nfind 0 0\n",
"13\nadd 5 5\nadd 5 6\nadd 5 7\nadd 6 5\nadd 6 6\nadd 6 7\nadd 7 5\nadd 7 6\nadd 7 7\nfind 6 6\nremove 7 7\nfind 6 6\nfind 4 4\n"
] | [
"1 1\n3 4\n1 1\n",
"7 7\n-1\n5 5\n"
] | none | 0 | [] | 1,601,246,388 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 10 | 2,000 | 819,200 | def DPoints2_find(s,sk,l):
find_x=-1
find_y=-1
for i in sk:
if i>l[0]:
for j in s[i]:
if j>l[1]:
find_y=j
find_x=i
break
if find_y!=-1:
break
if find_y==-1:
return -1
else:
return [find_x,find_y]
sheet={}
sheet_k=[]
result=[]
n=int(input())
for _ in range(0,n):
oper=input()
oper=oper.split()
if oper[0]=="add":
if int(oper[1]) in sheet.keys():
sheet[int(oper[1])].append(int(oper[2]))
sheet[int(oper[1])]=sorted(sheet[int(oper[1])])
else:
sheet[int(oper[1])]=[]
sheet[int(oper[1])].append(int(oper[2]))
sheet[int(oper[1])]=sorted(sheet[int(oper[1])])
sheet_k=sorted(sheet.keys())
elif oper[0]=="remove":
sheet[int(oper[1])].remove(int(oper[2]))
if len(sheet[int(oper[1])])==0:
del sheet[int(oper[1])]
sheet_k.remove(int(oper[1]))
else:
result.append(DPoints2_find(sheet,sheet_k,[int(oper[1]),int(oper[2])]))
for i in result:
if i==-1:
print(i)
else:
print(*i) | Title: Points
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point (0,<=0) is located in the bottom-left corner, *Ox* axis is directed right, *Oy* axis is directed up. Pete gives Bob requests of three types:
- add x y — on the sheet of paper Bob marks a point with coordinates (*x*,<=*y*). For each request of this type it's guaranteed that point (*x*,<=*y*) is not yet marked on Bob's sheet at the time of the request. - remove x y — on the sheet of paper Bob erases the previously marked point with coordinates (*x*,<=*y*). For each request of this type it's guaranteed that point (*x*,<=*y*) is already marked on Bob's sheet at the time of the request. - find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point (*x*,<=*y*). Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete.
Bob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to 2·105, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please!
Input Specification:
The first input line contains number *n* (1<=≤<=*n*<=≤<=2·105) — amount of requests. Then there follow *n* lines — descriptions of the requests. add x y describes the request to add a point, remove x y — the request to erase a point, find x y — the request to find the bottom-left point. All the coordinates in the input file are non-negative and don't exceed 109.
Output Specification:
For each request of type find x y output in a separate line the answer to it — coordinates of the bottommost among the leftmost marked points, lying strictly above and to the right of point (*x*,<=*y*). If there are no points strictly above and to the right of point (*x*,<=*y*), output -1.
Demo Input:
['7\nadd 1 1\nadd 3 4\nfind 0 0\nremove 1 1\nfind 0 0\nadd 1 1\nfind 0 0\n', '13\nadd 5 5\nadd 5 6\nadd 5 7\nadd 6 5\nadd 6 6\nadd 6 7\nadd 7 5\nadd 7 6\nadd 7 7\nfind 6 6\nremove 7 7\nfind 6 6\nfind 4 4\n']
Demo Output:
['1 1\n3 4\n1 1\n', '7 7\n-1\n5 5\n']
Note:
none | ```python
def DPoints2_find(s,sk,l):
find_x=-1
find_y=-1
for i in sk:
if i>l[0]:
for j in s[i]:
if j>l[1]:
find_y=j
find_x=i
break
if find_y!=-1:
break
if find_y==-1:
return -1
else:
return [find_x,find_y]
sheet={}
sheet_k=[]
result=[]
n=int(input())
for _ in range(0,n):
oper=input()
oper=oper.split()
if oper[0]=="add":
if int(oper[1]) in sheet.keys():
sheet[int(oper[1])].append(int(oper[2]))
sheet[int(oper[1])]=sorted(sheet[int(oper[1])])
else:
sheet[int(oper[1])]=[]
sheet[int(oper[1])].append(int(oper[2]))
sheet[int(oper[1])]=sorted(sheet[int(oper[1])])
sheet_k=sorted(sheet.keys())
elif oper[0]=="remove":
sheet[int(oper[1])].remove(int(oper[2]))
if len(sheet[int(oper[1])])==0:
del sheet[int(oper[1])]
sheet_k.remove(int(oper[1]))
else:
result.append(DPoints2_find(sheet,sheet_k,[int(oper[1]),int(oper[2])]))
for i in result:
if i==-1:
print(i)
else:
print(*i)
``` | 0 |
471 | A | MUH and Sticks | PROGRAMMING | 1,100 | [
"implementation"
] | null | null | Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
- Four sticks represent the animal's legs, these sticks should have the same length. - Two remaining sticks represent the animal's head and body. The bear's head stick must be shorter than the body stick. The elephant, however, has a long trunk, so his head stick must be as long as the body stick. Note that there are no limits on the relations between the leg sticks and the head and body sticks.
Your task is to find out which animal can be made from the given stick set. The zoo keeper wants the sticks back after the game, so they must never be broken, even bears understand it. | The single line contains six space-separated integers *l**i* (1<=≤<=*l**i*<=≤<=9) — the lengths of the six sticks. It is guaranteed that the input is such that you cannot make both animals from the sticks. | If you can make a bear from the given set, print string "Bear" (without the quotes). If you can make an elephant, print string "Elephant" (wıthout the quotes). If you can make neither a bear nor an elephant, print string "Alien" (without the quotes). | [
"4 2 5 4 4 4\n",
"4 4 5 4 4 5\n",
"1 2 3 4 5 6\n"
] | [
"Bear",
"Elephant",
"Alien"
] | If you're out of creative ideas, see instructions below which show how to make a bear and an elephant in the first two samples. The stick of length 2 is in red, the sticks of length 4 are in green, the sticks of length 5 are in blue. | 500 | [
{
"input": "4 2 5 4 4 4",
"output": "Bear"
},
{
"input": "4 4 5 4 4 5",
"output": "Elephant"
},
{
"input": "1 2 3 4 5 6",
"output": "Alien"
},
{
"input": "5 5 5 5 5 5",
"output": "Elephant"
},
{
"input": "1 1 1 2 3 5",
"output": "Alien"
},
{
"input": "... | 1,653,783,028 | 2,147,483,647 | Python 3 | OK | TESTS | 29 | 46 | 0 |
sticks = list(map(int, input().split()))
#print(sticks)
sticks.sort()
hb = [(0, 5), (4, 5), (0, 1)]
for head, body in hb:
cur = sticks[3]
flag = True
for i in range(6):
if i != head and i != body:
if sticks[i] != cur:
flag = False
break
if not flag:
continue
if sticks[head] < sticks[body]:
print("Bear")
else:
print("Elephant")
exit()
print("Alien")
| Title: MUH and Sticks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
- Four sticks represent the animal's legs, these sticks should have the same length. - Two remaining sticks represent the animal's head and body. The bear's head stick must be shorter than the body stick. The elephant, however, has a long trunk, so his head stick must be as long as the body stick. Note that there are no limits on the relations between the leg sticks and the head and body sticks.
Your task is to find out which animal can be made from the given stick set. The zoo keeper wants the sticks back after the game, so they must never be broken, even bears understand it.
Input Specification:
The single line contains six space-separated integers *l**i* (1<=≤<=*l**i*<=≤<=9) — the lengths of the six sticks. It is guaranteed that the input is such that you cannot make both animals from the sticks.
Output Specification:
If you can make a bear from the given set, print string "Bear" (without the quotes). If you can make an elephant, print string "Elephant" (wıthout the quotes). If you can make neither a bear nor an elephant, print string "Alien" (without the quotes).
Demo Input:
['4 2 5 4 4 4\n', '4 4 5 4 4 5\n', '1 2 3 4 5 6\n']
Demo Output:
['Bear', 'Elephant', 'Alien']
Note:
If you're out of creative ideas, see instructions below which show how to make a bear and an elephant in the first two samples. The stick of length 2 is in red, the sticks of length 4 are in green, the sticks of length 5 are in blue. | ```python
sticks = list(map(int, input().split()))
#print(sticks)
sticks.sort()
hb = [(0, 5), (4, 5), (0, 1)]
for head, body in hb:
cur = sticks[3]
flag = True
for i in range(6):
if i != head and i != body:
if sticks[i] != cur:
flag = False
break
if not flag:
continue
if sticks[head] < sticks[body]:
print("Bear")
else:
print("Elephant")
exit()
print("Alien")
``` | 3 | |
766 | B | Mahmoud and a Triangle | PROGRAMMING | 1,000 | [
"constructive algorithms",
"geometry",
"greedy",
"math",
"number theory",
"sortings"
] | null | null | Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle.
Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area. | The first line contains single integer *n* (3<=≤<=*n*<=≤<=105) — the number of line segments Mahmoud has.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — the lengths of line segments Mahmoud has. | In the only line print "YES" if he can choose exactly three line segments and form a non-degenerate triangle with them, and "NO" otherwise. | [
"5\n1 5 3 2 4\n",
"3\n4 1 2\n"
] | [
"YES\n",
"NO\n"
] | For the first example, he can use line segments with lengths 2, 4 and 5 to form a non-degenerate triangle. | 1,000 | [
{
"input": "5\n1 5 3 2 4",
"output": "YES"
},
{
"input": "3\n4 1 2",
"output": "NO"
},
{
"input": "30\n197 75 517 39724 7906061 1153471 3 15166 168284 3019844 272293 316 16 24548 42 118 5792 5 9373 1866366 4886214 24 2206 712886 104005 1363 836 64273 440585 3576",
"output": "NO"
},... | 1,655,541,797 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 31 | 0 | n, f=int(input()), 0
a=list(map(int,input().split()))
a.sort()
for i in range(1, n-1):
if a[i-1]+a[i]<=a[i+1]:
f+=1
break
if f==1:
print("YES")
else:
print("NO") | Title: Mahmoud and a Triangle
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle.
Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.
Input Specification:
The first line contains single integer *n* (3<=≤<=*n*<=≤<=105) — the number of line segments Mahmoud has.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — the lengths of line segments Mahmoud has.
Output Specification:
In the only line print "YES" if he can choose exactly three line segments and form a non-degenerate triangle with them, and "NO" otherwise.
Demo Input:
['5\n1 5 3 2 4\n', '3\n4 1 2\n']
Demo Output:
['YES\n', 'NO\n']
Note:
For the first example, he can use line segments with lengths 2, 4 and 5 to form a non-degenerate triangle. | ```python
n, f=int(input()), 0
a=list(map(int,input().split()))
a.sort()
for i in range(1, n-1):
if a[i-1]+a[i]<=a[i+1]:
f+=1
break
if f==1:
print("YES")
else:
print("NO")
``` | 0 | |
302 | A | Eugeny and Array | PROGRAMMING | 800 | [
"implementation"
] | null | null | Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries:
- Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of array *a* can be rearranged so as the sum *a**l**i*<=+<=*a**l**i*<=+<=1<=+<=...<=+<=*a**r**i*<==<=0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries. | The first line contains integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (*a**i*<==<=-1,<=1). Next *m* lines contain Eugene's queries. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). | Print *m* integers — the responses to Eugene's queries in the order they occur in the input. | [
"2 3\n1 -1\n1 1\n1 2\n2 2\n",
"5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5\n"
] | [
"0\n1\n0\n",
"0\n1\n0\n1\n0\n"
] | none | 500 | [
{
"input": "2 3\n1 -1\n1 1\n1 2\n2 2",
"output": "0\n1\n0"
},
{
"input": "5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5",
"output": "0\n1\n0\n1\n0"
},
{
"input": "3 3\n1 1 1\n2 2\n1 1\n1 1",
"output": "0\n0\n0"
},
{
"input": "4 4\n-1 -1 -1 -1\n1 3\n1 2\n1 2\n1 1",
"output": "... | 1,632,581,855 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 46 | 6,758,400 | n, m = map(int, input().split())
a = list(map(int, input().split()))
ans = []
for i in range(m):
l, r = map(int, input().split())
result = 0 if (r - l + 1) % 2 else 1
ans.append(result)
for val in ans:
print(val)
| Title: Eugeny and Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries:
- Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of array *a* can be rearranged so as the sum *a**l**i*<=+<=*a**l**i*<=+<=1<=+<=...<=+<=*a**r**i*<==<=0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input Specification:
The first line contains integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (*a**i*<==<=-1,<=1). Next *m* lines contain Eugene's queries. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*).
Output Specification:
Print *m* integers — the responses to Eugene's queries in the order they occur in the input.
Demo Input:
['2 3\n1 -1\n1 1\n1 2\n2 2\n', '5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5\n']
Demo Output:
['0\n1\n0\n', '0\n1\n0\n1\n0\n']
Note:
none | ```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
ans = []
for i in range(m):
l, r = map(int, input().split())
result = 0 if (r - l + 1) % 2 else 1
ans.append(result)
for val in ans:
print(val)
``` | 0 | |
740 | A | Alyona and copybooks | PROGRAMMING | 1,300 | [
"brute force",
"implementation"
] | null | null | Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for *a* rubles, a pack of two copybooks for *b* rubles, and a pack of three copybooks for *c* rubles. Alyona already has *n* copybooks.
What is the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase. | The only line contains 4 integers *n*, *a*, *b*, *c* (1<=≤<=*n*,<=*a*,<=*b*,<=*c*<=≤<=109). | Print the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4. | [
"1 1 3 4\n",
"6 2 1 1\n",
"4 4 4 4\n",
"999999999 1000000000 1000000000 1000000000\n"
] | [
"3\n",
"1\n",
"0\n",
"1000000000\n"
] | In the first example Alyona can buy 3 packs of 1 copybook for 3*a* = 3 rubles in total. After that she will have 4 copybooks which she can split between the subjects equally.
In the second example Alyuna can buy a pack of 2 copybooks for *b* = 1 ruble. She will have 8 copybooks in total.
In the third example Alyona can split the copybooks she already has between the 4 subject equally, so she doesn't need to buy anything.
In the fourth example Alyona should buy one pack of one copybook. | 500 | [
{
"input": "1 1 3 4",
"output": "3"
},
{
"input": "6 2 1 1",
"output": "1"
},
{
"input": "4 4 4 4",
"output": "0"
},
{
"input": "999999999 1000000000 1000000000 1000000000",
"output": "1000000000"
},
{
"input": "1016 3 2 1",
"output": "0"
},
{
"input":... | 1,479,920,574 | 1,674 | Python 3 | RUNTIME_ERROR | PRETESTS | 2 | 46 | 0 | d = input()
d = [int(x) for x in d.split()]
n,a,b,c = d[0],d[1],d[2],d[3]
counter = []
if n%4==0:
print(0)
else:
m = n%4
if m==3:
counter.append(a)
counter.append(b+c)
elif m==2:
counter.append(2*a)
counter.append(b)
counter.append(2*c)
else:
counter.append(b+a)
counter.append(3*a)
counter.append(c)
print(min(counter))
| Title: Alyona and copybooks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for *a* rubles, a pack of two copybooks for *b* rubles, and a pack of three copybooks for *c* rubles. Alyona already has *n* copybooks.
What is the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase.
Input Specification:
The only line contains 4 integers *n*, *a*, *b*, *c* (1<=≤<=*n*,<=*a*,<=*b*,<=*c*<=≤<=109).
Output Specification:
Print the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4.
Demo Input:
['1 1 3 4\n', '6 2 1 1\n', '4 4 4 4\n', '999999999 1000000000 1000000000 1000000000\n']
Demo Output:
['3\n', '1\n', '0\n', '1000000000\n']
Note:
In the first example Alyona can buy 3 packs of 1 copybook for 3*a* = 3 rubles in total. After that she will have 4 copybooks which she can split between the subjects equally.
In the second example Alyuna can buy a pack of 2 copybooks for *b* = 1 ruble. She will have 8 copybooks in total.
In the third example Alyona can split the copybooks she already has between the 4 subject equally, so she doesn't need to buy anything.
In the fourth example Alyona should buy one pack of one copybook. | ```python
d = input()
d = [int(x) for x in d.split()]
n,a,b,c = d[0],d[1],d[2],d[3]
counter = []
if n%4==0:
print(0)
else:
m = n%4
if m==3:
counter.append(a)
counter.append(b+c)
elif m==2:
counter.append(2*a)
counter.append(b)
counter.append(2*c)
else:
counter.append(b+a)
counter.append(3*a)
counter.append(c)
print(min(counter))
``` | -1 | |
331 | C1 | The Great Julya Calendar | PROGRAMMING | 1,100 | [
"dp"
] | null | null | Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero. | The single line contains the magic integer *n*, 0<=≤<=*n*.
- to get 20 points, you need to solve the problem with constraints: *n*<=≤<=106 (subproblem C1); - to get 40 points, you need to solve the problem with constraints: *n*<=≤<=1012 (subproblems C1+C2); - to get 100 points, you need to solve the problem with constraints: *n*<=≤<=1018 (subproblems C1+C2+C3). | Print a single integer — the minimum number of subtractions that turns the magic number to a zero. | [
"24\n"
] | [
"5"
] | In the first test sample the minimum number of operations can be reached by the following sequence of subtractions: | 20 | [
{
"input": "24",
"output": "5"
},
{
"input": "0",
"output": "0"
},
{
"input": "3",
"output": "1"
},
{
"input": "8",
"output": "1"
},
{
"input": "9",
"output": "1"
},
{
"input": "10",
"output": "2"
},
{
"input": "31",
"output": "6"
},
... | 1,608,833,155 | 2,147,483,647 | Python 3 | OK | TESTS1 | 24 | 404 | 0 | n,c=int(input()),0
while n:n-=int(max(str(n)));c+=1
print(c) | Title: The Great Julya Calendar
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input Specification:
The single line contains the magic integer *n*, 0<=≤<=*n*.
- to get 20 points, you need to solve the problem with constraints: *n*<=≤<=106 (subproblem C1); - to get 40 points, you need to solve the problem with constraints: *n*<=≤<=1012 (subproblems C1+C2); - to get 100 points, you need to solve the problem with constraints: *n*<=≤<=1018 (subproblems C1+C2+C3).
Output Specification:
Print a single integer — the minimum number of subtractions that turns the magic number to a zero.
Demo Input:
['24\n']
Demo Output:
['5']
Note:
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions: | ```python
n,c=int(input()),0
while n:n-=int(max(str(n)));c+=1
print(c)
``` | 3 | |
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,635,928,116 | 2,147,483,647 | Python 3 | OK | TESTS | 96 | 46 | 4,300,800 | def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def nok(a, b):
return a // gcd(a, b) * b
n, k = map(int, input().split())
print(nok(n, 10 ** 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 gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def nok(a, b):
return a // gcd(a, b) * b
n, k = map(int, input().split())
print(nok(n, 10 ** k))
``` | 3 | |
899 | B | Months and Years | PROGRAMMING | 1,200 | [
"implementation"
] | null | null | Everybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December.
A year is leap in one of two cases: either its number is divisible by 4, but not divisible by 100, or is divisible by 400. For example, the following years are leap: 2000, 2004, but years 1900 and 2018 are not leap.
In this problem you are given *n* (1<=≤<=*n*<=≤<=24) integers *a*1,<=*a*2,<=...,<=*a**n*, and you have to check if these integers could be durations in days of *n* consecutive months, according to Gregorian calendar. Note that these months could belong to several consecutive years. In other words, check if there is a month in some year, such that its duration is *a*1 days, duration of the next month is *a*2 days, and so on. | The first line contains single integer *n* (1<=≤<=*n*<=≤<=24) — the number of integers.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (28<=≤<=*a**i*<=≤<=31) — the numbers you are to check. | If there are several consecutive months that fit the sequence, print "YES" (without quotes). Otherwise, print "NO" (without quotes).
You can print each letter in arbitrary case (small or large). | [
"4\n31 31 30 31\n",
"2\n30 30\n",
"5\n29 31 30 31 30\n",
"3\n31 28 30\n",
"3\n31 31 28\n"
] | [
"Yes\n\n",
"No\n\n",
"Yes\n\n",
"No\n\n",
"Yes\n\n"
] | In the first example the integers can denote months July, August, September and October.
In the second example the answer is no, because there are no two consecutive months each having 30 days.
In the third example the months are: February (leap year) — March — April – May — June.
In the fourth example the number of days in the second month is 28, so this is February. March follows February and has 31 days, but not 30, so the answer is NO.
In the fifth example the months are: December — January — February (non-leap year). | 1,000 | [
{
"input": "4\n31 31 30 31",
"output": "Yes"
},
{
"input": "2\n30 30",
"output": "No"
},
{
"input": "5\n29 31 30 31 30",
"output": "Yes"
},
{
"input": "3\n31 28 30",
"output": "No"
},
{
"input": "3\n31 31 28",
"output": "Yes"
},
{
"input": "24\n29 28 3... | 1,639,596,797 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 4 | 31 | 0 | n = int(input())
months = '312931303130313130313031'
m = input()
for i in m:
if i == ' ':
m = m.replace(i,'')
for i in m:
if i == '8':
m = m.replace(i,'9')
if months.find(m) == -1:
print('NO')
else:
print('YES') | Title: Months and Years
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Everybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December.
A year is leap in one of two cases: either its number is divisible by 4, but not divisible by 100, or is divisible by 400. For example, the following years are leap: 2000, 2004, but years 1900 and 2018 are not leap.
In this problem you are given *n* (1<=≤<=*n*<=≤<=24) integers *a*1,<=*a*2,<=...,<=*a**n*, and you have to check if these integers could be durations in days of *n* consecutive months, according to Gregorian calendar. Note that these months could belong to several consecutive years. In other words, check if there is a month in some year, such that its duration is *a*1 days, duration of the next month is *a*2 days, and so on.
Input Specification:
The first line contains single integer *n* (1<=≤<=*n*<=≤<=24) — the number of integers.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (28<=≤<=*a**i*<=≤<=31) — the numbers you are to check.
Output Specification:
If there are several consecutive months that fit the sequence, print "YES" (without quotes). Otherwise, print "NO" (without quotes).
You can print each letter in arbitrary case (small or large).
Demo Input:
['4\n31 31 30 31\n', '2\n30 30\n', '5\n29 31 30 31 30\n', '3\n31 28 30\n', '3\n31 31 28\n']
Demo Output:
['Yes\n\n', 'No\n\n', 'Yes\n\n', 'No\n\n', 'Yes\n\n']
Note:
In the first example the integers can denote months July, August, September and October.
In the second example the answer is no, because there are no two consecutive months each having 30 days.
In the third example the months are: February (leap year) — March — April – May — June.
In the fourth example the number of days in the second month is 28, so this is February. March follows February and has 31 days, but not 30, so the answer is NO.
In the fifth example the months are: December — January — February (non-leap year). | ```python
n = int(input())
months = '312931303130313130313031'
m = input()
for i in m:
if i == ' ':
m = m.replace(i,'')
for i in m:
if i == '8':
m = m.replace(i,'9')
if months.find(m) == -1:
print('NO')
else:
print('YES')
``` | 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,590,096,910 | 2,147,483,647 | PyPy 3 | OK | TESTS | 102 | 140 | 0 | a = input()
n = len(a)
a = int(a, 2)
a ^= int(input(),2)
a = bin(a)[2:]
print('0'*(n-len(a))+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
a = input()
n = len(a)
a = int(a, 2)
a ^= int(input(),2)
a = bin(a)[2:]
print('0'*(n-len(a))+a)
``` | 3.965 |
127 | A | Wasted Time | PROGRAMMING | 900 | [
"geometry"
] | null | null | Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.
Mr. Scrooge's signature can be represented as a polyline *A*1*A*2... *A**n*. Scrooge signs like that: first it places a pen at the point *A*1, then draws a segment from point *A*1 to point *A*2, then he draws a segment from point *A*2 to point *A*3 and so on to point *A**n*, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — 50 millimeters per second.
Scrooge signed exactly *k* papers throughout his life and all those signatures look the same.
Find the total time Scrooge wasted signing the papers. | The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=1000). Each of the following *n* lines contains the coordinates of the polyline's endpoints. The *i*-th one contains coordinates of the point *A**i* — integers *x**i* and *y**i*, separated by a space.
All points *A**i* are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters. | Print one real number — the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10<=-<=6. | [
"2 1\n0 0\n10 0\n",
"5 10\n3 1\n-5 6\n-2 -1\n3 2\n10 0\n",
"6 10\n5 0\n4 0\n6 0\n3 0\n7 0\n2 0\n"
] | [
"0.200000000",
"6.032163204",
"3.000000000"
] | none | 500 | [
{
"input": "2 1\n0 0\n10 0",
"output": "0.200000000"
},
{
"input": "5 10\n3 1\n-5 6\n-2 -1\n3 2\n10 0",
"output": "6.032163204"
},
{
"input": "6 10\n5 0\n4 0\n6 0\n3 0\n7 0\n2 0",
"output": "3.000000000"
},
{
"input": "10 95\n-20 -5\n2 -8\n14 13\n10 3\n17 11\n13 -12\n-6 11\n1... | 1,550,839,223 | 2,147,483,647 | PyPy 3 | OK | TESTS | 42 | 342 | 512,000 | from collections import deque, Counter, OrderedDict
from heapq import nsmallest, nlargest
from math import ceil,floor,log,log2,sqrt,gcd,factorial,pow
def binNumber(n,size=4):
return bin(n)[2:].zfill(size)
def iar():
return list(map(int,input().split()))
def ini():
return int(input())
def isp():
return map(int,input().split())
def sti():
return str(input())
def par(a):
print(' '.join(list(map(str,a))))
def tdl(outerListSize,innerListSize,defaultValue = 0):
return [[defaultValue]*innerListSize for i in range(outerListSize)]
class pair:
def __init__(self,f,s):
self.fi = f
self.se = s
def __lt__(self,other):
return (self.fi,self.se) < (other.fi,other.se)
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
def dist(x1,y1,x2,y2):
return sqrt((x2-x1)**2 + (y2-y1)**2)
if __name__ == "__main__":
n,k = isp()
s = 0
p = []
for _ in range(n):
x,y = isp()
p.append(pair(x,y))
for i in range(1,n):
s += dist(p[i].fi,p[i].se,p[i-1].fi,p[i-1].se)
s *= k
print(s/50) | Title: Wasted Time
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.
Mr. Scrooge's signature can be represented as a polyline *A*1*A*2... *A**n*. Scrooge signs like that: first it places a pen at the point *A*1, then draws a segment from point *A*1 to point *A*2, then he draws a segment from point *A*2 to point *A*3 and so on to point *A**n*, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — 50 millimeters per second.
Scrooge signed exactly *k* papers throughout his life and all those signatures look the same.
Find the total time Scrooge wasted signing the papers.
Input Specification:
The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=1000). Each of the following *n* lines contains the coordinates of the polyline's endpoints. The *i*-th one contains coordinates of the point *A**i* — integers *x**i* and *y**i*, separated by a space.
All points *A**i* are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.
Output Specification:
Print one real number — the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10<=-<=6.
Demo Input:
['2 1\n0 0\n10 0\n', '5 10\n3 1\n-5 6\n-2 -1\n3 2\n10 0\n', '6 10\n5 0\n4 0\n6 0\n3 0\n7 0\n2 0\n']
Demo Output:
['0.200000000', '6.032163204', '3.000000000']
Note:
none | ```python
from collections import deque, Counter, OrderedDict
from heapq import nsmallest, nlargest
from math import ceil,floor,log,log2,sqrt,gcd,factorial,pow
def binNumber(n,size=4):
return bin(n)[2:].zfill(size)
def iar():
return list(map(int,input().split()))
def ini():
return int(input())
def isp():
return map(int,input().split())
def sti():
return str(input())
def par(a):
print(' '.join(list(map(str,a))))
def tdl(outerListSize,innerListSize,defaultValue = 0):
return [[defaultValue]*innerListSize for i in range(outerListSize)]
class pair:
def __init__(self,f,s):
self.fi = f
self.se = s
def __lt__(self,other):
return (self.fi,self.se) < (other.fi,other.se)
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
def dist(x1,y1,x2,y2):
return sqrt((x2-x1)**2 + (y2-y1)**2)
if __name__ == "__main__":
n,k = isp()
s = 0
p = []
for _ in range(n):
x,y = isp()
p.append(pair(x,y))
for i in range(1,n):
s += dist(p[i].fi,p[i].se,p[i-1].fi,p[i-1].se)
s *= k
print(s/50)
``` | 3 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string *s*, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring *t* of the string *s*.
Prefix supposed that the substring *t* is the beginning of the string *s*; Suffix supposed that the substring *t* should be the end of the string *s*; and Obelix supposed that *t* should be located somewhere inside the string *s*, that is, *t* is neither its beginning, nor its end.
Asterix chose the substring *t* so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring *t* aloud, the temple doors opened.
You know the string *s*. Find the substring *t* or determine that such substring does not exist and all that's been written above is just a nice legend. | You are given the string *s* whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters. | Print the string *t*. If a suitable *t* string does not exist, then print "Just a legend" without the quotes. | [
"fixprefixsuffix\n",
"abcdabc\n"
] | [
"fix",
"Just a legend"
] | none | 0 | [
{
"input": "fixprefixsuffix",
"output": "fix"
},
{
"input": "abcdabc",
"output": "Just a legend"
},
{
"input": "qwertyqwertyqwerty",
"output": "qwerty"
},
{
"input": "papapapap",
"output": "papap"
},
{
"input": "aaaaaaaaaa",
"output": "aaaaaaaa"
},
{
"... | 1,465,354,301 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 25 | 2,000 | 8,192,000 | import math
from collections import *
from heapq import *
s=input()
l=len(s)
if l==1 or l==2:
print("Just a legend")
else:
vv=False
for i in range(l-2,0,-1):
s1=s[0:i]
s2=s[l-i:l]
if s1==s2:
v=False
for j in range(1,l-i):
s3=s[j:j+i]
if s3==s2:
v=True
break
if v:
print(s1)
vv=True
break
if not vv:
print("Just a legend")
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string *s*, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring *t* of the string *s*.
Prefix supposed that the substring *t* is the beginning of the string *s*; Suffix supposed that the substring *t* should be the end of the string *s*; and Obelix supposed that *t* should be located somewhere inside the string *s*, that is, *t* is neither its beginning, nor its end.
Asterix chose the substring *t* so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring *t* aloud, the temple doors opened.
You know the string *s*. Find the substring *t* or determine that such substring does not exist and all that's been written above is just a nice legend.
Input Specification:
You are given the string *s* whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output Specification:
Print the string *t*. If a suitable *t* string does not exist, then print "Just a legend" without the quotes.
Demo Input:
['fixprefixsuffix\n', 'abcdabc\n']
Demo Output:
['fix', 'Just a legend']
Note:
none | ```python
import math
from collections import *
from heapq import *
s=input()
l=len(s)
if l==1 or l==2:
print("Just a legend")
else:
vv=False
for i in range(l-2,0,-1):
s1=s[0:i]
s2=s[l-i:l]
if s1==s2:
v=False
for j in range(1,l-i):
s3=s[j:j+i]
if s3==s2:
v=True
break
if v:
print(s1)
vv=True
break
if not vv:
print("Just a legend")
``` | 0 | |
653 | B | Bear and Compressing | PROGRAMMING | 1,300 | [
"brute force",
"dfs and similar",
"dp",
"strings"
] | null | null | Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of *q* possible operations. Limak can perform them in any order, any operation may be applied any number of times. The *i*-th operation is described by a string *a**i* of length two and a string *b**i* of length one. No two of *q* possible operations have the same string *a**i*.
When Limak has a string *s* he can perform the *i*-th operation on *s* if the first two letters of *s* match a two-letter string *a**i*. Performing the *i*-th operation removes first two letters of *s* and inserts there a string *b**i*. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string *s* exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any *a**i*.
Limak wants to start with a string of length *n* and perform *n*<=-<=1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows. | The first line contains two integers *n* and *q* (2<=≤<=*n*<=≤<=6, 1<=≤<=*q*<=≤<=36) — the length of the initial string and the number of available operations.
The next *q* lines describe the possible operations. The *i*-th of them contains two strings *a**i* and *b**i* (|*a**i*|<==<=2,<=|*b**i*|<==<=1). It's guaranteed that *a**i*<=≠<=*a**j* for *i*<=≠<=*j* and that all *a**i* and *b**i* consist of only first six lowercase English letters. | Print the number of strings of length *n* that Limak will be able to transform to string "a" by applying only operations given in the input. | [
"3 5\nab a\ncc c\nca a\nee c\nff d\n",
"2 8\naf e\ndc d\ncc f\nbc b\nda b\neb a\nbb b\nff c\n",
"6 2\nbb a\nba a\n"
] | [
"4\n",
"1\n",
"0\n"
] | In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
- "cab" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "ab" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "a" - "cca" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "ca" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "a" - "eea" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "ca" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". | 1,000 | [
{
"input": "3 5\nab a\ncc c\nca a\nee c\nff d",
"output": "4"
},
{
"input": "2 8\naf e\ndc d\ncc f\nbc b\nda b\neb a\nbb b\nff c",
"output": "1"
},
{
"input": "6 2\nbb a\nba a",
"output": "0"
},
{
"input": "2 5\nfe b\nbb a\naf b\nfd b\nbf c",
"output": "1"
},
{
"i... | 1,458,381,605 | 5,105 | Python 3 | OK | TESTS | 32 | 108 | 5,324,800 | import collections
n, q = map(int, input().split())
d = collections.defaultdict(list)
cnt, t = [0] * 6, [0] * 6
for i in range(q):
s1, s2 = input().split()
d[s2].append(s1)
cnt[ord(s2) - ord('a')] += 1
for s in d['a']:
t[ord(s[0]) - ord('a')] += 1
for i in range(n - 2):
p = [0] * 6
for j in range(6):
if t[j] == 0:
continue
for s in d[chr(j + 97)]:
p[ord(s[0]) - ord('a')] += t[j]
t = p
print(sum(t))
| Title: Bear and Compressing
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of *q* possible operations. Limak can perform them in any order, any operation may be applied any number of times. The *i*-th operation is described by a string *a**i* of length two and a string *b**i* of length one. No two of *q* possible operations have the same string *a**i*.
When Limak has a string *s* he can perform the *i*-th operation on *s* if the first two letters of *s* match a two-letter string *a**i*. Performing the *i*-th operation removes first two letters of *s* and inserts there a string *b**i*. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string *s* exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any *a**i*.
Limak wants to start with a string of length *n* and perform *n*<=-<=1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
Input Specification:
The first line contains two integers *n* and *q* (2<=≤<=*n*<=≤<=6, 1<=≤<=*q*<=≤<=36) — the length of the initial string and the number of available operations.
The next *q* lines describe the possible operations. The *i*-th of them contains two strings *a**i* and *b**i* (|*a**i*|<==<=2,<=|*b**i*|<==<=1). It's guaranteed that *a**i*<=≠<=*a**j* for *i*<=≠<=*j* and that all *a**i* and *b**i* consist of only first six lowercase English letters.
Output Specification:
Print the number of strings of length *n* that Limak will be able to transform to string "a" by applying only operations given in the input.
Demo Input:
['3 5\nab a\ncc c\nca a\nee c\nff d\n', '2 8\naf e\ndc d\ncc f\nbc b\nda b\neb a\nbb b\nff c\n', '6 2\nbb a\nba a\n']
Demo Output:
['4\n', '1\n', '0\n']
Note:
In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
- "cab" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "ab" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "a" - "cca" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "ca" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "a" - "eea" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "ca" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". | ```python
import collections
n, q = map(int, input().split())
d = collections.defaultdict(list)
cnt, t = [0] * 6, [0] * 6
for i in range(q):
s1, s2 = input().split()
d[s2].append(s1)
cnt[ord(s2) - ord('a')] += 1
for s in d['a']:
t[ord(s[0]) - ord('a')] += 1
for i in range(n - 2):
p = [0] * 6
for j in range(6):
if t[j] == 0:
continue
for s in d[chr(j + 97)]:
p[ord(s[0]) - ord('a')] += t[j]
t = p
print(sum(t))
``` | 3 | |
1,009 | B | Minimum Ternary String | PROGRAMMING | 1,400 | [
"greedy",
"implementation"
] | null | null | You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
- "010210" $\rightarrow$ "100210"; - "010210" $\rightarrow$ "001210"; - "010210" $\rightarrow$ "010120"; - "010210" $\rightarrow$ "010201".
Note than you cannot swap "02" $\rightarrow$ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String $a$ is lexicographically less than string $b$ (if strings $a$ and $b$ have the same length) if there exists some position $i$ ($1 \le i \le |a|$, where $|s|$ is the length of the string $s$) such that for every $j < i$ holds $a_j = b_j$, and $a_i < b_i$. | The first line of the input contains the string $s$ consisting only of characters '0', '1' and '2', its length is between $1$ and $10^5$ (inclusive). | Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero). | [
"100210\n",
"11222121\n",
"20\n"
] | [
"001120\n",
"11112222\n",
"20\n"
] | none | 0 | [
{
"input": "100210",
"output": "001120"
},
{
"input": "11222121",
"output": "11112222"
},
{
"input": "20",
"output": "20"
},
{
"input": "1002",
"output": "0012"
},
{
"input": "10",
"output": "01"
},
{
"input": "000021",
"output": "000012"
},
{
... | 1,532,266,676 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 3 | 1,000 | 1,433,600 | s = input()
s = list(s)
l = len(s)
while True:
asis = s[:]
for i in range(l):
if s[i] == '1':
start = i
zero = 0
one = 1
for j in range(l-i-1):
if s[i+j+1] == '2':
break
elif s[i+j+1] == '0':
zero += 1
else:
one += 1
if zero != 0:
for i in range(zero):
s[start+i] = '0'
for i in range(one):
s[start+zero+i] = '1'
for i in range(l):
if s[i] == '2':
start = i
zero = 0
one = 0
two = 1
for j in range(l-i-1):
if s[i+j+1] == '2':
break
elif s[i+j+1] == '0':
zero += 1
else:
one += 1
if one != 0:
for i in range(one):
s[start+i] = '1'
for i in range(two):
s[start+one+i] = '2'
if zero != 0:
for i in range(zero):
s[start+one+two+i] = '0'
if asis == s:
break
output = ''
for i in s:
output += i
print(output)
| Title: Minimum Ternary String
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
- "010210" $\rightarrow$ "100210"; - "010210" $\rightarrow$ "001210"; - "010210" $\rightarrow$ "010120"; - "010210" $\rightarrow$ "010201".
Note than you cannot swap "02" $\rightarrow$ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String $a$ is lexicographically less than string $b$ (if strings $a$ and $b$ have the same length) if there exists some position $i$ ($1 \le i \le |a|$, where $|s|$ is the length of the string $s$) such that for every $j < i$ holds $a_j = b_j$, and $a_i < b_i$.
Input Specification:
The first line of the input contains the string $s$ consisting only of characters '0', '1' and '2', its length is between $1$ and $10^5$ (inclusive).
Output Specification:
Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Demo Input:
['100210\n', '11222121\n', '20\n']
Demo Output:
['001120\n', '11112222\n', '20\n']
Note:
none | ```python
s = input()
s = list(s)
l = len(s)
while True:
asis = s[:]
for i in range(l):
if s[i] == '1':
start = i
zero = 0
one = 1
for j in range(l-i-1):
if s[i+j+1] == '2':
break
elif s[i+j+1] == '0':
zero += 1
else:
one += 1
if zero != 0:
for i in range(zero):
s[start+i] = '0'
for i in range(one):
s[start+zero+i] = '1'
for i in range(l):
if s[i] == '2':
start = i
zero = 0
one = 0
two = 1
for j in range(l-i-1):
if s[i+j+1] == '2':
break
elif s[i+j+1] == '0':
zero += 1
else:
one += 1
if one != 0:
for i in range(one):
s[start+i] = '1'
for i in range(two):
s[start+one+i] = '2'
if zero != 0:
for i in range(zero):
s[start+one+two+i] = '0'
if asis == s:
break
output = ''
for i in s:
output += i
print(output)
``` | 0 | |
218 | B | Airport | PROGRAMMING | 1,100 | [
"implementation"
] | null | null | Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:
- it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=><=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency).
The only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer?
The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person. | The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains *m* integers *a*1,<=*a*2,<=...,<=*a**m* (1<=≤<=*a**i*<=≤<=1000) — *a**i* stands for the number of empty seats in the *i*-th plane before the ticket office starts selling tickets.
The numbers in the lines are separated by a space. It is guaranteed that there are at least *n* empty seats in total. | Print two integers — the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly. | [
"4 3\n2 1 1\n",
"4 3\n2 2 2\n"
] | [
"5 5\n",
"7 6\n"
] | In the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.
In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 2-nd plane, the 3-rd person — to the 3-rd plane, the 4-th person — to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 1-st plane, the 3-rd person — to the 2-nd plane, the 4-th person — to the 2-nd plane. | 500 | [
{
"input": "4 3\n2 1 1",
"output": "5 5"
},
{
"input": "4 3\n2 2 2",
"output": "7 6"
},
{
"input": "10 5\n10 3 3 1 2",
"output": "58 26"
},
{
"input": "10 1\n10",
"output": "55 55"
},
{
"input": "10 1\n100",
"output": "955 955"
},
{
"input": "10 2\n4 7... | 1,621,706,522 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 6 | 124 | 0 | n,p=map(int,input().split())
A=list(map(int,input().split()))
A.sort()
D=A[::-1]
mn=0
k=n
for i in A:
if k>=i:
mn+=(i)*(i+1)//2
k-=i
else:
mn+=((k)*((2*i)+(k-1)*(-1)))//2
break
mx=0
D.append(0)
for a in range(len(D)-1):
d=D[a]-D[a+1]
if (a+1)*d<=n:
mx+=(((d)*((2*D[a])+(d-1)*(-1)))//2)*(a+1)
n-=d*(a+1)
else:
l=(n//(a+1))
mx+=(((l)*(2*D[a]+(l-1)*(-1))//2)*(a+1))
n-=l*(a+1)
mx+=(D[a]-l)*(n%(a+1))
print(mx,mn) | Title: Airport
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:
- it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=><=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency).
The only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer?
The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains *m* integers *a*1,<=*a*2,<=...,<=*a**m* (1<=≤<=*a**i*<=≤<=1000) — *a**i* stands for the number of empty seats in the *i*-th plane before the ticket office starts selling tickets.
The numbers in the lines are separated by a space. It is guaranteed that there are at least *n* empty seats in total.
Output Specification:
Print two integers — the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly.
Demo Input:
['4 3\n2 1 1\n', '4 3\n2 2 2\n']
Demo Output:
['5 5\n', '7 6\n']
Note:
In the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.
In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 2-nd plane, the 3-rd person — to the 3-rd plane, the 4-th person — to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 1-st plane, the 3-rd person — to the 2-nd plane, the 4-th person — to the 2-nd plane. | ```python
n,p=map(int,input().split())
A=list(map(int,input().split()))
A.sort()
D=A[::-1]
mn=0
k=n
for i in A:
if k>=i:
mn+=(i)*(i+1)//2
k-=i
else:
mn+=((k)*((2*i)+(k-1)*(-1)))//2
break
mx=0
D.append(0)
for a in range(len(D)-1):
d=D[a]-D[a+1]
if (a+1)*d<=n:
mx+=(((d)*((2*D[a])+(d-1)*(-1)))//2)*(a+1)
n-=d*(a+1)
else:
l=(n//(a+1))
mx+=(((l)*(2*D[a]+(l-1)*(-1))//2)*(a+1))
n-=l*(a+1)
mx+=(D[a]-l)*(n%(a+1))
print(mx,mn)
``` | 0 | |
118 | A | String Task | PROGRAMMING | 1,000 | [
"implementation",
"strings"
] | null | null | Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
- deletes all the vowels, - inserts a character "." before each consonant, - replaces all uppercase consonants with corresponding lowercase ones.
Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string.
Help Petya cope with this easy task. | The first line represents input string of Petya's program. This string only consists of uppercase and lowercase Latin letters and its length is from 1 to 100, inclusive. | Print the resulting string. It is guaranteed that this string is not empty. | [
"tour\n",
"Codeforces\n",
"aBAcAba\n"
] | [
".t.r\n",
".c.d.f.r.c.s\n",
".b.c.b\n"
] | none | 500 | [
{
"input": "tour",
"output": ".t.r"
},
{
"input": "Codeforces",
"output": ".c.d.f.r.c.s"
},
{
"input": "aBAcAba",
"output": ".b.c.b"
},
{
"input": "obn",
"output": ".b.n"
},
{
"input": "wpwl",
"output": ".w.p.w.l"
},
{
"input": "ggdvq",
"output": "... | 1,695,183,151 | 2,147,483,647 | Python 3 | OK | TESTS | 42 | 92 | 0 | string = input()
string = string.lower()
str_ = ""
for i in string:
if i not in "aouiye":
str_ += "." + i
print(str_) | Title: String Task
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
- deletes all the vowels, - inserts a character "." before each consonant, - replaces all uppercase consonants with corresponding lowercase ones.
Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string.
Help Petya cope with this easy task.
Input Specification:
The first line represents input string of Petya's program. This string only consists of uppercase and lowercase Latin letters and its length is from 1 to 100, inclusive.
Output Specification:
Print the resulting string. It is guaranteed that this string is not empty.
Demo Input:
['tour\n', 'Codeforces\n', 'aBAcAba\n']
Demo Output:
['.t.r\n', '.c.d.f.r.c.s\n', '.b.c.b\n']
Note:
none | ```python
string = input()
string = string.lower()
str_ = ""
for i in string:
if i not in "aouiye":
str_ += "." + i
print(str_)
``` | 3 | |
963 | A | Alternating Sum | PROGRAMMING | 1,800 | [
"math",
"number theory"
] | null | null | You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \leq i \leq n$ it's satisfied that $s_{i} = s_{i - k}$.
Find out the non-negative remainder of division of $\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$ by $10^{9} + 9$.
Note that the modulo is unusual! | The first line contains four integers $n, a, b$ and $k$ $(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$.
The second line contains a sequence of length $k$ consisting of characters '+' and '-'.
If the $i$-th character (0-indexed) is '+', then $s_{i} = 1$, otherwise $s_{i} = -1$.
Note that only the first $k$ members of the sequence are given, the rest can be obtained using the periodicity property. | Output a single integer — value of given expression modulo $10^{9} + 9$. | [
"2 2 3 3\n+-+\n",
"4 1 5 1\n-\n"
] | [
"7\n",
"999999228\n"
] | In the first example:
$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$ = $2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$ = 7
In the second example:
$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$. | 500 | [
{
"input": "2 2 3 3\n+-+",
"output": "7"
},
{
"input": "4 1 5 1\n-",
"output": "999999228"
},
{
"input": "1 1 4 2\n-+",
"output": "3"
},
{
"input": "3 1 4 4\n+--+",
"output": "45"
},
{
"input": "5 1 1 6\n++---+",
"output": "0"
},
{
"input": "5 2 2 6\n+... | 1,525,717,136 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | #include <iostream>
#include<inttypes.h>
#include<math.h>
#define for(i,a,b) for(int i=a;i<b ; i++)
using namespace std;
long long int puiss(long long int x,long long int y){long long int res=1;for(i,0,y){res=res*x;}return res;}
long long int reste(long long int x,long long int y){long long int q=abs(x/y);return x+(q+1)*y;}
int main()
{
//cout << puiss(5,3) << endl;
long long int n,a,b,k;
cin >> n >> a >>b >> k;
string ch;
cin >> ch;
long long int s=0;
for(i,0,n+1){
if (ch[i%k]=='+'){s=s+puiss(a,n-i)*puiss(b,i);}
else{s=s-puiss(a,n-i)*puiss(b,i);}
}
long long int v;
v=puiss(10,9)+9;
v=reste(s,v);
cout << v << endl;
//long long int j=423834578;
//cout << j << endl;
return 0;
}
| Title: Alternating Sum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \leq i \leq n$ it's satisfied that $s_{i} = s_{i - k}$.
Find out the non-negative remainder of division of $\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$ by $10^{9} + 9$.
Note that the modulo is unusual!
Input Specification:
The first line contains four integers $n, a, b$ and $k$ $(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$.
The second line contains a sequence of length $k$ consisting of characters '+' and '-'.
If the $i$-th character (0-indexed) is '+', then $s_{i} = 1$, otherwise $s_{i} = -1$.
Note that only the first $k$ members of the sequence are given, the rest can be obtained using the periodicity property.
Output Specification:
Output a single integer — value of given expression modulo $10^{9} + 9$.
Demo Input:
['2 2 3 3\n+-+\n', '4 1 5 1\n-\n']
Demo Output:
['7\n', '999999228\n']
Note:
In the first example:
$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$ = $2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$ = 7
In the second example:
$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$. | ```python
#include <iostream>
#include<inttypes.h>
#include<math.h>
#define for(i,a,b) for(int i=a;i<b ; i++)
using namespace std;
long long int puiss(long long int x,long long int y){long long int res=1;for(i,0,y){res=res*x;}return res;}
long long int reste(long long int x,long long int y){long long int q=abs(x/y);return x+(q+1)*y;}
int main()
{
//cout << puiss(5,3) << endl;
long long int n,a,b,k;
cin >> n >> a >>b >> k;
string ch;
cin >> ch;
long long int s=0;
for(i,0,n+1){
if (ch[i%k]=='+'){s=s+puiss(a,n-i)*puiss(b,i);}
else{s=s-puiss(a,n-i)*puiss(b,i);}
}
long long int v;
v=puiss(10,9)+9;
v=reste(s,v);
cout << v << endl;
//long long int j=423834578;
//cout << j << endl;
return 0;
}
``` | -1 | |
194 | A | Exams | PROGRAMMING | 900 | [
"implementation",
"math"
] | null | null | One day the Codeforces round author sat exams. He had *n* exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2.
The author would need to spend too much time and effort to make the sum of his marks strictly more than *k*. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than *k*, the author's mum won't be pleased at all.
The Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams.
Help the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all *n* exams equal exactly *k*. | The single input line contains space-separated integers *n* and *k* (1<=≤<=*n*<=≤<=50, 1<=≤<=*k*<=≤<=250) — the number of exams and the required sum of marks.
It is guaranteed that there exists a way to pass *n* exams in the way that makes the sum of marks equal exactly *k*. | Print the single number — the minimum number of exams that the author will get a 2 for, considering that the sum of marks for all exams must equal *k*. | [
"4 8\n",
"4 10\n",
"1 3\n"
] | [
"4\n",
"2\n",
"0\n"
] | In the first sample the author has to get a 2 for all his exams.
In the second sample he should get a 3 for two exams and a 2 for two more.
In the third sample he should get a 3 for one exam. | 500 | [
{
"input": "4 8",
"output": "4"
},
{
"input": "4 10",
"output": "2"
},
{
"input": "1 3",
"output": "0"
},
{
"input": "1 2",
"output": "1"
},
{
"input": "4 9",
"output": "3"
},
{
"input": "50 234",
"output": "0"
},
{
"input": "50 100",
"... | 1,618,612,675 | 2,147,483,647 | Python 3 | OK | TESTS | 38 | 124 | 0 | n, k = map(int, input().split())
two = k//n
rem = k % n
if two > 2:
print(0)
else:
print(n-rem)
| Title: Exams
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day the Codeforces round author sat exams. He had *n* exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2.
The author would need to spend too much time and effort to make the sum of his marks strictly more than *k*. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than *k*, the author's mum won't be pleased at all.
The Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams.
Help the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all *n* exams equal exactly *k*.
Input Specification:
The single input line contains space-separated integers *n* and *k* (1<=≤<=*n*<=≤<=50, 1<=≤<=*k*<=≤<=250) — the number of exams and the required sum of marks.
It is guaranteed that there exists a way to pass *n* exams in the way that makes the sum of marks equal exactly *k*.
Output Specification:
Print the single number — the minimum number of exams that the author will get a 2 for, considering that the sum of marks for all exams must equal *k*.
Demo Input:
['4 8\n', '4 10\n', '1 3\n']
Demo Output:
['4\n', '2\n', '0\n']
Note:
In the first sample the author has to get a 2 for all his exams.
In the second sample he should get a 3 for two exams and a 2 for two more.
In the third sample he should get a 3 for one exam. | ```python
n, k = map(int, input().split())
two = k//n
rem = k % n
if two > 2:
print(0)
else:
print(n-rem)
``` | 3 | |
404 | A | Valera and X | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals *n* squares (*n* is an odd number) and each unit square contains some small letter of the English alphabet.
Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:
- on both diagonals of the square paper all letters are the same; - all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals.
Help Valera, write the program that completes the described task for him. | The first line contains integer *n* (3<=≤<=*n*<=<<=300; *n* is odd). Each of the next *n* lines contains *n* small English letters — the description of Valera's paper. | Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes. | [
"5\nxooox\noxoxo\nsoxoo\noxoxo\nxooox\n",
"3\nwsw\nsws\nwsw\n",
"3\nxpx\npxp\nxpe\n"
] | [
"NO\n",
"YES\n",
"NO\n"
] | none | 500 | [
{
"input": "5\nxooox\noxoxo\nsoxoo\noxoxo\nxooox",
"output": "NO"
},
{
"input": "3\nwsw\nsws\nwsw",
"output": "YES"
},
{
"input": "3\nxpx\npxp\nxpe",
"output": "NO"
},
{
"input": "5\nliiil\nilili\niilii\nilili\nliiil",
"output": "YES"
},
{
"input": "7\nbwccccb\nck... | 1,650,916,866 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | #include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define yes cout<<"yes\n";
#define Yes cout<<"Yes\n";
#define YES cout<<"YES\n";
#define no cout<<"no\n";
#define No cout<<"No\n";
#define NO cout<<"NO\n";
#define loop(n) for(int i=0;i<n;i++)
#define all(x) x.begin(),x.end()
typedef long long ll;
struct interval
{
int s,e;
};
bool sortthis(interval i1, interval i2)
{
return i1.s<i2.s;
}
void solve()
{
ll n;cin>>n;char arr[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>arr[i][j];
}
}
char a=arr[0][0];
char b=arr[0][1];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
{
if(arr[i][j] != a)
{
NO
return;
}
}
else if (i == n-1-j)
{
if(arr[i][n-1-j] != a)
{
NO
return;
}
}
else
if(arr[i][j] != b)
{
NO
return;
}
}
}
YES
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif
ll t=1;
//cin>>t;
while(t--)
{
solve();
}
return 0;
}
| Title: Valera and X
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals *n* squares (*n* is an odd number) and each unit square contains some small letter of the English alphabet.
Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:
- on both diagonals of the square paper all letters are the same; - all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals.
Help Valera, write the program that completes the described task for him.
Input Specification:
The first line contains integer *n* (3<=≤<=*n*<=<<=300; *n* is odd). Each of the next *n* lines contains *n* small English letters — the description of Valera's paper.
Output Specification:
Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes.
Demo Input:
['5\nxooox\noxoxo\nsoxoo\noxoxo\nxooox\n', '3\nwsw\nsws\nwsw\n', '3\nxpx\npxp\nxpe\n']
Demo Output:
['NO\n', 'YES\n', 'NO\n']
Note:
none | ```python
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define yes cout<<"yes\n";
#define Yes cout<<"Yes\n";
#define YES cout<<"YES\n";
#define no cout<<"no\n";
#define No cout<<"No\n";
#define NO cout<<"NO\n";
#define loop(n) for(int i=0;i<n;i++)
#define all(x) x.begin(),x.end()
typedef long long ll;
struct interval
{
int s,e;
};
bool sortthis(interval i1, interval i2)
{
return i1.s<i2.s;
}
void solve()
{
ll n;cin>>n;char arr[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>arr[i][j];
}
}
char a=arr[0][0];
char b=arr[0][1];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
{
if(arr[i][j] != a)
{
NO
return;
}
}
else if (i == n-1-j)
{
if(arr[i][n-1-j] != a)
{
NO
return;
}
}
else
if(arr[i][j] != b)
{
NO
return;
}
}
}
YES
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif
ll t=1;
//cin>>t;
while(t--)
{
solve();
}
return 0;
}
``` | -1 | |
550 | A | Two Substrings | PROGRAMMING | 1,500 | [
"brute force",
"dp",
"greedy",
"implementation",
"strings"
] | null | null | You are given string *s*. Your task is to determine if the given string *s* contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | The only line of input contains a string *s* of length between 1 and 105 consisting of uppercase Latin letters. | Print "YES" (without the quotes), if string *s* contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | [
"ABA\n",
"BACFAB\n",
"AXBYBXA\n"
] | [
"NO\n",
"YES\n",
"NO\n"
] | In the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".
In the second sample test there are the following occurrences of the substrings: BACFAB.
In the third sample test there is no substring "AB" nor substring "BA". | 1,000 | [
{
"input": "ABA",
"output": "NO"
},
{
"input": "BACFAB",
"output": "YES"
},
{
"input": "AXBYBXA",
"output": "NO"
},
{
"input": "ABABAB",
"output": "YES"
},
{
"input": "BBBBBBBBBB",
"output": "NO"
},
{
"input": "ABBA",
"output": "YES"
},
{
"... | 1,690,004,464 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 3 | 46 | 0 | st = input()
ab = st.count("AB")
ba = st.count("BA")
aba = st.count("ABA")
print("NO") if ab==0 and ba==0 or aba!=0 else print("YES")
# print("NO" if ab==0 and ba == 0 and aba!=0)
| Title: Two Substrings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given string *s*. Your task is to determine if the given string *s* contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
Input Specification:
The only line of input contains a string *s* of length between 1 and 105 consisting of uppercase Latin letters.
Output Specification:
Print "YES" (without the quotes), if string *s* contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.
Demo Input:
['ABA\n', 'BACFAB\n', 'AXBYBXA\n']
Demo Output:
['NO\n', 'YES\n', 'NO\n']
Note:
In the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".
In the second sample test there are the following occurrences of the substrings: BACFAB.
In the third sample test there is no substring "AB" nor substring "BA". | ```python
st = input()
ab = st.count("AB")
ba = st.count("BA")
aba = st.count("ABA")
print("NO") if ab==0 and ba==0 or aba!=0 else print("YES")
# print("NO" if ab==0 and ba == 0 and aba!=0)
``` | 0 | |
522 | A | Reposts | PROGRAMMING | 1,200 | [
"*special",
"dfs and similar",
"dp",
"graphs",
"trees"
] | null | null | One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.
Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke. | The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.
We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user. | Print a single integer — the maximum length of a repost chain. | [
"5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya\n",
"6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp\n",
"1\nSoMeStRaNgEgUe repos... | [
"6\n",
"2\n",
"2\n"
] | none | 500 | [
{
"input": "5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya",
"output": "6"
},
{
"input": "6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforc... | 1,460,392,537 | 2,147,483,647 | PyPy 3 | OK | TESTS | 36 | 124 | 102,400 | __author__ = 'Utena'
n=int(input())
reposts=dict()
for i in range(n):
s=input().split()
reposts[s[0].lower()]=s[2].lower()
prev=['polycarp']
t=1
while True:
next=[]
for a in reposts.keys():
if reposts[a] in prev:
next.append(a)
if next==[]:
break
else:
t+=1
prev=next
print(t) | Title: Reposts
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.
Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.
Input Specification:
The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.
We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.
Output Specification:
Print a single integer — the maximum length of a repost chain.
Demo Input:
['5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya\n', '6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp\n', '1\nSoMeStRaNgEgUe reposted PoLyCaRp\n']
Demo Output:
['6\n', '2\n', '2\n']
Note:
none | ```python
__author__ = 'Utena'
n=int(input())
reposts=dict()
for i in range(n):
s=input().split()
reposts[s[0].lower()]=s[2].lower()
prev=['polycarp']
t=1
while True:
next=[]
for a in reposts.keys():
if reposts[a] in prev:
next.append(a)
if next==[]:
break
else:
t+=1
prev=next
print(t)
``` | 3 | |
333 | A | Secrets | PROGRAMMING | 1,600 | [
"greedy"
] | null | null | Gerald has been selling state secrets at leisure. All the secrets cost the same: *n* marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.
One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?
The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of *n* marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least *n* marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want. | The single line contains a single integer *n* (1<=≤<=*n*<=≤<=1017).
Please, do not use the %lld specifier to read or write 64 bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. | In a single line print an integer: the maximum number of coins the unlucky buyer could have paid with. | [
"1\n",
"4\n"
] | [
"1\n",
"2\n"
] | In the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change.
In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three coins as he wants to minimize the number of coins that he gives. | 500 | [
{
"input": "1",
"output": "1"
},
{
"input": "4",
"output": "2"
},
{
"input": "3",
"output": "1"
},
{
"input": "8",
"output": "3"
},
{
"input": "10",
"output": "4"
},
{
"input": "100000000000000000",
"output": "33333333333333334"
},
{
"input... | 1,621,410,784 | 2,147,483,647 | PyPy 3 | OK | TESTS | 28 | 184 | 0 | n=int(input())
while n%3==0:
n//=3
print((n-1)//3+1) | Title: Secrets
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Gerald has been selling state secrets at leisure. All the secrets cost the same: *n* marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.
One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?
The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of *n* marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least *n* marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want.
Input Specification:
The single line contains a single integer *n* (1<=≤<=*n*<=≤<=1017).
Please, do not use the %lld specifier to read or write 64 bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output Specification:
In a single line print an integer: the maximum number of coins the unlucky buyer could have paid with.
Demo Input:
['1\n', '4\n']
Demo Output:
['1\n', '2\n']
Note:
In the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change.
In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three coins as he wants to minimize the number of coins that he gives. | ```python
n=int(input())
while n%3==0:
n//=3
print((n-1)//3+1)
``` | 3 | |
22 | C | System Administrator | PROGRAMMING | 1,700 | [
"graphs"
] | C. System Administrator | 1 | 256 | Bob got a job as a system administrator in X corporation. His first task was to connect *n* servers with the help of *m* two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index *v* fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers. | The first input line contains 3 space-separated integer numbers *n*, *m*, *v* (3<=≤<=*n*<=≤<=105,<=0<=≤<=*m*<=≤<=105,<=1<=≤<=*v*<=≤<=*n*), *n* — amount of servers, *m* — amount of direct connections, *v* — index of the server that fails and leads to the failure of the whole system. | If it is impossible to connect the servers in the required way, output -1. Otherwise output *m* lines with 2 numbers each — description of all the direct connections in the system. Each direct connection is described by two numbers — indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any. | [
"5 6 3\n",
"6 100 1\n"
] | [
"1 2\n2 3\n3 4\n4 5\n1 3\n3 5\n",
"-1\n"
] | none | 0 | [
{
"input": "5 6 3",
"output": "1 3\n2 3\n4 3\n5 3\n1 2\n1 4"
},
{
"input": "6 100 1",
"output": "-1"
},
{
"input": "10 26 1",
"output": "2 1\n3 1\n4 1\n5 1\n6 1\n7 1\n8 1\n9 1\n10 1\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n3 4\n3 5\n3 6\n3 7\n3 8\n3 9\n4 5\n4 6\n4 7\n4 8"
},
{
"in... | 1,599,835,561 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 0 | 109 | 0 | nodes,connections,focal=[int(x) for x in input().split()]
if connections>1+((nodes-1)*(nodes-2))//2:
print(-1)
else:
counter=0
while counter<min(connections,nodes):
if counter+1!=focal:
print(focal,counter+1)
counter+=1
nodes-=1
if connections>counter:
for i in range(1,nodes+1):
for j in range(i,nodes+1):
if connections>counter:
if i!=focal and j!=focal and i!=j:
print(i,j)
counter+=1
else:
exit() | Title: System Administrator
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Bob got a job as a system administrator in X corporation. His first task was to connect *n* servers with the help of *m* two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index *v* fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
Input Specification:
The first input line contains 3 space-separated integer numbers *n*, *m*, *v* (3<=≤<=*n*<=≤<=105,<=0<=≤<=*m*<=≤<=105,<=1<=≤<=*v*<=≤<=*n*), *n* — amount of servers, *m* — amount of direct connections, *v* — index of the server that fails and leads to the failure of the whole system.
Output Specification:
If it is impossible to connect the servers in the required way, output -1. Otherwise output *m* lines with 2 numbers each — description of all the direct connections in the system. Each direct connection is described by two numbers — indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
Demo Input:
['5 6 3\n', '6 100 1\n']
Demo Output:
['1 2\n2 3\n3 4\n4 5\n1 3\n3 5\n', '-1\n']
Note:
none | ```python
nodes,connections,focal=[int(x) for x in input().split()]
if connections>1+((nodes-1)*(nodes-2))//2:
print(-1)
else:
counter=0
while counter<min(connections,nodes):
if counter+1!=focal:
print(focal,counter+1)
counter+=1
nodes-=1
if connections>counter:
for i in range(1,nodes+1):
for j in range(i,nodes+1):
if connections>counter:
if i!=focal and j!=focal and i!=j:
print(i,j)
counter+=1
else:
exit()
``` | 0 |
427 | A | Police Recruits | PROGRAMMING | 800 | [
"implementation"
] | null | null | The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.
Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated. | The first line of input will contain an integer *n* (1<=≤<=*n*<=≤<=105), the number of events. The next line will contain *n* space-separated integers.
If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time. | Print a single integer, the number of crimes which will go untreated. | [
"3\n-1 -1 1\n",
"8\n1 -1 1 -1 -1 1 1 1\n",
"11\n-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1\n"
] | [
"2\n",
"1\n",
"8\n"
] | Lets consider the second example:
1. Firstly one person is hired. 1. Then crime appears, the last hired person will investigate this crime. 1. One more person is hired. 1. One more crime appears, the last hired person will investigate this crime. 1. Crime appears. There is no free policeman at the time, so this crime will go untreated. 1. One more person is hired. 1. One more person is hired. 1. One more person is hired.
The answer is one, as one crime (on step 5) will go untreated. | 500 | [
{
"input": "3\n-1 -1 1",
"output": "2"
},
{
"input": "8\n1 -1 1 -1 -1 1 1 1",
"output": "1"
},
{
"input": "11\n-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1",
"output": "8"
},
{
"input": "7\n-1 -1 1 1 -1 -1 1",
"output": "2"
},
{
"input": "21\n-1 -1 -1 -1 -1 3 2 -1 6 -1 -1 2 1 ... | 1,685,574,558 | 2,147,483,647 | Python 3 | OK | TESTS | 63 | 61 | 9,728,000 | import sys
import math
def main():
#n,k = map(int, input().split())
#a = [int(x) for x in sys.stdin.readline().split()]
#t = int(input())
t = int(input())
a = [int(x) for x in sys.stdin.readline().split()]
crimes=0
soldiers=0
for x in a:
if x >= 1:
soldiers += x
if x == -1:
if soldiers>0:
#crimes -= 1
soldiers -=1
else:
crimes += 1
print(crimes)
main()
| Title: Police Recruits
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.
Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.
Input Specification:
The first line of input will contain an integer *n* (1<=≤<=*n*<=≤<=105), the number of events. The next line will contain *n* space-separated integers.
If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.
Output Specification:
Print a single integer, the number of crimes which will go untreated.
Demo Input:
['3\n-1 -1 1\n', '8\n1 -1 1 -1 -1 1 1 1\n', '11\n-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1\n']
Demo Output:
['2\n', '1\n', '8\n']
Note:
Lets consider the second example:
1. Firstly one person is hired. 1. Then crime appears, the last hired person will investigate this crime. 1. One more person is hired. 1. One more crime appears, the last hired person will investigate this crime. 1. Crime appears. There is no free policeman at the time, so this crime will go untreated. 1. One more person is hired. 1. One more person is hired. 1. One more person is hired.
The answer is one, as one crime (on step 5) will go untreated. | ```python
import sys
import math
def main():
#n,k = map(int, input().split())
#a = [int(x) for x in sys.stdin.readline().split()]
#t = int(input())
t = int(input())
a = [int(x) for x in sys.stdin.readline().split()]
crimes=0
soldiers=0
for x in a:
if x >= 1:
soldiers += x
if x == -1:
if soldiers>0:
#crimes -= 1
soldiers -=1
else:
crimes += 1
print(crimes)
main()
``` | 3 | |
180 | A | Defragmentation | PROGRAMMING | 1,800 | [
"implementation"
] | null | null | In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to *n*. The disk has *m* recorded files, the *i*-th file occupies clusters with numbers *a**i*,<=1, *a**i*,<=2, ..., *a**i*,<=*n**i*. These clusters are not necessarily located consecutively on the disk, but the order in which they are given corresponds to their sequence in the file (cluster *a**i*,<=1 contains the first fragment of the *i*-th file, cluster *a**i*,<=2 has the second fragment, etc.). Also the disc must have one or several clusters which are free from files.
You are permitted to perform operations of copying the contents of cluster number *i* to cluster number *j* (*i* and *j* must be different). Moreover, if the cluster number *j* used to keep some information, it is lost forever. Clusters are not cleaned, but after the defragmentation is complete, some of them are simply declared unusable (although they may possibly still contain some fragments of files).
Your task is to use a sequence of copy operations to ensure that each file occupies a contiguous area of memory. Each file should occupy a consecutive cluster section, the files must follow one after another from the beginning of the hard disk. After defragmentation all free (unused) clusters should be at the end of the hard disk. After defragmenting files can be placed in an arbitrary order. Clusters of each file should go consecutively from first to last. See explanatory examples in the notes.
Print the sequence of operations leading to the disk defragmentation. Note that you do not have to minimize the number of operations, but it should not exceed 2*n*. | The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=200) — the number of clusters and the number of files, correspondingly. Next *m* lines contain descriptions of the files. The first number in the line is *n**i* (*n**i*<=≥<=1), the number of clusters occupied by the *i*-th file. Then follow *n**i* numbers *a**i*,<=1, *a**i*,<=2, ..., *a**i*,<=*n**i* (1<=≤<=*a**i*,<=*j*<=≤<=*n*). It is guaranteed that each cluster number occurs not more than once and , that is, there exists at least one unused cluster. Numbers on each line are separated by spaces. | In the first line print a single integer *k* (0<=≤<=*k*<=≤<=2*n*) — the number of operations needed to defragment the disk. Next *k* lines should contain the operations' descriptions as "*i* *j*" (copy the contents of the cluster number *i* to the cluster number *j*). | [
"7 2\n2 1 2\n3 3 4 5\n",
"7 2\n2 1 3\n3 2 4 5\n"
] | [
"0\n",
"3\n2 6\n3 2\n6 3\n"
] | Let's say that a disk consists of 8 clusters and contains two files. The first file occupies two clusters and the second file occupies three clusters. Let's look at examples of correct and incorrect positions of files after defragmentation.
Example 2: each file must occupy a contiguous area of memory.
Example 3: the order of files to each other is not important, at first the second file can be written, and then — the first one.
Example 4: violating the order of file fragments to each other is not allowed.
Example 5: unused clusters should be located at the end, and in this example the unused clusters are 3, 7, 8. | 0 | [
{
"input": "7 2\n2 1 2\n3 3 4 5",
"output": "0"
},
{
"input": "7 2\n2 1 3\n3 2 4 5",
"output": "3\n2 6\n3 2\n6 3"
},
{
"input": "2 1\n1 2",
"output": "1\n2 1"
},
{
"input": "3 1\n2 3 1",
"output": "2\n1 2\n3 1"
},
{
"input": "3 2\n1 3\n1 2",
"output": "1\n3 1"... | 1,584,480,894 | 2,147,483,647 | Python 3 | OK | TESTS | 24 | 248 | 512,000 | import sys
n, m, *inp = map(int, sys.stdin.read().split())
inp.reverse()
f = [[0 for x in range(201)] for y in range(201)] #2D Array
c = [(0,0)]*201
f_size = [0]*201
def putData(f_id, s_id, c_id):
global f, c
f[f_id][s_id] = c_id
c[c_id] = (f_id, s_id)
for f_id in range(1, m+1):
f_size[f_id] = inp.pop()
for s_id in range(1, f_size[f_id]+1):
c_id = inp.pop()
putData(f_id, s_id, c_id)
e_id = c[1:].index((0,0))+1
next_id = 1
op = []
for f_id in range(1, m+1):
for s_id in range(1, f_size[f_id]+1):
if c[next_id]==(f_id, s_id):
next_id += 1
continue
if c[next_id] != (0, 0):
op.append((next_id, e_id))
putData(c[next_id][0], c[next_id][1], e_id)
e_id = f[f_id][s_id]
c[e_id] = (0,0)
op.append((e_id, next_id))
putData(f_id, s_id, next_id)
next_id += 1
print(len(op))
for p in op:
print("%d %d" % p)
| Title: Defragmentation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to *n*. The disk has *m* recorded files, the *i*-th file occupies clusters with numbers *a**i*,<=1, *a**i*,<=2, ..., *a**i*,<=*n**i*. These clusters are not necessarily located consecutively on the disk, but the order in which they are given corresponds to their sequence in the file (cluster *a**i*,<=1 contains the first fragment of the *i*-th file, cluster *a**i*,<=2 has the second fragment, etc.). Also the disc must have one or several clusters which are free from files.
You are permitted to perform operations of copying the contents of cluster number *i* to cluster number *j* (*i* and *j* must be different). Moreover, if the cluster number *j* used to keep some information, it is lost forever. Clusters are not cleaned, but after the defragmentation is complete, some of them are simply declared unusable (although they may possibly still contain some fragments of files).
Your task is to use a sequence of copy operations to ensure that each file occupies a contiguous area of memory. Each file should occupy a consecutive cluster section, the files must follow one after another from the beginning of the hard disk. After defragmentation all free (unused) clusters should be at the end of the hard disk. After defragmenting files can be placed in an arbitrary order. Clusters of each file should go consecutively from first to last. See explanatory examples in the notes.
Print the sequence of operations leading to the disk defragmentation. Note that you do not have to minimize the number of operations, but it should not exceed 2*n*.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=200) — the number of clusters and the number of files, correspondingly. Next *m* lines contain descriptions of the files. The first number in the line is *n**i* (*n**i*<=≥<=1), the number of clusters occupied by the *i*-th file. Then follow *n**i* numbers *a**i*,<=1, *a**i*,<=2, ..., *a**i*,<=*n**i* (1<=≤<=*a**i*,<=*j*<=≤<=*n*). It is guaranteed that each cluster number occurs not more than once and , that is, there exists at least one unused cluster. Numbers on each line are separated by spaces.
Output Specification:
In the first line print a single integer *k* (0<=≤<=*k*<=≤<=2*n*) — the number of operations needed to defragment the disk. Next *k* lines should contain the operations' descriptions as "*i* *j*" (copy the contents of the cluster number *i* to the cluster number *j*).
Demo Input:
['7 2\n2 1 2\n3 3 4 5\n', '7 2\n2 1 3\n3 2 4 5\n']
Demo Output:
['0\n', '3\n2 6\n3 2\n6 3\n']
Note:
Let's say that a disk consists of 8 clusters and contains two files. The first file occupies two clusters and the second file occupies three clusters. Let's look at examples of correct and incorrect positions of files after defragmentation.
Example 2: each file must occupy a contiguous area of memory.
Example 3: the order of files to each other is not important, at first the second file can be written, and then — the first one.
Example 4: violating the order of file fragments to each other is not allowed.
Example 5: unused clusters should be located at the end, and in this example the unused clusters are 3, 7, 8. | ```python
import sys
n, m, *inp = map(int, sys.stdin.read().split())
inp.reverse()
f = [[0 for x in range(201)] for y in range(201)] #2D Array
c = [(0,0)]*201
f_size = [0]*201
def putData(f_id, s_id, c_id):
global f, c
f[f_id][s_id] = c_id
c[c_id] = (f_id, s_id)
for f_id in range(1, m+1):
f_size[f_id] = inp.pop()
for s_id in range(1, f_size[f_id]+1):
c_id = inp.pop()
putData(f_id, s_id, c_id)
e_id = c[1:].index((0,0))+1
next_id = 1
op = []
for f_id in range(1, m+1):
for s_id in range(1, f_size[f_id]+1):
if c[next_id]==(f_id, s_id):
next_id += 1
continue
if c[next_id] != (0, 0):
op.append((next_id, e_id))
putData(c[next_id][0], c[next_id][1], e_id)
e_id = f[f_id][s_id]
c[e_id] = (0,0)
op.append((e_id, next_id))
putData(f_id, s_id, next_id)
next_id += 1
print(len(op))
for p in op:
print("%d %d" % p)
``` | 3 | |
952 | F | 2 + 2 != 4 | PROGRAMMING | 2,400 | [] | null | null | One very experienced problem writer decided to prepare a problem for April Fools Day contest. The task was very simple - given an arithmetic expression, return the result of evaluating this expression. However, looks like there is a bug in the reference solution... | The only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive. | Reproduce the output of the reference solution, including the bug. | [
"8-7+6-5+4-3+2-1-0\n",
"2+2\n",
"112-37\n"
] | [
"4\n",
"-46\n",
"375\n"
] | none | 0 | [
{
"input": "8-7+6-5+4-3+2-1-0",
"output": "4"
},
{
"input": "2+2",
"output": "-46"
},
{
"input": "112-37",
"output": "375"
},
{
"input": "255+255+255+255+255+255+255+255+255+255",
"output": "-42450"
},
{
"input": "0-255-255-255-255-255-255-255-255-255",
"outpu... | 1,666,681,531 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | from random import randint
n = input()
if n[0] = "8":
print(4)
elif n[0] == "2":
print(-46)
elif n[0] == "1":
print(375)
else:
print(randint(-10**6, 10**6)) | Title: 2 + 2 != 4
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One very experienced problem writer decided to prepare a problem for April Fools Day contest. The task was very simple - given an arithmetic expression, return the result of evaluating this expression. However, looks like there is a bug in the reference solution...
Input Specification:
The only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive.
Output Specification:
Reproduce the output of the reference solution, including the bug.
Demo Input:
['8-7+6-5+4-3+2-1-0\n', '2+2\n', '112-37\n']
Demo Output:
['4\n', '-46\n', '375\n']
Note:
none | ```python
from random import randint
n = input()
if n[0] = "8":
print(4)
elif n[0] == "2":
print(-46)
elif n[0] == "1":
print(375)
else:
print(randint(-10**6, 10**6))
``` | -1 | |
25 | C | Roads in Berland | PROGRAMMING | 1,900 | [
"graphs",
"shortest paths"
] | C. Roads in Berland | 2 | 256 | There are *n* cities numbered from 1 to *n* in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build *k* new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | The first line contains integer *n* (2<=≤<=*n*<=≤<=300) — amount of cities in Berland. Then there follow *n* lines with *n* integer numbers each — the matrix of shortest distances. *j*-th integer in the *i*-th row — *d**i*,<=*j*, the shortest distance between cities *i* and *j*. It is guaranteed that *d**i*,<=*i*<==<=0,<=*d**i*,<=*j*<==<=*d**j*,<=*i*, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads.
Next line contains integer *k* (1<=≤<=*k*<=≤<=300) — amount of planned roads. Following *k* lines contain the description of the planned roads. Each road is described by three space-separated integers *a**i*, *b**i*, *c**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*,<=1<=≤<=*c**i*<=≤<=1000) — *a**i* and *b**i* — pair of cities, which the road connects, *c**i* — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | Output *k* space-separated integers *q**i* (1<=≤<=*i*<=≤<=*k*). *q**i* should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to *i*. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | [
"2\n0 5\n5 0\n1\n1 2 3\n",
"3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1\n"
] | [
"3 ",
"17 12 "
] | none | 0 | [
{
"input": "2\n0 5\n5 0\n1\n1 2 3",
"output": "3 "
},
{
"input": "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1",
"output": "17 12 "
},
{
"input": "3\n0 983 173\n983 0 810\n173 810 0\n3\n3 2 567\n2 3 767\n1 2 763",
"output": "1480 1480 1480 "
},
{
"input": "4\n0 537 1064 656\n537 0... | 1,697,096,338 | 2,147,483,647 | PyPy 3-64 | TIME_LIMIT_EXCEEDED | TESTS | 6 | 2,000 | 12,185,600 | from collections import defaultdict
def dijkstra(graph, start, end):
import heapq
heap = [(0, start)] # cost from start node,end node
visited = set()
while heap:
(cost, u) = heapq.heappop(heap)
if u in visited:
continue
visited.add(u)
if u == end:
return cost
for v, c in graph[u]:
if v in visited:
continue
next_item = cost + c
heapq.heappush(heap, (next_item, v))
return -1
def main():
n = int(input())
graph = defaultdict(list)
for i in range(n):
row = list(map(int, input().split()))
for j in range(n):
graph[i].append((j, row[j]))
graph[j].append((i, row[j]))
ans = []
k = int(input())
for _ in range(k):
a,b,c = map(int, input().split())
a-=1
b-=1
graph[a].append((b, c))
graph[b].append((a, c))
tot = 0
for u in range(n):
for v in range(u):
cur = dijkstra(graph, u, v)
tot += cur
ans.append(tot)
print(*ans)
main() | Title: Roads in Berland
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
There are *n* cities numbered from 1 to *n* in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build *k* new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
Input Specification:
The first line contains integer *n* (2<=≤<=*n*<=≤<=300) — amount of cities in Berland. Then there follow *n* lines with *n* integer numbers each — the matrix of shortest distances. *j*-th integer in the *i*-th row — *d**i*,<=*j*, the shortest distance between cities *i* and *j*. It is guaranteed that *d**i*,<=*i*<==<=0,<=*d**i*,<=*j*<==<=*d**j*,<=*i*, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads.
Next line contains integer *k* (1<=≤<=*k*<=≤<=300) — amount of planned roads. Following *k* lines contain the description of the planned roads. Each road is described by three space-separated integers *a**i*, *b**i*, *c**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*,<=1<=≤<=*c**i*<=≤<=1000) — *a**i* and *b**i* — pair of cities, which the road connects, *c**i* — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
Output Specification:
Output *k* space-separated integers *q**i* (1<=≤<=*i*<=≤<=*k*). *q**i* should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to *i*. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
Demo Input:
['2\n0 5\n5 0\n1\n1 2 3\n', '3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1\n']
Demo Output:
['3 ', '17 12 ']
Note:
none | ```python
from collections import defaultdict
def dijkstra(graph, start, end):
import heapq
heap = [(0, start)] # cost from start node,end node
visited = set()
while heap:
(cost, u) = heapq.heappop(heap)
if u in visited:
continue
visited.add(u)
if u == end:
return cost
for v, c in graph[u]:
if v in visited:
continue
next_item = cost + c
heapq.heappush(heap, (next_item, v))
return -1
def main():
n = int(input())
graph = defaultdict(list)
for i in range(n):
row = list(map(int, input().split()))
for j in range(n):
graph[i].append((j, row[j]))
graph[j].append((i, row[j]))
ans = []
k = int(input())
for _ in range(k):
a,b,c = map(int, input().split())
a-=1
b-=1
graph[a].append((b, c))
graph[b].append((a, c))
tot = 0
for u in range(n):
for v in range(u):
cur = dijkstra(graph, u, v)
tot += cur
ans.append(tot)
print(*ans)
main()
``` | 0 |
715 | D | Create a Maze | PROGRAMMING | 3,100 | [
"constructive algorithms"
] | null | null | ZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of *n*<=×<=*m* rooms, and the rooms are arranged in *n* rows (numbered from the top to the bottom starting from 1) and *m* columns (numbered from the left to the right starting from 1). The room in the *i*-th row and *j*-th column is denoted by (*i*,<=*j*). A player starts in the room (1,<=1) and wants to reach the room (*n*,<=*m*).
Each room has four doors (except for ones at the maze border), one on each of its walls, and two adjacent by the wall rooms shares the same door. Some of the doors are locked, which means it is impossible to pass through the door. For example, if the door connecting (*i*,<=*j*) and (*i*,<=*j*<=+<=1) is locked, then we can't go from (*i*,<=*j*) to (*i*,<=*j*<=+<=1). Also, one can only travel between the rooms downwards (from the room (*i*,<=*j*) to the room (*i*<=+<=1,<=*j*)) or rightwards (from the room (*i*,<=*j*) to the room (*i*,<=*j*<=+<=1)) provided the corresponding door is not locked.
ZS the Coder considers a maze to have difficulty *x* if there is exactly *x* ways of travelling from the room (1,<=1) to the room (*n*,<=*m*). Two ways are considered different if they differ by the sequence of rooms visited while travelling.
Your task is to create a maze such that its difficulty is exactly equal to *T*. In addition, ZS the Coder doesn't like large mazes, so the size of the maze and the number of locked doors are limited. Sounds simple enough, right? | The first and only line of the input contains a single integer *T* (1<=≤<=*T*<=≤<=1018), the difficulty of the required maze. | The first line should contain two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=50) — the number of rows and columns of the maze respectively.
The next line should contain a single integer *k* (0<=≤<=*k*<=≤<=300) — the number of locked doors in the maze.
Then, *k* lines describing locked doors should follow. Each of them should contain four integers, *x*1,<=*y*1,<=*x*2,<=*y*2. This means that the door connecting room (*x*1,<=*y*1) and room (*x*2,<=*y*2) is locked. Note that room (*x*2,<=*y*2) should be adjacent either to the right or to the bottom of (*x*1,<=*y*1), i.e. *x*2<=+<=*y*2 should be equal to *x*1<=+<=*y*1<=+<=1. There should not be a locked door that appears twice in the list.
It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them. | [
"3\n",
"4\n"
] | [
"3 2\n0\n",
"4 3\n3\n1 2 2 2\n3 2 3 3\n1 3 2 3"
] | Here are how the sample input and output looks like. The colored arrows denotes all the possible paths while a red cross denotes a locked door.
In the first sample case:
In the second sample case: | 2,500 | [
{
"input": "3",
"output": "4 4\n5\n1 2 2 2\n1 3 2 3\n1 4 2 4\n2 1 2 2\n4 1 4 2"
},
{
"input": "4",
"output": "4 4\n4\n1 2 2 2\n1 3 2 3\n2 1 2 2\n4 1 4 2"
},
{
"input": "576460752303423488",
"output": "48 48\n233\n1 2 2 2\n1 3 2 3\n2 1 2 2\n2 4 2 5\n2 6 3 6\n2 7 3 7\n3 4 3 5\n3 5 4 5\... | 1,653,312,338 | 2,147,483,647 | PyPy 3 | OK | TESTS | 164 | 93 | 2,457,600 | corr = lambda x, y: 1 <= x <= n and 1 <= y <= m
T = int(input())
a = []
while T:
a.append(T % 6)
T //= 6
L = len(a)
n = m = L * 2 + 2
ans = [(1, 2, 2, 2), (2, 1, 2, 2)]
f = [[1] * 9 for i in range(7)]
f[1][2] = f[2][2] = f[2][6] = f[3][5] = 0
f[4][5] = f[4][6] = f[5][2] = f[5][5] = f[5][6] = 0
p = [0] * 9
p[1] = 3, 1, 3, 2
p[2] = 4, 1, 4, 2
p[3] = 4, 2, 5, 2
p[4] = 4, 3, 5, 3
p[5] = 1, 3, 2, 3
p[6] = 1, 4, 2, 4
p[7] = 2, 4, 2, 5
p[8] = 3, 4, 3, 5
for i in range(L):
bit = a[L - i - 1]
for j in range(1, 9):
if not f[bit][j]: continue
x1, y1, x2, y2 = p[j]; D = 2 * i
x1 += D; y1 += D; x2 += D; y2 += D
if corr(x2, y2): ans.append((x1, y1, x2, y2))
for i in range(L - 1):
x1, y1 = 5 + i * 2, 1 + i * 2
x2, y2 = 1 + i * 2, 5 + i * 2
ans.append((x1, y1, x1 + 1, y1))
ans.append((x1, y1 + 1, x1 + 1, y1 + 1))
ans.append((x2, y2, x2, y2 + 1))
ans.append((x2 + 1, y2, x2 + 1, y2 + 1))
print(n, m)
print(len(ans))
[print(*i) for i in ans]
| Title: Create a Maze
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
ZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of *n*<=×<=*m* rooms, and the rooms are arranged in *n* rows (numbered from the top to the bottom starting from 1) and *m* columns (numbered from the left to the right starting from 1). The room in the *i*-th row and *j*-th column is denoted by (*i*,<=*j*). A player starts in the room (1,<=1) and wants to reach the room (*n*,<=*m*).
Each room has four doors (except for ones at the maze border), one on each of its walls, and two adjacent by the wall rooms shares the same door. Some of the doors are locked, which means it is impossible to pass through the door. For example, if the door connecting (*i*,<=*j*) and (*i*,<=*j*<=+<=1) is locked, then we can't go from (*i*,<=*j*) to (*i*,<=*j*<=+<=1). Also, one can only travel between the rooms downwards (from the room (*i*,<=*j*) to the room (*i*<=+<=1,<=*j*)) or rightwards (from the room (*i*,<=*j*) to the room (*i*,<=*j*<=+<=1)) provided the corresponding door is not locked.
ZS the Coder considers a maze to have difficulty *x* if there is exactly *x* ways of travelling from the room (1,<=1) to the room (*n*,<=*m*). Two ways are considered different if they differ by the sequence of rooms visited while travelling.
Your task is to create a maze such that its difficulty is exactly equal to *T*. In addition, ZS the Coder doesn't like large mazes, so the size of the maze and the number of locked doors are limited. Sounds simple enough, right?
Input Specification:
The first and only line of the input contains a single integer *T* (1<=≤<=*T*<=≤<=1018), the difficulty of the required maze.
Output Specification:
The first line should contain two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=50) — the number of rows and columns of the maze respectively.
The next line should contain a single integer *k* (0<=≤<=*k*<=≤<=300) — the number of locked doors in the maze.
Then, *k* lines describing locked doors should follow. Each of them should contain four integers, *x*1,<=*y*1,<=*x*2,<=*y*2. This means that the door connecting room (*x*1,<=*y*1) and room (*x*2,<=*y*2) is locked. Note that room (*x*2,<=*y*2) should be adjacent either to the right or to the bottom of (*x*1,<=*y*1), i.e. *x*2<=+<=*y*2 should be equal to *x*1<=+<=*y*1<=+<=1. There should not be a locked door that appears twice in the list.
It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them.
Demo Input:
['3\n', '4\n']
Demo Output:
['3 2\n0\n', '4 3\n3\n1 2 2 2\n3 2 3 3\n1 3 2 3']
Note:
Here are how the sample input and output looks like. The colored arrows denotes all the possible paths while a red cross denotes a locked door.
In the first sample case:
In the second sample case: | ```python
corr = lambda x, y: 1 <= x <= n and 1 <= y <= m
T = int(input())
a = []
while T:
a.append(T % 6)
T //= 6
L = len(a)
n = m = L * 2 + 2
ans = [(1, 2, 2, 2), (2, 1, 2, 2)]
f = [[1] * 9 for i in range(7)]
f[1][2] = f[2][2] = f[2][6] = f[3][5] = 0
f[4][5] = f[4][6] = f[5][2] = f[5][5] = f[5][6] = 0
p = [0] * 9
p[1] = 3, 1, 3, 2
p[2] = 4, 1, 4, 2
p[3] = 4, 2, 5, 2
p[4] = 4, 3, 5, 3
p[5] = 1, 3, 2, 3
p[6] = 1, 4, 2, 4
p[7] = 2, 4, 2, 5
p[8] = 3, 4, 3, 5
for i in range(L):
bit = a[L - i - 1]
for j in range(1, 9):
if not f[bit][j]: continue
x1, y1, x2, y2 = p[j]; D = 2 * i
x1 += D; y1 += D; x2 += D; y2 += D
if corr(x2, y2): ans.append((x1, y1, x2, y2))
for i in range(L - 1):
x1, y1 = 5 + i * 2, 1 + i * 2
x2, y2 = 1 + i * 2, 5 + i * 2
ans.append((x1, y1, x1 + 1, y1))
ans.append((x1, y1 + 1, x1 + 1, y1 + 1))
ans.append((x2, y2, x2, y2 + 1))
ans.append((x2 + 1, y2, x2 + 1, y2 + 1))
print(n, m)
print(len(ans))
[print(*i) for i in ans]
``` | 3 | |
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,601,870,017 | 2,147,483,647 | Python 3 | OK | TESTS | 40 | 109 | 0 | li = ['h','e','l','l','o']
str = input()
i=0
for j in range(0,len(str)):
if(str[j] == li[i]):
i=i+1
if(i==len(li)):
break;
if(i>=5):
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
li = ['h','e','l','l','o']
str = input()
i=0
for j in range(0,len(str)):
if(str[j] == li[i]):
i=i+1
if(i==len(li)):
break;
if(i>=5):
print('YES')
else:
print('NO')
``` | 3.9455 |
124 | A | The number of positions | PROGRAMMING | 1,000 | [
"math"
] | null | null | Petr stands in line of *n* people, but he doesn't know exactly which position he occupies. He can say that there are no less than *a* people standing in front of him and no more than *b* people standing behind him. Find the number of different positions Petr can occupy. | The only line contains three integers *n*, *a* and *b* (0<=≤<=*a*,<=*b*<=<<=*n*<=≤<=100). | Print the single number — the number of the sought positions. | [
"3 1 1\n",
"5 2 3\n"
] | [
"2\n",
"3\n"
] | The possible positions in the first sample are: 2 and 3 (if we number the positions starting with 1).
In the second sample they are 3, 4 and 5. | 500 | [
{
"input": "3 1 1",
"output": "2"
},
{
"input": "5 2 3",
"output": "3"
},
{
"input": "5 4 0",
"output": "1"
},
{
"input": "6 5 5",
"output": "1"
},
{
"input": "9 4 3",
"output": "4"
},
{
"input": "11 4 6",
"output": "7"
},
{
"input": "13 8 ... | 1,685,643,367 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 60 | 0 | n, x, y = map(int, input().split())
possible_spots = max(n - x, y)
print(possible_spots)
| Title: The number of positions
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petr stands in line of *n* people, but he doesn't know exactly which position he occupies. He can say that there are no less than *a* people standing in front of him and no more than *b* people standing behind him. Find the number of different positions Petr can occupy.
Input Specification:
The only line contains three integers *n*, *a* and *b* (0<=≤<=*a*,<=*b*<=<<=*n*<=≤<=100).
Output Specification:
Print the single number — the number of the sought positions.
Demo Input:
['3 1 1\n', '5 2 3\n']
Demo Output:
['2\n', '3\n']
Note:
The possible positions in the first sample are: 2 and 3 (if we number the positions starting with 1).
In the second sample they are 3, 4 and 5. | ```python
n, x, y = map(int, input().split())
possible_spots = max(n - x, y)
print(possible_spots)
``` | 0 | |
735 | A | Ostap and Grasshopper | PROGRAMMING | 800 | [
"implementation",
"strings"
] | null | null | On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length *n* such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect.
Ostap knows that grasshopper is able to jump to any empty cell that is exactly *k* cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if *k*<==<=1 the grasshopper can jump to a neighboring cell only, and if *k*<==<=2 the grasshopper can jump over a single cell.
Your goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect. | The first line of the input contains two integers *n* and *k* (2<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=*n*<=-<=1) — the number of cells in the line and the length of one grasshopper's jump.
The second line contains a string of length *n* consisting of characters '.', '#', 'G' and 'T'. Character '.' means that the corresponding cell is empty, character '#' means that the corresponding cell contains an obstacle and grasshopper can't jump there. Character 'G' means that the grasshopper starts at this position and, finally, 'T' means that the target insect is located at this cell. It's guaranteed that characters 'G' and 'T' appear in this line exactly once. | If there exists a sequence of jumps (each jump of length *k*), such that the grasshopper can get from his initial position to the cell with the insect, print "YES" (without quotes) in the only line of the input. Otherwise, print "NO" (without quotes). | [
"5 2\n#G#T#\n",
"6 1\nT....G\n",
"7 3\nT..#..G\n",
"6 2\n..GT..\n"
] | [
"YES\n",
"YES\n",
"NO\n",
"NO\n"
] | In the first sample, the grasshopper can make one jump to the right in order to get from cell 2 to cell 4.
In the second sample, the grasshopper is only able to jump to neighboring cells but the way to the insect is free — he can get there by jumping left 5 times.
In the third sample, the grasshopper can't make a single jump.
In the fourth sample, the grasshopper can only jump to the cells with odd indices, thus he won't be able to reach the insect. | 500 | [
{
"input": "5 2\n#G#T#",
"output": "YES"
},
{
"input": "6 1\nT....G",
"output": "YES"
},
{
"input": "7 3\nT..#..G",
"output": "NO"
},
{
"input": "6 2\n..GT..",
"output": "NO"
},
{
"input": "2 1\nGT",
"output": "YES"
},
{
"input": "100 5\nG####.####.###... | 1,556,849,174 | 374 | Python 3 | RUNTIME_ERROR | TESTS | 11 | 108 | 0 | n, k = map(int, input().split())
s = input()
G, T = -1, -1
for i in range(n):
if s[i] == 'G':
G = i
elif s[i] == 'T':
T = i
if G < T:
while G < T and s[G] != '#':
G += k
if s[G] == 'T':
print('YES')
exit()
print('NO')
else:
while G > T and s[G] != '#':
G -= k
if s[G] == 'T':
print('YES')
exit()
print('NO')
| Title: Ostap and Grasshopper
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length *n* such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect.
Ostap knows that grasshopper is able to jump to any empty cell that is exactly *k* cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if *k*<==<=1 the grasshopper can jump to a neighboring cell only, and if *k*<==<=2 the grasshopper can jump over a single cell.
Your goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect.
Input Specification:
The first line of the input contains two integers *n* and *k* (2<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=*n*<=-<=1) — the number of cells in the line and the length of one grasshopper's jump.
The second line contains a string of length *n* consisting of characters '.', '#', 'G' and 'T'. Character '.' means that the corresponding cell is empty, character '#' means that the corresponding cell contains an obstacle and grasshopper can't jump there. Character 'G' means that the grasshopper starts at this position and, finally, 'T' means that the target insect is located at this cell. It's guaranteed that characters 'G' and 'T' appear in this line exactly once.
Output Specification:
If there exists a sequence of jumps (each jump of length *k*), such that the grasshopper can get from his initial position to the cell with the insect, print "YES" (without quotes) in the only line of the input. Otherwise, print "NO" (without quotes).
Demo Input:
['5 2\n#G#T#\n', '6 1\nT....G\n', '7 3\nT..#..G\n', '6 2\n..GT..\n']
Demo Output:
['YES\n', 'YES\n', 'NO\n', 'NO\n']
Note:
In the first sample, the grasshopper can make one jump to the right in order to get from cell 2 to cell 4.
In the second sample, the grasshopper is only able to jump to neighboring cells but the way to the insect is free — he can get there by jumping left 5 times.
In the third sample, the grasshopper can't make a single jump.
In the fourth sample, the grasshopper can only jump to the cells with odd indices, thus he won't be able to reach the insect. | ```python
n, k = map(int, input().split())
s = input()
G, T = -1, -1
for i in range(n):
if s[i] == 'G':
G = i
elif s[i] == 'T':
T = i
if G < T:
while G < T and s[G] != '#':
G += k
if s[G] == 'T':
print('YES')
exit()
print('NO')
else:
while G > T and s[G] != '#':
G -= k
if s[G] == 'T':
print('YES')
exit()
print('NO')
``` | -1 | |
25 | A | IQ test | PROGRAMMING | 1,300 | [
"brute force"
] | A. IQ test | 2 | 256 | Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness. | The first line contains integer *n* (3<=≤<=*n*<=≤<=100) — amount of numbers in the task. The second line contains *n* space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness. | Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order. | [
"5\n2 4 7 8 10\n",
"4\n1 2 1 1\n"
] | [
"3\n",
"2\n"
] | none | 0 | [
{
"input": "5\n2 4 7 8 10",
"output": "3"
},
{
"input": "4\n1 2 1 1",
"output": "2"
},
{
"input": "3\n1 2 2",
"output": "1"
},
{
"input": "3\n100 99 100",
"output": "2"
},
{
"input": "3\n5 3 2",
"output": "3"
},
{
"input": "4\n43 28 1 91",
"output"... | 1,618,547,461 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 92 | 0 | n=int(input())
l=list(map(int,input().split()))
e,o=0,0
e_i,o_i=0,0
for i in range(n):
if l[i]%2==0:
e+=1
e_i=i
if l[i]%2==1:
o+=1
o_i=i
if e>1 and o==1:
print(l[o_i])
break
if o>1 and e==1:
print(l[e_i])
break | Title: IQ test
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
Input Specification:
The first line contains integer *n* (3<=≤<=*n*<=≤<=100) — amount of numbers in the task. The second line contains *n* space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.
Output Specification:
Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.
Demo Input:
['5\n2 4 7 8 10\n', '4\n1 2 1 1\n']
Demo Output:
['3\n', '2\n']
Note:
none | ```python
n=int(input())
l=list(map(int,input().split()))
e,o=0,0
e_i,o_i=0,0
for i in range(n):
if l[i]%2==0:
e+=1
e_i=i
if l[i]%2==1:
o+=1
o_i=i
if e>1 and o==1:
print(l[o_i])
break
if o>1 and e==1:
print(l[e_i])
break
``` | 0 |
525 | A | Vitaliy and Pie | PROGRAMMING | 1,100 | [
"greedy",
"hashing",
"strings"
] | null | null | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1.
The potato pie is located in the *n*-th room and Vitaly needs to go there.
Each pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key.
In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F.
Each of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.
Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*.
Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | The first line of the input contains a positive integer *n* (2<=≤<=*n*<=≤<=105) — the number of rooms in the house.
The second line of the input contains string *s* of length 2·*n*<=-<=2. Let's number the elements of the string from left to right, starting from one.
The odd positions in the given string *s* contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position *i* of the given string *s* contains a lowercase Latin letter — the type of the key that lies in room number (*i*<=+<=1)<=/<=2.
The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position *i* of the given string *s* contains an uppercase letter — the type of the door that leads from room *i*<=/<=2 to room *i*<=/<=2<=+<=1. | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room *n*. | [
"3\naAbB\n",
"4\naBaCaB\n",
"5\nxYyXzZaZ\n"
] | [
"0\n",
"3\n",
"2\n"
] | none | 250 | [
{
"input": "3\naAbB",
"output": "0"
},
{
"input": "4\naBaCaB",
"output": "3"
},
{
"input": "5\nxYyXzZaZ",
"output": "2"
},
{
"input": "26\naAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyY",
"output": "0"
},
{
"input": "26\nzAyBxCwDvEuFtGsHrIqJpKoLnMmNlOkPjQiRhSg... | 1,685,625,248 | 2,147,483,647 | Python 3 | OK | TESTS | 46 | 140 | 409,600 | n = int(input())
s = input()
d = {}
lt = 'qwertyuiopasdfghjklmnbvcxz'
for l in lt:
d[l] = 0
cnt = 0
for i in s:
if i.islower():
d[i] += 1
else:
if d[i.lower()] <= 0:
cnt += 1
else:
d[i.lower()] -= 1
print(cnt)
| Title: Vitaliy and Pie
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1.
The potato pie is located in the *n*-th room and Vitaly needs to go there.
Each pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key.
In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F.
Each of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.
Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*.
Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
Input Specification:
The first line of the input contains a positive integer *n* (2<=≤<=*n*<=≤<=105) — the number of rooms in the house.
The second line of the input contains string *s* of length 2·*n*<=-<=2. Let's number the elements of the string from left to right, starting from one.
The odd positions in the given string *s* contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position *i* of the given string *s* contains a lowercase Latin letter — the type of the key that lies in room number (*i*<=+<=1)<=/<=2.
The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position *i* of the given string *s* contains an uppercase letter — the type of the door that leads from room *i*<=/<=2 to room *i*<=/<=2<=+<=1.
Output Specification:
Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room *n*.
Demo Input:
['3\naAbB\n', '4\naBaCaB\n', '5\nxYyXzZaZ\n']
Demo Output:
['0\n', '3\n', '2\n']
Note:
none | ```python
n = int(input())
s = input()
d = {}
lt = 'qwertyuiopasdfghjklmnbvcxz'
for l in lt:
d[l] = 0
cnt = 0
for i in s:
if i.islower():
d[i] += 1
else:
if d[i.lower()] <= 0:
cnt += 1
else:
d[i.lower()] -= 1
print(cnt)
``` | 3 | |
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,696,927,014 | 2,147,483,647 | PyPy 3-64 | RUNTIME_ERROR | TESTS | 0 | 122 | 2,867,200 | t=int(input())
for i in range(0,t):
n=map(int,input().split())
for j in n:
count=0
for w in range(1,j+1):
if(j%w==0):
count=count+1
if(count==3):
print("YES")
else:
print("NO") | 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
t=int(input())
for i in range(0,t):
n=map(int,input().split())
for j in n:
count=0
for w in range(1,j+1):
if(j%w==0):
count=count+1
if(count==3):
print("YES")
else:
print("NO")
``` | -1 | |
152 | A | Marks | PROGRAMMING | 900 | [
"implementation"
] | null | null | Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.
Overall the group has *n* students. They received marks for *m* subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.
Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.
Your task is to find the number of successful students in the group. | The first input line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the number of students and the number of subjects, correspondingly. Next *n* lines each containing *m* characters describe the gradebook. Each character in the gradebook is a number from 1 to 9. Note that the marks in a rows are not sepatated by spaces. | Print the single number — the number of successful students in the given group. | [
"3 3\n223\n232\n112\n",
"3 5\n91728\n11828\n11111\n"
] | [
"2\n",
"3\n"
] | In the first sample test the student number 1 is the best at subjects 1 and 3, student 2 is the best at subjects 1 and 2, but student 3 isn't the best at any subject.
In the second sample test each student is the best at at least one subject. | 500 | [
{
"input": "3 3\n223\n232\n112",
"output": "2"
},
{
"input": "3 5\n91728\n11828\n11111",
"output": "3"
},
{
"input": "2 2\n48\n27",
"output": "1"
},
{
"input": "2 1\n4\n6",
"output": "1"
},
{
"input": "1 2\n57",
"output": "1"
},
{
"input": "1 1\n5",
... | 1,446,896,860 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 46 | 0 | import operator
n,m = list(map(int,input().split(" ")))
s = []
r = [0 for d in range(n)]
for i in range(n):
s.append(list(map(int,[d for d in input()])))
for i in range(m):
g = [d[i] for d in s]
max_index = max(enumerate(g), key=operator.itemgetter(1))[0]
r[max_index] = 1
print(n-r.count(0))
| Title: Marks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.
Overall the group has *n* students. They received marks for *m* subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.
Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.
Your task is to find the number of successful students in the group.
Input Specification:
The first input line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the number of students and the number of subjects, correspondingly. Next *n* lines each containing *m* characters describe the gradebook. Each character in the gradebook is a number from 1 to 9. Note that the marks in a rows are not sepatated by spaces.
Output Specification:
Print the single number — the number of successful students in the given group.
Demo Input:
['3 3\n223\n232\n112\n', '3 5\n91728\n11828\n11111\n']
Demo Output:
['2\n', '3\n']
Note:
In the first sample test the student number 1 is the best at subjects 1 and 3, student 2 is the best at subjects 1 and 2, but student 3 isn't the best at any subject.
In the second sample test each student is the best at at least one subject. | ```python
import operator
n,m = list(map(int,input().split(" ")))
s = []
r = [0 for d in range(n)]
for i in range(n):
s.append(list(map(int,[d for d in input()])))
for i in range(m):
g = [d[i] for d in s]
max_index = max(enumerate(g), key=operator.itemgetter(1))[0]
r[max_index] = 1
print(n-r.count(0))
``` | 0 | |
1,003 | A | Polycarp's Pockets | PROGRAMMING | 800 | [
"implementation"
] | null | null | Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins into two pockets as follows: $[1, 2, 3], [2, 3, 4]$.
Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that. | The first line of the input contains one integer $n$ ($1 \le n \le 100$) — the number of coins.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$) — values of coins. | Print only one integer — the minimum number of pockets Polycarp needs to distribute all the coins so no two coins with the same value are put into the same pocket. | [
"6\n1 2 4 3 3 2\n",
"1\n100\n"
] | [
"2\n",
"1\n"
] | none | 0 | [
{
"input": "6\n1 2 4 3 3 2",
"output": "2"
},
{
"input": "1\n100",
"output": "1"
},
{
"input": "100\n100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100... | 1,599,199,869 | 2,147,483,647 | PyPy 3 | OK | TESTS | 37 | 140 | 0 | n=int(input())
l=input().split()
li=[int(i) for i in l]
maxa=0
hashi=dict()
for i in li:
if i in hashi:
hashi[i]+=1
else:
hashi[i]=1
for i in hashi:
maxa=max(maxa,hashi[i])
print(maxa)
| Title: Polycarp's Pockets
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins into two pockets as follows: $[1, 2, 3], [2, 3, 4]$.
Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that.
Input Specification:
The first line of the input contains one integer $n$ ($1 \le n \le 100$) — the number of coins.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$) — values of coins.
Output Specification:
Print only one integer — the minimum number of pockets Polycarp needs to distribute all the coins so no two coins with the same value are put into the same pocket.
Demo Input:
['6\n1 2 4 3 3 2\n', '1\n100\n']
Demo Output:
['2\n', '1\n']
Note:
none | ```python
n=int(input())
l=input().split()
li=[int(i) for i in l]
maxa=0
hashi=dict()
for i in li:
if i in hashi:
hashi[i]+=1
else:
hashi[i]=1
for i in hashi:
maxa=max(maxa,hashi[i])
print(maxa)
``` | 3 | |
146 | A | Lucky Ticket | PROGRAMMING | 800 | [
"implementation"
] | null | null | Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals *n* (*n* is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first *n*<=/<=2 digits) equals the sum of digits in the second half (the sum of the last *n*<=/<=2 digits). Check if the given ticket is lucky. | The first line contains an even integer *n* (2<=≤<=*n*<=≤<=50) — the length of the ticket number that needs to be checked. The second line contains an integer whose length equals exactly *n* — the ticket number. The number may contain leading zeros. | On the first line print "YES" if the given ticket number is lucky. Otherwise, print "NO" (without the quotes). | [
"2\n47\n",
"4\n4738\n",
"4\n4774\n"
] | [
"NO\n",
"NO\n",
"YES\n"
] | In the first sample the sum of digits in the first half does not equal the sum of digits in the second half (4 ≠ 7).
In the second sample the ticket number is not the lucky number. | 500 | [
{
"input": "2\n47",
"output": "NO"
},
{
"input": "4\n4738",
"output": "NO"
},
{
"input": "4\n4774",
"output": "YES"
},
{
"input": "4\n4570",
"output": "NO"
},
{
"input": "6\n477477",
"output": "YES"
},
{
"input": "6\n777777",
"output": "YES"
},
... | 1,587,410,500 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 5 | 280 | 0 | n = int(input())
s = input()
print('NYOE S'[sum(int(i) for i in s[:n // 2]) == sum(int(i) for i in s[n // 2:]) and set(s) == {'4', '7'} :: 2]) | Title: Lucky Ticket
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals *n* (*n* is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first *n*<=/<=2 digits) equals the sum of digits in the second half (the sum of the last *n*<=/<=2 digits). Check if the given ticket is lucky.
Input Specification:
The first line contains an even integer *n* (2<=≤<=*n*<=≤<=50) — the length of the ticket number that needs to be checked. The second line contains an integer whose length equals exactly *n* — the ticket number. The number may contain leading zeros.
Output Specification:
On the first line print "YES" if the given ticket number is lucky. Otherwise, print "NO" (without the quotes).
Demo Input:
['2\n47\n', '4\n4738\n', '4\n4774\n']
Demo Output:
['NO\n', 'NO\n', 'YES\n']
Note:
In the first sample the sum of digits in the first half does not equal the sum of digits in the second half (4 ≠ 7).
In the second sample the ticket number is not the lucky number. | ```python
n = int(input())
s = input()
print('NYOE S'[sum(int(i) for i in s[:n // 2]) == sum(int(i) for i in s[n // 2:]) and set(s) == {'4', '7'} :: 2])
``` | 0 | |
294 | B | Shaass and Bookshelf | PROGRAMMING | 1,700 | [
"dp",
"greedy"
] | null | null | Shaass has *n* books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the *i*-th book is *t**i* and its pages' width is equal to *w**i*. The thickness of each book is either 1 or 2. All books have the same page heights.
Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure.
Help Shaass to find the minimum total thickness of the vertical books that we can achieve. | The first line of the input contains an integer *n*, (1<=≤<=*n*<=≤<=100). Each of the next *n* lines contains two integers *t**i* and *w**i* denoting the thickness and width of the *i*-th book correspondingly, (1<=≤<=*t**i*<=≤<=2,<=1<=≤<=*w**i*<=≤<=100). | On the only line of the output print the minimum total thickness of the vertical books that we can achieve. | [
"5\n1 12\n1 3\n2 15\n2 5\n2 1\n",
"3\n1 10\n2 1\n2 4\n"
] | [
"5\n",
"3\n"
] | none | 1,000 | [
{
"input": "5\n1 12\n1 3\n2 15\n2 5\n2 1",
"output": "5"
},
{
"input": "3\n1 10\n2 1\n2 4",
"output": "3"
},
{
"input": "10\n2 10\n2 4\n2 8\n2 3\n2 5\n2 6\n1 2\n1 10\n1 10\n2 5",
"output": "12"
},
{
"input": "1\n2 7",
"output": "2"
},
{
"input": "50\n1 24\n1 16\n1... | 1,661,278,359 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 11 | 93 | 10,956,800 | import sys
import math
import collections
from heapq import heappush, heappop
from functools import reduce
input = sys.stdin.readline
ints = lambda: list(map(int, input().split()))
n = int(input())
b = []
mx = 0
for _ in range(n):
t, w = ints()
mx += w
b.append((t, w))
dp = [[math.inf for _ in range(mx + 1)] for _ in range(n + 1)]
dp[0][0] = 0
for i in range(n):
for j in range(mx + 1):
if dp[i][j] != math.inf:
dp[i + 1][j] = min(dp[i + 1][j], b[i][0] + dp[i][j])
dp[i + 1][j + b[i][1]] = min(dp[i + 1][j + b[i][1]], dp[i][j])
ans = math.inf
for i in range(mx + 1):
if i <= dp[-1][i]:
ans = min(ans, dp[-1][i])
print(ans)
| Title: Shaass and Bookshelf
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Shaass has *n* books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the *i*-th book is *t**i* and its pages' width is equal to *w**i*. The thickness of each book is either 1 or 2. All books have the same page heights.
Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure.
Help Shaass to find the minimum total thickness of the vertical books that we can achieve.
Input Specification:
The first line of the input contains an integer *n*, (1<=≤<=*n*<=≤<=100). Each of the next *n* lines contains two integers *t**i* and *w**i* denoting the thickness and width of the *i*-th book correspondingly, (1<=≤<=*t**i*<=≤<=2,<=1<=≤<=*w**i*<=≤<=100).
Output Specification:
On the only line of the output print the minimum total thickness of the vertical books that we can achieve.
Demo Input:
['5\n1 12\n1 3\n2 15\n2 5\n2 1\n', '3\n1 10\n2 1\n2 4\n']
Demo Output:
['5\n', '3\n']
Note:
none | ```python
import sys
import math
import collections
from heapq import heappush, heappop
from functools import reduce
input = sys.stdin.readline
ints = lambda: list(map(int, input().split()))
n = int(input())
b = []
mx = 0
for _ in range(n):
t, w = ints()
mx += w
b.append((t, w))
dp = [[math.inf for _ in range(mx + 1)] for _ in range(n + 1)]
dp[0][0] = 0
for i in range(n):
for j in range(mx + 1):
if dp[i][j] != math.inf:
dp[i + 1][j] = min(dp[i + 1][j], b[i][0] + dp[i][j])
dp[i + 1][j + b[i][1]] = min(dp[i + 1][j + b[i][1]], dp[i][j])
ans = math.inf
for i in range(mx + 1):
if i <= dp[-1][i]:
ans = min(ans, dp[-1][i])
print(ans)
``` | 0 | |
896 | A | Nephren gives a riddle | PROGRAMMING | 1,700 | [
"binary search",
"dfs and similar"
] | null | null |
Nephren is playing a game with little leprechauns.
She gives them an infinite array of strings, *f*0... ∞.
*f*0 is "What are you doing at the end of the world? Are you busy? Will you save us?".
She wants to let more people know about it, so she defines *f**i*<==<= "What are you doing while sending "*f**i*<=-<=1"? Are you busy? Will you send "*f**i*<=-<=1"?" for all *i*<=≥<=1.
For example, *f*1 is
"What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of *f*1.
It can be seen that the characters in *f**i* are letters, question marks, (possibly) quotation marks and spaces.
Nephren will ask the little leprechauns *q* times. Each time she will let them find the *k*-th character of *f**n*. The characters are indexed starting from 1. If *f**n* consists of less than *k* characters, output '.' (without quotes).
Can you answer her queries? | The first line contains one integer *q* (1<=≤<=*q*<=≤<=10) — the number of Nephren's questions.
Each of the next *q* lines describes Nephren's question and contains two integers *n* and *k* (0<=≤<=*n*<=≤<=105,<=1<=≤<=*k*<=≤<=1018). | One line containing *q* characters. The *i*-th character in it should be the answer for the *i*-th query. | [
"3\n1 1\n1 2\n1 111111111111\n",
"5\n0 69\n1 194\n1 139\n0 47\n1 66\n",
"10\n4 1825\n3 75\n3 530\n4 1829\n4 1651\n3 187\n4 584\n4 255\n4 774\n2 474\n"
] | [
"Wh.",
"abdef",
"Areyoubusy"
] | For the first two examples, refer to *f*<sub class="lower-index">0</sub> and *f*<sub class="lower-index">1</sub> given in the legend. | 500 | [
{
"input": "3\n1 1\n1 2\n1 111111111111",
"output": "Wh."
},
{
"input": "5\n0 69\n1 194\n1 139\n0 47\n1 66",
"output": "abdef"
},
{
"input": "10\n4 1825\n3 75\n3 530\n4 1829\n4 1651\n3 187\n4 584\n4 255\n4 774\n2 474",
"output": "Areyoubusy"
},
{
"input": "1\n0 1",
"outpu... | 1,662,622,532 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 31 | 102,400 | from functools import cache
import sys
sys.setrecursionlimit(100004)
input=sys.stdin.readline
if __name__=='__main__':
s0="What are you doing at the end of the world? Are you busy? Will you save us?"
# print(len(s0))
head='What are you doing while sending "'
# print(len(head))
mid='"? Are you busy? Will you send "'
# print(len(mid))
tail='"?'
# print(len(tail))
@cache
def length(n):
return 75 if n==0 else length(n-1)+34+32+2
def found(n,k):
if n==0:
return s0[k] if k<=75 else '.'
pre,now=length(n-1),length(n)
s1,s2,s3,s4=34,34+pre,34+pre+32,34+pre+32+pre
# print(s1,s2,s3,s4)
if k<s1:
return head[k]
elif s1<=k<s2:
return found(n-1,k-s1)
elif s2<=k<s3:
return mid[k-s2]
elif s3<=k<s4:
return found(n-1,k-s3)
elif s4<=k<now:
return tail[k-s4]
else:
return '.'
t=int(input())
for _ in range(t):
n,k=map(int,input().split())
print(found(n,k-1),end='')
| Title: Nephren gives a riddle
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Nephren is playing a game with little leprechauns.
She gives them an infinite array of strings, *f*0... ∞.
*f*0 is "What are you doing at the end of the world? Are you busy? Will you save us?".
She wants to let more people know about it, so she defines *f**i*<==<= "What are you doing while sending "*f**i*<=-<=1"? Are you busy? Will you send "*f**i*<=-<=1"?" for all *i*<=≥<=1.
For example, *f*1 is
"What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of *f*1.
It can be seen that the characters in *f**i* are letters, question marks, (possibly) quotation marks and spaces.
Nephren will ask the little leprechauns *q* times. Each time she will let them find the *k*-th character of *f**n*. The characters are indexed starting from 1. If *f**n* consists of less than *k* characters, output '.' (without quotes).
Can you answer her queries?
Input Specification:
The first line contains one integer *q* (1<=≤<=*q*<=≤<=10) — the number of Nephren's questions.
Each of the next *q* lines describes Nephren's question and contains two integers *n* and *k* (0<=≤<=*n*<=≤<=105,<=1<=≤<=*k*<=≤<=1018).
Output Specification:
One line containing *q* characters. The *i*-th character in it should be the answer for the *i*-th query.
Demo Input:
['3\n1 1\n1 2\n1 111111111111\n', '5\n0 69\n1 194\n1 139\n0 47\n1 66\n', '10\n4 1825\n3 75\n3 530\n4 1829\n4 1651\n3 187\n4 584\n4 255\n4 774\n2 474\n']
Demo Output:
['Wh.', 'abdef', 'Areyoubusy']
Note:
For the first two examples, refer to *f*<sub class="lower-index">0</sub> and *f*<sub class="lower-index">1</sub> given in the legend. | ```python
from functools import cache
import sys
sys.setrecursionlimit(100004)
input=sys.stdin.readline
if __name__=='__main__':
s0="What are you doing at the end of the world? Are you busy? Will you save us?"
# print(len(s0))
head='What are you doing while sending "'
# print(len(head))
mid='"? Are you busy? Will you send "'
# print(len(mid))
tail='"?'
# print(len(tail))
@cache
def length(n):
return 75 if n==0 else length(n-1)+34+32+2
def found(n,k):
if n==0:
return s0[k] if k<=75 else '.'
pre,now=length(n-1),length(n)
s1,s2,s3,s4=34,34+pre,34+pre+32,34+pre+32+pre
# print(s1,s2,s3,s4)
if k<s1:
return head[k]
elif s1<=k<s2:
return found(n-1,k-s1)
elif s2<=k<s3:
return mid[k-s2]
elif s3<=k<s4:
return found(n-1,k-s3)
elif s4<=k<now:
return tail[k-s4]
else:
return '.'
t=int(input())
for _ in range(t):
n,k=map(int,input().split())
print(found(n,k-1),end='')
``` | -1 | |
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,687,443,780 | 1,080 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 31 | 0 | n , l = map(int , input().split())
arr = sorted( map( int, input().split() ) )
min_d = max( arr[0] , l - arr[-1] )
dist = [ min_d ]
for i in range(l-1):
a, b = arr[i] , arr[i+1]
mid = (a+b)/2 -a
if mid > min_d :
dist.append( mid )
dist = sorted( dist )
for d in dist:
is_true = True
for i in range(l-1):
a, b = arr[i] , arr[i+1]
mid = (a+b)/2 -a
if mid > d:
is_true = False
break
if is_true:
print(d)
break
| 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 , l = map(int , input().split())
arr = sorted( map( int, input().split() ) )
min_d = max( arr[0] , l - arr[-1] )
dist = [ min_d ]
for i in range(l-1):
a, b = arr[i] , arr[i+1]
mid = (a+b)/2 -a
if mid > min_d :
dist.append( mid )
dist = sorted( dist )
for d in dist:
is_true = True
for i in range(l-1):
a, b = arr[i] , arr[i+1]
mid = (a+b)/2 -a
if mid > d:
is_true = False
break
if is_true:
print(d)
break
``` | -1 | |
979 | C | Kuro and Walking Route | PROGRAMMING | 1,600 | [
"dfs and similar",
"trees"
] | null | null | Kuro is living in a country called Uberland, consisting of $n$ towns, numbered from $1$ to $n$, and $n - 1$ bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns $a$ and $b$. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns $(u, v)$ ($u \neq v$) and walk from $u$ using the shortest path to $v$ (note that $(u, v)$ is considered to be different from $(v, u)$).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index $x$) and Beetopia (denoted with the index $y$). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns $(u, v)$ if on the path from $u$ to $v$, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city $(u, v)$ he can take as his route. Since he’s not really bright, he asked you to help him with this problem. | The first line contains three integers $n$, $x$ and $y$ ($1 \leq n \leq 3 \cdot 10^5$, $1 \leq x, y \leq n$, $x \ne y$) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
$n - 1$ lines follow, each line contains two integers $a$ and $b$ ($1 \leq a, b \leq n$, $a \ne b$), describes a road connecting two towns $a$ and $b$.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree. | A single integer resembles the number of pair of towns $(u, v)$ that Kuro can use as his walking route. | [
"3 1 3\n1 2\n2 3\n",
"3 1 3\n1 2\n1 3\n"
] | [
"5",
"4"
] | On the first example, Kuro can choose these pairs:
- $(1, 2)$: his route would be $1 \rightarrow 2$, - $(2, 3)$: his route would be $2 \rightarrow 3$, - $(3, 2)$: his route would be $3 \rightarrow 2$, - $(2, 1)$: his route would be $2 \rightarrow 1$, - $(3, 1)$: his route would be $3 \rightarrow 2 \rightarrow 1$.
Kuro can't choose pair $(1, 3)$ since his walking route would be $1 \rightarrow 2 \rightarrow 3$, in which Kuro visits town $1$ (Flowrisa) and then visits town $3$ (Beetopia), which is not allowed (note that pair $(3, 1)$ is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
- $(1, 2)$: his route would be $1 \rightarrow 2$, - $(2, 1)$: his route would be $2 \rightarrow 1$, - $(3, 2)$: his route would be $3 \rightarrow 1 \rightarrow 2$, - $(3, 1)$: his route would be $3 \rightarrow 1$. | 1,250 | [
{
"input": "3 1 3\n1 2\n2 3",
"output": "5"
},
{
"input": "3 1 3\n1 2\n1 3",
"output": "4"
},
{
"input": "61 26 12\n33 38\n32 8\n27 59\n1 21\n61 57\n61 22\n35 18\n61 14\n39 56\n50 10\n1 42\n21 43\n61 41\n31 30\n35 9\n23 28\n39 34\n39 4\n39 25\n27 60\n45 51\n1 11\n35 26\n29 15\n23 44\n31 ... | 1,528,091,861 | 2,147,483,647 | PyPy 3 | TIME_LIMIT_EXCEEDED | TESTS | 4 | 2,000 | 51,916,800 | n,x,y=[int(x)for x in input().split()]
adj=[[]for i in range(n+1)]
for i in range(n-1):
a,b = [int(x) for x in input().split()]
adj[a].append(b)
adj[b].append(a)
v=[0]*(n+1)
ph=[]
def dfs(i=x):
ph.append(i)
if i==y:
return True
v[i]=1
for ss in adj[i]:
if v[ss]==0:
if dfs(ss):
return True
ph.pop()
return False
dfs()
# print(ph)
def get_num(r,ex):
visit=[0]*(n+1)
visit[ex]=1
visit[r]=1
next=[r]
i=0
while i<len(next):
for ss in adj[next[i]]:
if visit[ss]==0:
next.append(ss)
visit[ss]=1
i+=1
return len(next)
xx=get_num(x,ph[1])
yy=get_num(y,ph[-2])
print(n*n-n-xx*yy)
| Title: Kuro and Walking Route
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Kuro is living in a country called Uberland, consisting of $n$ towns, numbered from $1$ to $n$, and $n - 1$ bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns $a$ and $b$. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns $(u, v)$ ($u \neq v$) and walk from $u$ using the shortest path to $v$ (note that $(u, v)$ is considered to be different from $(v, u)$).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index $x$) and Beetopia (denoted with the index $y$). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns $(u, v)$ if on the path from $u$ to $v$, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city $(u, v)$ he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input Specification:
The first line contains three integers $n$, $x$ and $y$ ($1 \leq n \leq 3 \cdot 10^5$, $1 \leq x, y \leq n$, $x \ne y$) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
$n - 1$ lines follow, each line contains two integers $a$ and $b$ ($1 \leq a, b \leq n$, $a \ne b$), describes a road connecting two towns $a$ and $b$.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output Specification:
A single integer resembles the number of pair of towns $(u, v)$ that Kuro can use as his walking route.
Demo Input:
['3 1 3\n1 2\n2 3\n', '3 1 3\n1 2\n1 3\n']
Demo Output:
['5', '4']
Note:
On the first example, Kuro can choose these pairs:
- $(1, 2)$: his route would be $1 \rightarrow 2$, - $(2, 3)$: his route would be $2 \rightarrow 3$, - $(3, 2)$: his route would be $3 \rightarrow 2$, - $(2, 1)$: his route would be $2 \rightarrow 1$, - $(3, 1)$: his route would be $3 \rightarrow 2 \rightarrow 1$.
Kuro can't choose pair $(1, 3)$ since his walking route would be $1 \rightarrow 2 \rightarrow 3$, in which Kuro visits town $1$ (Flowrisa) and then visits town $3$ (Beetopia), which is not allowed (note that pair $(3, 1)$ is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
- $(1, 2)$: his route would be $1 \rightarrow 2$, - $(2, 1)$: his route would be $2 \rightarrow 1$, - $(3, 2)$: his route would be $3 \rightarrow 1 \rightarrow 2$, - $(3, 1)$: his route would be $3 \rightarrow 1$. | ```python
n,x,y=[int(x)for x in input().split()]
adj=[[]for i in range(n+1)]
for i in range(n-1):
a,b = [int(x) for x in input().split()]
adj[a].append(b)
adj[b].append(a)
v=[0]*(n+1)
ph=[]
def dfs(i=x):
ph.append(i)
if i==y:
return True
v[i]=1
for ss in adj[i]:
if v[ss]==0:
if dfs(ss):
return True
ph.pop()
return False
dfs()
# print(ph)
def get_num(r,ex):
visit=[0]*(n+1)
visit[ex]=1
visit[r]=1
next=[r]
i=0
while i<len(next):
for ss in adj[next[i]]:
if visit[ss]==0:
next.append(ss)
visit[ss]=1
i+=1
return len(next)
xx=get_num(x,ph[1])
yy=get_num(y,ph[-2])
print(n*n-n-xx*yy)
``` | 0 | |
1,008 | A | Romaji | PROGRAMMING | 900 | [
"implementation",
"strings"
] | null | null | Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not.
Help Vitya find out if a word $s$ is Berlanese. | The first line of the input contains the string $s$ consisting of $|s|$ ($1\leq |s|\leq 100$) lowercase Latin letters. | Print "YES" (without quotes) if there is a vowel after every consonant except "n", otherwise print "NO".
You can print each letter in any case (upper or lower). | [
"sumimasen\n",
"ninja\n",
"codeforces\n"
] | [
"YES\n",
"YES\n",
"NO\n"
] | In the first and second samples, a vowel goes after each consonant except "n", so the word is Berlanese.
In the third sample, the consonant "c" goes after the consonant "r", and the consonant "s" stands on the end, so the word is not Berlanese. | 500 | [
{
"input": "sumimasen",
"output": "YES"
},
{
"input": "ninja",
"output": "YES"
},
{
"input": "codeforces",
"output": "NO"
},
{
"input": "auuaoonntanonnuewannnnpuuinniwoonennyolonnnvienonpoujinndinunnenannmuveoiuuhikucuziuhunnnmunzancenen",
"output": "YES"
},
{
"in... | 1,637,167,506 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 5 | 46 | 0 | a=input()
v='aeioun'
l=len(a)-1
count=0
c=False
k=0
for i in a:
if i in v:
k+=1
if k==len(a):
print("YES")
else:
if a[l] in v:
for i in range(l):
if a[i] not in v:
if a[i+1] in v:
c=True
else:
count+=1
if c==True and count==0:
print("YES")
else:
print("NO")
else:
print("NO") | Title: Romaji
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not.
Help Vitya find out if a word $s$ is Berlanese.
Input Specification:
The first line of the input contains the string $s$ consisting of $|s|$ ($1\leq |s|\leq 100$) lowercase Latin letters.
Output Specification:
Print "YES" (without quotes) if there is a vowel after every consonant except "n", otherwise print "NO".
You can print each letter in any case (upper or lower).
Demo Input:
['sumimasen\n', 'ninja\n', 'codeforces\n']
Demo Output:
['YES\n', 'YES\n', 'NO\n']
Note:
In the first and second samples, a vowel goes after each consonant except "n", so the word is Berlanese.
In the third sample, the consonant "c" goes after the consonant "r", and the consonant "s" stands on the end, so the word is not Berlanese. | ```python
a=input()
v='aeioun'
l=len(a)-1
count=0
c=False
k=0
for i in a:
if i in v:
k+=1
if k==len(a):
print("YES")
else:
if a[l] in v:
for i in range(l):
if a[i] not in v:
if a[i+1] in v:
c=True
else:
count+=1
if c==True and count==0:
print("YES")
else:
print("NO")
else:
print("NO")
``` | 0 | |
409 | D | Big Data | PROGRAMMING | 1,700 | [
"*special"
] | null | null | Little Petya wanted to give an April Fools Day present to some scientists. After some hesitation he decided to give them the array that he got as a present in Codeforces Round #153 (Div.2). The scientists rejoiced at the gift and decided to put some important facts to this array. Here are the first few of the facts:
- The highest mountain above sea level in the world is Mount Everest. Its peak rises to 8848 m. - The largest board game tournament consisted of 958 participants playing chapaev.- The largest online maths competition consisted of 12766 participants.- The Nile is credited as the longest river in the world. From its farthest stream in Burundi, it extends 6695 km in length.- While not in flood, the main stretches of the Amazon river in South America can reach widths of up to 1100 km at its widest points.- Angel Falls is the highest waterfall. Its greatest single drop measures 807 m.- The Hotel Everest View above Namche, Nepal — the village closest to Everest base camp – is at a record height of 31962 m- Uranium is the heaviest of all the naturally occurring elements. Its most common isotope has a nucleus containing 146 neutrons.- The coldest permanently inhabited place is the Siberian village of Oymyakon, where the temperature of -68°C was registered in the twentieth century.- The longest snake held in captivity is over 25 feet long. Its name is Medusa.- Colonel Meow holds the world record for longest fur on a cat — almost 134 centimeters.- Sea otters can have up to 10000 hairs per square inch. This is the most dense fur in the animal kingdom.- The largest state of USA is Alaska; its area is 663268 square miles- Alaska has a longer coastline than all of the other 49 U.S. States put together: it is 154103 miles long.- Lake Baikal is the largest freshwater lake in the world. It reaches 1642 meters in depth and contains around one-fifth of the world’s unfrozen fresh water.- The most colorful national flag is the one of Turkmenistan, with 106 colors. | The input will contain a single integer between 1 and 16. | Output a single integer. | [
"1\n",
"7\n"
] | [
"1\n",
"0\n"
] | none | 0 | [
{
"input": "1",
"output": "1"
},
{
"input": "7",
"output": "0"
},
{
"input": "13",
"output": "1"
},
{
"input": "3",
"output": "0"
},
{
"input": "8",
"output": "1"
},
{
"input": "16",
"output": "0"
},
{
"input": "11",
"output": "0"
},
... | 1,622,285,409 | 2,147,483,647 | Python 3 | OK | TESTS | 16 | 62 | 0 | print("1001010111001010"[int(input())-1]) | Title: Big Data
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Petya wanted to give an April Fools Day present to some scientists. After some hesitation he decided to give them the array that he got as a present in Codeforces Round #153 (Div.2). The scientists rejoiced at the gift and decided to put some important facts to this array. Here are the first few of the facts:
- The highest mountain above sea level in the world is Mount Everest. Its peak rises to 8848 m. - The largest board game tournament consisted of 958 participants playing chapaev.- The largest online maths competition consisted of 12766 participants.- The Nile is credited as the longest river in the world. From its farthest stream in Burundi, it extends 6695 km in length.- While not in flood, the main stretches of the Amazon river in South America can reach widths of up to 1100 km at its widest points.- Angel Falls is the highest waterfall. Its greatest single drop measures 807 m.- The Hotel Everest View above Namche, Nepal — the village closest to Everest base camp – is at a record height of 31962 m- Uranium is the heaviest of all the naturally occurring elements. Its most common isotope has a nucleus containing 146 neutrons.- The coldest permanently inhabited place is the Siberian village of Oymyakon, where the temperature of -68°C was registered in the twentieth century.- The longest snake held in captivity is over 25 feet long. Its name is Medusa.- Colonel Meow holds the world record for longest fur on a cat — almost 134 centimeters.- Sea otters can have up to 10000 hairs per square inch. This is the most dense fur in the animal kingdom.- The largest state of USA is Alaska; its area is 663268 square miles- Alaska has a longer coastline than all of the other 49 U.S. States put together: it is 154103 miles long.- Lake Baikal is the largest freshwater lake in the world. It reaches 1642 meters in depth and contains around one-fifth of the world’s unfrozen fresh water.- The most colorful national flag is the one of Turkmenistan, with 106 colors.
Input Specification:
The input will contain a single integer between 1 and 16.
Output Specification:
Output a single integer.
Demo Input:
['1\n', '7\n']
Demo Output:
['1\n', '0\n']
Note:
none | ```python
print("1001010111001010"[int(input())-1])
``` | 3 | |
514 | A | Chewbaсca and Number | PROGRAMMING | 1,200 | [
"greedy",
"implementation"
] | null | null | Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*.
Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero. | The first line contains a single integer *x* (1<=≤<=*x*<=≤<=1018) — the number that Luke Skywalker gave to Chewbacca. | Print the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes. | [
"27\n",
"4545\n"
] | [
"22\n",
"4444\n"
] | none | 500 | [
{
"input": "27",
"output": "22"
},
{
"input": "4545",
"output": "4444"
},
{
"input": "1",
"output": "1"
},
{
"input": "9",
"output": "9"
},
{
"input": "8772",
"output": "1222"
},
{
"input": "81",
"output": "11"
},
{
"input": "71723447",
... | 1,682,724,748 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 4 | 62 | 0 | x = list(map(int, list(input())))
y = [9-a for a in x]
ans = str(x[0])
for i in range(1, len(x)):
ans += str(min(x[i], y[i]))
print(ans) | Title: Chewbaсca and Number
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*.
Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.
Input Specification:
The first line contains a single integer *x* (1<=≤<=*x*<=≤<=1018) — the number that Luke Skywalker gave to Chewbacca.
Output Specification:
Print the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes.
Demo Input:
['27\n', '4545\n']
Demo Output:
['22\n', '4444\n']
Note:
none | ```python
x = list(map(int, list(input())))
y = [9-a for a in x]
ans = str(x[0])
for i in range(1, len(x)):
ans += str(min(x[i], y[i]))
print(ans)
``` | 0 | |
801 | B | Valued Keys | PROGRAMMING | 900 | [
"constructive algorithms",
"greedy",
"strings"
] | null | null | You found a mysterious function *f*. The function takes two strings *s*1 and *s*2. These strings must consist only of lowercase English letters, and must be the same length.
The output of the function *f* is another string of the same length. The *i*-th character of the output is equal to the minimum of the *i*-th character of *s*1 and the *i*-th character of *s*2.
For example, *f*("ab", "ba") = "aa", and *f*("nzwzl", "zizez") = "niwel".
You found two strings *x* and *y* of the same length and consisting of only lowercase English letters. Find any string *z* such that *f*(*x*,<=*z*)<==<=*y*, or print -1 if no such string *z* exists. | The first line of input contains the string *x*.
The second line of input contains the string *y*.
Both *x* and *y* consist only of lowercase English letters, *x* and *y* have same length and this length is between 1 and 100. | If there is no string *z* such that *f*(*x*,<=*z*)<==<=*y*, print -1.
Otherwise, print a string *z* such that *f*(*x*,<=*z*)<==<=*y*. If there are multiple possible answers, print any of them. The string *z* should be the same length as *x* and *y* and consist only of lowercase English letters. | [
"ab\naa\n",
"nzwzl\nniwel\n",
"ab\nba\n"
] | [
"ba\n",
"xiyez\n",
"-1\n"
] | The first case is from the statement.
Another solution for the second case is "zizez"
There is no solution for the third case. That is, there is no *z* such that *f*("ab", *z*) = "ba". | 1,000 | [
{
"input": "ab\naa",
"output": "ba"
},
{
"input": "nzwzl\nniwel",
"output": "xiyez"
},
{
"input": "ab\nba",
"output": "-1"
},
{
"input": "r\nl",
"output": "l"
},
{
"input": "d\ny",
"output": "-1"
},
{
"input": "yvowz\ncajav",
"output": "cajav"
},... | 1,616,514,367 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 8 | 108 | 0 | try:
x = input()
z = input()
y = ""
v = True
for i in range(len(x)):
if ascii(x[i]) < ascii(z[i]):
print(-1)
v = False
else:
y = y + z[i]
if v:
print(y)
except:
pass | Title: Valued Keys
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You found a mysterious function *f*. The function takes two strings *s*1 and *s*2. These strings must consist only of lowercase English letters, and must be the same length.
The output of the function *f* is another string of the same length. The *i*-th character of the output is equal to the minimum of the *i*-th character of *s*1 and the *i*-th character of *s*2.
For example, *f*("ab", "ba") = "aa", and *f*("nzwzl", "zizez") = "niwel".
You found two strings *x* and *y* of the same length and consisting of only lowercase English letters. Find any string *z* such that *f*(*x*,<=*z*)<==<=*y*, or print -1 if no such string *z* exists.
Input Specification:
The first line of input contains the string *x*.
The second line of input contains the string *y*.
Both *x* and *y* consist only of lowercase English letters, *x* and *y* have same length and this length is between 1 and 100.
Output Specification:
If there is no string *z* such that *f*(*x*,<=*z*)<==<=*y*, print -1.
Otherwise, print a string *z* such that *f*(*x*,<=*z*)<==<=*y*. If there are multiple possible answers, print any of them. The string *z* should be the same length as *x* and *y* and consist only of lowercase English letters.
Demo Input:
['ab\naa\n', 'nzwzl\nniwel\n', 'ab\nba\n']
Demo Output:
['ba\n', 'xiyez\n', '-1\n']
Note:
The first case is from the statement.
Another solution for the second case is "zizez"
There is no solution for the third case. That is, there is no *z* such that *f*("ab", *z*) = "ba". | ```python
try:
x = input()
z = input()
y = ""
v = True
for i in range(len(x)):
if ascii(x[i]) < ascii(z[i]):
print(-1)
v = False
else:
y = y + z[i]
if v:
print(y)
except:
pass
``` | 0 | |
151 | A | Soft Drinking | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt.
To make a toast, each friend needs *nl* milliliters of the drink, a slice of lime and *np* grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make? | The first and only line contains positive integers *n*, *k*, *l*, *c*, *d*, *p*, *nl*, *np*, not exceeding 1000 and no less than 1. The numbers are separated by exactly one space. | Print a single integer — the number of toasts each friend can make. | [
"3 4 5 10 8 100 3 1\n",
"5 100 10 1 19 90 4 3\n",
"10 1000 1000 25 23 1 50 1\n"
] | [
"2\n",
"3\n",
"0\n"
] | A comment to the first sample:
Overall the friends have 4 * 5 = 20 milliliters of the drink, it is enough to make 20 / 3 = 6 toasts. The limes are enough for 10 * 8 = 80 toasts and the salt is enough for 100 / 1 = 100 toasts. However, there are 3 friends in the group, so the answer is *min*(6, 80, 100) / 3 = 2. | 500 | [
{
"input": "3 4 5 10 8 100 3 1",
"output": "2"
},
{
"input": "5 100 10 1 19 90 4 3",
"output": "3"
},
{
"input": "10 1000 1000 25 23 1 50 1",
"output": "0"
},
{
"input": "1 7 4 5 5 8 3 2",
"output": "4"
},
{
"input": "2 3 3 5 5 10 1 3",
"output": "1"
},
{
... | 1,684,320,878 | 2,147,483,647 | Python 3 | OK | TESTS | 27 | 92 | 0 | a,b,c,d,e,f,g,h=map(int,input().split())
q=b*c
w=q//g
e=d*e
r=f//h
print(int(min(w,e,r)/a))
| Title: Soft Drinking
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt.
To make a toast, each friend needs *nl* milliliters of the drink, a slice of lime and *np* grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?
Input Specification:
The first and only line contains positive integers *n*, *k*, *l*, *c*, *d*, *p*, *nl*, *np*, not exceeding 1000 and no less than 1. The numbers are separated by exactly one space.
Output Specification:
Print a single integer — the number of toasts each friend can make.
Demo Input:
['3 4 5 10 8 100 3 1\n', '5 100 10 1 19 90 4 3\n', '10 1000 1000 25 23 1 50 1\n']
Demo Output:
['2\n', '3\n', '0\n']
Note:
A comment to the first sample:
Overall the friends have 4 * 5 = 20 milliliters of the drink, it is enough to make 20 / 3 = 6 toasts. The limes are enough for 10 * 8 = 80 toasts and the salt is enough for 100 / 1 = 100 toasts. However, there are 3 friends in the group, so the answer is *min*(6, 80, 100) / 3 = 2. | ```python
a,b,c,d,e,f,g,h=map(int,input().split())
q=b*c
w=q//g
e=d*e
r=f//h
print(int(min(w,e,r)/a))
``` | 3 | |
722 | A | Broken Clock | PROGRAMMING | 1,300 | [
"brute force",
"implementation"
] | null | null | You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.
You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.
For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39. | The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively.
The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes. | The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them. | [
"24\n17:30\n",
"12\n17:30\n",
"24\n99:99\n"
] | [
"17:30\n",
"07:30\n",
"09:09\n"
] | none | 500 | [
{
"input": "24\n17:30",
"output": "17:30"
},
{
"input": "12\n17:30",
"output": "07:30"
},
{
"input": "24\n99:99",
"output": "09:09"
},
{
"input": "12\n05:54",
"output": "05:54"
},
{
"input": "12\n00:05",
"output": "01:05"
},
{
"input": "24\n23:80",
... | 1,475,334,021 | 3,321 | Python 3 | WRONG_ANSWER | PRETESTS | 0 | 30 | 0 | mode = int(input())
time = input()
i = 0
h = 0
m = 0
while(time[i] != ':'):
h = h * 10 + int(time[i])
i += 1
i += 1
while(i < 4):
m = m * 10 + int(time[i])
i += 1
if(mode == 24):
if(not(0 <= h <= 23)):
h %= 10
if(not(0 <= m <= 59)):
m %= 10
if(mode == 12):
if(not(1 <= h <= 12)):
h %= 10
if(not(0 <= m <= 59)):
m %= 10
print(h // 10, h % 10, ':', m // 10, m % 10, sep='')
| Title: Broken Clock
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.
You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.
For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.
Input Specification:
The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively.
The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.
Output Specification:
The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.
Demo Input:
['24\n17:30\n', '12\n17:30\n', '24\n99:99\n']
Demo Output:
['17:30\n', '07:30\n', '09:09\n']
Note:
none | ```python
mode = int(input())
time = input()
i = 0
h = 0
m = 0
while(time[i] != ':'):
h = h * 10 + int(time[i])
i += 1
i += 1
while(i < 4):
m = m * 10 + int(time[i])
i += 1
if(mode == 24):
if(not(0 <= h <= 23)):
h %= 10
if(not(0 <= m <= 59)):
m %= 10
if(mode == 12):
if(not(1 <= h <= 12)):
h %= 10
if(not(0 <= m <= 59)):
m %= 10
print(h // 10, h % 10, ':', m // 10, m % 10, sep='')
``` | 0 | |
873 | B | Balanced Substring | PROGRAMMING | 1,500 | [
"dp",
"implementation"
] | null | null | You are given a string *s* consisting only of characters 0 and 1. A substring [*l*,<=*r*] of *s* is a string *s**l**s**l*<=+<=1*s**l*<=+<=2... *s**r*, and its length equals to *r*<=-<=*l*<=+<=1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.
You have to determine the length of the longest balanced substring of *s*. | The first line contains *n* (1<=≤<=*n*<=≤<=100000) — the number of characters in *s*.
The second line contains a string *s* consisting of exactly *n* characters. Only characters 0 and 1 can appear in *s*. | If there is no non-empty balanced substring in *s*, print 0. Otherwise, print the length of the longest balanced substring. | [
"8\n11010111\n",
"3\n111\n"
] | [
"4\n",
"0\n"
] | In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.
In the second example it's impossible to find a non-empty balanced substring. | 0 | [
{
"input": "8\n11010111",
"output": "4"
},
{
"input": "3\n111",
"output": "0"
},
{
"input": "11\n00001000100",
"output": "2"
},
{
"input": "10\n0100000000",
"output": "2"
},
{
"input": "13\n0001000011010",
"output": "6"
},
{
"input": "14\n0000010010101... | 1,511,419,209 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 4 | 62 | 0 | n = int(input())
a = list(input())
s1 = []
s2 = []
for i in range(n):
a[i] = int(a[i])
if a[i] == 0:
a[i] = -1
s = 0
for i in range(n-1 ):
s += a[i]
if i % 2 == 1:
s1.append(s)
else:
s2.append(s)
r = 0
rmax = 0
for i in range(len(s1)-1):
if s1[i] == s1[i+1]:
r += 1
if r >= rmax:
rmax = r
else:
r = 0
r = 0
for i in range(len(s1)-1):
if s2[i] == s2[i+1]:
r += 1
if r >= rmax:
rmax = r
else:
r = 0
print(rmax*2)
| Title: Balanced Substring
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a string *s* consisting only of characters 0 and 1. A substring [*l*,<=*r*] of *s* is a string *s**l**s**l*<=+<=1*s**l*<=+<=2... *s**r*, and its length equals to *r*<=-<=*l*<=+<=1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.
You have to determine the length of the longest balanced substring of *s*.
Input Specification:
The first line contains *n* (1<=≤<=*n*<=≤<=100000) — the number of characters in *s*.
The second line contains a string *s* consisting of exactly *n* characters. Only characters 0 and 1 can appear in *s*.
Output Specification:
If there is no non-empty balanced substring in *s*, print 0. Otherwise, print the length of the longest balanced substring.
Demo Input:
['8\n11010111\n', '3\n111\n']
Demo Output:
['4\n', '0\n']
Note:
In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.
In the second example it's impossible to find a non-empty balanced substring. | ```python
n = int(input())
a = list(input())
s1 = []
s2 = []
for i in range(n):
a[i] = int(a[i])
if a[i] == 0:
a[i] = -1
s = 0
for i in range(n-1 ):
s += a[i]
if i % 2 == 1:
s1.append(s)
else:
s2.append(s)
r = 0
rmax = 0
for i in range(len(s1)-1):
if s1[i] == s1[i+1]:
r += 1
if r >= rmax:
rmax = r
else:
r = 0
r = 0
for i in range(len(s1)-1):
if s2[i] == s2[i+1]:
r += 1
if r >= rmax:
rmax = r
else:
r = 0
print(rmax*2)
``` | 0 | |
1,009 | A | Game Shopping | PROGRAMMING | 800 | [
"implementation"
] | null | null | Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$.
Maxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$.
Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.
When Maxim stands at the position $i$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $i$-th game using this bill. After Maxim tried to buy the $n$-th game, he leaves the shop.
Maxim buys the $i$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $i$-th game. If he successfully buys the $i$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.
For example, for array $c = [2, 4, 5, 2, 4]$ and array $a = [5, 3, 4, 6]$ the following process takes place: Maxim buys the first game using the first bill (its value is $5$), the bill disappears, after that the second bill (with value $3$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $c_2 > a_2$, the same with the third game, then he buys the fourth game using the bill of value $a_2$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $a_3$.
Your task is to get the number of games Maxim will buy. | The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 1000$) — the number of games and the number of bills in Maxim's wallet.
The second line of the input contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le 1000$), where $c_i$ is the cost of the $i$-th game.
The third line of the input contains $m$ integers $a_1, a_2, \dots, a_m$ ($1 \le a_j \le 1000$), where $a_j$ is the value of the $j$-th bill from the Maxim's wallet. | Print a single integer — the number of games Maxim will buy. | [
"5 4\n2 4 5 2 4\n5 3 4 6\n",
"5 2\n20 40 50 20 40\n19 20\n",
"6 4\n4 8 15 16 23 42\n1000 1000 1000 1000\n"
] | [
"3\n",
"0\n",
"4\n"
] | The first example is described in the problem statement.
In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop.
In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet. | 0 | [
{
"input": "5 4\n2 4 5 2 4\n5 3 4 6",
"output": "3"
},
{
"input": "5 2\n20 40 50 20 40\n19 20",
"output": "0"
},
{
"input": "6 4\n4 8 15 16 23 42\n1000 1000 1000 1000",
"output": "4"
},
{
"input": "5 1\n1 1 1 1 1\n5",
"output": "1"
},
{
"input": "5 1\n10 1 1 1 1\n... | 1,547,913,598 | 2,147,483,647 | Python 3 | OK | TESTS | 19 | 109 | 0 | n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
zero1 = 0 ; zero2 = 0
for i in a:
if zero2 < m and i <= b[zero2]:
zero1 += 1 ; zero2 += 1
print(zero1)
| Title: Game Shopping
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$.
Maxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$.
Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.
When Maxim stands at the position $i$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $i$-th game using this bill. After Maxim tried to buy the $n$-th game, he leaves the shop.
Maxim buys the $i$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $i$-th game. If he successfully buys the $i$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.
For example, for array $c = [2, 4, 5, 2, 4]$ and array $a = [5, 3, 4, 6]$ the following process takes place: Maxim buys the first game using the first bill (its value is $5$), the bill disappears, after that the second bill (with value $3$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $c_2 > a_2$, the same with the third game, then he buys the fourth game using the bill of value $a_2$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $a_3$.
Your task is to get the number of games Maxim will buy.
Input Specification:
The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 1000$) — the number of games and the number of bills in Maxim's wallet.
The second line of the input contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le 1000$), where $c_i$ is the cost of the $i$-th game.
The third line of the input contains $m$ integers $a_1, a_2, \dots, a_m$ ($1 \le a_j \le 1000$), where $a_j$ is the value of the $j$-th bill from the Maxim's wallet.
Output Specification:
Print a single integer — the number of games Maxim will buy.
Demo Input:
['5 4\n2 4 5 2 4\n5 3 4 6\n', '5 2\n20 40 50 20 40\n19 20\n', '6 4\n4 8 15 16 23 42\n1000 1000 1000 1000\n']
Demo Output:
['3\n', '0\n', '4\n']
Note:
The first example is described in the problem statement.
In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop.
In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet. | ```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
zero1 = 0 ; zero2 = 0
for i in a:
if zero2 < m and i <= b[zero2]:
zero1 += 1 ; zero2 += 1
print(zero1)
``` | 3 | |
835 | A | Key races | PROGRAMMING | 800 | [
"math"
] | null | null | Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *t*2 milliseconds.
If connection ping (delay) is *t* milliseconds, the competition passes for a participant as follows:
1. Exactly after *t* milliseconds after the start of the competition the participant receives the text to be entered. 1. Right after that he starts to type it. 1. Exactly *t* milliseconds after he ends typing all the text, the site receives information about it.
The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.
Given the length of the text and the information about participants, determine the result of the game. | The first line contains five integers *s*, *v*1, *v*2, *t*1, *t*2 (1<=≤<=*s*,<=*v*1,<=*v*2,<=*t*1,<=*t*2<=≤<=1000) — the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant. | If the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw print "Friendship". | [
"5 1 2 1 2\n",
"3 3 1 1 1\n",
"4 5 3 1 5\n"
] | [
"First\n",
"Second\n",
"Friendship\n"
] | In the first example, information on the success of the first participant comes in 7 milliseconds, of the second participant — in 14 milliseconds. So, the first wins.
In the second example, information on the success of the first participant comes in 11 milliseconds, of the second participant — in 5 milliseconds. So, the second wins.
In the third example, information on the success of the first participant comes in 22 milliseconds, of the second participant — in 22 milliseconds. So, it is be a draw. | 500 | [
{
"input": "5 1 2 1 2",
"output": "First"
},
{
"input": "3 3 1 1 1",
"output": "Second"
},
{
"input": "4 5 3 1 5",
"output": "Friendship"
},
{
"input": "1000 1000 1000 1000 1000",
"output": "Friendship"
},
{
"input": "1 1 1 1 1",
"output": "Friendship"
},
... | 1,628,969,138 | 2,147,483,647 | PyPy 3 | OK | TESTS | 32 | 108 | 20,172,800 | from sys import stdin, stdout
def read():
return stdin.readline().rstrip()
def read_int():
return int(read())
def read_ints():
return list(map(int, read().split()))
def solve():
s,v1,v2,t1,t2 = read_ints()
if v1*s+2*t1 < v2*s+2*t2:
print("First")
elif v1*s+2*t1 > v2*s+2*t2:
print("Second")
else:
print("Friendship")
solve()
| Title: Key races
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *t*2 milliseconds.
If connection ping (delay) is *t* milliseconds, the competition passes for a participant as follows:
1. Exactly after *t* milliseconds after the start of the competition the participant receives the text to be entered. 1. Right after that he starts to type it. 1. Exactly *t* milliseconds after he ends typing all the text, the site receives information about it.
The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.
Given the length of the text and the information about participants, determine the result of the game.
Input Specification:
The first line contains five integers *s*, *v*1, *v*2, *t*1, *t*2 (1<=≤<=*s*,<=*v*1,<=*v*2,<=*t*1,<=*t*2<=≤<=1000) — the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant.
Output Specification:
If the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw print "Friendship".
Demo Input:
['5 1 2 1 2\n', '3 3 1 1 1\n', '4 5 3 1 5\n']
Demo Output:
['First\n', 'Second\n', 'Friendship\n']
Note:
In the first example, information on the success of the first participant comes in 7 milliseconds, of the second participant — in 14 milliseconds. So, the first wins.
In the second example, information on the success of the first participant comes in 11 milliseconds, of the second participant — in 5 milliseconds. So, the second wins.
In the third example, information on the success of the first participant comes in 22 milliseconds, of the second participant — in 22 milliseconds. So, it is be a draw. | ```python
from sys import stdin, stdout
def read():
return stdin.readline().rstrip()
def read_int():
return int(read())
def read_ints():
return list(map(int, read().split()))
def solve():
s,v1,v2,t1,t2 = read_ints()
if v1*s+2*t1 < v2*s+2*t2:
print("First")
elif v1*s+2*t1 > v2*s+2*t2:
print("Second")
else:
print("Friendship")
solve()
``` | 3 | |
560 | A | Currency System in Geraldion | PROGRAMMING | 1,000 | [
"implementation",
"sortings"
] | null | null | A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum? | The first line contains number *n* (1<=≤<=*n*<=≤<=1000) — the number of values of the banknotes that used in Geraldion.
The second line contains *n* distinct space-separated numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=106) — the values of the banknotes. | Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print <=-<=1. | [
"5\n1 2 3 4 5\n"
] | [
"-1\n"
] | none | 500 | [
{
"input": "5\n1 2 3 4 5",
"output": "-1"
},
{
"input": "1\n2",
"output": "1"
},
{
"input": "10\n371054 506438 397130 1 766759 208409 769264 549213 641270 771837",
"output": "-1"
},
{
"input": "10\n635370 154890 909382 220996 276501 716105 538714 140162 171960 271264",
"o... | 1,439,450,701 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 11 | 77 | 3,993,600 | def prost(n):
a = 2
while n % a != 0 and n**0.5 > a :
a += 1
if n % a == 0 and n != 2:
return 0
else:
return 1
n = int(input())
ai = list(map(int,input().split()))
nums = [0]*1000000
answer = -1
for i in range(n):
nums[ai[i]] = 1
if nums[1] != 1:
answer = 1
print(answer) | Title: Currency System in Geraldion
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
Input Specification:
The first line contains number *n* (1<=≤<=*n*<=≤<=1000) — the number of values of the banknotes that used in Geraldion.
The second line contains *n* distinct space-separated numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=106) — the values of the banknotes.
Output Specification:
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print <=-<=1.
Demo Input:
['5\n1 2 3 4 5\n']
Demo Output:
['-1\n']
Note:
none | ```python
def prost(n):
a = 2
while n % a != 0 and n**0.5 > a :
a += 1
if n % a == 0 and n != 2:
return 0
else:
return 1
n = int(input())
ai = list(map(int,input().split()))
nums = [0]*1000000
answer = -1
for i in range(n):
nums[ai[i]] = 1
if nums[1] != 1:
answer = 1
print(answer)
``` | -1 | |
26 | B | Regular Bracket Sequence | PROGRAMMING | 1,400 | [
"greedy"
] | B. Regular Bracket Sequence | 5 | 256 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.
One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | Output the maximum possible length of a regular bracket sequence. | [
"(()))(\n",
"((()())\n"
] | [
"4\n",
"6\n"
] | none | 1,000 | [
{
"input": "(()))(",
"output": "4"
},
{
"input": "((()())",
"output": "6"
},
{
"input": "(",
"output": "0"
},
{
"input": ")",
"output": "0"
},
{
"input": ")(()(",
"output": "2"
},
{
"input": "))))))(",
"output": "0"
},
{
"input": "()()(()((... | 1,679,224,950 | 2,147,483,647 | Python 3 | OK | TESTS | 38 | 872 | 6,144,000 | x = list(input())
c1 = 0
c2 = 0
for i in range(len(x)):
if x[-1] == "(" and c1 == 0:
x.pop()
elif x[-1] == ")":
x.pop()
c1+=1
else:
x.pop()
c1-=1
c2+=2
print(c2) | Title: Regular Bracket Sequence
Time Limit: 5 seconds
Memory Limit: 256 megabytes
Problem Description:
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.
One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?
Input Specification:
Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106.
Output Specification:
Output the maximum possible length of a regular bracket sequence.
Demo Input:
['(()))(\n', '((()())\n']
Demo Output:
['4\n', '6\n']
Note:
none | ```python
x = list(input())
c1 = 0
c2 = 0
for i in range(len(x)):
if x[-1] == "(" and c1 == 0:
x.pop()
elif x[-1] == ")":
x.pop()
c1+=1
else:
x.pop()
c1-=1
c2+=2
print(c2)
``` | 3.901356 |
437 | C | The Child and Toy | PROGRAMMING | 1,400 | [
"graphs",
"greedy",
"sortings"
] | null | null | On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of *n* parts and *m* ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part *i* as *v**i*. The child spend *v**f*1<=+<=*v**f*2<=+<=...<=+<=*v**f**k* energy for removing part *i* where *f*1,<=*f*2,<=...,<=*f**k* are the parts that are directly connected to the *i*-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all *n* parts. | The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=1000; 0<=≤<=*m*<=≤<=2000). The second line contains *n* integers: *v*1,<=*v*2,<=...,<=*v**n* (0<=≤<=*v**i*<=≤<=105). Then followed *m* lines, each line contains two integers *x**i* and *y**i*, representing a rope from part *x**i* to part *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*; *x**i*<=≠<=*y**i*).
Consider all the parts are numbered from 1 to *n*. | Output the minimum total energy the child should spend to remove all *n* parts of the toy. | [
"4 3\n10 20 30 40\n1 4\n1 2\n2 3\n",
"4 4\n100 100 100 100\n1 2\n2 3\n2 4\n3 4\n",
"7 10\n40 10 20 10 20 80 40\n1 5\n4 7\n4 5\n5 2\n5 7\n6 4\n1 6\n1 3\n4 3\n1 4\n"
] | [
"40\n",
"400\n",
"160\n"
] | One of the optimal sequence of actions in the first sample is:
- First, remove part 3, cost of the action is 20. - Then, remove part 2, cost of the action is 10. - Next, remove part 4, cost of the action is 10. - At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts. | 1,500 | [
{
"input": "4 3\n10 20 30 40\n1 4\n1 2\n2 3",
"output": "40"
},
{
"input": "4 4\n100 100 100 100\n1 2\n2 3\n2 4\n3 4",
"output": "400"
},
{
"input": "7 10\n40 10 20 10 20 80 40\n1 5\n4 7\n4 5\n5 2\n5 7\n6 4\n1 6\n1 3\n4 3\n1 4",
"output": "160"
},
{
"input": "1 0\n23333",
... | 1,640,872,503 | 2,147,483,647 | Python 3 | OK | TESTS | 29 | 62 | 102,400 | from collections import defaultdict
n,m = map(int,input().split())
A = list(map(int,input().split()))
d = defaultdict(list)
ans = 0
for i in range(m):
a,b = map(int,input().split())
ans += min(A[a-1],A[b-1])
print(ans) | Title: The Child and Toy
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of *n* parts and *m* ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part *i* as *v**i*. The child spend *v**f*1<=+<=*v**f*2<=+<=...<=+<=*v**f**k* energy for removing part *i* where *f*1,<=*f*2,<=...,<=*f**k* are the parts that are directly connected to the *i*-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all *n* parts.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=1000; 0<=≤<=*m*<=≤<=2000). The second line contains *n* integers: *v*1,<=*v*2,<=...,<=*v**n* (0<=≤<=*v**i*<=≤<=105). Then followed *m* lines, each line contains two integers *x**i* and *y**i*, representing a rope from part *x**i* to part *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*; *x**i*<=≠<=*y**i*).
Consider all the parts are numbered from 1 to *n*.
Output Specification:
Output the minimum total energy the child should spend to remove all *n* parts of the toy.
Demo Input:
['4 3\n10 20 30 40\n1 4\n1 2\n2 3\n', '4 4\n100 100 100 100\n1 2\n2 3\n2 4\n3 4\n', '7 10\n40 10 20 10 20 80 40\n1 5\n4 7\n4 5\n5 2\n5 7\n6 4\n1 6\n1 3\n4 3\n1 4\n']
Demo Output:
['40\n', '400\n', '160\n']
Note:
One of the optimal sequence of actions in the first sample is:
- First, remove part 3, cost of the action is 20. - Then, remove part 2, cost of the action is 10. - Next, remove part 4, cost of the action is 10. - At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts. | ```python
from collections import defaultdict
n,m = map(int,input().split())
A = list(map(int,input().split()))
d = defaultdict(list)
ans = 0
for i in range(m):
a,b = map(int,input().split())
ans += min(A[a-1],A[b-1])
print(ans)
``` | 3 | |
626 | E | Simple Skewness | PROGRAMMING | 2,400 | [
"binary search",
"math",
"ternary search"
] | null | null | Define the simple skewness of a collection of numbers to be the collection's mean minus its median. You are given a list of *n* (not necessarily distinct) integers. Find the non-empty subset (with repetition) with the maximum simple skewness.
The mean of a collection is the average of its elements. The median of a collection is its middle element when all of its elements are sorted, or the average of its two middle elements if it has even size. | The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=200 000) — the number of elements in the list.
The second line contains *n* integers *x**i* (0<=≤<=*x**i*<=≤<=1<=000<=000) — the *i*th element of the list. | In the first line, print a single integer *k* — the size of the subset.
In the second line, print *k* integers — the elements of the subset in any order.
If there are multiple optimal subsets, print any. | [
"4\n1 2 3 12\n",
"4\n1 1 2 2\n",
"2\n1 2\n"
] | [
"3\n1 2 12 \n",
"3\n1 1 2 \n",
"2\n1 2\n"
] | In the first case, the optimal subset is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/04cdbd07a0375de9c557422eca077386392a9349.png" style="max-width: 100.0%;max-height: 100.0%;"/>, which has mean 5, median 2, and simple skewness of 5 - 2 = 3.
In the second case, the optimal subset is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/af49670de7c27def20edf0ec421d9bb17d904c94.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Note that repetition is allowed.
In the last case, any subset has the same median and mean, so all have simple skewness of 0. | 2,000 | [
{
"input": "4\n1 2 3 12",
"output": "3\n1 2 12 "
},
{
"input": "4\n1 1 2 2",
"output": "3\n1 1 2 "
},
{
"input": "2\n1 2",
"output": "2\n1 2"
},
{
"input": "1\n1000000",
"output": "1\n1000000 "
},
{
"input": "20\n999999 999998 999996 999992 999984 999968 999936 99... | 1,644,314,034 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 3 | 30 | 0 | n = int(input())
array = list(map(int,input().split()))
array.sort()
dataarray = []
skewness = []
for i in range(1, n):
temparray = []
temparray.append(array[i])
for j in range(min(i, len(array)-i)):
if sum(temparray)/len(temparray) < (array[i-j-1]+array[-1-j])/2:
temparray.insert(0,array[i-j-1])
temparray.append(array[-1-j])
if j == min(i, len(array)-i)-1:
skewness.append((sum(temparray)/len(temparray))-array[i])
dataarray.append(temparray)
else:
skewness.append((sum(temparray) / len(temparray)) - array[i])
dataarray.append(temparray)
break
print(len(dataarray[skewness.index(max(skewness))]))
print(" ".join(list(map(str,dataarray[skewness.index(max(skewness))])))) | Title: Simple Skewness
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Define the simple skewness of a collection of numbers to be the collection's mean minus its median. You are given a list of *n* (not necessarily distinct) integers. Find the non-empty subset (with repetition) with the maximum simple skewness.
The mean of a collection is the average of its elements. The median of a collection is its middle element when all of its elements are sorted, or the average of its two middle elements if it has even size.
Input Specification:
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=200 000) — the number of elements in the list.
The second line contains *n* integers *x**i* (0<=≤<=*x**i*<=≤<=1<=000<=000) — the *i*th element of the list.
Output Specification:
In the first line, print a single integer *k* — the size of the subset.
In the second line, print *k* integers — the elements of the subset in any order.
If there are multiple optimal subsets, print any.
Demo Input:
['4\n1 2 3 12\n', '4\n1 1 2 2\n', '2\n1 2\n']
Demo Output:
['3\n1 2 12 \n', '3\n1 1 2 \n', '2\n1 2\n']
Note:
In the first case, the optimal subset is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/04cdbd07a0375de9c557422eca077386392a9349.png" style="max-width: 100.0%;max-height: 100.0%;"/>, which has mean 5, median 2, and simple skewness of 5 - 2 = 3.
In the second case, the optimal subset is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/af49670de7c27def20edf0ec421d9bb17d904c94.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Note that repetition is allowed.
In the last case, any subset has the same median and mean, so all have simple skewness of 0. | ```python
n = int(input())
array = list(map(int,input().split()))
array.sort()
dataarray = []
skewness = []
for i in range(1, n):
temparray = []
temparray.append(array[i])
for j in range(min(i, len(array)-i)):
if sum(temparray)/len(temparray) < (array[i-j-1]+array[-1-j])/2:
temparray.insert(0,array[i-j-1])
temparray.append(array[-1-j])
if j == min(i, len(array)-i)-1:
skewness.append((sum(temparray)/len(temparray))-array[i])
dataarray.append(temparray)
else:
skewness.append((sum(temparray) / len(temparray)) - array[i])
dataarray.append(temparray)
break
print(len(dataarray[skewness.index(max(skewness))]))
print(" ".join(list(map(str,dataarray[skewness.index(max(skewness))]))))
``` | -1 | |
148 | A | Insomnia cure | PROGRAMMING | 800 | [
"constructive algorithms",
"implementation",
"math"
] | null | null | «One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every *k*-th dragon got punched in the face with a frying pan. Every *l*-th dragon got his tail shut into the balcony door. Every *m*-th dragon got his paws trampled with sharp heels. Finally, she threatened every *n*-th dragon to call her mom, and he withdrew in panic.
How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of *d* dragons? | Input data contains integer numbers *k*,<=*l*,<=*m*,<=*n* and *d*, each number in a separate line (1<=≤<=*k*,<=*l*,<=*m*,<=*n*<=≤<=10, 1<=≤<=*d*<=≤<=105). | Output the number of damaged dragons. | [
"1\n2\n3\n4\n12\n",
"2\n3\n4\n5\n24\n"
] | [
"12\n",
"17\n"
] | In the first case every first dragon got punched with a frying pan. Some of the dragons suffered from other reasons as well, but the pan alone would be enough.
In the second case dragons 1, 7, 11, 13, 17, 19 and 23 escaped unharmed. | 1,000 | [
{
"input": "1\n2\n3\n4\n12",
"output": "12"
},
{
"input": "2\n3\n4\n5\n24",
"output": "17"
},
{
"input": "1\n1\n1\n1\n100000",
"output": "100000"
},
{
"input": "10\n9\n8\n7\n6",
"output": "0"
},
{
"input": "8\n4\n4\n3\n65437",
"output": "32718"
},
{
"i... | 1,679,124,450 | 2,147,483,647 | Python 3 | OK | TESTS | 40 | 92 | 0 | #using inclusion exclusion principle
def lcm(l):
if len(l)==2:
for i in range(1,l[0]*l[1]+1):
if i%l[0]==0 and i%l[1]==0:
return i
if len(l)==3:
for i in range(1,l[0]*l[1]*l[2]+1):
if i%l[0]==0 and i%l[1]==0 and i%l[2]==0:
return i
if len(l)==4:
for i in range(1,l[0]*l[1]*l[2]*l[3]+1):
if i%l[0]==0 and i%l[1]==0 and i%l[2]==0 and i%l[3]==0:
return i
a=int(input())
b=int(input())
c=int(input())
d=int(input())
n=int(input())
lcm_ab=n//lcm([a,b])
lcm_ac=n//lcm([a,c])
lcm_ad=n//lcm([a,d])
lcm_bc=n//lcm([b,c])
lcm_bd=n//lcm([b,d])
lcm_cd=n//lcm([c,d])
lcm_abc=n//lcm([a,b,c])
lcm_abd=n//lcm([a,b,d])
lcm_acd=n//lcm([a,c,d])
lcm_bcd=n//lcm([b,c,d])
lcm_abcd=n//lcm([a,b,c,d])
dragons=(n//a+n//b+n//c+n//d)-(lcm_ab+lcm_ac+lcm_ad+lcm_bc+lcm_bd+lcm_cd)+(lcm_abc+lcm_abd+lcm_acd+lcm_bcd)-lcm_abcd
print(dragons)
#alternate method but time inefficient
'''a=int(input())
b=int(input())
c=int(input())
d=int(input())
n=int(input())
l=[]
if a==1 or b==1 or c==1 or d==1:
print(n)
elif a>n and b>n and c>n and d>n:
print(0)
else:
for i in range(1,n+1):
l.append(i)
damaged=[]
for i in range(1,n+1,a):
if i not in damaged:
damaged.append(i)
for i in range(1,n+1,b):
if i not in damaged:
damaged.append(i)
for i in range(1,n+1,c):
if i not in damaged:
damaged.append(i)
for i in range(1,n+1,d):
if i not in damaged:
damaged.append(i)
print(len(damaged))'''
| Title: Insomnia cure
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every *k*-th dragon got punched in the face with a frying pan. Every *l*-th dragon got his tail shut into the balcony door. Every *m*-th dragon got his paws trampled with sharp heels. Finally, she threatened every *n*-th dragon to call her mom, and he withdrew in panic.
How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of *d* dragons?
Input Specification:
Input data contains integer numbers *k*,<=*l*,<=*m*,<=*n* and *d*, each number in a separate line (1<=≤<=*k*,<=*l*,<=*m*,<=*n*<=≤<=10, 1<=≤<=*d*<=≤<=105).
Output Specification:
Output the number of damaged dragons.
Demo Input:
['1\n2\n3\n4\n12\n', '2\n3\n4\n5\n24\n']
Demo Output:
['12\n', '17\n']
Note:
In the first case every first dragon got punched with a frying pan. Some of the dragons suffered from other reasons as well, but the pan alone would be enough.
In the second case dragons 1, 7, 11, 13, 17, 19 and 23 escaped unharmed. | ```python
#using inclusion exclusion principle
def lcm(l):
if len(l)==2:
for i in range(1,l[0]*l[1]+1):
if i%l[0]==0 and i%l[1]==0:
return i
if len(l)==3:
for i in range(1,l[0]*l[1]*l[2]+1):
if i%l[0]==0 and i%l[1]==0 and i%l[2]==0:
return i
if len(l)==4:
for i in range(1,l[0]*l[1]*l[2]*l[3]+1):
if i%l[0]==0 and i%l[1]==0 and i%l[2]==0 and i%l[3]==0:
return i
a=int(input())
b=int(input())
c=int(input())
d=int(input())
n=int(input())
lcm_ab=n//lcm([a,b])
lcm_ac=n//lcm([a,c])
lcm_ad=n//lcm([a,d])
lcm_bc=n//lcm([b,c])
lcm_bd=n//lcm([b,d])
lcm_cd=n//lcm([c,d])
lcm_abc=n//lcm([a,b,c])
lcm_abd=n//lcm([a,b,d])
lcm_acd=n//lcm([a,c,d])
lcm_bcd=n//lcm([b,c,d])
lcm_abcd=n//lcm([a,b,c,d])
dragons=(n//a+n//b+n//c+n//d)-(lcm_ab+lcm_ac+lcm_ad+lcm_bc+lcm_bd+lcm_cd)+(lcm_abc+lcm_abd+lcm_acd+lcm_bcd)-lcm_abcd
print(dragons)
#alternate method but time inefficient
'''a=int(input())
b=int(input())
c=int(input())
d=int(input())
n=int(input())
l=[]
if a==1 or b==1 or c==1 or d==1:
print(n)
elif a>n and b>n and c>n and d>n:
print(0)
else:
for i in range(1,n+1):
l.append(i)
damaged=[]
for i in range(1,n+1,a):
if i not in damaged:
damaged.append(i)
for i in range(1,n+1,b):
if i not in damaged:
damaged.append(i)
for i in range(1,n+1,c):
if i not in damaged:
damaged.append(i)
for i in range(1,n+1,d):
if i not in damaged:
damaged.append(i)
print(len(damaged))'''
``` | 3 | |
208 | A | Dubstep | PROGRAMMING | 900 | [
"strings"
] | null | null | Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.
For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".
Recently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song. | The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters. It is guaranteed that before Vasya remixed the song, no word contained substring "WUB" in it; Vasya didn't change the word order. It is also guaranteed that initially the song had at least one word. | Print the words of the initial song that Vasya used to make a dubsteb remix. Separate the words with a space. | [
"WUBWUBABCWUB\n",
"WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB\n"
] | [
"ABC ",
"WE ARE THE CHAMPIONS MY FRIEND "
] | In the first sample: "WUBWUBABCWUB" = "WUB" + "WUB" + "ABC" + "WUB". That means that the song originally consisted of a single word "ABC", and all words "WUB" were added by Vasya.
In the second sample Vasya added a single word "WUB" between all neighbouring words, in the beginning and in the end, except for words "ARE" and "THE" — between them Vasya added two "WUB". | 500 | [
{
"input": "WUBWUBABCWUB",
"output": "ABC "
},
{
"input": "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB",
"output": "WE ARE THE CHAMPIONS MY FRIEND "
},
{
"input": "WUBWUBWUBSR",
"output": "SR "
},
{
"input": "RWUBWUBWUBLWUB",
"output": "R L "
},
{
"input": "... | 1,694,456,959 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 3 | 154 | 2,252,800 | import re
x = input()
if re.match(r'WUB', x):
x = re.sub(r'WUB', ' ', x)
c=0
for i in x:
if i==' ':
c+=1
else:
break
print(x[c:]) | Title: Dubstep
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.
For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".
Recently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.
Input Specification:
The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters. It is guaranteed that before Vasya remixed the song, no word contained substring "WUB" in it; Vasya didn't change the word order. It is also guaranteed that initially the song had at least one word.
Output Specification:
Print the words of the initial song that Vasya used to make a dubsteb remix. Separate the words with a space.
Demo Input:
['WUBWUBABCWUB\n', 'WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB\n']
Demo Output:
['ABC ', 'WE ARE THE CHAMPIONS MY FRIEND ']
Note:
In the first sample: "WUBWUBABCWUB" = "WUB" + "WUB" + "ABC" + "WUB". That means that the song originally consisted of a single word "ABC", and all words "WUB" were added by Vasya.
In the second sample Vasya added a single word "WUB" between all neighbouring words, in the beginning and in the end, except for words "ARE" and "THE" — between them Vasya added two "WUB". | ```python
import re
x = input()
if re.match(r'WUB', x):
x = re.sub(r'WUB', ' ', x)
c=0
for i in x:
if i==' ':
c+=1
else:
break
print(x[c:])
``` | 0 | |
381 | A | Sereja and Dima | PROGRAMMING | 800 | [
"greedy",
"implementation",
"two pointers"
] | null | null | Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.
Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.
Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her. | The first line contains integer *n* (1<=≤<=*n*<=≤<=1000) — the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000. | On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game. | [
"4\n4 1 2 10\n",
"7\n1 2 3 4 5 6 7\n"
] | [
"12 5\n",
"16 12\n"
] | In the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5. | 500 | [
{
"input": "4\n4 1 2 10",
"output": "12 5"
},
{
"input": "7\n1 2 3 4 5 6 7",
"output": "16 12"
},
{
"input": "42\n15 29 37 22 16 5 26 31 6 32 19 3 45 36 33 14 25 20 48 7 42 11 24 28 9 18 8 21 47 17 38 40 44 4 35 1 43 39 41 27 12 13",
"output": "613 418"
},
{
"input": "43\n32 ... | 1,687,615,289 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 31 | 0 | n=int(input())
list1=list(map(int,input().split()))
list1.sort()
list1.reverse()
jawad=0
yara=0
for x in list1:
if list1.index(x)%2!=0:
jawad+=x
else:
yara+=x
print(yara,jawad)
| Title: Sereja and Dima
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.
Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.
Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=1000) — the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.
Output Specification:
On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.
Demo Input:
['4\n4 1 2 10\n', '7\n1 2 3 4 5 6 7\n']
Demo Output:
['12 5\n', '16 12\n']
Note:
In the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5. | ```python
n=int(input())
list1=list(map(int,input().split()))
list1.sort()
list1.reverse()
jawad=0
yara=0
for x in list1:
if list1.index(x)%2!=0:
jawad+=x
else:
yara+=x
print(yara,jawad)
``` | 0 | |
600 | B | Queries about less or equal elements | PROGRAMMING | 1,300 | [
"binary search",
"data structures",
"sortings",
"two pointers"
] | null | null | You are given two arrays of integers *a* and *b*. For each element of the second array *b**j* you should find the number of elements in array *a* that are less than or equal to the value *b**j*. | The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=2·105) — the sizes of arrays *a* and *b*.
The second line contains *n* integers — the elements of array *a* (<=-<=109<=≤<=*a**i*<=≤<=109).
The third line contains *m* integers — the elements of array *b* (<=-<=109<=≤<=*b**j*<=≤<=109). | Print *m* integers, separated by spaces: the *j*-th of which is equal to the number of such elements in array *a* that are less than or equal to the value *b**j*. | [
"5 4\n1 3 5 7 9\n6 4 2 8\n",
"5 5\n1 2 1 2 5\n3 1 4 1 5\n"
] | [
"3 2 1 4\n",
"4 2 4 2 5\n"
] | none | 0 | [
{
"input": "5 4\n1 3 5 7 9\n6 4 2 8",
"output": "3 2 1 4"
},
{
"input": "5 5\n1 2 1 2 5\n3 1 4 1 5",
"output": "4 2 4 2 5"
},
{
"input": "1 1\n-1\n-2",
"output": "0"
},
{
"input": "1 1\n-80890826\n686519510",
"output": "1"
},
{
"input": "11 11\n237468511 -77918754... | 1,650,817,694 | 2,147,483,647 | Python 3 | OK | TESTS | 60 | 623 | 17,203,200 | from bisect import *
I=lambda:map(int,input().split())
I()
l=sorted(I())
for e in I():print(bisect_right(l,e),end=' ') | Title: Queries about less or equal elements
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two arrays of integers *a* and *b*. For each element of the second array *b**j* you should find the number of elements in array *a* that are less than or equal to the value *b**j*.
Input Specification:
The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=2·105) — the sizes of arrays *a* and *b*.
The second line contains *n* integers — the elements of array *a* (<=-<=109<=≤<=*a**i*<=≤<=109).
The third line contains *m* integers — the elements of array *b* (<=-<=109<=≤<=*b**j*<=≤<=109).
Output Specification:
Print *m* integers, separated by spaces: the *j*-th of which is equal to the number of such elements in array *a* that are less than or equal to the value *b**j*.
Demo Input:
['5 4\n1 3 5 7 9\n6 4 2 8\n', '5 5\n1 2 1 2 5\n3 1 4 1 5\n']
Demo Output:
['3 2 1 4\n', '4 2 4 2 5\n']
Note:
none | ```python
from bisect import *
I=lambda:map(int,input().split())
I()
l=sorted(I())
for e in I():print(bisect_right(l,e),end=' ')
``` | 3 | |
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,621,341,220 | 2,147,483,647 | PyPy 3 | TIME_LIMIT_EXCEEDED | TESTS | 3 | 1,000 | 1,536,000 | n, k = list(map(int, input().split()))
b = 10**k
l = max(n,b)
s = min(n,b)
i = l
while True:
if i%s == 0:
print(i)
break
else:
i += l
| 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
n, k = list(map(int, input().split()))
b = 10**k
l = max(n,b)
s = min(n,b)
i = l
while True:
if i%s == 0:
print(i)
break
else:
i += l
``` | 0 | |
10 | D | LCIS | PROGRAMMING | 2,800 | [
"dp"
] | D. LCIS | 1 | 256 | This problem differs from one which was on the online contest.
The sequence *a*1,<=*a*2,<=...,<=*a**n* is called increasing, if *a**i*<=<<=*a**i*<=+<=1 for *i*<=<<=*n*.
The sequence *s*1,<=*s*2,<=...,<=*s**k* is called the subsequence of the sequence *a*1,<=*a*2,<=...,<=*a**n*, if there exist such a set of indexes 1<=≤<=*i*1<=<<=*i*2<=<<=...<=<<=*i**k*<=≤<=*n* that *a**i**j*<==<=*s**j*. In other words, the sequence *s* can be derived from the sequence *a* by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=500) — the length of the first sequence. The second line contains *n* space-separated integers from the range [0,<=109] — elements of the first sequence. The third line contains an integer *m* (1<=≤<=*m*<=≤<=500) — the length of the second sequence. The fourth line contains *m* space-separated integers from the range [0,<=109] — elements of the second sequence. | In the first line output *k* — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any. | [
"7\n2 3 1 6 5 4 6\n4\n1 3 5 6\n",
"5\n1 2 0 2 1\n3\n1 0 1\n"
] | [
"3\n3 5 6 \n",
"2\n0 1 \n"
] | none | 0 | [
{
"input": "7\n2 3 1 6 5 4 6\n4\n1 3 5 6",
"output": "3\n3 5 6 "
},
{
"input": "5\n1 2 0 2 1\n3\n1 0 1",
"output": "2\n0 1 "
},
{
"input": "2\n6 10\n3\n6 3 3",
"output": "1\n6 "
},
{
"input": "1\n7\n2\n7 9",
"output": "1\n7 "
},
{
"input": "3\n37 49 24\n3\n33 5 70... | 1,608,455,491 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 77 | 204,800 | n = int(input())
arr1 = list(map(int, input().split()))
m = int(input())
arr2 = list(map(int, input().split()))
D = []
for i in range(0, n+1):
D.append([])
D[i].append([])
for j in range(1, m+1):
D[0].append([])
for i in range(1, n+1):
for j in range(1, m+1):
if arr1[i-1]==arr2[j-1]:
D[i].append(list(D[i-1][j-1]))
D[i][j].append(arr1[i-1])
elif len(D[i-1][j])>len(D[i][j-1]):
D[i].append(D[i-1][j])
else:
D[i].append(D[i][j-1])
print(len(D[n][m]))
print(*D[n][m])
| Title: LCIS
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
This problem differs from one which was on the online contest.
The sequence *a*1,<=*a*2,<=...,<=*a**n* is called increasing, if *a**i*<=<<=*a**i*<=+<=1 for *i*<=<<=*n*.
The sequence *s*1,<=*s*2,<=...,<=*s**k* is called the subsequence of the sequence *a*1,<=*a*2,<=...,<=*a**n*, if there exist such a set of indexes 1<=≤<=*i*1<=<<=*i*2<=<<=...<=<<=*i**k*<=≤<=*n* that *a**i**j*<==<=*s**j*. In other words, the sequence *s* can be derived from the sequence *a* by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=500) — the length of the first sequence. The second line contains *n* space-separated integers from the range [0,<=109] — elements of the first sequence. The third line contains an integer *m* (1<=≤<=*m*<=≤<=500) — the length of the second sequence. The fourth line contains *m* space-separated integers from the range [0,<=109] — elements of the second sequence.
Output Specification:
In the first line output *k* — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Demo Input:
['7\n2 3 1 6 5 4 6\n4\n1 3 5 6\n', '5\n1 2 0 2 1\n3\n1 0 1\n']
Demo Output:
['3\n3 5 6 \n', '2\n0 1 \n']
Note:
none | ```python
n = int(input())
arr1 = list(map(int, input().split()))
m = int(input())
arr2 = list(map(int, input().split()))
D = []
for i in range(0, n+1):
D.append([])
D[i].append([])
for j in range(1, m+1):
D[0].append([])
for i in range(1, n+1):
for j in range(1, m+1):
if arr1[i-1]==arr2[j-1]:
D[i].append(list(D[i-1][j-1]))
D[i][j].append(arr1[i-1])
elif len(D[i-1][j])>len(D[i][j-1]):
D[i].append(D[i-1][j])
else:
D[i].append(D[i][j-1])
print(len(D[n][m]))
print(*D[n][m])
``` | 0 |
886 | B | Vlad and Cafes | PROGRAMMING | 1,000 | [] | null | null | Vlad likes to eat in cafes very much. During his life, he has visited cafes *n* times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe. | In first line there is one integer *n* (1<=≤<=*n*<=≤<=2·105) — number of cafes indices written by Vlad.
In second line, *n* numbers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=2·105) are written — indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted. | Print one integer — index of the cafe that Vlad hasn't visited for as long as possible. | [
"5\n1 3 2 1 2\n",
"6\n2 1 2 2 4 1\n"
] | [
"3\n",
"2\n"
] | In first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer.
In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes. | 1,000 | [
{
"input": "5\n1 3 2 1 2",
"output": "3"
},
{
"input": "6\n2 1 2 2 4 1",
"output": "2"
},
{
"input": "1\n0",
"output": "0"
},
{
"input": "1\n200000",
"output": "200000"
},
{
"input": "2\n2018 2017",
"output": "2018"
},
{
"input": "5\n100 1000 1000 1000... | 1,510,507,817 | 5,117 | Python 3 | TIME_LIMIT_EXCEEDED | PRETESTS | 4 | 2,000 | 14,233,600 | n = int(input())
s = [int(k) for k in input().split()]
s1 = []
for i in range(0, n):
if s[i] in s1:
s1.remove(s[i])
s1.append(s[i])
print(s1[0]) | Title: Vlad and Cafes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vlad likes to eat in cafes very much. During his life, he has visited cafes *n* times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.
Input Specification:
In first line there is one integer *n* (1<=≤<=*n*<=≤<=2·105) — number of cafes indices written by Vlad.
In second line, *n* numbers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=2·105) are written — indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted.
Output Specification:
Print one integer — index of the cafe that Vlad hasn't visited for as long as possible.
Demo Input:
['5\n1 3 2 1 2\n', '6\n2 1 2 2 4 1\n']
Demo Output:
['3\n', '2\n']
Note:
In first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer.
In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes. | ```python
n = int(input())
s = [int(k) for k in input().split()]
s1 = []
for i in range(0, n):
if s[i] in s1:
s1.remove(s[i])
s1.append(s[i])
print(s1[0])
``` | 0 | |
954 | A | Diagonal Walking | PROGRAMMING | 800 | [
"implementation"
] | null | null | Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.
Your problem is to print the minimum possible length of the sequence of moves after the replacements. | The first line of the input contains one integer *n* (1<=≤<=*n*<=≤<=100) — the length of the sequence. The second line contains the sequence consisting of *n* characters U and R. | Print the minimum possible length of the sequence of moves after all replacements are done. | [
"5\nRUURU\n",
"17\nUUURRRRRUUURURUUU\n"
] | [
"3\n",
"13\n"
] | In the first test the shortened sequence of moves may be DUD (its length is 3).
In the second test the shortened sequence of moves can be UUDRRRDUDDUUU (its length is 13). | 0 | [
{
"input": "5\nRUURU",
"output": "3"
},
{
"input": "17\nUUURRRRRUUURURUUU",
"output": "13"
},
{
"input": "100\nUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU",
"output": "100"
},
{
"input": "100\nRRURRUUUURURRRURRRRURRRRRR... | 1,637,549,303 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | n = int(input(' '))
s = input(' ')
c=0
d=0
while d<n-1:
if((s[d]=='U' and s[d+1]=='R') or (s[d]=='R' and s[d+1]=='U'))
c = c + 1
i = i + 2
else:
i = i + 1
result = n - count
print(res) | Title: Diagonal Walking
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.
Your problem is to print the minimum possible length of the sequence of moves after the replacements.
Input Specification:
The first line of the input contains one integer *n* (1<=≤<=*n*<=≤<=100) — the length of the sequence. The second line contains the sequence consisting of *n* characters U and R.
Output Specification:
Print the minimum possible length of the sequence of moves after all replacements are done.
Demo Input:
['5\nRUURU\n', '17\nUUURRRRRUUURURUUU\n']
Demo Output:
['3\n', '13\n']
Note:
In the first test the shortened sequence of moves may be DUD (its length is 3).
In the second test the shortened sequence of moves can be UUDRRRDUDDUUU (its length is 13). | ```python
n = int(input(' '))
s = input(' ')
c=0
d=0
while d<n-1:
if((s[d]=='U' and s[d+1]=='R') or (s[d]=='R' and s[d+1]=='U'))
c = c + 1
i = i + 2
else:
i = i + 1
result = n - count
print(res)
``` | -1 | |
723 | A | The New Year: Meeting Friends | PROGRAMMING | 800 | [
"implementation",
"math",
"sortings"
] | null | null | There are three friend living on the straight line *Ox* in Lineland. The first friend lives at the point *x*1, the second friend lives at the point *x*2, and the third friend lives at the point *x*3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?
It's guaranteed that the optimal answer is always integer. | The first line of the input contains three distinct integers *x*1, *x*2 and *x*3 (1<=≤<=*x*1,<=*x*2,<=*x*3<=≤<=100) — the coordinates of the houses of the first, the second and the third friends respectively. | Print one integer — the minimum total distance the friends need to travel in order to meet together. | [
"7 1 4\n",
"30 20 10\n"
] | [
"6\n",
"20\n"
] | In the first sample, friends should meet at the point 4. Thus, the first friend has to travel the distance of 3 (from the point 7 to the point 4), the second friend also has to travel the distance of 3 (from the point 1 to the point 4), while the third friend should not go anywhere because he lives at the point 4. | 500 | [
{
"input": "7 1 4",
"output": "6"
},
{
"input": "30 20 10",
"output": "20"
},
{
"input": "1 4 100",
"output": "99"
},
{
"input": "100 1 91",
"output": "99"
},
{
"input": "1 45 100",
"output": "99"
},
{
"input": "1 2 3",
"output": "2"
},
{
"... | 1,681,794,458 | 2,147,483,647 | Python 3 | OK | TESTS | 48 | 62 | 0 | arr = input().split()
arr = [int(x) for x in arr]
arr.sort()
distanceArr = []
for i in range(arr[0], arr[2] + 1):
distanceArr.append(abs(arr[0] - i) + abs(arr[1] - i) + abs(arr[2] - i))
print(min(distanceArr)) | Title: The New Year: Meeting Friends
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are three friend living on the straight line *Ox* in Lineland. The first friend lives at the point *x*1, the second friend lives at the point *x*2, and the third friend lives at the point *x*3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?
It's guaranteed that the optimal answer is always integer.
Input Specification:
The first line of the input contains three distinct integers *x*1, *x*2 and *x*3 (1<=≤<=*x*1,<=*x*2,<=*x*3<=≤<=100) — the coordinates of the houses of the first, the second and the third friends respectively.
Output Specification:
Print one integer — the minimum total distance the friends need to travel in order to meet together.
Demo Input:
['7 1 4\n', '30 20 10\n']
Demo Output:
['6\n', '20\n']
Note:
In the first sample, friends should meet at the point 4. Thus, the first friend has to travel the distance of 3 (from the point 7 to the point 4), the second friend also has to travel the distance of 3 (from the point 1 to the point 4), while the third friend should not go anywhere because he lives at the point 4. | ```python
arr = input().split()
arr = [int(x) for x in arr]
arr.sort()
distanceArr = []
for i in range(arr[0], arr[2] + 1):
distanceArr.append(abs(arr[0] - i) + abs(arr[1] - i) + abs(arr[2] - i))
print(min(distanceArr))
``` | 3 | |
1 | A | Theatre Square | PROGRAMMING | 1,000 | [
"math"
] | A. Theatre Square | 1 | 256 | Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square. | The input contains three positive integer numbers in the first line: *n*,<=<=*m* and *a* (1<=≤<=<=*n*,<=*m*,<=*a*<=≤<=109). | Write the needed number of flagstones. | [
"6 6 4\n"
] | [
"4\n"
] | none | 0 | [
{
"input": "6 6 4",
"output": "4"
},
{
"input": "1 1 1",
"output": "1"
},
{
"input": "2 1 1",
"output": "2"
},
{
"input": "1 2 1",
"output": "2"
},
{
"input": "2 2 1",
"output": "4"
},
{
"input": "2 1 2",
"output": "1"
},
{
"input": "1 1 3"... | 1,688,446,321 | 2,147,483,647 | Python 3 | OK | TESTS | 20 | 31 | 0 | # Codeforces 1A Theatre Square
def tiles(size, length):
reqd = size // length
rem = size % length
return reqd if rem == 0 else reqd + 1
n, m, a = (int(i) for i in input().split())
print(tiles(n, a) * tiles(m, a)) | 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
# Codeforces 1A Theatre Square
def tiles(size, length):
reqd = size // length
rem = size % length
return reqd if rem == 0 else reqd + 1
n, m, a = (int(i) for i in input().split())
print(tiles(n, a) * tiles(m, a))
``` | 3.9845 |
569 | A | Music | PROGRAMMING | 1,500 | [
"implementation",
"math"
] | null | null | Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is *T* seconds. Lesha downloads the first *S* seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For *q* seconds of real time the Internet allows you to download *q*<=-<=1 seconds of the track.
Tell Lesha, for how many times he will start the song, including the very first start. | The single line contains three integers *T*,<=*S*,<=*q* (2<=≤<=*q*<=≤<=104, 1<=≤<=*S*<=<<=*T*<=≤<=105). | Print a single integer — the number of times the song will be restarted. | [
"5 2 2\n",
"5 4 7\n",
"6 2 3\n"
] | [
"2\n",
"1\n",
"1\n"
] | In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.
In the second test, the song is almost downloaded, and Lesha will start it only once.
In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case. | 500 | [
{
"input": "5 2 2",
"output": "2"
},
{
"input": "5 4 7",
"output": "1"
},
{
"input": "6 2 3",
"output": "1"
},
{
"input": "2 1 2",
"output": "1"
},
{
"input": "2 1 3",
"output": "1"
},
{
"input": "2 1 10000",
"output": "1"
},
{
"input": "12... | 1,444,284,830 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 46 | 0 | import sys
for line in sys.stdin:
t,s,q=map(int,line.split())
r=float(q-1)/q
i = 0
while s<t:
s=float(s)/(1-r)
i+=1
print (i) | Title: Music
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is *T* seconds. Lesha downloads the first *S* seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For *q* seconds of real time the Internet allows you to download *q*<=-<=1 seconds of the track.
Tell Lesha, for how many times he will start the song, including the very first start.
Input Specification:
The single line contains three integers *T*,<=*S*,<=*q* (2<=≤<=*q*<=≤<=104, 1<=≤<=*S*<=<<=*T*<=≤<=105).
Output Specification:
Print a single integer — the number of times the song will be restarted.
Demo Input:
['5 2 2\n', '5 4 7\n', '6 2 3\n']
Demo Output:
['2\n', '1\n', '1\n']
Note:
In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.
In the second test, the song is almost downloaded, and Lesha will start it only once.
In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case. | ```python
import sys
for line in sys.stdin:
t,s,q=map(int,line.split())
r=float(q-1)/q
i = 0
while s<t:
s=float(s)/(1-r)
i+=1
print (i)
``` | 0 | |
599 | A | Patrick and Shopping | PROGRAMMING | 800 | [
"implementation"
] | null | null | Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a *d*1 meter long road between his house and the first shop and a *d*2 meter long road between his house and the second shop. Also, there is a road of length *d*3 directly connecting these two shops to each other. Help Patrick calculate the minimum distance that he needs to walk in order to go to both shops and return to his house.
Patrick always starts at his house. He should visit both shops moving only along the three existing roads and return back to his house. He doesn't mind visiting the same shop or passing the same road multiple times. The only goal is to minimize the total distance traveled. | The first line of the input contains three integers *d*1, *d*2, *d*3 (1<=≤<=*d*1,<=*d*2,<=*d*3<=≤<=108) — the lengths of the paths.
- *d*1 is the length of the path connecting Patrick's house and the first shop; - *d*2 is the length of the path connecting Patrick's house and the second shop; - *d*3 is the length of the path connecting both shops. | Print the minimum distance that Patrick will have to walk in order to visit both shops and return to his house. | [
"10 20 30\n",
"1 1 5\n"
] | [
"60\n",
"4\n"
] | The first sample is shown on the picture in the problem statement. One of the optimal routes is: house <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> first shop <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> second shop <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> house.
In the second sample one of the optimal routes is: house <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> first shop <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> house <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> second shop <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> house. | 500 | [
{
"input": "10 20 30",
"output": "60"
},
{
"input": "1 1 5",
"output": "4"
},
{
"input": "100 33 34",
"output": "134"
},
{
"input": "777 777 777",
"output": "2331"
},
{
"input": "2 2 8",
"output": "8"
},
{
"input": "12 34 56",
"output": "92"
},
... | 1,659,683,878 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 31 | 0 | a,b,c = list(map(int, input().split()))
if(a+b < c):
dis = (a+b)*2
elif(a+b > c):
dis = (a+b+c)
else:
dis = (a+b+c)
print(dis) | Title: Patrick and Shopping
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a *d*1 meter long road between his house and the first shop and a *d*2 meter long road between his house and the second shop. Also, there is a road of length *d*3 directly connecting these two shops to each other. Help Patrick calculate the minimum distance that he needs to walk in order to go to both shops and return to his house.
Patrick always starts at his house. He should visit both shops moving only along the three existing roads and return back to his house. He doesn't mind visiting the same shop or passing the same road multiple times. The only goal is to minimize the total distance traveled.
Input Specification:
The first line of the input contains three integers *d*1, *d*2, *d*3 (1<=≤<=*d*1,<=*d*2,<=*d*3<=≤<=108) — the lengths of the paths.
- *d*1 is the length of the path connecting Patrick's house and the first shop; - *d*2 is the length of the path connecting Patrick's house and the second shop; - *d*3 is the length of the path connecting both shops.
Output Specification:
Print the minimum distance that Patrick will have to walk in order to visit both shops and return to his house.
Demo Input:
['10 20 30\n', '1 1 5\n']
Demo Output:
['60\n', '4\n']
Note:
The first sample is shown on the picture in the problem statement. One of the optimal routes is: house <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> first shop <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> second shop <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> house.
In the second sample one of the optimal routes is: house <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> first shop <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> house <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> second shop <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> house. | ```python
a,b,c = list(map(int, input().split()))
if(a+b < c):
dis = (a+b)*2
elif(a+b > c):
dis = (a+b+c)
else:
dis = (a+b+c)
print(dis)
``` | 0 | |
267 | A | Subtractions | PROGRAMMING | 900 | [
"math",
"number theory"
] | null | null | You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).
You've got some number of pairs (*a**i*,<=*b**i*). How many operations will be performed for each of them? | The first line contains the number of pairs *n* (1<=<=≤<=<=*n*<=<=≤<=<=1000). Then follow *n* lines, each line contains a pair of positive integers *a**i*,<=*b**i* (1<=<=≤<=<=*a**i*,<=<=*b**i*<=<=≤<=<=109). | Print the sought number of operations for each pair on a single line. | [
"2\n4 17\n7 987654321\n"
] | [
"8\n141093479\n"
] | none | 500 | [
{
"input": "2\n4 17\n7 987654321",
"output": "8\n141093479"
},
{
"input": "10\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321",
"output": "141093479\n141093479\n141093479\n141093479\n141093479\n141093479\n141093479... | 1,633,726,217 | 2,147,483,647 | Python 3 | OK | TESTS | 35 | 62 | 6,963,200 | for x in range(int(input())):
a, b = [int(x) for x in input().split()]
count = 0
while a != 0 and b != 0:
if a > b:
factor = (a-b)//b + 1
a -= factor*b
count+=factor
else:
factor = (b-a)//a+1
b -= factor*a
count+=factor
print(count) | Title: Subtractions
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).
You've got some number of pairs (*a**i*,<=*b**i*). How many operations will be performed for each of them?
Input Specification:
The first line contains the number of pairs *n* (1<=<=≤<=<=*n*<=<=≤<=<=1000). Then follow *n* lines, each line contains a pair of positive integers *a**i*,<=*b**i* (1<=<=≤<=<=*a**i*,<=<=*b**i*<=<=≤<=<=109).
Output Specification:
Print the sought number of operations for each pair on a single line.
Demo Input:
['2\n4 17\n7 987654321\n']
Demo Output:
['8\n141093479\n']
Note:
none | ```python
for x in range(int(input())):
a, b = [int(x) for x in input().split()]
count = 0
while a != 0 and b != 0:
if a > b:
factor = (a-b)//b + 1
a -= factor*b
count+=factor
else:
factor = (b-a)//a+1
b -= factor*a
count+=factor
print(count)
``` | 3 | |
918 | B | Radio Station | PROGRAMMING | 900 | [
"implementation",
"strings"
] | null | null | As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has *n* servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form "command ip;" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers.
Each ip is of form "a.b.c.d" where *a*, *b*, *c* and *d* are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has *m* commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is "command ip;" Dustin has to replace it with "command ip; #name" where name is the name of the server with ip equal to ip.
Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him. | The first line of input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000).
The next *n* lines contain the names and ips of the servers. Each line contains a string name, name of the server and a string ip, ip of the server, separated by space (1<=≤<=|*name*|<=≤<=10, *name* only consists of English lowercase letters). It is guaranteed that all ip are distinct.
The next *m* lines contain the commands in the configuration file. Each line is of form "command ip;" (1<=≤<=|*command*|<=≤<=10, command only consists of English lowercase letters). It is guaranteed that ip belongs to one of the *n* school servers. | Print *m* lines, the commands in the configuration file after Dustin did his task. | [
"2 2\nmain 192.168.0.2\nreplica 192.168.0.1\nblock 192.168.0.1;\nproxy 192.168.0.2;\n",
"3 5\ngoogle 8.8.8.8\ncodeforces 212.193.33.27\nserver 138.197.64.57\nredirect 138.197.64.57;\nblock 8.8.8.8;\ncf 212.193.33.27;\nunblock 8.8.8.8;\ncheck 138.197.64.57;\n"
] | [
"block 192.168.0.1; #replica\nproxy 192.168.0.2; #main\n",
"redirect 138.197.64.57; #server\nblock 8.8.8.8; #google\ncf 212.193.33.27; #codeforces\nunblock 8.8.8.8; #google\ncheck 138.197.64.57; #server\n"
] | none | 1,000 | [
{
"input": "2 2\nmain 192.168.0.2\nreplica 192.168.0.1\nblock 192.168.0.1;\nproxy 192.168.0.2;",
"output": "block 192.168.0.1; #replica\nproxy 192.168.0.2; #main"
},
{
"input": "3 5\ngoogle 8.8.8.8\ncodeforces 212.193.33.27\nserver 138.197.64.57\nredirect 138.197.64.57;\nblock 8.8.8.8;\ncf 212.193.3... | 1,563,450,879 | 2,147,483,647 | Python 3 | OK | TESTS | 28 | 124 | 409,600 | n,m=map(int, input().split())
name=[]
ip1=[]
command=[]
ip2=[]
for i in range(n):
s=input().split()
name.append(s[0])
ip1.append(s[1])
for i in range(m):
s=input().split()
command.append(s[0])
ip2.append(s[1])
for i in range(m):
index=ip1.index(ip2[i][0:len(ip2[i])-1])
print("{} {} {}".format(command[i], ip2[i], "#"+name[index]))
| Title: Radio Station
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has *n* servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form "command ip;" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers.
Each ip is of form "a.b.c.d" where *a*, *b*, *c* and *d* are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has *m* commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is "command ip;" Dustin has to replace it with "command ip; #name" where name is the name of the server with ip equal to ip.
Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.
Input Specification:
The first line of input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000).
The next *n* lines contain the names and ips of the servers. Each line contains a string name, name of the server and a string ip, ip of the server, separated by space (1<=≤<=|*name*|<=≤<=10, *name* only consists of English lowercase letters). It is guaranteed that all ip are distinct.
The next *m* lines contain the commands in the configuration file. Each line is of form "command ip;" (1<=≤<=|*command*|<=≤<=10, command only consists of English lowercase letters). It is guaranteed that ip belongs to one of the *n* school servers.
Output Specification:
Print *m* lines, the commands in the configuration file after Dustin did his task.
Demo Input:
['2 2\nmain 192.168.0.2\nreplica 192.168.0.1\nblock 192.168.0.1;\nproxy 192.168.0.2;\n', '3 5\ngoogle 8.8.8.8\ncodeforces 212.193.33.27\nserver 138.197.64.57\nredirect 138.197.64.57;\nblock 8.8.8.8;\ncf 212.193.33.27;\nunblock 8.8.8.8;\ncheck 138.197.64.57;\n']
Demo Output:
['block 192.168.0.1; #replica\nproxy 192.168.0.2; #main\n', 'redirect 138.197.64.57; #server\nblock 8.8.8.8; #google\ncf 212.193.33.27; #codeforces\nunblock 8.8.8.8; #google\ncheck 138.197.64.57; #server\n']
Note:
none | ```python
n,m=map(int, input().split())
name=[]
ip1=[]
command=[]
ip2=[]
for i in range(n):
s=input().split()
name.append(s[0])
ip1.append(s[1])
for i in range(m):
s=input().split()
command.append(s[0])
ip2.append(s[1])
for i in range(m):
index=ip1.index(ip2[i][0:len(ip2[i])-1])
print("{} {} {}".format(command[i], ip2[i], "#"+name[index]))
``` | 3 | |
39 | B | Company Income Growth | PROGRAMMING | 1,300 | [
"greedy"
] | B. Company Income Growth | 2 | 64 | Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to *a*1 billion bourles, in 2002 — to *a*2 billion, ..., and in the current (2000<=+<=*n*)-th year — *a**n* billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to 1 billion bourles, in the second year — 2 billion bourles etc., each following year the income increases by 1 billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers *a**i* can even occur negative ones that are a sign of the company’s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers *a**i* from the sequence and leave only some subsequence that has perfect growth.
Thus Petya has to choose a sequence of years *y*1, *y*2, ..., *y**k*,so that in the year *y*1 the company income amounted to 1 billion bourles, in the year *y*2 — 2 billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). The next line contains *n* integers *a**i* (<=-<=100<=≤<=*a**i*<=≤<=100). The number *a**i* determines the income of BerSoft company in the (2000<=+<=*i*)-th year. The numbers in the line are separated by spaces. | Output *k* — the maximum possible length of a perfect sequence. In the next line output the sequence of years *y*1, *y*2, ..., *y**k*. Separate the numbers by spaces. If the answer is not unique, output any. If no solution exist, output one number 0. | [
"10\n-2 1 1 3 2 3 4 -10 -2 5\n",
"3\n-1 -2 -3\n"
] | [
"5\n2002 2005 2006 2007 2010\n",
"0\n"
] | none | 0 | [
{
"input": "10\n-2 1 1 3 2 3 4 -10 -2 5",
"output": "5\n2002 2005 2006 2007 2010 "
},
{
"input": "3\n-1 -2 -3",
"output": "0"
},
{
"input": "1\n0",
"output": "0"
},
{
"input": "1\n0",
"output": "0"
},
{
"input": "2\n-1 1",
"output": "1\n2002 "
},
{
"in... | 1,524,487,676 | 2,147,483,647 | Python 3 | OK | TESTS | 35 | 156 | 7,065,600 | _, values,i,years = int(input()),[int(i) for i in input().split(" ")],1,[]
if 1 in values:
years.append(values.index(1))
i=2
while i in values[years[-1]:]:
years.append(values[years[-1]:].index(i)+years[-1])
i+=1
print(len(years))
if len(years) !=0:
for year in years:
print(2001+year,end=" ")
print() | Title: Company Income Growth
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to *a*1 billion bourles, in 2002 — to *a*2 billion, ..., and in the current (2000<=+<=*n*)-th year — *a**n* billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to 1 billion bourles, in the second year — 2 billion bourles etc., each following year the income increases by 1 billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers *a**i* can even occur negative ones that are a sign of the company’s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers *a**i* from the sequence and leave only some subsequence that has perfect growth.
Thus Petya has to choose a sequence of years *y*1, *y*2, ..., *y**k*,so that in the year *y*1 the company income amounted to 1 billion bourles, in the year *y*2 — 2 billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). The next line contains *n* integers *a**i* (<=-<=100<=≤<=*a**i*<=≤<=100). The number *a**i* determines the income of BerSoft company in the (2000<=+<=*i*)-th year. The numbers in the line are separated by spaces.
Output Specification:
Output *k* — the maximum possible length of a perfect sequence. In the next line output the sequence of years *y*1, *y*2, ..., *y**k*. Separate the numbers by spaces. If the answer is not unique, output any. If no solution exist, output one number 0.
Demo Input:
['10\n-2 1 1 3 2 3 4 -10 -2 5\n', '3\n-1 -2 -3\n']
Demo Output:
['5\n2002 2005 2006 2007 2010\n', '0\n']
Note:
none | ```python
_, values,i,years = int(input()),[int(i) for i in input().split(" ")],1,[]
if 1 in values:
years.append(values.index(1))
i=2
while i in values[years[-1]:]:
years.append(values[years[-1]:].index(i)+years[-1])
i+=1
print(len(years))
if len(years) !=0:
for year in years:
print(2001+year,end=" ")
print()
``` | 3.908357 |
124 | A | The number of positions | PROGRAMMING | 1,000 | [
"math"
] | null | null | Petr stands in line of *n* people, but he doesn't know exactly which position he occupies. He can say that there are no less than *a* people standing in front of him and no more than *b* people standing behind him. Find the number of different positions Petr can occupy. | The only line contains three integers *n*, *a* and *b* (0<=≤<=*a*,<=*b*<=<<=*n*<=≤<=100). | Print the single number — the number of the sought positions. | [
"3 1 1\n",
"5 2 3\n"
] | [
"2\n",
"3\n"
] | The possible positions in the first sample are: 2 and 3 (if we number the positions starting with 1).
In the second sample they are 3, 4 and 5. | 500 | [
{
"input": "3 1 1",
"output": "2"
},
{
"input": "5 2 3",
"output": "3"
},
{
"input": "5 4 0",
"output": "1"
},
{
"input": "6 5 5",
"output": "1"
},
{
"input": "9 4 3",
"output": "4"
},
{
"input": "11 4 6",
"output": "7"
},
{
"input": "13 8 ... | 1,689,877,742 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 2 | 122 | 0 | a,b,c=map(int,input().split())
v=a-b
if(v<=b):
print(b)
else:
print(v) | Title: The number of positions
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petr stands in line of *n* people, but he doesn't know exactly which position he occupies. He can say that there are no less than *a* people standing in front of him and no more than *b* people standing behind him. Find the number of different positions Petr can occupy.
Input Specification:
The only line contains three integers *n*, *a* and *b* (0<=≤<=*a*,<=*b*<=<<=*n*<=≤<=100).
Output Specification:
Print the single number — the number of the sought positions.
Demo Input:
['3 1 1\n', '5 2 3\n']
Demo Output:
['2\n', '3\n']
Note:
The possible positions in the first sample are: 2 and 3 (if we number the positions starting with 1).
In the second sample they are 3, 4 and 5. | ```python
a,b,c=map(int,input().split())
v=a-b
if(v<=b):
print(b)
else:
print(v)
``` | 0 | |
337 | D | Book of Evil | PROGRAMMING | 2,000 | [
"dfs and similar",
"divide and conquer",
"dp",
"trees"
] | null | null | Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains *n* settlements numbered from 1 to *n*. Moving through the swamp is very difficult, so people tramped exactly *n*<=-<=1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.
The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range *d*. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance *d* or less from the settlement where the Book resides.
Manao has heard of *m* settlements affected by the Book of Evil. Their numbers are *p*1,<=*p*2,<=...,<=*p**m*. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task. | The first line contains three space-separated integers *n*, *m* and *d* (1<=≤<=*m*<=≤<=*n*<=≤<=100000; 0<=≤<=*d*<=≤<=*n*<=-<=1). The second line contains *m* distinct space-separated integers *p*1,<=*p*2,<=...,<=*p**m* (1<=≤<=*p**i*<=≤<=*n*). Then *n*<=-<=1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers *a**i* and *b**i* representing the ends of this path. | Print a single number — the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0. | [
"6 2 3\n1 2\n1 5\n2 3\n3 4\n4 5\n5 6\n"
] | [
"3\n"
] | Sample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5. | 2,000 | [
{
"input": "6 2 3\n1 2\n1 5\n2 3\n3 4\n4 5\n5 6",
"output": "3"
},
{
"input": "2 2 1\n2 1\n1 2",
"output": "2"
},
{
"input": "50 2 5\n9 14\n46 34\n40 35\n44 30\n32 16\n1 38\n48 2\n17 14\n50 25\n6 1\n45 19\n21 15\n22 11\n15 33\n8 28\n2 32\n10 22\n37 3\n43 39\n25 16\n9 19\n16 3\n28 32\n20 ... | 1,672,849,933 | 2,147,483,647 | PyPy 3 | MEMORY_LIMIT_EXCEEDED | TESTS | 0 | 122 | 268,390,400 | # LUOGU_RID: 98703200
import sys
sys.setrecursionlimit(10000000)
n, m, d = [int(i) for i in input().split()]
exist = [False] * (n + 1)
for i in input().split():
exist[int(i)] = True
dest = [[] for _ in range(n + 1)]
for _ in range(n - 1):
a, b = [int(i) for i in input().split()]
dest[a].append(b)
dest[b].append(a)
d_subtree = [-10000000] * (n + 1)
def dfs1(x, p):
if exist[x]:
d_subtree[x] = 0
for to in dest[x]:
if to != p:
dfs1(to, x)
d_subtree[x] = max(d_subtree[x], d_subtree[to] + 1)
dfs1(1, -1)
d_else = [-10000000] * (n + 1)
def dfs2(x, p):
max1 = -10000000
max2 = -10000000
if exist[x]:
d_else[x] = max(0, d_else[x])
for to in dest[x]:
if to == p:
continue
if d_subtree[to] > max1:
max2 = max1
max1 = d_subtree[to]
elif d_subtree[to] > max2:
max2 = d_subtree[to]
for to in dest[x]:
if to == p:
continue
sDist = max2 if d_subtree[to] == max1 else max1
if sDist >= 0:
sDist += 2
d_else[to] = max(sDist, d_else[x] + 1)
dfs2(to, x)
dfs2(1, -1)
print(sum([(d_subtree[i] <= d and d_else[i] <= d) for i in range(1, 1 + n)]))
# print("d_subtree", d_subtree[1:])
# print("d_else", d_else[1:])
# print([(d_subtree[i] <= d and d_else[i] <= d) for i in range(1, 1 + n)])
| Title: Book of Evil
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains *n* settlements numbered from 1 to *n*. Moving through the swamp is very difficult, so people tramped exactly *n*<=-<=1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.
The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range *d*. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance *d* or less from the settlement where the Book resides.
Manao has heard of *m* settlements affected by the Book of Evil. Their numbers are *p*1,<=*p*2,<=...,<=*p**m*. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.
Input Specification:
The first line contains three space-separated integers *n*, *m* and *d* (1<=≤<=*m*<=≤<=*n*<=≤<=100000; 0<=≤<=*d*<=≤<=*n*<=-<=1). The second line contains *m* distinct space-separated integers *p*1,<=*p*2,<=...,<=*p**m* (1<=≤<=*p**i*<=≤<=*n*). Then *n*<=-<=1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers *a**i* and *b**i* representing the ends of this path.
Output Specification:
Print a single number — the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0.
Demo Input:
['6 2 3\n1 2\n1 5\n2 3\n3 4\n4 5\n5 6\n']
Demo Output:
['3\n']
Note:
Sample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5. | ```python
# LUOGU_RID: 98703200
import sys
sys.setrecursionlimit(10000000)
n, m, d = [int(i) for i in input().split()]
exist = [False] * (n + 1)
for i in input().split():
exist[int(i)] = True
dest = [[] for _ in range(n + 1)]
for _ in range(n - 1):
a, b = [int(i) for i in input().split()]
dest[a].append(b)
dest[b].append(a)
d_subtree = [-10000000] * (n + 1)
def dfs1(x, p):
if exist[x]:
d_subtree[x] = 0
for to in dest[x]:
if to != p:
dfs1(to, x)
d_subtree[x] = max(d_subtree[x], d_subtree[to] + 1)
dfs1(1, -1)
d_else = [-10000000] * (n + 1)
def dfs2(x, p):
max1 = -10000000
max2 = -10000000
if exist[x]:
d_else[x] = max(0, d_else[x])
for to in dest[x]:
if to == p:
continue
if d_subtree[to] > max1:
max2 = max1
max1 = d_subtree[to]
elif d_subtree[to] > max2:
max2 = d_subtree[to]
for to in dest[x]:
if to == p:
continue
sDist = max2 if d_subtree[to] == max1 else max1
if sDist >= 0:
sDist += 2
d_else[to] = max(sDist, d_else[x] + 1)
dfs2(to, x)
dfs2(1, -1)
print(sum([(d_subtree[i] <= d and d_else[i] <= d) for i in range(1, 1 + n)]))
# print("d_subtree", d_subtree[1:])
# print("d_else", d_else[1:])
# print([(d_subtree[i] <= d and d_else[i] <= d) for i in range(1, 1 + n)])
``` | 0 | |
322 | A | Ciel and Dancing | PROGRAMMING | 1,000 | [
"greedy"
] | null | null | Fox Ciel and her friends are in a dancing room. There are *n* boys and *m* girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:
- either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before); - or the girl in the dancing pair must dance for the first time.
Help Fox Ciel to make a schedule that they can dance as many songs as possible. | The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the number of boys and girls in the dancing room. | In the first line print *k* — the number of songs during which they can dance. Then in the following *k* lines, print the indexes of boys and girls dancing during songs chronologically. You can assume that the boys are indexed from 1 to *n*, and the girls are indexed from 1 to *m*. | [
"2 1\n",
"2 2\n"
] | [
"2\n1 1\n2 1\n",
"3\n1 1\n1 2\n2 2\n"
] | In test case 1, there are 2 boys and 1 girl. We can have 2 dances: the 1st boy and 1st girl (during the first song), the 2nd boy and 1st girl (during the second song).
And in test case 2, we have 2 boys with 2 girls, the answer is 3. | 500 | [
{
"input": "2 1",
"output": "2\n1 1\n2 1"
},
{
"input": "2 2",
"output": "3\n1 1\n1 2\n2 2"
},
{
"input": "1 1",
"output": "1\n1 1"
},
{
"input": "2 3",
"output": "4\n1 1\n1 2\n1 3\n2 3"
},
{
"input": "4 4",
"output": "7\n1 1\n1 2\n1 3\n1 4\n4 4\n3 4\n2 4"
}... | 1,626,766,833 | 2,147,483,647 | PyPy 3 | OK | TESTS | 28 | 248 | 20,172,800 | b,g=map(int,input().split());g-=1
print(b+g)
for i in range(1,b+1):print(i,1)
for i in range(2,g+2):print(b,i) | Title: Ciel and Dancing
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Fox Ciel and her friends are in a dancing room. There are *n* boys and *m* girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:
- either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before); - or the girl in the dancing pair must dance for the first time.
Help Fox Ciel to make a schedule that they can dance as many songs as possible.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the number of boys and girls in the dancing room.
Output Specification:
In the first line print *k* — the number of songs during which they can dance. Then in the following *k* lines, print the indexes of boys and girls dancing during songs chronologically. You can assume that the boys are indexed from 1 to *n*, and the girls are indexed from 1 to *m*.
Demo Input:
['2 1\n', '2 2\n']
Demo Output:
['2\n1 1\n2 1\n', '3\n1 1\n1 2\n2 2\n']
Note:
In test case 1, there are 2 boys and 1 girl. We can have 2 dances: the 1st boy and 1st girl (during the first song), the 2nd boy and 1st girl (during the second song).
And in test case 2, we have 2 boys with 2 girls, the answer is 3. | ```python
b,g=map(int,input().split());g-=1
print(b+g)
for i in range(1,b+1):print(i,1)
for i in range(2,g+2):print(b,i)
``` | 3 | |
961 | A | Tetris | PROGRAMMING | 900 | [
"implementation"
] | null | null | You are given a following process.
There is a platform with $n$ columns. $1 \times 1$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column.
When all of the $n$ columns have at least one square in them, the bottom row is being removed. You will receive $1$ point for this, and all the squares left will fall down one row.
You task is to calculate the amount of points you will receive. | The first line of input contain 2 integer numbers $n$ and $m$ ($1 \le n, m \le 1000$) — the length of the platform and the number of the squares.
The next line contain $m$ integer numbers $c_1, c_2, \dots, c_m$ ($1 \le c_i \le n$) — column in which $i$-th square will appear. | Print one integer — the amount of points you will receive. | [
"3 9\n1 1 2 2 2 3 1 2 3\n"
] | [
"2\n"
] | In the sample case the answer will be equal to $2$ because after the appearing of $6$-th square will be removed one row (counts of the squares on the platform will look like $[2~ 3~ 1]$, and after removing one row will be $[1~ 2~ 0]$).
After the appearing of $9$-th square counts will be $[2~ 3~ 1]$, and after removing one row it will look like $[1~ 2~ 0]$.
So the answer will be equal to $2$. | 0 | [
{
"input": "3 9\n1 1 2 2 2 3 1 2 3",
"output": "2"
},
{
"input": "1 7\n1 1 1 1 1 1 1",
"output": "7"
},
{
"input": "1 1\n1",
"output": "1"
},
{
"input": "3 5\n1 1 1 2 3",
"output": "1"
},
{
"input": "4 6\n4 4 4 4 4 4",
"output": "0"
},
{
"input": "4 6\... | 1,637,379,064 | 2,147,483,647 | Python 3 | OK | TESTS | 29 | 46 | 0 | n,m=[int(x) for x in input().split()]
a=[int(x) for x in input().split()]
lst=[0]*(n+1)
for i in a:
lst[i]+=1
res=max(lst)
for i in range(1,n+1):
if lst[i]<res:
res=lst[i]
print(res) | Title: Tetris
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a following process.
There is a platform with $n$ columns. $1 \times 1$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column.
When all of the $n$ columns have at least one square in them, the bottom row is being removed. You will receive $1$ point for this, and all the squares left will fall down one row.
You task is to calculate the amount of points you will receive.
Input Specification:
The first line of input contain 2 integer numbers $n$ and $m$ ($1 \le n, m \le 1000$) — the length of the platform and the number of the squares.
The next line contain $m$ integer numbers $c_1, c_2, \dots, c_m$ ($1 \le c_i \le n$) — column in which $i$-th square will appear.
Output Specification:
Print one integer — the amount of points you will receive.
Demo Input:
['3 9\n1 1 2 2 2 3 1 2 3\n']
Demo Output:
['2\n']
Note:
In the sample case the answer will be equal to $2$ because after the appearing of $6$-th square will be removed one row (counts of the squares on the platform will look like $[2~ 3~ 1]$, and after removing one row will be $[1~ 2~ 0]$).
After the appearing of $9$-th square counts will be $[2~ 3~ 1]$, and after removing one row it will look like $[1~ 2~ 0]$.
So the answer will be equal to $2$. | ```python
n,m=[int(x) for x in input().split()]
a=[int(x) for x in input().split()]
lst=[0]*(n+1)
for i in a:
lst[i]+=1
res=max(lst)
for i in range(1,n+1):
if lst[i]<res:
res=lst[i]
print(res)
``` | 3 | |
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,695,110,074 | 2,147,483,647 | Python 3 | OK | TESTS | 32 | 46 | 0 | n,l = map(int,input().split())
l1 = list(map(int,input().split()))
l1.sort()
diff = 0
for i in range(n-1):
a = float( (l1[i+1] - l1[i])/2 )
diff = max(a ,diff)
diff = max((l-l1[-1]) , diff , l1[0] - 0)
diff= float(diff)
format(diff, '.6f')
print(diff) | 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,l = map(int,input().split())
l1 = list(map(int,input().split()))
l1.sort()
diff = 0
for i in range(n-1):
a = float( (l1[i+1] - l1[i])/2 )
diff = max(a ,diff)
diff = max((l-l1[-1]) , diff , l1[0] - 0)
diff= float(diff)
format(diff, '.6f')
print(diff)
``` | 3 | |
387 | B | George and Round | PROGRAMMING | 1,200 | [
"brute force",
"greedy",
"two pointers"
] | null | null | George decided to prepare a Codesecrof round, so he has prepared *m* problems for the round. Let's number the problems with integers 1 through *m*. George estimates the *i*-th problem's complexity by integer *b**i*.
To make the round good, he needs to put at least *n* problems there. Besides, he needs to have at least one problem with complexity exactly *a*1, at least one with complexity exactly *a*2, ..., and at least one with complexity exactly *a**n*. Of course, the round can also have problems with other complexities.
George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity *c* to any positive integer complexity *d* (*c*<=≥<=*d*), by changing limits on the input data.
However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the *m* he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity. | The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a*1<=<<=*a*2<=<<=...<=<<=*a**n*<=≤<=106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b*1<=≤<=*b*2...<=≤<=*b**m*<=≤<=106) — the complexities of the problems prepared by George. | Print a single integer — the answer to the problem. | [
"3 5\n1 2 3\n1 2 2 3 3\n",
"3 5\n1 2 3\n1 1 1 1 1\n",
"3 1\n2 3 4\n1\n"
] | [
"0\n",
"2\n",
"3\n"
] | In the first sample the set of the prepared problems meets the requirements for a good round.
In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.
In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4. | 1,000 | [
{
"input": "3 5\n1 2 3\n1 2 2 3 3",
"output": "0"
},
{
"input": "3 5\n1 2 3\n1 1 1 1 1",
"output": "2"
},
{
"input": "3 1\n2 3 4\n1",
"output": "3"
},
{
"input": "29 100\n20 32 41 67 72 155 331 382 399 412 465 470 484 511 515 529 616 637 679 715 733 763 826 843 862 903 925 97... | 1,598,001,831 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 3 | 155 | 25,292,800 | n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
x=max(max(a),max(b))
c=[0]*x
d=[0]*x
for i in range(n):
c[a[i]-1]+=1
for i in range(m):
d[b[i]-1]+=1
ans=0
for i in range(x):
if c[i]>d[i]:
ans+=c[i]-d[i]
print(ans) | Title: George and Round
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
George decided to prepare a Codesecrof round, so he has prepared *m* problems for the round. Let's number the problems with integers 1 through *m*. George estimates the *i*-th problem's complexity by integer *b**i*.
To make the round good, he needs to put at least *n* problems there. Besides, he needs to have at least one problem with complexity exactly *a*1, at least one with complexity exactly *a*2, ..., and at least one with complexity exactly *a**n*. Of course, the round can also have problems with other complexities.
George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity *c* to any positive integer complexity *d* (*c*<=≥<=*d*), by changing limits on the input data.
However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the *m* he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a*1<=<<=*a*2<=<<=...<=<<=*a**n*<=≤<=106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b*1<=≤<=*b*2...<=≤<=*b**m*<=≤<=106) — the complexities of the problems prepared by George.
Output Specification:
Print a single integer — the answer to the problem.
Demo Input:
['3 5\n1 2 3\n1 2 2 3 3\n', '3 5\n1 2 3\n1 1 1 1 1\n', '3 1\n2 3 4\n1\n']
Demo Output:
['0\n', '2\n', '3\n']
Note:
In the first sample the set of the prepared problems meets the requirements for a good round.
In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.
In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4. | ```python
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
x=max(max(a),max(b))
c=[0]*x
d=[0]*x
for i in range(n):
c[a[i]-1]+=1
for i in range(m):
d[b[i]-1]+=1
ans=0
for i in range(x):
if c[i]>d[i]:
ans+=c[i]-d[i]
print(ans)
``` | 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,652,193,909 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 92 | 0 | word = str(input())
upperCount = 0
lowerCount = 0
for item in word:
if item.isupper() == True:
upperCount += 1
else:
lowerCount += 1
if lowerCount >= upperCount:
print(word.lower())
else:
print(word.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
word = str(input())
upperCount = 0
lowerCount = 0
for item in word:
if item.isupper() == True:
upperCount += 1
else:
lowerCount += 1
if lowerCount >= upperCount:
print(word.lower())
else:
print(word.upper())
``` | 3.977 |
0 | none | none | none | 0 | [
"none"
] | null | null | Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are *n* players (including Limak himself) and right now all of them have bids on the table. *i*-th of them has bid with size *a**i* dollars.
Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot? | First line of input contains an integer *n* (2<=≤<=*n*<=≤<=105), the number of players.
The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — the bids of players. | Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise. | [
"4\n75 150 75 50\n",
"3\n100 150 250\n"
] | [
"Yes\n",
"No\n"
] | In the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.
It can be shown that in the second sample test there is no way to make all bids equal. | 0 | [
{
"input": "4\n75 150 75 50",
"output": "Yes"
},
{
"input": "3\n100 150 250",
"output": "No"
},
{
"input": "7\n34 34 68 34 34 68 34",
"output": "Yes"
},
{
"input": "10\n72 96 12 18 81 20 6 2 54 1",
"output": "No"
},
{
"input": "20\n958692492 954966768 77387000 724... | 1,573,100,040 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 23 | 373 | 7,475,200 | n = int(input())
numbers = list(map(int, input().split()))
MAX = 32000
bs = [True] * MAX
primes = []
def sieve():
bs[0] = False
bs[1] = False
for i in range(2, MAX):
if bs[i]:
for j in range(i * i, MAX, i):
bs[j] = False
primes.append(i)
def num_pfs(number):
num_pfs = 0
for p in primes:
if p * p > number:
break
while number % p == 0:
if p > 3:
num_pfs += 1
number //= p
if number > 1:
if number > 3:
num_pfs += 1
return num_pfs
sieve()
pfs = num_pfs(numbers[0])
possible = True
for i in range(1, len(numbers)):
if num_pfs(numbers[i]) != pfs:
possible = False
break
if possible:
print("Yes")
else:
print("No")
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are *n* players (including Limak himself) and right now all of them have bids on the table. *i*-th of them has bid with size *a**i* dollars.
Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
Input Specification:
First line of input contains an integer *n* (2<=≤<=*n*<=≤<=105), the number of players.
The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — the bids of players.
Output Specification:
Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.
Demo Input:
['4\n75 150 75 50\n', '3\n100 150 250\n']
Demo Output:
['Yes\n', 'No\n']
Note:
In the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.
It can be shown that in the second sample test there is no way to make all bids equal. | ```python
n = int(input())
numbers = list(map(int, input().split()))
MAX = 32000
bs = [True] * MAX
primes = []
def sieve():
bs[0] = False
bs[1] = False
for i in range(2, MAX):
if bs[i]:
for j in range(i * i, MAX, i):
bs[j] = False
primes.append(i)
def num_pfs(number):
num_pfs = 0
for p in primes:
if p * p > number:
break
while number % p == 0:
if p > 3:
num_pfs += 1
number //= p
if number > 1:
if number > 3:
num_pfs += 1
return num_pfs
sieve()
pfs = num_pfs(numbers[0])
possible = True
for i in range(1, len(numbers)):
if num_pfs(numbers[i]) != pfs:
possible = False
break
if possible:
print("Yes")
else:
print("No")
``` | 0 | |
493 | B | Vasya and Wrestling | PROGRAMMING | 1,400 | [
"implementation"
] | null | null | Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won. | The first line contains number *n* — the number of techniques that the wrestlers have used (1<=≤<=*n*<=≤<=2·105).
The following *n* lines contain integer numbers *a**i* (|*a**i*|<=≤<=109, *a**i*<=≠<=0). If *a**i* is positive, that means that the first wrestler performed the technique that was awarded with *a**i* points. And if *a**i* is negative, that means that the second wrestler performed the technique that was awarded with (<=-<=*a**i*) points.
The techniques are given in chronological order. | If the first wrestler wins, print string "first", otherwise print "second" | [
"5\n1\n2\n-3\n-4\n3\n",
"3\n-1\n-2\n3\n",
"2\n4\n-4\n"
] | [
"second\n",
"first\n",
"second\n"
] | Sequence *x* = *x*<sub class="lower-index">1</sub>*x*<sub class="lower-index">2</sub>... *x*<sub class="lower-index">|*x*|</sub> is lexicographically larger than sequence *y* = *y*<sub class="lower-index">1</sub>*y*<sub class="lower-index">2</sub>... *y*<sub class="lower-index">|*y*|</sub>, if either |*x*| > |*y*| and *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">|*y*|</sub> = *y*<sub class="lower-index">|*y*|</sub>, or there is such number *r* (*r* < |*x*|, *r* < |*y*|), 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>.
We use notation |*a*| to denote length of sequence *a*. | 1,000 | [
{
"input": "5\n1\n2\n-3\n-4\n3",
"output": "second"
},
{
"input": "3\n-1\n-2\n3",
"output": "first"
},
{
"input": "2\n4\n-4",
"output": "second"
},
{
"input": "7\n1\n2\n-3\n4\n5\n-6\n7",
"output": "first"
},
{
"input": "14\n1\n2\n3\n4\n5\n6\n7\n-8\n-9\n-10\n-11\n-... | 1,418,653,551 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 6 | 62 | 0 | k=0
i=int(input())
while i>0:
n=int(input())
k+=n
i-=1
if k>0 or k==0 and n>0:
print('first')
if k<0 or k==0 and n<0:
print('second')
| Title: Vasya and Wrestling
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input Specification:
The first line contains number *n* — the number of techniques that the wrestlers have used (1<=≤<=*n*<=≤<=2·105).
The following *n* lines contain integer numbers *a**i* (|*a**i*|<=≤<=109, *a**i*<=≠<=0). If *a**i* is positive, that means that the first wrestler performed the technique that was awarded with *a**i* points. And if *a**i* is negative, that means that the second wrestler performed the technique that was awarded with (<=-<=*a**i*) points.
The techniques are given in chronological order.
Output Specification:
If the first wrestler wins, print string "first", otherwise print "second"
Demo Input:
['5\n1\n2\n-3\n-4\n3\n', '3\n-1\n-2\n3\n', '2\n4\n-4\n']
Demo Output:
['second\n', 'first\n', 'second\n']
Note:
Sequence *x* = *x*<sub class="lower-index">1</sub>*x*<sub class="lower-index">2</sub>... *x*<sub class="lower-index">|*x*|</sub> is lexicographically larger than sequence *y* = *y*<sub class="lower-index">1</sub>*y*<sub class="lower-index">2</sub>... *y*<sub class="lower-index">|*y*|</sub>, if either |*x*| > |*y*| and *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">|*y*|</sub> = *y*<sub class="lower-index">|*y*|</sub>, or there is such number *r* (*r* < |*x*|, *r* < |*y*|), 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>.
We use notation |*a*| to denote length of sequence *a*. | ```python
k=0
i=int(input())
while i>0:
n=int(input())
k+=n
i-=1
if k>0 or k==0 and n>0:
print('first')
if k<0 or k==0 and n<0:
print('second')
``` | 0 | |
592 | C | The Big Race | PROGRAMMING | 1,800 | [
"math"
] | null | null | Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of *L* meters today.
Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.
While watching previous races the organizers have noticed that Willman can perform only steps of length equal to *w* meters, and Bolt can perform only steps of length equal to *b* meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes).
Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance *L*.
Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to *t* (both are included). What is the probability that Willman and Bolt tie again today? | The first line of the input contains three integers *t*, *w* and *b* (1<=≤<=*t*,<=*w*,<=*b*<=≤<=5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. | Print the answer to the problem as an irreducible fraction . Follow the format of the samples output.
The fraction (*p* and *q* are integers, and both *p*<=≥<=0 and *q*<=><=0 holds) is called irreducible, if there is no such integer *d*<=><=1, that both *p* and *q* are divisible by *d*. | [
"10 3 2\n",
"7 1 2\n"
] | [
"3/10\n",
"3/7\n"
] | In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack. | 1,500 | [
{
"input": "10 3 2",
"output": "3/10"
},
{
"input": "7 1 2",
"output": "3/7"
},
{
"input": "1 1 1",
"output": "1/1"
},
{
"input": "5814 31 7",
"output": "94/2907"
},
{
"input": "94268 813 766",
"output": "765/94268"
},
{
"input": "262610 5583 4717",
... | 1,446,314,579 | 5,579 | Python 3 | WRONG_ANSWER | PRETESTS | 2 | 46 | 0 | def lcm(a,b):
m = a*b
while a != 0 and b != 0:
if a > b:
a %= b
else:
b %= a
return m // (a+b)
t,w,b = map(int,input().split())
if (t % 3 == 0):
print('1/',end ='')
print(t/3)
else:
print('3/',end='')
print(t)
| Title: The Big Race
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of *L* meters today.
Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.
While watching previous races the organizers have noticed that Willman can perform only steps of length equal to *w* meters, and Bolt can perform only steps of length equal to *b* meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes).
Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance *L*.
Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to *t* (both are included). What is the probability that Willman and Bolt tie again today?
Input Specification:
The first line of the input contains three integers *t*, *w* and *b* (1<=≤<=*t*,<=*w*,<=*b*<=≤<=5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively.
Output Specification:
Print the answer to the problem as an irreducible fraction . Follow the format of the samples output.
The fraction (*p* and *q* are integers, and both *p*<=≥<=0 and *q*<=><=0 holds) is called irreducible, if there is no such integer *d*<=><=1, that both *p* and *q* are divisible by *d*.
Demo Input:
['10 3 2\n', '7 1 2\n']
Demo Output:
['3/10\n', '3/7\n']
Note:
In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack. | ```python
def lcm(a,b):
m = a*b
while a != 0 and b != 0:
if a > b:
a %= b
else:
b %= a
return m // (a+b)
t,w,b = map(int,input().split())
if (t % 3 == 0):
print('1/',end ='')
print(t/3)
else:
print('3/',end='')
print(t)
``` | 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.