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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
34 | A | Reconnaissance 2 | PROGRAMMING | 800 | [
"implementation"
] | A. Reconnaissance 2 | 2 | 256 | *n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit. | The first line contains integer *n* (2<=≤<=*n*<=≤<=100) — amount of soldiers. Then follow the heights of the soldiers in their order in the circle — *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1000). The soldier heights are given in clockwise or counterclockwise direction. | Output two integers — indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle. | [
"5\n10 12 13 15 10\n",
"4\n10 20 30 40\n"
] | [
"5 1\n",
"1 2\n"
] | none | 500 | [
{
"input": "5\n10 12 13 15 10",
"output": "5 1"
},
{
"input": "4\n10 20 30 40",
"output": "1 2"
},
{
"input": "6\n744 359 230 586 944 442",
"output": "2 3"
},
{
"input": "5\n826 747 849 687 437",
"output": "1 2"
},
{
"input": "5\n999 999 993 969 999",
"output"... | 1,607,662,357 | 757 | Python 3 | OK | TESTS | 20 | 216 | 307,200 | n = int(input())
l = list(map(int,input().split()))
m = []
for i in range(len(l)-1):
m.append(abs(l[i+1] - l[i]))
m.append(abs(l[-1] - l[0]))
mh = m.index(min(m)) + 1
if mh < n:
print(mh,mh+1)
else:
print(mh,1)
| Title: Reconnaissance 2
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
*n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.
Input Specification:
The first line contains integer *n* (2<=≤<=*n*<=≤<=100) — amount of soldiers. Then follow the heights of the soldiers in their order in the circle — *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1000). The soldier heights are given in clockwise or counterclockwise direction.
Output Specification:
Output two integers — indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.
Demo Input:
['5\n10 12 13 15 10\n', '4\n10 20 30 40\n']
Demo Output:
['5 1\n', '1 2\n']
Note:
none | ```python
n = int(input())
l = list(map(int,input().split()))
m = []
for i in range(len(l)-1):
m.append(abs(l[i+1] - l[i]))
m.append(abs(l[-1] - l[0]))
mh = m.index(min(m)) + 1
if mh < n:
print(mh,mh+1)
else:
print(mh,1)
``` | 3.945428 |
616 | C | The Labyrinth | PROGRAMMING | 1,600 | [
"dfs and similar"
] | null | null | You are given a rectangular field of *n*<=×<=*m* cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.
Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.
For each impassable cell (*x*,<=*y*) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (*x*,<=*y*). You should do it for each impassable cell independently.
The answer should be printed as a matrix with *n* rows and *m* columns. The *j*-th symbol of the *i*-th row should be "." if the cell is empty at the start. Otherwise the *j*-th symbol of the *i*-th row should contain the only digit —- the answer modulo 10. The matrix should be printed without any spaces.
To make your output faster it is recommended to build the output as an array of *n* strings having length *m* and print it as a sequence of lines. It will be much faster than writing character-by-character.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. | The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and columns in the field.
Each of the next *n* lines contains *m* symbols: "." for empty cells, "*" for impassable cells. | Print the answer as a matrix as described above. See the examples to precise the format of the output. | [
"3 3\n*.*\n.*.\n*.*\n",
"4 5\n**..*\n..***\n.*.*.\n*.*.*\n"
] | [
"3.3\n.5.\n3.3\n",
"46..3\n..732\n.6.4.\n5.4.3\n"
] | In first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner). | 0 | [
{
"input": "3 3\n*.*\n.*.\n*.*",
"output": "3.3\n.5.\n3.3"
},
{
"input": "4 5\n**..*\n..***\n.*.*.\n*.*.*",
"output": "46..3\n..732\n.6.4.\n5.4.3"
},
{
"input": "1 1\n*",
"output": "1"
},
{
"input": "1 1\n.",
"output": "."
},
{
"input": "1 10\n**********",
"ou... | 1,625,199,236 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 8 | 77 | 102,400 | from collections import deque
def bfs(i, j, tablero):
contador = 1
actual = (i, j)
cola = deque([])
visitados = []
cola.append(actual)
while len(cola) > 0:
actual = cola.popleft()
x = actual[0]
y = actual[1]
if(x-1 >= 0):
if((x-1, y) not in visitados and tablero[x-1][y] == "."):
cola.append((x-1, y))
visitados.append((x-1, y))
contador += 1
if(y-1 >= 0):
if((x, y-1) not in visitados and tablero[x][y-1] == "."):
cola.append((x, y-1))
visitados.append((x, y-1))
contador += 1
if(x+1 < len(tablero)):
if((x+1, y) not in visitados and tablero[x+1][y] == "."):
cola.append((x+1, y))
visitados.append((x+1, y))
contador += 1
if(y+1 < len(tablero[0])):
if((x, y+1) not in visitados and tablero[x][y+1] == "."):
cola.append((x, y+1))
visitados.append((x, y+1))
contador += 1
return contador
nm = [int(i) for i in input().split(" ")]
n = nm[0]
m = nm[1]
mapa = list()
for i in range(n):
p = input()
aux = list()
for c in p:
aux.append(c)
mapa.append(aux)
tablero_nuevo = mapa.copy()
for i in range(len(mapa)):
for j in range(len(mapa[0])):
if(mapa[i][j] == "*"):
numero = bfs(i, j, mapa)
tablero_nuevo[i][j] = numero
co = 0
for i in tablero_nuevo:
co += 1
for j in i:
print(j, end="")
if(co != n):
print()
| Title: The Labyrinth
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a rectangular field of *n*<=×<=*m* cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.
Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.
For each impassable cell (*x*,<=*y*) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (*x*,<=*y*). You should do it for each impassable cell independently.
The answer should be printed as a matrix with *n* rows and *m* columns. The *j*-th symbol of the *i*-th row should be "." if the cell is empty at the start. Otherwise the *j*-th symbol of the *i*-th row should contain the only digit —- the answer modulo 10. The matrix should be printed without any spaces.
To make your output faster it is recommended to build the output as an array of *n* strings having length *m* and print it as a sequence of lines. It will be much faster than writing character-by-character.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
Input Specification:
The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and columns in the field.
Each of the next *n* lines contains *m* symbols: "." for empty cells, "*" for impassable cells.
Output Specification:
Print the answer as a matrix as described above. See the examples to precise the format of the output.
Demo Input:
['3 3\n*.*\n.*.\n*.*\n', '4 5\n**..*\n..***\n.*.*.\n*.*.*\n']
Demo Output:
['3.3\n.5.\n3.3\n', '46..3\n..732\n.6.4.\n5.4.3\n']
Note:
In first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner). | ```python
from collections import deque
def bfs(i, j, tablero):
contador = 1
actual = (i, j)
cola = deque([])
visitados = []
cola.append(actual)
while len(cola) > 0:
actual = cola.popleft()
x = actual[0]
y = actual[1]
if(x-1 >= 0):
if((x-1, y) not in visitados and tablero[x-1][y] == "."):
cola.append((x-1, y))
visitados.append((x-1, y))
contador += 1
if(y-1 >= 0):
if((x, y-1) not in visitados and tablero[x][y-1] == "."):
cola.append((x, y-1))
visitados.append((x, y-1))
contador += 1
if(x+1 < len(tablero)):
if((x+1, y) not in visitados and tablero[x+1][y] == "."):
cola.append((x+1, y))
visitados.append((x+1, y))
contador += 1
if(y+1 < len(tablero[0])):
if((x, y+1) not in visitados and tablero[x][y+1] == "."):
cola.append((x, y+1))
visitados.append((x, y+1))
contador += 1
return contador
nm = [int(i) for i in input().split(" ")]
n = nm[0]
m = nm[1]
mapa = list()
for i in range(n):
p = input()
aux = list()
for c in p:
aux.append(c)
mapa.append(aux)
tablero_nuevo = mapa.copy()
for i in range(len(mapa)):
for j in range(len(mapa[0])):
if(mapa[i][j] == "*"):
numero = bfs(i, j, mapa)
tablero_nuevo[i][j] = numero
co = 0
for i in tablero_nuevo:
co += 1
for j in i:
print(j, end="")
if(co != n):
print()
``` | 0 | |
29 | E | Quarrel | PROGRAMMING | 2,400 | [
"graphs",
"shortest paths"
] | E. Quarrel | 1 | 256 | Friends Alex and Bob live in Bertown. In this town there are *n* crossroads, some of them are connected by bidirectional roads of equal length. Bob lives in a house at the crossroads number 1, Alex — in a house at the crossroads number *n*.
One day Alex and Bob had a big quarrel, and they refused to see each other. It occurred that today Bob needs to get from his house to the crossroads *n* and Alex needs to get from his house to the crossroads 1. And they don't want to meet at any of the crossroads, but they can meet in the middle of the street, when passing it in opposite directions. Alex and Bob asked you, as their mutual friend, to help them with this difficult task.
Find for Alex and Bob such routes with equal number of streets that the guys can follow these routes and never appear at the same crossroads at the same time. They are allowed to meet in the middle of the street when moving toward each other (see Sample 1). Among all possible routes, select such that the number of streets in it is the least possible. Until both guys reach their destinations, none of them can stay without moving.
The guys are moving simultaneously with equal speeds, i.e. it is possible that when one of them reaches some of the crossroads, the other one leaves it. For example, Alex can move from crossroad 1 to crossroad 2, while Bob moves from crossroad 2 to crossroad 3.
If the required routes don't exist, your program should output -1. | The first line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=500,<=1<=≤<=*m*<=≤<=10000) — the amount of crossroads and the amount of roads. Each of the following *m* lines contains two integers — the numbers of crossroads connected by the road. It is guaranteed that no road connects a crossroads with itself and no two crossroads are connected by more than one road. | If the required routes don't exist, output -1. Otherwise, the first line should contain integer *k* — the length of shortest routes (the length of the route is the amount of roads in it). The next line should contain *k*<=+<=1 integers — Bob's route, i.e. the numbers of *k*<=+<=1 crossroads passed by Bob. The last line should contain Alex's route in the same format. If there are several optimal solutions, output any of them. | [
"2 1\n1 2\n",
"7 5\n1 2\n2 7\n7 6\n2 3\n3 4\n",
"7 6\n1 2\n2 7\n7 6\n2 3\n3 4\n1 5\n"
] | [
"1\n1 2 \n2 1 \n",
"-1\n",
"6\n1 2 3 4 3 2 7 \n7 6 7 2 1 5 1 \n"
] | none | 2,500 | [
{
"input": "2 1\n1 2",
"output": "1\n1 2 \n2 1 "
},
{
"input": "7 5\n1 2\n2 7\n7 6\n2 3\n3 4",
"output": "-1"
},
{
"input": "7 6\n1 2\n2 7\n7 6\n2 3\n3 4\n1 5",
"output": "6\n1 2 3 4 3 2 7 \n7 6 7 2 1 5 1 "
},
{
"input": "6 10\n3 6\n3 5\n1 3\n2 6\n5 4\n6 4\n6 5\n5 1\n2 3\n1 2... | 1,689,604,993 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 92 | 0 | print("_RANDOM_GUESS_1689604992.6477947")# 1689604992.6478164 | Title: Quarrel
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Friends Alex and Bob live in Bertown. In this town there are *n* crossroads, some of them are connected by bidirectional roads of equal length. Bob lives in a house at the crossroads number 1, Alex — in a house at the crossroads number *n*.
One day Alex and Bob had a big quarrel, and they refused to see each other. It occurred that today Bob needs to get from his house to the crossroads *n* and Alex needs to get from his house to the crossroads 1. And they don't want to meet at any of the crossroads, but they can meet in the middle of the street, when passing it in opposite directions. Alex and Bob asked you, as their mutual friend, to help them with this difficult task.
Find for Alex and Bob such routes with equal number of streets that the guys can follow these routes and never appear at the same crossroads at the same time. They are allowed to meet in the middle of the street when moving toward each other (see Sample 1). Among all possible routes, select such that the number of streets in it is the least possible. Until both guys reach their destinations, none of them can stay without moving.
The guys are moving simultaneously with equal speeds, i.e. it is possible that when one of them reaches some of the crossroads, the other one leaves it. For example, Alex can move from crossroad 1 to crossroad 2, while Bob moves from crossroad 2 to crossroad 3.
If the required routes don't exist, your program should output -1.
Input Specification:
The first line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=500,<=1<=≤<=*m*<=≤<=10000) — the amount of crossroads and the amount of roads. Each of the following *m* lines contains two integers — the numbers of crossroads connected by the road. It is guaranteed that no road connects a crossroads with itself and no two crossroads are connected by more than one road.
Output Specification:
If the required routes don't exist, output -1. Otherwise, the first line should contain integer *k* — the length of shortest routes (the length of the route is the amount of roads in it). The next line should contain *k*<=+<=1 integers — Bob's route, i.e. the numbers of *k*<=+<=1 crossroads passed by Bob. The last line should contain Alex's route in the same format. If there are several optimal solutions, output any of them.
Demo Input:
['2 1\n1 2\n', '7 5\n1 2\n2 7\n7 6\n2 3\n3 4\n', '7 6\n1 2\n2 7\n7 6\n2 3\n3 4\n1 5\n']
Demo Output:
['1\n1 2 \n2 1 \n', '-1\n', '6\n1 2 3 4 3 2 7 \n7 6 7 2 1 5 1 \n']
Note:
none | ```python
print("_RANDOM_GUESS_1689604992.6477947")# 1689604992.6478164
``` | 0 |
8 | C | Looking for Order | PROGRAMMING | 2,000 | [
"bitmasks",
"dp"
] | C. Looking for Order | 4 | 512 | Girl Lena likes it when everything is in order, and looks for order everywhere. Once she was getting ready for the University and noticed that the room was in a mess — all the objects from her handbag were thrown about the room. Of course, she wanted to put them back into her handbag. The problem is that the girl cannot carry more than two objects at a time, and cannot move the handbag. Also, if he has taken an object, she cannot put it anywhere except her handbag — her inherent sense of order does not let her do so.
You are given the coordinates of the handbag and the coordinates of the objects in some Сartesian coordinate system. It is known that the girl covers the distance between any two objects in the time equal to the squared length of the segment between the points of the objects. It is also known that initially the coordinates of the girl and the handbag are the same. You are asked to find such an order of actions, that the girl can put all the objects back into her handbag in a minimum time period. | The first line of the input file contains the handbag's coordinates *x**s*,<=*y**s*. The second line contains number *n* (1<=≤<=*n*<=≤<=24) — the amount of objects the girl has. The following *n* lines contain the objects' coordinates. All the coordinates do not exceed 100 in absolute value. All the given positions are different. All the numbers are integer. | In the first line output the only number — the minimum time the girl needs to put the objects into her handbag.
In the second line output the possible optimum way for Lena. Each object in the input is described by its index number (from 1 to *n*), the handbag's point is described by number 0. The path should start and end in the handbag's point. If there are several optimal paths, print any of them. | [
"0 0\n2\n1 1\n-1 1\n",
"1 1\n3\n4 3\n3 4\n0 0\n"
] | [
"8\n0 1 2 0 \n",
"32\n0 1 2 0 3 0 \n"
] | none | 0 | [
{
"input": "0 0\n2\n1 1\n-1 1",
"output": "8\n0 1 2 0 "
},
{
"input": "1 1\n3\n4 3\n3 4\n0 0",
"output": "32\n0 1 2 0 3 0 "
},
{
"input": "-3 4\n1\n2 2",
"output": "58\n0 1 0 "
},
{
"input": "7 -7\n2\n3 1\n-3 8",
"output": "490\n0 1 2 0 "
},
{
"input": "3 -9\n3\n0... | 1,665,859,983 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 4 | 61 | 0 | def go(mask,prev,ci):
if (mask==(o)):
return (x-a[prev][0])**2 + (y-a[prev][1])**2
if (dp[ci][prev][mask]!=-1):
return dp[ci][prev][mask]
if (ci<2):
ans = 10**18
for i in range(n):
if ((2**i)&mask ==0):
if (prev==-1):
c1 = (a[i][0]-x)**2 + (a[i][1]-y)**2 + go(mask^(2**i),i,ci+1)
else:
c1 = (a[i][0]-a[prev][0])**2 + (a[i][1]-a[prev][1])**2 + go(mask^(2**i),i,ci+1)
ans = min(ans,c1)
if (ci==2):
ans = 10**18
for i in range(n):
if ((2**i)&mask ==0):
c1 = (x-a[prev][0])**2 + (x-a[prev][1])**2 + go(mask,-1,ci&0)
ans = min(ans,c1)
dp[ci][prev][mask] = ans
return ans
def trace(mask,prev,ci):
if (mask==(o)):
return (x-a[prev][0])**2 + (y-a[prev][1])**2
ans = dp[ci][prev][mask]
if (ci<2):
# ans = 10**18
for i in range(n):
if ((2**i)&mask ==0):
if (prev==-1):
c1 = (a[i][0]-x)**2 + (a[i][1]-y)**2 + go(mask^(2**i),i,ci+1)
if (c1==ans):
print(i+1,end=' ')
trace(mask^(2**i),i,ci+1)
return 0
else:
c1 = (a[i][0]-a[prev][0])**2 + (a[i][1]-a[prev][1])**2 + go(mask^(2**i),i,ci+1)
if (c1==ans):
print(i+1,end=' ')
trace(mask^(2**i),i,ci+1)
return 0
ans = min(ans,c1)
if (ci==2):
# ans = 10**18
for i in range(n):
if ((2**i)&mask ==0):
c1 = (x-a[prev][0])**2 + (x-a[prev][1])**2 + go(mask,-1,ci&0)
if (c1==ans):
print(0,end=' ')
trace(mask,-1,ci&0)
return 0
ans = min(ans,c1)
# dp[ci][prev][mask] = ans
return 0
x,y = map(int,input().split())
n = int(input())
a = []
for i in range(n):
a.append(list(map(int,input().split())))
dp = [ ]
for i in range(3):
q = [ ]
for j in range(n+1):
r = [ ]
for k in range(2**n+1):
r.append(-1)
q.append(r)
dp.append(q)
o = (2**n - 1)
print(go(0,-1,0))
print(0,end=' ')
trace(0,-1,0)
print(0,end=' ')
| Title: Looking for Order
Time Limit: 4 seconds
Memory Limit: 512 megabytes
Problem Description:
Girl Lena likes it when everything is in order, and looks for order everywhere. Once she was getting ready for the University and noticed that the room was in a mess — all the objects from her handbag were thrown about the room. Of course, she wanted to put them back into her handbag. The problem is that the girl cannot carry more than two objects at a time, and cannot move the handbag. Also, if he has taken an object, she cannot put it anywhere except her handbag — her inherent sense of order does not let her do so.
You are given the coordinates of the handbag and the coordinates of the objects in some Сartesian coordinate system. It is known that the girl covers the distance between any two objects in the time equal to the squared length of the segment between the points of the objects. It is also known that initially the coordinates of the girl and the handbag are the same. You are asked to find such an order of actions, that the girl can put all the objects back into her handbag in a minimum time period.
Input Specification:
The first line of the input file contains the handbag's coordinates *x**s*,<=*y**s*. The second line contains number *n* (1<=≤<=*n*<=≤<=24) — the amount of objects the girl has. The following *n* lines contain the objects' coordinates. All the coordinates do not exceed 100 in absolute value. All the given positions are different. All the numbers are integer.
Output Specification:
In the first line output the only number — the minimum time the girl needs to put the objects into her handbag.
In the second line output the possible optimum way for Lena. Each object in the input is described by its index number (from 1 to *n*), the handbag's point is described by number 0. The path should start and end in the handbag's point. If there are several optimal paths, print any of them.
Demo Input:
['0 0\n2\n1 1\n-1 1\n', '1 1\n3\n4 3\n3 4\n0 0\n']
Demo Output:
['8\n0 1 2 0 \n', '32\n0 1 2 0 3 0 \n']
Note:
none | ```python
def go(mask,prev,ci):
if (mask==(o)):
return (x-a[prev][0])**2 + (y-a[prev][1])**2
if (dp[ci][prev][mask]!=-1):
return dp[ci][prev][mask]
if (ci<2):
ans = 10**18
for i in range(n):
if ((2**i)&mask ==0):
if (prev==-1):
c1 = (a[i][0]-x)**2 + (a[i][1]-y)**2 + go(mask^(2**i),i,ci+1)
else:
c1 = (a[i][0]-a[prev][0])**2 + (a[i][1]-a[prev][1])**2 + go(mask^(2**i),i,ci+1)
ans = min(ans,c1)
if (ci==2):
ans = 10**18
for i in range(n):
if ((2**i)&mask ==0):
c1 = (x-a[prev][0])**2 + (x-a[prev][1])**2 + go(mask,-1,ci&0)
ans = min(ans,c1)
dp[ci][prev][mask] = ans
return ans
def trace(mask,prev,ci):
if (mask==(o)):
return (x-a[prev][0])**2 + (y-a[prev][1])**2
ans = dp[ci][prev][mask]
if (ci<2):
# ans = 10**18
for i in range(n):
if ((2**i)&mask ==0):
if (prev==-1):
c1 = (a[i][0]-x)**2 + (a[i][1]-y)**2 + go(mask^(2**i),i,ci+1)
if (c1==ans):
print(i+1,end=' ')
trace(mask^(2**i),i,ci+1)
return 0
else:
c1 = (a[i][0]-a[prev][0])**2 + (a[i][1]-a[prev][1])**2 + go(mask^(2**i),i,ci+1)
if (c1==ans):
print(i+1,end=' ')
trace(mask^(2**i),i,ci+1)
return 0
ans = min(ans,c1)
if (ci==2):
# ans = 10**18
for i in range(n):
if ((2**i)&mask ==0):
c1 = (x-a[prev][0])**2 + (x-a[prev][1])**2 + go(mask,-1,ci&0)
if (c1==ans):
print(0,end=' ')
trace(mask,-1,ci&0)
return 0
ans = min(ans,c1)
# dp[ci][prev][mask] = ans
return 0
x,y = map(int,input().split())
n = int(input())
a = []
for i in range(n):
a.append(list(map(int,input().split())))
dp = [ ]
for i in range(3):
q = [ ]
for j in range(n+1):
r = [ ]
for k in range(2**n+1):
r.append(-1)
q.append(r)
dp.append(q)
o = (2**n - 1)
print(go(0,-1,0))
print(0,end=' ')
trace(0,-1,0)
print(0,end=' ')
``` | 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,676,792,206 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 6 | 62 | 0 | n, k, l, c, d, p, nl, np = map(int,input().split())
x = (k * l) / nl
y = p / np
z = min(x,y,d)
print(int(z/n)) | 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
n, k, l, c, d, p, nl, np = map(int,input().split())
x = (k * l) / nl
y = p / np
z = min(x,y,d)
print(int(z/n))
``` | 0 | |
596 | B | Wilbur and Array | PROGRAMMING | 1,100 | [
"greedy",
"implementation"
] | null | null | Wilbur the pig is tinkering with arrays again. He has the array *a*1,<=*a*2,<=...,<=*a**n* initially consisting of *n* zeros. At one step, he can choose any index *i* and either add 1 to all elements *a**i*,<=*a**i*<=+<=1,<=... ,<=*a**n* or subtract 1 from all elements *a**i*,<=*a**i*<=+<=1,<=...,<=*a**n*. His goal is to end up with the array *b*1,<=*b*2,<=...,<=*b**n*.
Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value. | The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=200<=000) — the length of the array *a**i*. Initially *a**i*<==<=0 for every position *i*, so this array is not given in the input.
The second line of the input contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (<=-<=109<=≤<=*b**i*<=≤<=109). | Print the minimum number of steps that Wilbur needs to make in order to achieve *a**i*<==<=*b**i* for all *i*. | [
"5\n1 2 3 4 5\n",
"4\n1 2 2 1\n"
] | [
"5",
"3"
] | In the first sample, Wilbur may successively choose indices 1, 2, 3, 4, and 5, and add 1 to corresponding suffixes.
In the second sample, Wilbur first chooses indices 1 and 2 and adds 1 to corresponding suffixes, then he chooses index 4 and subtract 1. | 1,000 | [
{
"input": "5\n1 2 3 4 5",
"output": "5"
},
{
"input": "4\n1 2 2 1",
"output": "3"
},
{
"input": "3\n1 2 4",
"output": "4"
},
{
"input": "6\n1 2 3 6 5 4",
"output": "8"
},
{
"input": "10\n2 1 4 3 6 5 8 7 10 9",
"output": "19"
},
{
"input": "7\n12 6 12 ... | 1,586,685,846 | 2,147,483,647 | Python 3 | OK | TESTS | 76 | 264 | 18,329,600 | n=int(input())
m=list(map(int,input().split()))[:n]
s=abs(m[0])
for i in range(1,n):
d=abs(m[i]-m[i-1])
s=s+d
print(s)
| Title: Wilbur and Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Wilbur the pig is tinkering with arrays again. He has the array *a*1,<=*a*2,<=...,<=*a**n* initially consisting of *n* zeros. At one step, he can choose any index *i* and either add 1 to all elements *a**i*,<=*a**i*<=+<=1,<=... ,<=*a**n* or subtract 1 from all elements *a**i*,<=*a**i*<=+<=1,<=...,<=*a**n*. His goal is to end up with the array *b*1,<=*b*2,<=...,<=*b**n*.
Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.
Input Specification:
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=200<=000) — the length of the array *a**i*. Initially *a**i*<==<=0 for every position *i*, so this array is not given in the input.
The second line of the input contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (<=-<=109<=≤<=*b**i*<=≤<=109).
Output Specification:
Print the minimum number of steps that Wilbur needs to make in order to achieve *a**i*<==<=*b**i* for all *i*.
Demo Input:
['5\n1 2 3 4 5\n', '4\n1 2 2 1\n']
Demo Output:
['5', '3']
Note:
In the first sample, Wilbur may successively choose indices 1, 2, 3, 4, and 5, and add 1 to corresponding suffixes.
In the second sample, Wilbur first chooses indices 1 and 2 and adds 1 to corresponding suffixes, then he chooses index 4 and subtract 1. | ```python
n=int(input())
m=list(map(int,input().split()))[:n]
s=abs(m[0])
for i in range(1,n):
d=abs(m[i]-m[i-1])
s=s+d
print(s)
``` | 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,696,964,508 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 46 | 0 | n,m,a=map(int,input().split())
if round(n/a) <(n/a) and round(m/a) <(m/a) :
F=((round(n/a))+1) *4
S=((round(m/a))+1)*2
else:
F=round(n/a) *4
S=round(m/a) *2
T=F*S
print(T) | Title: Theatre Square
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
Input Specification:
The input contains three positive integer numbers in the first line: *n*,<=<=*m* and *a* (1<=≤<=<=*n*,<=*m*,<=*a*<=≤<=109).
Output Specification:
Write the needed number of flagstones.
Demo Input:
['6 6 4\n']
Demo Output:
['4\n']
Note:
none | ```python
n,m,a=map(int,input().split())
if round(n/a) <(n/a) and round(m/a) <(m/a) :
F=((round(n/a))+1) *4
S=((round(m/a))+1)*2
else:
F=round(n/a) *4
S=round(m/a) *2
T=F*S
print(T)
``` | 0 |
181 | A | Series of Crimes | PROGRAMMING | 800 | [
"brute force",
"geometry",
"implementation"
] | null | null | The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.
The Berland capital's map is represented by an *n*<=×<=*m* rectangular table. Each cell of the table on the map represents some districts of the capital.
The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map.
Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed. | The first line contains two space-separated integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=100) — the number of rows and columns in the table, correspondingly.
Each of the next *n* lines contains *m* characters — the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".".
It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements. | Print two integers — the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right. | [
"3 2\n.*\n..\n**\n",
"3 3\n*.*\n*..\n...\n"
] | [
"1 1\n",
"2 3\n"
] | none | 500 | [
{
"input": "3 2\n.*\n..\n**",
"output": "1 1"
},
{
"input": "2 5\n*....\n*...*",
"output": "1 5"
},
{
"input": "7 2\n..\n**\n..\n..\n..\n..\n.*",
"output": "7 1"
},
{
"input": "7 2\n*.\n..\n..\n..\n..\n..\n**",
"output": "1 2"
},
{
"input": "2 10\n*......*..\n....... | 1,664,223,514 | 2,147,483,647 | Python 3 | OK | TESTS | 36 | 92 | 0 | n, m = map(int, input().split())
c = []
f1, f2 = False, False
for i in range(n):
a = input()
if a.count("*") == 1:
r1 = i
c1 = a.find("*")
f1 = True
elif a.count("*") == 2:
r2 = i
f2 = True
c.append(a)
if f1 and f2:
break
for x in range(m):
if c[r2][x] == "*":
if x != c1:
c2 = x
break
print("{} {}".format(r1+1, c2+1)) | Title: Series of Crimes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.
The Berland capital's map is represented by an *n*<=×<=*m* rectangular table. Each cell of the table on the map represents some districts of the capital.
The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map.
Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.
Input Specification:
The first line contains two space-separated integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=100) — the number of rows and columns in the table, correspondingly.
Each of the next *n* lines contains *m* characters — the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".".
It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements.
Output Specification:
Print two integers — the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right.
Demo Input:
['3 2\n.*\n..\n**\n', '3 3\n*.*\n*..\n...\n']
Demo Output:
['1 1\n', '2 3\n']
Note:
none | ```python
n, m = map(int, input().split())
c = []
f1, f2 = False, False
for i in range(n):
a = input()
if a.count("*") == 1:
r1 = i
c1 = a.find("*")
f1 = True
elif a.count("*") == 2:
r2 = i
f2 = True
c.append(a)
if f1 and f2:
break
for x in range(m):
if c[r2][x] == "*":
if x != c1:
c2 = x
break
print("{} {}".format(r1+1, c2+1))
``` | 3 | |
534 | B | Covered Path | PROGRAMMING | 1,400 | [
"dp",
"greedy",
"math"
] | null | null | The on-board computer on Polycarp's car measured that the car speed at the beginning of some section of the path equals *v*1 meters per second, and in the end it is *v*2 meters per second. We know that this section of the route took exactly *t* seconds to pass.
Assuming that at each of the seconds the speed is constant, and between seconds the speed can change at most by *d* meters per second in absolute value (i.e., the difference in the speed of any two adjacent seconds does not exceed *d* in absolute value), find the maximum possible length of the path section in meters. | The first line contains two integers *v*1 and *v*2 (1<=≤<=*v*1,<=*v*2<=≤<=100) — the speeds in meters per second at the beginning of the segment and at the end of the segment, respectively.
The second line contains two integers *t* (2<=≤<=*t*<=≤<=100) — the time when the car moves along the segment in seconds, *d* (0<=≤<=*d*<=≤<=10) — the maximum value of the speed change between adjacent seconds.
It is guaranteed that there is a way to complete the segment so that:
- the speed in the first second equals *v*1, - the speed in the last second equals *v*2, - the absolute value of difference of speeds between any two adjacent seconds doesn't exceed *d*. | Print the maximum possible length of the path segment in meters. | [
"5 6\n4 2\n",
"10 10\n10 0\n"
] | [
"26",
"100"
] | In the first sample the sequence of speeds of Polycarpus' car can look as follows: 5, 7, 8, 6. Thus, the total path is 5 + 7 + 8 + 6 = 26 meters.
In the second sample, as *d* = 0, the car covers the whole segment at constant speed *v* = 10. In *t* = 10 seconds it covers the distance of 100 meters. | 1,000 | [
{
"input": "5 6\n4 2",
"output": "26"
},
{
"input": "10 10\n10 0",
"output": "100"
},
{
"input": "87 87\n2 10",
"output": "174"
},
{
"input": "1 11\n6 2",
"output": "36"
},
{
"input": "100 10\n10 10",
"output": "550"
},
{
"input": "1 1\n100 10",
"o... | 1,575,200,343 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 108 | 0 | v1,v2=map(int,input().split())
t,d=map(int,input().split())
ii=0
q=v1+v2
for i in range(t-2):
if (abs((v1+d)-v2))<=((t-i-3)*d):
v1+=d
q+=v1
else:
v1+=(abs(abs((v1+d)-v2)-((t-i-3)*d))-d)
q+=v1
ii=i+1
break
for i in range(t-ii-2):
if (v1-d)>v2:
v1-=d
q+=v1
else:
break
print(q) | Title: Covered Path
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The on-board computer on Polycarp's car measured that the car speed at the beginning of some section of the path equals *v*1 meters per second, and in the end it is *v*2 meters per second. We know that this section of the route took exactly *t* seconds to pass.
Assuming that at each of the seconds the speed is constant, and between seconds the speed can change at most by *d* meters per second in absolute value (i.e., the difference in the speed of any two adjacent seconds does not exceed *d* in absolute value), find the maximum possible length of the path section in meters.
Input Specification:
The first line contains two integers *v*1 and *v*2 (1<=≤<=*v*1,<=*v*2<=≤<=100) — the speeds in meters per second at the beginning of the segment and at the end of the segment, respectively.
The second line contains two integers *t* (2<=≤<=*t*<=≤<=100) — the time when the car moves along the segment in seconds, *d* (0<=≤<=*d*<=≤<=10) — the maximum value of the speed change between adjacent seconds.
It is guaranteed that there is a way to complete the segment so that:
- the speed in the first second equals *v*1, - the speed in the last second equals *v*2, - the absolute value of difference of speeds between any two adjacent seconds doesn't exceed *d*.
Output Specification:
Print the maximum possible length of the path segment in meters.
Demo Input:
['5 6\n4 2\n', '10 10\n10 0\n']
Demo Output:
['26', '100']
Note:
In the first sample the sequence of speeds of Polycarpus' car can look as follows: 5, 7, 8, 6. Thus, the total path is 5 + 7 + 8 + 6 = 26 meters.
In the second sample, as *d* = 0, the car covers the whole segment at constant speed *v* = 10. In *t* = 10 seconds it covers the distance of 100 meters. | ```python
v1,v2=map(int,input().split())
t,d=map(int,input().split())
ii=0
q=v1+v2
for i in range(t-2):
if (abs((v1+d)-v2))<=((t-i-3)*d):
v1+=d
q+=v1
else:
v1+=(abs(abs((v1+d)-v2)-((t-i-3)*d))-d)
q+=v1
ii=i+1
break
for i in range(t-ii-2):
if (v1-d)>v2:
v1-=d
q+=v1
else:
break
print(q)
``` | 0 | |
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,692,110,820 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 1 | 77 | 0 | n = int(input())
for i in range(1, n+1):
i= str(input())
x = len(i)
f= x-2
if f>9:
first= i[0]
last= i[-1]
print(first, end="")
print(f, end="")
print(last)
else:
print(i)
| 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())
for i in range(1, n+1):
i= str(input())
x = len(i)
f= x-2
if f>9:
first= i[0]
last= i[-1]
print(first, end="")
print(f, end="")
print(last)
else:
print(i)
``` | 0 |
915 | G | Coprime Arrays | PROGRAMMING | 2,300 | [
"math",
"number theory"
] | null | null | Let's call an array *a* of size *n* coprime iff *gcd*(*a*1,<=*a*2,<=...,<=*a**n*)<==<=1, where *gcd* is the greatest common divisor of the arguments.
You are given two numbers *n* and *k*. For each *i* (1<=≤<=*i*<=≤<=*k*) you have to determine the number of coprime arrays *a* of size *n* such that for every *j* (1<=≤<=*j*<=≤<=*n*) 1<=≤<=*a**j*<=≤<=*i*. Since the answers can be very large, you have to calculate them modulo 109<=+<=7. | The first line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=2·106) — the size of the desired arrays and the maximum upper bound on elements, respectively. | Since printing 2·106 numbers may take a lot of time, you have to output the answer in such a way:
Let *b**i* be the number of coprime arrays with elements in range [1,<=*i*], taken modulo 109<=+<=7. You have to print , taken modulo 109<=+<=7. Here denotes bitwise xor operation (^ in C++ or Java, xor in Pascal). | [
"3 4\n",
"2000000 8\n"
] | [
"82\n",
"339310063\n"
] | Explanation of the example:
Since the number of coprime arrays is large, we will list the arrays that are non-coprime, but contain only elements in range [1, *i*]:
For *i* = 1, the only array is coprime. *b*<sub class="lower-index">1</sub> = 1.
For *i* = 2, array [2, 2, 2] is not coprime. *b*<sub class="lower-index">2</sub> = 7.
For *i* = 3, arrays [2, 2, 2] and [3, 3, 3] are not coprime. *b*<sub class="lower-index">3</sub> = 25.
For *i* = 4, arrays [2, 2, 2], [3, 3, 3], [2, 2, 4], [2, 4, 2], [2, 4, 4], [4, 2, 2], [4, 2, 4], [4, 4, 2] and [4, 4, 4] are not coprime. *b*<sub class="lower-index">4</sub> = 55. | 0 | [
{
"input": "3 4",
"output": "82"
},
{
"input": "2000000 8",
"output": "339310063"
},
{
"input": "1000 1000",
"output": "293255159"
},
{
"input": "400000 400000",
"output": "641589365"
},
{
"input": "1000 2000",
"output": "946090030"
},
{
"input": "4000... | 1,699,822,412 | 6,812 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 46 | 0 | import sys
input = sys.stdin.buffer.readline
p = 10**9+7
def process(n, k):
b = [0 for i in range(k+1)]
b[1] = 1
for i in range(2, k+1):
b[i] = pow(i, n, p)
for j in range(2, i+1):
if j*j > i:
break
b[i]-=b[j]
if j*j < i:
b[i]-=b[i//j]
answer = 0
for i in range(1, k+1):
answer = (answer+(b[i]^i))%p
print(answer)
return
n, k = [int(x) for x in input().split()]
process(n, k) | Title: Coprime Arrays
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's call an array *a* of size *n* coprime iff *gcd*(*a*1,<=*a*2,<=...,<=*a**n*)<==<=1, where *gcd* is the greatest common divisor of the arguments.
You are given two numbers *n* and *k*. For each *i* (1<=≤<=*i*<=≤<=*k*) you have to determine the number of coprime arrays *a* of size *n* such that for every *j* (1<=≤<=*j*<=≤<=*n*) 1<=≤<=*a**j*<=≤<=*i*. Since the answers can be very large, you have to calculate them modulo 109<=+<=7.
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=2·106) — the size of the desired arrays and the maximum upper bound on elements, respectively.
Output Specification:
Since printing 2·106 numbers may take a lot of time, you have to output the answer in such a way:
Let *b**i* be the number of coprime arrays with elements in range [1,<=*i*], taken modulo 109<=+<=7. You have to print , taken modulo 109<=+<=7. Here denotes bitwise xor operation (^ in C++ or Java, xor in Pascal).
Demo Input:
['3 4\n', '2000000 8\n']
Demo Output:
['82\n', '339310063\n']
Note:
Explanation of the example:
Since the number of coprime arrays is large, we will list the arrays that are non-coprime, but contain only elements in range [1, *i*]:
For *i* = 1, the only array is coprime. *b*<sub class="lower-index">1</sub> = 1.
For *i* = 2, array [2, 2, 2] is not coprime. *b*<sub class="lower-index">2</sub> = 7.
For *i* = 3, arrays [2, 2, 2] and [3, 3, 3] are not coprime. *b*<sub class="lower-index">3</sub> = 25.
For *i* = 4, arrays [2, 2, 2], [3, 3, 3], [2, 2, 4], [2, 4, 2], [2, 4, 4], [4, 2, 2], [4, 2, 4], [4, 4, 2] and [4, 4, 4] are not coprime. *b*<sub class="lower-index">4</sub> = 55. | ```python
import sys
input = sys.stdin.buffer.readline
p = 10**9+7
def process(n, k):
b = [0 for i in range(k+1)]
b[1] = 1
for i in range(2, k+1):
b[i] = pow(i, n, p)
for j in range(2, i+1):
if j*j > i:
break
b[i]-=b[j]
if j*j < i:
b[i]-=b[i//j]
answer = 0
for i in range(1, k+1):
answer = (answer+(b[i]^i))%p
print(answer)
return
n, k = [int(x) for x in input().split()]
process(n, k)
``` | 0 | |
39 | D | Cubical Planet | PROGRAMMING | 1,100 | [
"math"
] | D. Cubical Planet | 2 | 64 | You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0,<=0,<=0) and (1,<=1,<=1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. | The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. | Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". | [
"0 0 0\n0 1 0\n",
"1 1 0\n0 1 0\n",
"0 0 0\n1 1 1\n"
] | [
"YES\n",
"YES\n",
"NO\n"
] | none | 0 | [
{
"input": "0 0 0\n0 1 0",
"output": "YES"
},
{
"input": "1 1 0\n0 1 0",
"output": "YES"
},
{
"input": "0 0 0\n1 1 1",
"output": "NO"
},
{
"input": "0 0 0\n1 0 0",
"output": "YES"
},
{
"input": "0 0 0\n0 1 0",
"output": "YES"
},
{
"input": "0 0 0\n1 1 ... | 1,552,318,879 | 2,147,483,647 | Python 3 | OK | TESTS | 59 | 216 | 0 | il = lambda: list(map(int, input().split()))
y=all(i!=j for i,j in zip(il(),il()))
print('YNEOS'[int(y)::2]) | Title: Cubical Planet
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0,<=0,<=0) and (1,<=1,<=1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube.
Input Specification:
The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly.
Output Specification:
Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO".
Demo Input:
['0 0 0\n0 1 0\n', '1 1 0\n0 1 0\n', '0 0 0\n1 1 1\n']
Demo Output:
['YES\n', 'YES\n', 'NO\n']
Note:
none | ```python
il = lambda: list(map(int, input().split()))
y=all(i!=j for i,j in zip(il(),il()))
print('YNEOS'[int(y)::2])
``` | 3.946 |
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,548,873,653 | 2,147,483,647 | Python 3 | OK | TESTS | 185 | 124 | 0 | from math import floor, ceil, gcd
n, a, b, p, q = map(int, input().split())
pc = floor(n / a)
qc = floor(n / b)
l = (a * b) // gcd(a, b)
bc = floor(n / l)
pc -= bc
qc -= bc
ans = p * pc + q * qc + (p * bc) * (p >= q) + (q * bc) * (q > p)
print(ans) | 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 math import floor, ceil, gcd
n, a, b, p, q = map(int, input().split())
pc = floor(n / a)
qc = floor(n / b)
l = (a * b) // gcd(a, b)
bc = floor(n / l)
pc -= bc
qc -= bc
ans = p * pc + q * qc + (p * bc) * (p >= q) + (q * bc) * (q > p)
print(ans)
``` | 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,680,657,221 | 2,147,483,647 | PyPy 3 | OK | TESTS | 71 | 218 | 2,048,000 | import re
s = input()
print(*(i for i in s.split("WUB") if i != "")) | 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
s = input()
print(*(i for i in s.split("WUB") if i != ""))
``` | 3 | |
1 | A | Theatre Square | PROGRAMMING | 1,000 | [
"math"
] | A. Theatre Square | 1 | 256 | Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square. | The input contains three positive integer numbers in the first line: *n*,<=<=*m* and *a* (1<=≤<=<=*n*,<=*m*,<=*a*<=≤<=109). | Write the needed number of flagstones. | [
"6 6 4\n"
] | [
"4\n"
] | none | 0 | [
{
"input": "6 6 4",
"output": "4"
},
{
"input": "1 1 1",
"output": "1"
},
{
"input": "2 1 1",
"output": "2"
},
{
"input": "1 2 1",
"output": "2"
},
{
"input": "2 2 1",
"output": "4"
},
{
"input": "2 1 2",
"output": "1"
},
{
"input": "1 1 3"... | 1,648,721,334 | 2,147,483,647 | Python 3 | OK | TESTS | 20 | 46 | 0 | import math
a = [int(i) for i in input().split()]
print(str(math.ceil(a[0] / a[2]) * math.ceil(a[1] / a[2]))) | 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
import math
a = [int(i) for i in input().split()]
print(str(math.ceil(a[0] / a[2]) * math.ceil(a[1] / a[2])))
``` | 3.977 |
228 | A | Is your horseshoe on the other hoof? | PROGRAMMING | 800 | [
"implementation"
] | null | null | Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.
Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. | The first line contains four space-separated integers *s*1,<=*s*2,<=*s*3,<=*s*4 (1<=≤<=*s*1,<=*s*2,<=*s*3,<=*s*4<=≤<=109) — the colors of horseshoes Valera has.
Consider all possible colors indexed with integers. | Print a single integer — the minimum number of horseshoes Valera needs to buy. | [
"1 7 3 3\n",
"7 7 7 7\n"
] | [
"1\n",
"3\n"
] | none | 500 | [
{
"input": "1 7 3 3",
"output": "1"
},
{
"input": "7 7 7 7",
"output": "3"
},
{
"input": "81170865 673572653 756938629 995577259",
"output": "0"
},
{
"input": "3491663 217797045 522540872 715355328",
"output": "0"
},
{
"input": "251590420 586975278 916631563 58697... | 1,695,472,886 | 2,147,483,647 | Python 3 | OK | TESTS | 34 | 92 | 0 | s = input().split()
c = 0
for i in range(3):
f = 0
for j in range(i + 1, 4):
if s[i] == s[j]:
f = 1
break
if f == 1:
c += 1
print(c)
| Title: Is your horseshoe on the other hoof?
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.
Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
Input Specification:
The first line contains four space-separated integers *s*1,<=*s*2,<=*s*3,<=*s*4 (1<=≤<=*s*1,<=*s*2,<=*s*3,<=*s*4<=≤<=109) — the colors of horseshoes Valera has.
Consider all possible colors indexed with integers.
Output Specification:
Print a single integer — the minimum number of horseshoes Valera needs to buy.
Demo Input:
['1 7 3 3\n', '7 7 7 7\n']
Demo Output:
['1\n', '3\n']
Note:
none | ```python
s = input().split()
c = 0
for i in range(3):
f = 0
for j in range(i + 1, 4):
if s[i] == s[j]:
f = 1
break
if f == 1:
c += 1
print(c)
``` | 3 | |
727 | C | Guess the Array | PROGRAMMING | 1,400 | [
"constructive algorithms",
"interactive",
"math"
] | null | null | This is an interactive problem. You should use flush operation after each printed line. For example, in C++ you should use fflush(stdout), in Java you should use System.out.flush(), and in Pascal — flush(output).
In this problem you should guess an array *a* which is unknown for you. The only information you have initially is the length *n* of the array *a*.
The only allowed action is to ask the sum of two elements by their indices. Formally, you can print two indices *i* and *j* (the indices should be distinct). Then your program should read the response: the single integer equals to *a**i*<=+<=*a**j*.
It is easy to prove that it is always possible to guess the array using at most *n* requests.
Write a program that will guess the array *a* by making at most *n* requests. | none | none | [
"5\n \n9\n \n7\n \n9\n \n11\n \n6\n "
] | [
"? 1 5\n \n? 2 3\n \n? 4 1\n \n? 5 2\n \n? 3 4\n \n! 4 6 1 5 5"
] | The format of a test to make a hack is:
- The first line contains an integer number *n* (3 ≤ *n* ≤ 5000) — the length of the array.- The second line contains *n* numbers *a*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">2</sub>, ..., *a*<sub class="lower-index">*n*</sub> (1 ≤ *a*<sub class="lower-index">*i*</sub> ≤ 10<sup class="upper-index">5</sup>) — the elements of the array to guess. | 1,500 | [
{
"input": "5\n4 6 1 5 5",
"output": "5 out of 5"
},
{
"input": "3\n1 1 1",
"output": "3 out of 3"
},
{
"input": "4\n100 1 100 1",
"output": "4 out of 4"
},
{
"input": "10\n9 5 10 7 4 4 8 5 10 5",
"output": "10 out of 10"
},
{
"input": "3\n1 1 1",
"output": "3... | 1,599,627,926 | 2,147,483,647 | PyPy 3 | OK | TESTS | 36 | 389 | 5,324,800 | n = int(input())
a=[0]*n
print('?',1,2,flush=1)
a1=int(int(input()))
print('?',2,3,flush=1)
a2=int(int(input()))
print('?',1,3,flush=1)
a3=int(input())
a[0]=(a1+a3-a2)//2
a[1]=a1-a[0]
a[2]=a3-a[0]
for i in range(3,n):
print('?',1,i+1,flush=1)
p=int(input())
a[i]=p-a[0]
print('!',*a)
| Title: Guess the Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
This is an interactive problem. You should use flush operation after each printed line. For example, in C++ you should use fflush(stdout), in Java you should use System.out.flush(), and in Pascal — flush(output).
In this problem you should guess an array *a* which is unknown for you. The only information you have initially is the length *n* of the array *a*.
The only allowed action is to ask the sum of two elements by their indices. Formally, you can print two indices *i* and *j* (the indices should be distinct). Then your program should read the response: the single integer equals to *a**i*<=+<=*a**j*.
It is easy to prove that it is always possible to guess the array using at most *n* requests.
Write a program that will guess the array *a* by making at most *n* requests.
Input Specification:
none
Output Specification:
none
Demo Input:
['5\n\xa0\n9\n\xa0\n7\n\xa0\n9\n\xa0\n11\n\xa0\n6\n\xa0']
Demo Output:
['? 1 5\n\xa0\n? 2 3\n\xa0\n? 4 1\n\xa0\n? 5 2\n\xa0\n? 3 4\n\xa0\n! 4 6 1 5 5']
Note:
The format of a test to make a hack is:
- The first line contains an integer number *n* (3 ≤ *n* ≤ 5000) — the length of the array.- The second line contains *n* numbers *a*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">2</sub>, ..., *a*<sub class="lower-index">*n*</sub> (1 ≤ *a*<sub class="lower-index">*i*</sub> ≤ 10<sup class="upper-index">5</sup>) — the elements of the array to guess. | ```python
n = int(input())
a=[0]*n
print('?',1,2,flush=1)
a1=int(int(input()))
print('?',2,3,flush=1)
a2=int(int(input()))
print('?',1,3,flush=1)
a3=int(input())
a[0]=(a1+a3-a2)//2
a[1]=a1-a[0]
a[2]=a3-a[0]
for i in range(3,n):
print('?',1,i+1,flush=1)
p=int(input())
a[i]=p-a[0]
print('!',*a)
``` | 3 | |
765 | A | Neverending competitions | PROGRAMMING | 900 | [
"implementation",
"math"
] | null | null | There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back.
Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that:
- this list contains all Jinotega's flights in this year (in arbitrary order), - Jinotega has only flown from his hometown to a snooker contest and back, - after each competition Jinotega flies back home (though they may attend a competition in one place several times), - and finally, at the beginning of the year Jinotega was at home.
Please help them to determine Jinotega's location! | In the first line of input there is a single integer *n*: the number of Jinotega's flights (1<=≤<=*n*<=≤<=100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next *n* lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport.
It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. | If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". | [
"4\nSVO\nSVO->CDG\nLHR->SVO\nSVO->LHR\nCDG->SVO\n",
"3\nSVO\nSVO->HKT\nHKT->SVO\nSVO->RAP\n"
] | [
"home\n",
"contest\n"
] | In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. | 500 | [
{
"input": "4\nSVO\nSVO->CDG\nLHR->SVO\nSVO->LHR\nCDG->SVO",
"output": "home"
},
{
"input": "3\nSVO\nSVO->HKT\nHKT->SVO\nSVO->RAP",
"output": "contest"
},
{
"input": "1\nESJ\nESJ->TSJ",
"output": "contest"
},
{
"input": "2\nXMR\nFAJ->XMR\nXMR->FAJ",
"output": "home"
},
... | 1,578,646,510 | 2,147,483,647 | Python 3 | OK | TESTS | 23 | 108 | 307,200 | # import sys
# sys.stdin=open("input.in","r")
if int(input())%2==0:
print("home")
else:
print("contest")
| Title: Neverending competitions
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back.
Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that:
- this list contains all Jinotega's flights in this year (in arbitrary order), - Jinotega has only flown from his hometown to a snooker contest and back, - after each competition Jinotega flies back home (though they may attend a competition in one place several times), - and finally, at the beginning of the year Jinotega was at home.
Please help them to determine Jinotega's location!
Input Specification:
In the first line of input there is a single integer *n*: the number of Jinotega's flights (1<=≤<=*n*<=≤<=100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next *n* lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport.
It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement.
Output Specification:
If Jinotega is now at home, print "home" (without quotes), otherwise print "contest".
Demo Input:
['4\nSVO\nSVO->CDG\nLHR->SVO\nSVO->LHR\nCDG->SVO\n', '3\nSVO\nSVO->HKT\nHKT->SVO\nSVO->RAP\n']
Demo Output:
['home\n', 'contest\n']
Note:
In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. | ```python
# import sys
# sys.stdin=open("input.in","r")
if int(input())%2==0:
print("home")
else:
print("contest")
``` | 3 | |
898 | C | Phone Numbers | PROGRAMMING | 1,400 | [
"implementation",
"strings"
] | null | null | Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers.
Vasya decided to organize information about the phone numbers of friends. You will be given *n* strings — all entries from Vasya's phone books. Each entry starts with a friend's name. Then follows the number of phone numbers in the current entry, and then the phone numbers themselves. It is possible that several identical phones are recorded in the same record.
Vasya also believes that if the phone number *a* is a suffix of the phone number *b* (that is, the number *b* ends up with *a*), and both numbers are written by Vasya as the phone numbers of the same person, then *a* is recorded without the city code and it should not be taken into account.
The task is to print organized information about the phone numbers of Vasya's friends. It is possible that two different people have the same number. If one person has two numbers *x* and *y*, and *x* is a suffix of *y* (that is, *y* ends in *x*), then you shouldn't print number *x*. If the number of a friend in the Vasya's phone books is recorded several times in the same format, it is necessary to take it into account exactly once.
Read the examples to understand statement and format of the output better. | First line contains the integer *n* (1<=≤<=*n*<=≤<=20) — number of entries in Vasya's phone books.
The following *n* lines are followed by descriptions of the records in the format described in statement. Names of Vasya's friends are non-empty strings whose length does not exceed 10. They consists only of lowercase English letters. Number of phone numbers in one entry is not less than 1 is not more than 10. The telephone numbers consist of digits only. If you represent a phone number as a string, then its length will be in range from 1 to 10. Phone numbers can contain leading zeros. | Print out the ordered information about the phone numbers of Vasya's friends. First output *m* — number of friends that are found in Vasya's phone books.
The following *m* lines must contain entries in the following format "name number_of_phone_numbers phone_numbers". Phone numbers should be separated by a space. Each record must contain all the phone numbers of current friend.
Entries can be displayed in arbitrary order, phone numbers for one record can also be printed in arbitrary order. | [
"2\nivan 1 00123\nmasha 1 00123\n",
"3\nkarl 2 612 12\npetr 1 12\nkatya 1 612\n",
"4\nivan 3 123 123 456\nivan 2 456 456\nivan 8 789 3 23 6 56 9 89 2\ndasha 2 23 789\n"
] | [
"2\nmasha 1 00123 \nivan 1 00123 \n",
"3\nkatya 1 612 \npetr 1 12 \nkarl 1 612 \n",
"2\ndasha 2 23 789 \nivan 4 789 123 2 456 \n"
] | none | 1,500 | [
{
"input": "2\nivan 1 00123\nmasha 1 00123",
"output": "2\nmasha 1 00123 \nivan 1 00123 "
},
{
"input": "3\nkarl 2 612 12\npetr 1 12\nkatya 1 612",
"output": "3\nkatya 1 612 \npetr 1 12 \nkarl 1 612 "
},
{
"input": "4\nivan 3 123 123 456\nivan 2 456 456\nivan 8 789 3 23 6 56 9 89 2\ndash... | 1,541,004,850 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 0 | 109 | 0 | from sys import stdin
n=int(stdin.readline().strip())
d=dict()
for i in range(n):
s=stdin.readline().strip().split()
if s[0] in d:
d[s[0]]+=s[2::]
else:
d.update({s[0]:s[2::]})
for i in d:
d[i]=list(set(d[i]))
rem=[]
for j in range(len(d[i])):
for k in range(len(d[i])):
if k!=j and int(d[i][k])>int((d[i][j])) and d[i][k][len(d[i][k])-len(d[i][j])::]==d[i][j]:
rem.append(d[i][j])
rem=set(rem)
for j in rem:
d[i].remove(j)
print(i,len(d[i]),*d[i])
| Title: Phone Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers.
Vasya decided to organize information about the phone numbers of friends. You will be given *n* strings — all entries from Vasya's phone books. Each entry starts with a friend's name. Then follows the number of phone numbers in the current entry, and then the phone numbers themselves. It is possible that several identical phones are recorded in the same record.
Vasya also believes that if the phone number *a* is a suffix of the phone number *b* (that is, the number *b* ends up with *a*), and both numbers are written by Vasya as the phone numbers of the same person, then *a* is recorded without the city code and it should not be taken into account.
The task is to print organized information about the phone numbers of Vasya's friends. It is possible that two different people have the same number. If one person has two numbers *x* and *y*, and *x* is a suffix of *y* (that is, *y* ends in *x*), then you shouldn't print number *x*. If the number of a friend in the Vasya's phone books is recorded several times in the same format, it is necessary to take it into account exactly once.
Read the examples to understand statement and format of the output better.
Input Specification:
First line contains the integer *n* (1<=≤<=*n*<=≤<=20) — number of entries in Vasya's phone books.
The following *n* lines are followed by descriptions of the records in the format described in statement. Names of Vasya's friends are non-empty strings whose length does not exceed 10. They consists only of lowercase English letters. Number of phone numbers in one entry is not less than 1 is not more than 10. The telephone numbers consist of digits only. If you represent a phone number as a string, then its length will be in range from 1 to 10. Phone numbers can contain leading zeros.
Output Specification:
Print out the ordered information about the phone numbers of Vasya's friends. First output *m* — number of friends that are found in Vasya's phone books.
The following *m* lines must contain entries in the following format "name number_of_phone_numbers phone_numbers". Phone numbers should be separated by a space. Each record must contain all the phone numbers of current friend.
Entries can be displayed in arbitrary order, phone numbers for one record can also be printed in arbitrary order.
Demo Input:
['2\nivan 1 00123\nmasha 1 00123\n', '3\nkarl 2 612 12\npetr 1 12\nkatya 1 612\n', '4\nivan 3 123 123 456\nivan 2 456 456\nivan 8 789 3 23 6 56 9 89 2\ndasha 2 23 789\n']
Demo Output:
['2\nmasha 1 00123 \nivan 1 00123 \n', '3\nkatya 1 612 \npetr 1 12 \nkarl 1 612 \n', '2\ndasha 2 23 789 \nivan 4 789 123 2 456 \n']
Note:
none | ```python
from sys import stdin
n=int(stdin.readline().strip())
d=dict()
for i in range(n):
s=stdin.readline().strip().split()
if s[0] in d:
d[s[0]]+=s[2::]
else:
d.update({s[0]:s[2::]})
for i in d:
d[i]=list(set(d[i]))
rem=[]
for j in range(len(d[i])):
for k in range(len(d[i])):
if k!=j and int(d[i][k])>int((d[i][j])) and d[i][k][len(d[i][k])-len(d[i][j])::]==d[i][j]:
rem.append(d[i][j])
rem=set(rem)
for j in rem:
d[i].remove(j)
print(i,len(d[i]),*d[i])
``` | 0 | |
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,685,982,157 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 92 | 0 | k=int(input())
l=int(input())
m=int(input())
n=int(input())
d=int(input())
c=0
for i in range(0,d):
if (i%k)==0 or (i%l)==0 or (i%m)==0 or (i%n)==0:
c+=1
print(c) | 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
k=int(input())
l=int(input())
m=int(input())
n=int(input())
d=int(input())
c=0
for i in range(0,d):
if (i%k)==0 or (i%l)==0 or (i%m)==0 or (i%n)==0:
c+=1
print(c)
``` | 0 | |
825 | A | Binary Protocol | PROGRAMMING | 1,100 | [
"implementation"
] | null | null | Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm:
- Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones). - Digits are written one by one in order corresponding to number and separated by single '0' character.
Though Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number. | The first line contains one integer number *n* (1<=≤<=*n*<=≤<=89) — length of the string *s*.
The second line contains string *s* — sequence of '0' and '1' characters, number in its encoded format. It is guaranteed that the number corresponding to the string is positive and doesn't exceed 109. The string always starts with '1'. | Print the decoded number. | [
"3\n111\n",
"9\n110011101\n"
] | [
"3\n",
"2031\n"
] | none | 0 | [
{
"input": "3\n111",
"output": "3"
},
{
"input": "9\n110011101",
"output": "2031"
},
{
"input": "1\n1",
"output": "1"
},
{
"input": "3\n100",
"output": "100"
},
{
"input": "5\n10001",
"output": "1001"
},
{
"input": "14\n11001100011000",
"output": "... | 1,500,219,449 | 1,949 | Python 3 | WRONG_ANSWER | TESTS | 4 | 61 | 5,529,600 | n=int(input())
s=list(input())
k=0
d=''
for i in range(n):
if s[i]=='1':
k+=1
elif s[i]=='0' and s[i-1]=='0':
s[i-1]='2'
s[i]='2'
d=d+'0'
elif k>0:
d=d+str(k)
k=0
#print(s)
d=d+str(k)
print(d)
| Title: Binary Protocol
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm:
- Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones). - Digits are written one by one in order corresponding to number and separated by single '0' character.
Though Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number.
Input Specification:
The first line contains one integer number *n* (1<=≤<=*n*<=≤<=89) — length of the string *s*.
The second line contains string *s* — sequence of '0' and '1' characters, number in its encoded format. It is guaranteed that the number corresponding to the string is positive and doesn't exceed 109. The string always starts with '1'.
Output Specification:
Print the decoded number.
Demo Input:
['3\n111\n', '9\n110011101\n']
Demo Output:
['3\n', '2031\n']
Note:
none | ```python
n=int(input())
s=list(input())
k=0
d=''
for i in range(n):
if s[i]=='1':
k+=1
elif s[i]=='0' and s[i-1]=='0':
s[i-1]='2'
s[i]='2'
d=d+'0'
elif k>0:
d=d+str(k)
k=0
#print(s)
d=d+str(k)
print(d)
``` | 0 | |
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,695,637,001 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 30 | 0 | a = input()
ans = a if len(a)<5 else a[0]+str(len(a)-2)+a[-1]
print(ans) | 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
a = input()
ans = a if len(a)<5 else a[0]+str(len(a)-2)+a[-1]
print(ans)
``` | 0 |
652 | D | Nested Segments | PROGRAMMING | 1,800 | [
"data structures",
"sortings"
] | null | null | You are given *n* segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=2·105) — the number of segments on a line.
Each of the next *n* lines contains two integers *l**i* and *r**i* (<=-<=109<=≤<=*l**i*<=<<=*r**i*<=≤<=109) — the coordinates of the left and the right ends of the *i*-th segment. It is guaranteed that there are no ends of some segments that coincide. | Print *n* lines. The *j*-th of them should contain the only integer *a**j* — the number of segments contained in the *j*-th segment. | [
"4\n1 8\n2 3\n4 7\n5 6\n",
"3\n3 4\n1 5\n2 6\n"
] | [
"3\n0\n1\n0\n",
"0\n1\n1\n"
] | none | 0 | [
{
"input": "4\n1 8\n2 3\n4 7\n5 6",
"output": "3\n0\n1\n0"
},
{
"input": "3\n3 4\n1 5\n2 6",
"output": "0\n1\n1"
},
{
"input": "1\n-1000000000 1000000000",
"output": "0"
},
{
"input": "2\n-1000000000 999999999\n-999999999 1000000000",
"output": "0\n0"
},
{
"input"... | 1,698,058,917 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 52 | 1,466 | 69,836,800 | '''
Descripttion: your project
version: 1.0
Author: ElysiaRealme
Date: 2023-10-23 16:56:58
LastEditors: ElysiaRealme
Language: Python
'''
from io import BytesIO, IOBase
import sys
import os
# import time
import bisect
# import functools
import math
import random
# import re
from collections import Counter, defaultdict, deque
# from copy import deepcopy
from functools import cmp_to_key, lru_cache, reduce
from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest
from itertools import accumulate, combinations, permutations
# from operator import add, iand, ior, itemgetter, mul, xor
# from string import ascii_lowercase, ascii_uppercase
from typing import *
input = lambda: sys.stdin.readline().rstrip("\r\n")
def I():
return input()
def II():
return int(input())
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
def GMI():
return map(lambda x: int(x) - 1, input().split())
def LGMI():
return list(map(lambda x: int(x) - 1, input().split()))
dx, dy = [0, 1, 0, -1, 1, -1, 1, -1], [1, 0, -1, 0, -1, -1, 1, 1]
inf = float('inf')
from bisect import *
class BIT:
def __init__(self, n):
self.tree = [0] * n # 注意下标从1开始
def lowbit(self, x):
return x & (-x)
# arr[i] += val
def update(self, i, val):
while i < len(self.tree):
self.tree[i] += val
i += self.lowbit(i)
# 返回arr[:i+1]的sum
def query(self, i):
res = 0
while i > 0:
res += self.tree[i]
i -= self.lowbit(i)
return res
t = II()
g = []
a = []
for i in range(1, t + 1):
l, r = MII()
g.append((r, l, i))
a.append(l)
a = sorted(set(a))
d = {}
for i, x in enumerate(a):
d[x] = i
g.sort()
tree = BIT(t + 10)
n = t
res = [0] * (n + 1)
#print(g)
for x in range(1, n + 1):
r, l, i = g[x - 1]
idx = d[l] + 1
tree.update(idx, 1)
res[i] = x - tree.query(idx)
for i in range(1, n + 1):
print(res[i]) | Title: Nested Segments
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given *n* segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=2·105) — the number of segments on a line.
Each of the next *n* lines contains two integers *l**i* and *r**i* (<=-<=109<=≤<=*l**i*<=<<=*r**i*<=≤<=109) — the coordinates of the left and the right ends of the *i*-th segment. It is guaranteed that there are no ends of some segments that coincide.
Output Specification:
Print *n* lines. The *j*-th of them should contain the only integer *a**j* — the number of segments contained in the *j*-th segment.
Demo Input:
['4\n1 8\n2 3\n4 7\n5 6\n', '3\n3 4\n1 5\n2 6\n']
Demo Output:
['3\n0\n1\n0\n', '0\n1\n1\n']
Note:
none | ```python
'''
Descripttion: your project
version: 1.0
Author: ElysiaRealme
Date: 2023-10-23 16:56:58
LastEditors: ElysiaRealme
Language: Python
'''
from io import BytesIO, IOBase
import sys
import os
# import time
import bisect
# import functools
import math
import random
# import re
from collections import Counter, defaultdict, deque
# from copy import deepcopy
from functools import cmp_to_key, lru_cache, reduce
from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest
from itertools import accumulate, combinations, permutations
# from operator import add, iand, ior, itemgetter, mul, xor
# from string import ascii_lowercase, ascii_uppercase
from typing import *
input = lambda: sys.stdin.readline().rstrip("\r\n")
def I():
return input()
def II():
return int(input())
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
def GMI():
return map(lambda x: int(x) - 1, input().split())
def LGMI():
return list(map(lambda x: int(x) - 1, input().split()))
dx, dy = [0, 1, 0, -1, 1, -1, 1, -1], [1, 0, -1, 0, -1, -1, 1, 1]
inf = float('inf')
from bisect import *
class BIT:
def __init__(self, n):
self.tree = [0] * n # 注意下标从1开始
def lowbit(self, x):
return x & (-x)
# arr[i] += val
def update(self, i, val):
while i < len(self.tree):
self.tree[i] += val
i += self.lowbit(i)
# 返回arr[:i+1]的sum
def query(self, i):
res = 0
while i > 0:
res += self.tree[i]
i -= self.lowbit(i)
return res
t = II()
g = []
a = []
for i in range(1, t + 1):
l, r = MII()
g.append((r, l, i))
a.append(l)
a = sorted(set(a))
d = {}
for i, x in enumerate(a):
d[x] = i
g.sort()
tree = BIT(t + 10)
n = t
res = [0] * (n + 1)
#print(g)
for x in range(1, n + 1):
r, l, i = g[x - 1]
idx = d[l] + 1
tree.update(idx, 1)
res[i] = x - tree.query(idx)
for i in range(1, n + 1):
print(res[i])
``` | 3 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Andryusha is an orderly boy and likes to keep things in their place.
Today he faced a problem to put his socks in the wardrobe. He has *n* distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to *n*. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.
Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time? | The first line contains the single integer *n* (1<=≤<=*n*<=≤<=105) — the number of sock pairs.
The second line contains 2*n* integers *x*1,<=*x*2,<=...,<=*x*2*n* (1<=≤<=*x**i*<=≤<=*n*), which describe the order in which Andryusha took the socks from the bag. More precisely, *x**i* means that the *i*-th sock Andryusha took out was from pair *x**i*.
It is guaranteed that Andryusha took exactly two socks of each pair. | Print single integer — the maximum number of socks that were on the table at the same time. | [
"1\n1 1\n",
"3\n2 1 1 3 2 3\n"
] | [
"1\n",
"2\n"
] | In the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.
In the second example Andryusha behaved as follows:
- Initially the table was empty, he took out a sock from pair 2 and put it on the table. - Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table. - Socks (1, 2) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe. - Sock (2) was on the table. Andryusha took out a sock from pair 3 and put it on the table. - Socks (2, 3) were on the table. Andryusha took out a sock from pair 2, and put this pair into the wardrobe. - Sock (3) was on the table. Andryusha took out a sock from pair 3 and put this pair into the wardrobe. | 0 | [
{
"input": "1\n1 1",
"output": "1"
},
{
"input": "3\n2 1 1 3 2 3",
"output": "2"
},
{
"input": "5\n5 1 3 2 4 3 1 2 4 5",
"output": "5"
},
{
"input": "10\n4 2 6 3 4 8 7 1 1 5 2 10 6 8 3 5 10 9 9 7",
"output": "6"
},
{
"input": "50\n30 47 31 38 37 50 36 43 9 23 2 2 ... | 1,623,072,743 | 2,147,483,647 | Python 3 | OK | TESTS | 56 | 280 | 14,131,200 | n = int(input())
st = set()
m = 0
c = 0
for i in list(map(int, input().split())):
if i in st:
c -= 1
else:
c += 1
st.add(i)
m = max(m, c)
print(m)
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Andryusha is an orderly boy and likes to keep things in their place.
Today he faced a problem to put his socks in the wardrobe. He has *n* distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to *n*. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.
Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?
Input Specification:
The first line contains the single integer *n* (1<=≤<=*n*<=≤<=105) — the number of sock pairs.
The second line contains 2*n* integers *x*1,<=*x*2,<=...,<=*x*2*n* (1<=≤<=*x**i*<=≤<=*n*), which describe the order in which Andryusha took the socks from the bag. More precisely, *x**i* means that the *i*-th sock Andryusha took out was from pair *x**i*.
It is guaranteed that Andryusha took exactly two socks of each pair.
Output Specification:
Print single integer — the maximum number of socks that were on the table at the same time.
Demo Input:
['1\n1 1\n', '3\n2 1 1 3 2 3\n']
Demo Output:
['1\n', '2\n']
Note:
In the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.
In the second example Andryusha behaved as follows:
- Initially the table was empty, he took out a sock from pair 2 and put it on the table. - Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table. - Socks (1, 2) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe. - Sock (2) was on the table. Andryusha took out a sock from pair 3 and put it on the table. - Socks (2, 3) were on the table. Andryusha took out a sock from pair 2, and put this pair into the wardrobe. - Sock (3) was on the table. Andryusha took out a sock from pair 3 and put this pair into the wardrobe. | ```python
n = int(input())
st = set()
m = 0
c = 0
for i in list(map(int, input().split())):
if i in st:
c -= 1
else:
c += 1
st.add(i)
m = max(m, c)
print(m)
``` | 3 | |
492 | A | Vanya and Cubes | PROGRAMMING | 800 | [
"implementation"
] | null | null | Vanya got *n* cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1<=+<=2<==<=3 cubes, the third level must have 1<=+<=2<=+<=3<==<=6 cubes, and so on. Thus, the *i*-th level of the pyramid must have 1<=+<=2<=+<=...<=+<=(*i*<=-<=1)<=+<=*i* cubes.
Vanya wants to know what is the maximum height of the pyramid that he can make using the given cubes. | The first line contains integer *n* (1<=≤<=*n*<=≤<=104) — the number of cubes given to Vanya. | Print the maximum possible height of the pyramid in the single line. | [
"1\n",
"25\n"
] | [
"1\n",
"4\n"
] | Illustration to the second sample: | 500 | [
{
"input": "1",
"output": "1"
},
{
"input": "25",
"output": "4"
},
{
"input": "2",
"output": "1"
},
{
"input": "4115",
"output": "28"
},
{
"input": "9894",
"output": "38"
},
{
"input": "7969",
"output": "35"
},
{
"input": "6560",
"outpu... | 1,695,400,227 | 2,147,483,647 | Python 3 | OK | TESTS | 25 | 46 | 0 | n = int(input())
height = 0
cubes_required = 0
while cubes_required <= n:
height += 1
cubes_required += height * (height + 1) // 2
print(height - 1)
| Title: Vanya and Cubes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya got *n* cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1<=+<=2<==<=3 cubes, the third level must have 1<=+<=2<=+<=3<==<=6 cubes, and so on. Thus, the *i*-th level of the pyramid must have 1<=+<=2<=+<=...<=+<=(*i*<=-<=1)<=+<=*i* cubes.
Vanya wants to know what is the maximum height of the pyramid that he can make using the given cubes.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=104) — the number of cubes given to Vanya.
Output Specification:
Print the maximum possible height of the pyramid in the single line.
Demo Input:
['1\n', '25\n']
Demo Output:
['1\n', '4\n']
Note:
Illustration to the second sample: | ```python
n = int(input())
height = 0
cubes_required = 0
while cubes_required <= n:
height += 1
cubes_required += height * (height + 1) // 2
print(height - 1)
``` | 3 | |
69 | A | Young Physicist | PROGRAMMING | 1,000 | [
"implementation",
"math"
] | A. Young Physicist | 2 | 256 | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. | The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100), then follow *n* lines containing three integers each: the *x**i* coordinate, the *y**i* coordinate and the *z**i* coordinate of the force vector, applied to the body (<=-<=100<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=100). | Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. | [
"3\n4 1 7\n-2 4 -1\n1 -5 -3\n",
"3\n3 -1 7\n-5 2 -4\n2 -1 -3\n"
] | [
"NO",
"YES"
] | none | 500 | [
{
"input": "3\n4 1 7\n-2 4 -1\n1 -5 -3",
"output": "NO"
},
{
"input": "3\n3 -1 7\n-5 2 -4\n2 -1 -3",
"output": "YES"
},
{
"input": "10\n21 32 -46\n43 -35 21\n42 2 -50\n22 40 20\n-27 -9 38\n-4 1 1\n-40 6 -31\n-13 -2 34\n-21 34 -12\n-32 -29 41",
"output": "NO"
},
{
"input": "10... | 1,601,559,725 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 6 | 218 | 307,200 | n=int(input())
d=[]
for i in range(n):
a=[x for x in input().split()]
x=a[0]
y=a[1]
z=a[2]
d.append(int(x)+int(y)+int(z))
x=d[0]
y=d[1]
z=d[2]
if int(x)+int(y)+int(z)==0:
print("YES")
elif int(x)+int(y)+int(z)!=0:
print("NO") | Title: Young Physicist
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
Input Specification:
The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100), then follow *n* lines containing three integers each: the *x**i* coordinate, the *y**i* coordinate and the *z**i* coordinate of the force vector, applied to the body (<=-<=100<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=100).
Output Specification:
Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.
Demo Input:
['3\n4 1 7\n-2 4 -1\n1 -5 -3\n', '3\n3 -1 7\n-5 2 -4\n2 -1 -3\n']
Demo Output:
['NO', 'YES']
Note:
none | ```python
n=int(input())
d=[]
for i in range(n):
a=[x for x in input().split()]
x=a[0]
y=a[1]
z=a[2]
d.append(int(x)+int(y)+int(z))
x=d[0]
y=d[1]
z=d[2]
if int(x)+int(y)+int(z)==0:
print("YES")
elif int(x)+int(y)+int(z)!=0:
print("NO")
``` | 0 |
8 | A | Train and Peter | PROGRAMMING | 1,200 | [
"strings"
] | A. Train and Peter | 1 | 64 | Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours. | The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order. | Output one of the four words without inverted commas:
- «forward» — if Peter could see such sequences only on the way from A to B; - «backward» — if Peter could see such sequences on the way from B to A; - «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A; - «fantasy» — if Peter could not see such sequences. | [
"atob\na\nb\n",
"aaacaaa\naca\naa\n"
] | [
"forward\n",
"both\n"
] | It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B. | 0 | [
{
"input": "atob\na\nb",
"output": "forward"
},
{
"input": "aaacaaa\naca\naa",
"output": "both"
},
{
"input": "aaa\naa\naa",
"output": "fantasy"
},
{
"input": "astalavista\nastla\nlavista",
"output": "fantasy"
},
{
"input": "abacabadabacaba\nabacaba\nabacaba",
... | 1,627,050,559 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 3 | 92 | 6,963,200 | s = input()
a = input()
b = input()
i = s.index(a)
j = b in s[i + len(a):] if (i != -1) else False
ri = s[::-1].index(a)
rj = b in s[::-1][i + len(a):] if (i != -1) else False
if(j):
print("both" if rj else "forward")
else:
print("backward" if rj else "fantasy")
| Title: Train and Peter
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input Specification:
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output Specification:
Output one of the four words without inverted commas:
- «forward» — if Peter could see such sequences only on the way from A to B; - «backward» — if Peter could see such sequences on the way from B to A; - «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A; - «fantasy» — if Peter could not see such sequences.
Demo Input:
['atob\na\nb\n', 'aaacaaa\naca\naa\n']
Demo Output:
['forward\n', 'both\n']
Note:
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B. | ```python
s = input()
a = input()
b = input()
i = s.index(a)
j = b in s[i + len(a):] if (i != -1) else False
ri = s[::-1].index(a)
rj = b in s[::-1][i + len(a):] if (i != -1) else False
if(j):
print("both" if rj else "forward")
else:
print("backward" if rj else "fantasy")
``` | -1 |
195 | C | Try and Catch | PROGRAMMING | 1,800 | [
"expression parsing",
"implementation"
] | null | null | Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.
The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks:
1. The try operator. It opens a new try-catch-block. 1. The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator.
The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.
Let's suggest that as a result of using some throw operator the program created an exception of type *a*. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type *a* as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception".
To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.
Your task is: given a program in VPL, determine, what message will be displayed on the screen. | The first line contains a single integer: *n* (1<=≤<=*n*<=≤<=105) the number of lines in the program. Next *n* lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces.
The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark.
The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols.
Length of any line in the input file does not exceed 50 symbols. | Print the message the screen will show after the given program is executed. | [
"8\ntry\n try\n throw ( AE ) \n catch ( BE, \"BE in line 3\")\n\n try\n catch(AE, \"AE in line 5\") \ncatch(AE,\"AE somewhere\")\n",
"8\ntry\n try\n throw ( AE ) \n catch ( AE, \"AE in line 3\")\n\n try\n catch(BE, \"BE in line 5\") \ncatch(AE,\"AE somewhere\")\n",
"8\ntry\... | [
"AE somewhere\n",
"AE in line 3\n",
"Unhandled Exception\n"
] | In the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,"BE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so the second block will be activated, because operator catch(AE,"AE somewhere") has exception type AE as parameter and operator catch(BE,"BE in line 3") has exception type BE.
In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,"AE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,"AE in line 3") is described earlier than catch(AE,"AE somewhere")
In the third sample there is no blocks that can be activated by an exception of type CE. | 1,500 | [
{
"input": "8\ntry\n try\n throw ( AE ) \n catch ( BE, \"BE in line 3\")\n\n try\n catch(AE, \"AE in line 5\") \ncatch(AE,\"AE somewhere\")",
"output": "AE somewhere"
},
{
"input": "8\ntry\n try\n throw ( AE ) \n catch ( AE, \"AE in line 3\")\n\n try\n catch(BE,... | 1,675,077,902 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 30 | 0 | def find_msg_in_brackets(line):
res = ""
is_start = False
for ch in line.strip():
if ch == ')':
break
if ch == '(':
is_start = True
continue
if is_start:
res += ch
return res
n = int(input())
i = 0
ms = dict()
find_throw = False
st = []
before = []
look = ""
for _ in range(n):
l = input()
if 'try' in l:
st.append(i)
if not find_throw:
before.append(i)
i += 1
elif 'throw' in l:
inter = find_msg_in_brackets(l)
look = inter.strip()
find_throw = True
elif 'catch' in l:
inter = find_msg_in_brackets(l)
tp, msg = inter.split(',')
ind = st.pop()
ms[ind] = (tp.strip(), msg.strip())
# print("look type", look)
# print(ms)
while before:
ind = before.pop()
if ms[ind][0] == look:
print(ms[ind][1])
exit()
print("Unhandled Exception")
| Title: Try and Catch
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.
The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks:
1. The try operator. It opens a new try-catch-block. 1. The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator.
The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.
Let's suggest that as a result of using some throw operator the program created an exception of type *a*. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type *a* as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception".
To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.
Your task is: given a program in VPL, determine, what message will be displayed on the screen.
Input Specification:
The first line contains a single integer: *n* (1<=≤<=*n*<=≤<=105) the number of lines in the program. Next *n* lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces.
The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark.
The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols.
Length of any line in the input file does not exceed 50 symbols.
Output Specification:
Print the message the screen will show after the given program is executed.
Demo Input:
['8\ntry\n try\n throw ( AE ) \n catch ( BE, "BE in line 3")\n\n try\n catch(AE, "AE in line 5") \ncatch(AE,"AE somewhere")\n', '8\ntry\n try\n throw ( AE ) \n catch ( AE, "AE in line 3")\n\n try\n catch(BE, "BE in line 5") \ncatch(AE,"AE somewhere")\n', '8\ntry\n try\n throw ( CE ) \n catch ( BE, "BE in line 3")\n\n try\n catch(AE, "AE in line 5") \ncatch(AE,"AE somewhere")\n']
Demo Output:
['AE somewhere\n', 'AE in line 3\n', 'Unhandled Exception\n']
Note:
In the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,"BE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so the second block will be activated, because operator catch(AE,"AE somewhere") has exception type AE as parameter and operator catch(BE,"BE in line 3") has exception type BE.
In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,"AE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,"AE in line 3") is described earlier than catch(AE,"AE somewhere")
In the third sample there is no blocks that can be activated by an exception of type CE. | ```python
def find_msg_in_brackets(line):
res = ""
is_start = False
for ch in line.strip():
if ch == ')':
break
if ch == '(':
is_start = True
continue
if is_start:
res += ch
return res
n = int(input())
i = 0
ms = dict()
find_throw = False
st = []
before = []
look = ""
for _ in range(n):
l = input()
if 'try' in l:
st.append(i)
if not find_throw:
before.append(i)
i += 1
elif 'throw' in l:
inter = find_msg_in_brackets(l)
look = inter.strip()
find_throw = True
elif 'catch' in l:
inter = find_msg_in_brackets(l)
tp, msg = inter.split(',')
ind = st.pop()
ms[ind] = (tp.strip(), msg.strip())
# print("look type", look)
# print(ms)
while before:
ind = before.pop()
if ms[ind][0] == look:
print(ms[ind][1])
exit()
print("Unhandled Exception")
``` | 0 | |
690 | C2 | Brain Network (medium) | PROGRAMMING | 1,500 | [
"dfs and similar",
"graphs",
"trees"
] | null | null | Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of *n* brains and *m* brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version. | The first line of the input contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100000) denoting the number of brains (which are conveniently numbered from 1 to *n*) and the number of brain connectors in the nervous system, respectively. In the next *m* lines, descriptions of brain connectors follow. Every connector is given as a pair of brains *a* *b* it connects (1<=≤<=*a*,<=*b*<=≤<=*n* and *a*<=≠<=*b*). | Print one number – the brain latency. | [
"4 3\n1 2\n1 3\n1 4\n",
"5 4\n1 2\n2 3\n3 4\n3 5\n"
] | [
"2",
"3"
] | none | 0 | [
{
"input": "2 1\n1 2",
"output": "1"
},
{
"input": "3 2\n2 1\n3 2",
"output": "2"
},
{
"input": "10 9\n5 1\n1 2\n9 3\n10 5\n6 3\n8 5\n2 7\n2 3\n9 4",
"output": "6"
},
{
"input": "4 3\n1 2\n1 3\n1 4",
"output": "2"
},
{
"input": "5 4\n1 2\n2 3\n3 4\n3 5",
"outp... | 1,672,698,339 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 7 | 467 | 15,462,400 | from collections import defaultdict
import heapq
n, m = tuple(map(int, input().split()))
tree = defaultdict(list)
for _ in range(m):
u, v = tuple(map(int, input().split()))
tree[u].append(v)
tree[v].append(u)
def solve(tree):
ans = 0
visited = {1}
def dfs(node):
nonlocal ans
res = []
for child in tree[node]:
if child not in visited:
visited.add(child)
res.append(dfs(child))
res.sort()
if not res:
ans = max(ans, 1)
return 1
if len(res) == 1:
ans = max(ans, 1 + res[-1])
else:
ans = max(ans, 1 + res[-1] + res[-2])
return 1 + res[-1]
dfs(1)
return ans if not ans else ans - 1
print(solve(tree))
| Title: Brain Network (medium)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of *n* brains and *m* brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input Specification:
The first line of the input contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100000) denoting the number of brains (which are conveniently numbered from 1 to *n*) and the number of brain connectors in the nervous system, respectively. In the next *m* lines, descriptions of brain connectors follow. Every connector is given as a pair of brains *a* *b* it connects (1<=≤<=*a*,<=*b*<=≤<=*n* and *a*<=≠<=*b*).
Output Specification:
Print one number – the brain latency.
Demo Input:
['4 3\n1 2\n1 3\n1 4\n', '5 4\n1 2\n2 3\n3 4\n3 5\n']
Demo Output:
['2', '3']
Note:
none | ```python
from collections import defaultdict
import heapq
n, m = tuple(map(int, input().split()))
tree = defaultdict(list)
for _ in range(m):
u, v = tuple(map(int, input().split()))
tree[u].append(v)
tree[v].append(u)
def solve(tree):
ans = 0
visited = {1}
def dfs(node):
nonlocal ans
res = []
for child in tree[node]:
if child not in visited:
visited.add(child)
res.append(dfs(child))
res.sort()
if not res:
ans = max(ans, 1)
return 1
if len(res) == 1:
ans = max(ans, 1 + res[-1])
else:
ans = max(ans, 1 + res[-1] + res[-2])
return 1 + res[-1]
dfs(1)
return ans if not ans else ans - 1
print(solve(tree))
``` | -1 | |
245 | A | System Administrator | PROGRAMMING | 800 | [
"implementation"
] | null | null | Polycarpus is a system administrator. There are two servers under his strict guidance — *a* and *b*. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers *x* and *y* (*x*<=+<=*y*<==<=10; *x*,<=*y*<=≥<=0). These numbers mean that *x* packets successfully reached the corresponding server through the network and *y* packets were lost.
Today Polycarpus has performed overall *n* ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results. | The first line contains a single integer *n* (2<=≤<=*n*<=≤<=1000) — the number of commands Polycarpus has fulfilled. Each of the following *n* lines contains three integers — the description of the commands. The *i*-th of these lines contains three space-separated integers *t**i*, *x**i*, *y**i* (1<=≤<=*t**i*<=≤<=2; *x**i*,<=*y**i*<=≥<=0; *x**i*<=+<=*y**i*<==<=10). If *t**i*<==<=1, then the *i*-th command is "ping a", otherwise the *i*-th command is "ping b". Numbers *x**i*, *y**i* represent the result of executing this command, that is, *x**i* packets reached the corresponding server successfully and *y**i* packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command. | In the first line print string "LIVE" (without the quotes) if server *a* is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server *b* in the similar format. | [
"2\n1 5 5\n2 6 4\n",
"3\n1 0 10\n2 0 10\n1 10 0\n"
] | [
"LIVE\nLIVE\n",
"LIVE\nDEAD\n"
] | Consider the first test case. There 10 packets were sent to server *a*, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server *b*, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server *a*, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server *b*, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network. | 0 | [
{
"input": "2\n1 5 5\n2 6 4",
"output": "LIVE\nLIVE"
},
{
"input": "3\n1 0 10\n2 0 10\n1 10 0",
"output": "LIVE\nDEAD"
},
{
"input": "10\n1 3 7\n2 4 6\n1 2 8\n2 5 5\n2 10 0\n2 10 0\n1 8 2\n2 2 8\n2 10 0\n1 1 9",
"output": "DEAD\nLIVE"
},
{
"input": "11\n1 8 2\n1 6 4\n1 9 1\n1... | 1,552,820,820 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 156 | 0 | x = int(input())
for i in range(x):
k = 0
y = list(map(int,input().split()))
for i in range(x):
if k == 1:
break
if y[1]>=5:
print("Live")
else:
print("Dead")
k = k + 1 | Title: System Administrator
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarpus is a system administrator. There are two servers under his strict guidance — *a* and *b*. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers *x* and *y* (*x*<=+<=*y*<==<=10; *x*,<=*y*<=≥<=0). These numbers mean that *x* packets successfully reached the corresponding server through the network and *y* packets were lost.
Today Polycarpus has performed overall *n* ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input Specification:
The first line contains a single integer *n* (2<=≤<=*n*<=≤<=1000) — the number of commands Polycarpus has fulfilled. Each of the following *n* lines contains three integers — the description of the commands. The *i*-th of these lines contains three space-separated integers *t**i*, *x**i*, *y**i* (1<=≤<=*t**i*<=≤<=2; *x**i*,<=*y**i*<=≥<=0; *x**i*<=+<=*y**i*<==<=10). If *t**i*<==<=1, then the *i*-th command is "ping a", otherwise the *i*-th command is "ping b". Numbers *x**i*, *y**i* represent the result of executing this command, that is, *x**i* packets reached the corresponding server successfully and *y**i* packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output Specification:
In the first line print string "LIVE" (without the quotes) if server *a* is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server *b* in the similar format.
Demo Input:
['2\n1 5 5\n2 6 4\n', '3\n1 0 10\n2 0 10\n1 10 0\n']
Demo Output:
['LIVE\nLIVE\n', 'LIVE\nDEAD\n']
Note:
Consider the first test case. There 10 packets were sent to server *a*, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server *b*, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server *a*, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server *b*, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network. | ```python
x = int(input())
for i in range(x):
k = 0
y = list(map(int,input().split()))
for i in range(x):
if k == 1:
break
if y[1]>=5:
print("Live")
else:
print("Dead")
k = k + 1
``` | 0 | |
791 | A | Bear and Big Brother | PROGRAMMING | 800 | [
"implementation"
] | null | null | Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh *a* and *b* respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.
After how many full years will Limak become strictly larger (strictly heavier) than Bob? | The only line of the input contains two integers *a* and *b* (1<=≤<=*a*<=≤<=*b*<=≤<=10) — the weight of Limak and the weight of Bob respectively. | Print one integer, denoting the integer number of years after which Limak will become strictly larger than Bob. | [
"4 7\n",
"4 9\n",
"1 1\n"
] | [
"2\n",
"3\n",
"1\n"
] | In the first sample, Limak weighs 4 and Bob weighs 7 initially. After one year their weights are 4·3 = 12 and 7·2 = 14 respectively (one weight is tripled while the other one is doubled). Limak isn't larger than Bob yet. After the second year weights are 36 and 28, so the first weight is greater than the second one. Limak became larger than Bob after two years so you should print 2.
In the second sample, Limak's and Bob's weights in next years are: 12 and 18, then 36 and 36, and finally 108 and 72 (after three years). The answer is 3. Remember that Limak wants to be larger than Bob and he won't be satisfied with equal weights.
In the third sample, Limak becomes larger than Bob after the first year. Their weights will be 3 and 2 then. | 500 | [
{
"input": "4 7",
"output": "2"
},
{
"input": "4 9",
"output": "3"
},
{
"input": "1 1",
"output": "1"
},
{
"input": "4 6",
"output": "2"
},
{
"input": "1 10",
"output": "6"
},
{
"input": "1 1",
"output": "1"
},
{
"input": "1 2",
"output... | 1,694,852,816 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 31 | 0 | r =1
s=0
c=0
v =0
n, m = map(int, input().split())
c = n
s = m
for i in range(m):
c = c * 3
s = s * 2
if c > s :
print(r)
elif c <= s :
r += 1
else:
v =0
| Title: Bear and Big Brother
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh *a* and *b* respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.
After how many full years will Limak become strictly larger (strictly heavier) than Bob?
Input Specification:
The only line of the input contains two integers *a* and *b* (1<=≤<=*a*<=≤<=*b*<=≤<=10) — the weight of Limak and the weight of Bob respectively.
Output Specification:
Print one integer, denoting the integer number of years after which Limak will become strictly larger than Bob.
Demo Input:
['4 7\n', '4 9\n', '1 1\n']
Demo Output:
['2\n', '3\n', '1\n']
Note:
In the first sample, Limak weighs 4 and Bob weighs 7 initially. After one year their weights are 4·3 = 12 and 7·2 = 14 respectively (one weight is tripled while the other one is doubled). Limak isn't larger than Bob yet. After the second year weights are 36 and 28, so the first weight is greater than the second one. Limak became larger than Bob after two years so you should print 2.
In the second sample, Limak's and Bob's weights in next years are: 12 and 18, then 36 and 36, and finally 108 and 72 (after three years). The answer is 3. Remember that Limak wants to be larger than Bob and he won't be satisfied with equal weights.
In the third sample, Limak becomes larger than Bob after the first year. Their weights will be 3 and 2 then. | ```python
r =1
s=0
c=0
v =0
n, m = map(int, input().split())
c = n
s = m
for i in range(m):
c = c * 3
s = s * 2
if c > s :
print(r)
elif c <= s :
r += 1
else:
v =0
``` | 0 | |
133 | A | HQ9+ | PROGRAMMING | 900 | [
"implementation"
] | null | null | HQ9+ is a joke programming language which has only four one-character instructions:
- "H" prints "Hello, World!",- "Q" prints the source code of the program itself,- "9" prints the lyrics of "99 Bottles of Beer" song, - "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.
You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output. | The input will consist of a single line *p* which will give a program in HQ9+. String *p* will contain between 1 and 100 characters, inclusive. ASCII-code of each character of *p* will be between 33 (exclamation mark) and 126 (tilde), inclusive. | Output "YES", if executing the program will produce any output, and "NO" otherwise. | [
"Hi!\n",
"Codeforces\n"
] | [
"YES\n",
"NO\n"
] | In the first case the program contains only one instruction — "H", which prints "Hello, World!".
In the second case none of the program characters are language instructions. | 500 | [
{
"input": "Hi!",
"output": "YES"
},
{
"input": "Codeforces",
"output": "NO"
},
{
"input": "a+b=c",
"output": "NO"
},
{
"input": "hq-lowercase",
"output": "NO"
},
{
"input": "Q",
"output": "YES"
},
{
"input": "9",
"output": "YES"
},
{
"inpu... | 1,691,661,359 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 62 | 0 | word=input()
print("YES" if "H" in word or "Q" in word or "9" in word or "+" in word else "No") | Title: HQ9+
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
HQ9+ is a joke programming language which has only four one-character instructions:
- "H" prints "Hello, World!",- "Q" prints the source code of the program itself,- "9" prints the lyrics of "99 Bottles of Beer" song, - "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.
You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.
Input Specification:
The input will consist of a single line *p* which will give a program in HQ9+. String *p* will contain between 1 and 100 characters, inclusive. ASCII-code of each character of *p* will be between 33 (exclamation mark) and 126 (tilde), inclusive.
Output Specification:
Output "YES", if executing the program will produce any output, and "NO" otherwise.
Demo Input:
['Hi!\n', 'Codeforces\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first case the program contains only one instruction — "H", which prints "Hello, World!".
In the second case none of the program characters are language instructions. | ```python
word=input()
print("YES" if "H" in word or "Q" in word or "9" in word or "+" in word else "No")
``` | 0 | |
747 | B | Mammoth's Genome Decoding | PROGRAMMING | 900 | [
"implementation",
"strings"
] | null | null | The process of mammoth's genome decoding in Berland comes to its end!
One of the few remaining tasks is to restore unrecognized nucleotides in a found chain *s*. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, *s* is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.
It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.
Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal. | The first line contains the integer *n* (4<=≤<=*n*<=≤<=255) — the length of the genome.
The second line contains the string *s* of length *n* — the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'. | If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes). | [
"8\nAG?C??CT\n",
"4\nAGCT\n",
"6\n????G?\n",
"4\nAA??\n"
] | [
"AGACGTCT\n",
"AGCT\n",
"===\n",
"===\n"
] | In the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.
In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.
In the third and the fourth examples it is impossible to decode the genom. | 1,000 | [
{
"input": "8\nAG?C??CT",
"output": "AGACGTCT"
},
{
"input": "4\nAGCT",
"output": "AGCT"
},
{
"input": "6\n????G?",
"output": "==="
},
{
"input": "4\nAA??",
"output": "==="
},
{
"input": "4\n????",
"output": "ACGT"
},
{
"input": "252\n???????GCG??T??TT... | 1,482,198,243 | 2,147,483,647 | Python 3 | OK | TESTS | 95 | 77 | 4,608,000 | from array import array
n = int(input())
g = input()
if n % 4 == 0:
gnome = array('u', list(g))
thr = n/4
indx_q = []
chk = {'A': 0, 'C': 0, 'G': 0, 'T': 0}
for i in range(len(gnome)):
if gnome[i] == '?':
indx_q.append(i)
else:
chk[gnome[i]] += 1
if chk['A'] > thr or chk['C'] > thr or chk['G'] > thr or chk['T'] > thr:
print('===')
else:
for key, value in chk.items():
for _ in range(int(thr-value)):
gnome[indx_q.pop()] = key
print(''.join(list(gnome)))
else:
print('===')
| Title: Mammoth's Genome Decoding
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The process of mammoth's genome decoding in Berland comes to its end!
One of the few remaining tasks is to restore unrecognized nucleotides in a found chain *s*. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, *s* is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.
It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.
Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.
Input Specification:
The first line contains the integer *n* (4<=≤<=*n*<=≤<=255) — the length of the genome.
The second line contains the string *s* of length *n* — the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.
Output Specification:
If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).
Demo Input:
['8\nAG?C??CT\n', '4\nAGCT\n', '6\n????G?\n', '4\nAA??\n']
Demo Output:
['AGACGTCT\n', 'AGCT\n', '===\n', '===\n']
Note:
In the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.
In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.
In the third and the fourth examples it is impossible to decode the genom. | ```python
from array import array
n = int(input())
g = input()
if n % 4 == 0:
gnome = array('u', list(g))
thr = n/4
indx_q = []
chk = {'A': 0, 'C': 0, 'G': 0, 'T': 0}
for i in range(len(gnome)):
if gnome[i] == '?':
indx_q.append(i)
else:
chk[gnome[i]] += 1
if chk['A'] > thr or chk['C'] > thr or chk['G'] > thr or chk['T'] > thr:
print('===')
else:
for key, value in chk.items():
for _ in range(int(thr-value)):
gnome[indx_q.pop()] = key
print(''.join(list(gnome)))
else:
print('===')
``` | 3 | |
677 | A | Vanya and Fence | PROGRAMMING | 800 | [
"implementation"
] | null | null | Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard? | The first line of the input contains two integers *n* and *h* (1<=≤<=*n*<=≤<=1000, 1<=≤<=*h*<=≤<=1000) — the number of friends and the height of the fence, respectively.
The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=2*h*), the *i*-th of them is equal to the height of the *i*-th person. | Print a single integer — the minimum possible valid width of the road. | [
"3 7\n4 5 14\n",
"6 1\n1 1 1 1 1 1\n",
"6 5\n7 6 8 9 10 5\n"
] | [
"4\n",
"6\n",
"11\n"
] | In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11. | 500 | [
{
"input": "3 7\n4 5 14",
"output": "4"
},
{
"input": "6 1\n1 1 1 1 1 1",
"output": "6"
},
{
"input": "6 5\n7 6 8 9 10 5",
"output": "11"
},
{
"input": "10 420\n214 614 297 675 82 740 174 23 255 15",
"output": "13"
},
{
"input": "10 561\n657 23 1096 487 785 66 481... | 1,692,636,640 | 2,147,483,647 | Python 3 | OK | TESTS | 29 | 46 | 0 | n=input().split()
f=int(n[0])
s=int(n[1])
h=0
l=input().split()
l=[int(i)for i in l]
for x in range(f):
if l[x]>s:
h+=2
else:
h+=1
print(h) | Title: Vanya and Fence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input Specification:
The first line of the input contains two integers *n* and *h* (1<=≤<=*n*<=≤<=1000, 1<=≤<=*h*<=≤<=1000) — the number of friends and the height of the fence, respectively.
The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=2*h*), the *i*-th of them is equal to the height of the *i*-th person.
Output Specification:
Print a single integer — the minimum possible valid width of the road.
Demo Input:
['3 7\n4 5 14\n', '6 1\n1 1 1 1 1 1\n', '6 5\n7 6 8 9 10 5\n']
Demo Output:
['4\n', '6\n', '11\n']
Note:
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11. | ```python
n=input().split()
f=int(n[0])
s=int(n[1])
h=0
l=input().split()
l=[int(i)for i in l]
for x in range(f):
if l[x]>s:
h+=2
else:
h+=1
print(h)
``` | 3 | |
670 | B | Game of Robots | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | In late autumn evening *n* robots gathered in the cheerful company of friends. Each robot has a unique identifier — an integer from 1 to 109.
At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the *n*-th robot says his identifier.
Your task is to determine the *k*-th identifier to be pronounced. | The first line contains two positive integers *n* and *k* (1<=≤<=*n*<=≤<=100<=000, 1<=≤<=*k*<=≤<=*min*(2·109,<=*n*·(*n*<=+<=1)<=/<=2).
The second line contains the sequence *id*1,<=*id*2,<=...,<=*id**n* (1<=≤<=*id**i*<=≤<=109) — identifiers of roborts. It is guaranteed that all identifiers are different. | Print the *k*-th pronounced identifier (assume that the numeration starts from 1). | [
"2 2\n1 2\n",
"4 5\n10 4 18 3\n"
] | [
"1\n",
"4\n"
] | In the first sample identifiers of robots will be pronounced in the following order: 1, 1, 2. As *k* = 2, the answer equals to 1.
In the second test case identifiers of robots will be pronounced in the following order: 10, 10, 4, 10, 4, 18, 10, 4, 18, 3. As *k* = 5, the answer equals to 4. | 750 | [
{
"input": "2 2\n1 2",
"output": "1"
},
{
"input": "4 5\n10 4 18 3",
"output": "4"
},
{
"input": "1 1\n4",
"output": "4"
},
{
"input": "2 1\n5 1",
"output": "5"
},
{
"input": "2 2\n1 4",
"output": "1"
},
{
"input": "2 3\n6 7",
"output": "7"
},
... | 1,690,845,383 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 143 | 93 | 12,697,600 | n, k = input().split()
ids = input().split()
pa = 1
ult = 1
k = int(k)
for i in range(int(n)):
if ult >= k:
ult -= pa
break
else:
pa += 1
ult += pa
index = (k - ult) - 1
print(ids[index]) | Title: Game of Robots
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In late autumn evening *n* robots gathered in the cheerful company of friends. Each robot has a unique identifier — an integer from 1 to 109.
At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the *n*-th robot says his identifier.
Your task is to determine the *k*-th identifier to be pronounced.
Input Specification:
The first line contains two positive integers *n* and *k* (1<=≤<=*n*<=≤<=100<=000, 1<=≤<=*k*<=≤<=*min*(2·109,<=*n*·(*n*<=+<=1)<=/<=2).
The second line contains the sequence *id*1,<=*id*2,<=...,<=*id**n* (1<=≤<=*id**i*<=≤<=109) — identifiers of roborts. It is guaranteed that all identifiers are different.
Output Specification:
Print the *k*-th pronounced identifier (assume that the numeration starts from 1).
Demo Input:
['2 2\n1 2\n', '4 5\n10 4 18 3\n']
Demo Output:
['1\n', '4\n']
Note:
In the first sample identifiers of robots will be pronounced in the following order: 1, 1, 2. As *k* = 2, the answer equals to 1.
In the second test case identifiers of robots will be pronounced in the following order: 10, 10, 4, 10, 4, 18, 10, 4, 18, 3. As *k* = 5, the answer equals to 4. | ```python
n, k = input().split()
ids = input().split()
pa = 1
ult = 1
k = int(k)
for i in range(int(n)):
if ult >= k:
ult -= pa
break
else:
pa += 1
ult += pa
index = (k - ult) - 1
print(ids[index])
``` | 3 | |
352 | A | Jeff and Digits | PROGRAMMING | 1,000 | [
"brute force",
"implementation",
"math"
] | null | null | Jeff's got *n* cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?
Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. | The first line contains integer *n* (1<=≤<=*n*<=≤<=103). The next line contains *n* integers *a*1, *a*2, ..., *a**n* (*a**i*<==<=0 or *a**i*<==<=5). Number *a**i* represents the digit that is written on the *i*-th card. | In a single line print the answer to the problem — the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. | [
"4\n5 0 5 0\n",
"11\n5 5 5 5 5 5 5 5 0 5 5\n"
] | [
"0\n",
"5555555550\n"
] | In the first test you can make only one number that is a multiple of 90 — 0.
In the second test you can make number 5555555550, it is a multiple of 90. | 500 | [
{
"input": "4\n5 0 5 0",
"output": "0"
},
{
"input": "11\n5 5 5 5 5 5 5 5 0 5 5",
"output": "5555555550"
},
{
"input": "7\n5 5 5 5 5 5 5",
"output": "-1"
},
{
"input": "1\n5",
"output": "-1"
},
{
"input": "1\n0",
"output": "0"
},
{
"input": "11\n5 0 5 ... | 1,634,543,514 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 7 | 154 | 0 | from sys import stdin as f
n = int(next(f))
zc = 0
fc = 0
for x in map(int, next(f).split()):
if x == 5:
fc += 1
else:
zc += 1
if fc < 9:
if zc == 0:
print(-1)
else:
print(0)
else:
print('5' * (fc // 9) * 9 + '0' * zc)
| Title: Jeff and Digits
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Jeff's got *n* cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?
Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=103). The next line contains *n* integers *a*1, *a*2, ..., *a**n* (*a**i*<==<=0 or *a**i*<==<=5). Number *a**i* represents the digit that is written on the *i*-th card.
Output Specification:
In a single line print the answer to the problem — the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1.
Demo Input:
['4\n5 0 5 0\n', '11\n5 5 5 5 5 5 5 5 0 5 5\n']
Demo Output:
['0\n', '5555555550\n']
Note:
In the first test you can make only one number that is a multiple of 90 — 0.
In the second test you can make number 5555555550, it is a multiple of 90. | ```python
from sys import stdin as f
n = int(next(f))
zc = 0
fc = 0
for x in map(int, next(f).split()):
if x == 5:
fc += 1
else:
zc += 1
if fc < 9:
if zc == 0:
print(-1)
else:
print(0)
else:
print('5' * (fc // 9) * 9 + '0' * zc)
``` | 0 | |
855 | A | Tom Riddle's Diary | PROGRAMMING | 800 | [
"brute force",
"implementation",
"strings"
] | null | null | Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.
He has names of *n* people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.
Formally, for a name *s**i* in the *i*-th line, output "YES" (without quotes) if there exists an index *j* such that *s**i*<==<=*s**j* and *j*<=<<=*i*, otherwise, output "NO" (without quotes). | First line of input contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of names in the list.
Next *n* lines each contain a string *s**i*, consisting of lowercase English letters. The length of each string is between 1 and 100. | Output *n* lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not.
You can print each letter in any case (upper or lower). | [
"6\ntom\nlucius\nginny\nharry\nginny\nharry\n",
"3\na\na\na\n"
] | [
"NO\nNO\nNO\nNO\nYES\nYES\n",
"NO\nYES\nYES\n"
] | In test case 1, for *i* = 5 there exists *j* = 3 such that *s*<sub class="lower-index">*i*</sub> = *s*<sub class="lower-index">*j*</sub> and *j* < *i*, which means that answer for *i* = 5 is "YES". | 500 | [
{
"input": "6\ntom\nlucius\nginny\nharry\nginny\nharry",
"output": "NO\nNO\nNO\nNO\nYES\nYES"
},
{
"input": "3\na\na\na",
"output": "NO\nYES\nYES"
},
{
"input": "1\nzn",
"output": "NO"
},
{
"input": "9\nliyzmbjwnzryjokufuxcqtzwworjeoxkbaqrujrhdidqdvwdfzilwszgnzglnnbogaclckfnb... | 1,672,198,765 | 2,147,483,647 | Python 3 | OK | TESTS | 55 | 46 | 0 | t=int(input())
arr=[]
count=0
for i in range(t):
s=input()
arr.append(s)
count=arr.count(s)
if count>1:
print("YES")
else:
print("NO")
| Title: Tom Riddle's Diary
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.
He has names of *n* people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.
Formally, for a name *s**i* in the *i*-th line, output "YES" (without quotes) if there exists an index *j* such that *s**i*<==<=*s**j* and *j*<=<<=*i*, otherwise, output "NO" (without quotes).
Input Specification:
First line of input contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of names in the list.
Next *n* lines each contain a string *s**i*, consisting of lowercase English letters. The length of each string is between 1 and 100.
Output Specification:
Output *n* lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not.
You can print each letter in any case (upper or lower).
Demo Input:
['6\ntom\nlucius\nginny\nharry\nginny\nharry\n', '3\na\na\na\n']
Demo Output:
['NO\nNO\nNO\nNO\nYES\nYES\n', 'NO\nYES\nYES\n']
Note:
In test case 1, for *i* = 5 there exists *j* = 3 such that *s*<sub class="lower-index">*i*</sub> = *s*<sub class="lower-index">*j*</sub> and *j* < *i*, which means that answer for *i* = 5 is "YES". | ```python
t=int(input())
arr=[]
count=0
for i in range(t):
s=input()
arr.append(s)
count=arr.count(s)
if count>1:
print("YES")
else:
print("NO")
``` | 3 | |
1,006 | B | Polycarp's Practice | PROGRAMMING | 1,200 | [
"greedy",
"implementation",
"sortings"
] | null | null | Polycarp is practicing his problem solving skill. He has a list of $n$ problems with difficulties $a_1, a_2, \dots, a_n$, respectively. His plan is to practice for exactly $k$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all $n$ problems in exactly $k$ days.
Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in $k$ days he will solve all the $n$ problems.
The profit of the $j$-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the $j$-th day (i.e. if he solves problems with indices from $l$ to $r$ during a day, then the profit of the day is $\max\limits_{l \le i \le r}a_i$). The total profit of his practice is the sum of the profits over all $k$ days of his practice.
You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all $n$ problems between $k$ days satisfying the conditions above in such a way, that the total profit is maximum.
For example, if $n = 8, k = 3$ and $a = [5, 4, 2, 6, 5, 1, 9, 2]$, one of the possible distributions with maximum total profit is: $[5, 4, 2], [6, 5], [1, 9, 2]$. Here the total profit equals $5 + 6 + 9 = 20$. | The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2000$) — the number of problems and the number of days, respectively.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2000$) — difficulties of problems in Polycarp's list, in the order they are placed in the list (i.e. in the order Polycarp will solve them). | In the first line of the output print the maximum possible total profit.
In the second line print exactly $k$ positive integers $t_1, t_2, \dots, t_k$ ($t_1 + t_2 + \dots + t_k$ must equal $n$), where $t_j$ means the number of problems Polycarp will solve during the $j$-th day in order to achieve the maximum possible total profit of his practice.
If there are many possible answers, you may print any of them. | [
"8 3\n5 4 2 6 5 1 9 2\n",
"5 1\n1 1 1 1 1\n",
"4 2\n1 2000 2000 2\n"
] | [
"20\n3 2 3",
"1\n5\n",
"4000\n2 2\n"
] | The first example is described in the problem statement.
In the second example there is only one possible distribution.
In the third example the best answer is to distribute problems in the following way: $[1, 2000], [2000, 2]$. The total profit of this distribution is $2000 + 2000 = 4000$. | 0 | [
{
"input": "8 3\n5 4 2 6 5 1 9 2",
"output": "20\n4 1 3"
},
{
"input": "5 1\n1 1 1 1 1",
"output": "1\n5"
},
{
"input": "4 2\n1 2000 2000 2",
"output": "4000\n2 2"
},
{
"input": "1 1\n2000",
"output": "2000\n1"
},
{
"input": "1 1\n1234",
"output": "1234\n1"
... | 1,601,168,866 | 766 | PyPy 3 | WRONG_ANSWER | TESTS | 0 | 155 | 307,200 | from collections import Counter
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = sorted(a, reverse=1)[:k]
print(sum(b))
b = Counter(b)
res = []
for i in range(n):
if a[i] in b and b[a[i]]:
b[a[i]] -= 1
res.append(i + 1)
res[-1] = n
for i in range(k - 1):
res[i + 1] -= res[i]
print(*res)
| Title: Polycarp's Practice
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp is practicing his problem solving skill. He has a list of $n$ problems with difficulties $a_1, a_2, \dots, a_n$, respectively. His plan is to practice for exactly $k$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all $n$ problems in exactly $k$ days.
Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in $k$ days he will solve all the $n$ problems.
The profit of the $j$-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the $j$-th day (i.e. if he solves problems with indices from $l$ to $r$ during a day, then the profit of the day is $\max\limits_{l \le i \le r}a_i$). The total profit of his practice is the sum of the profits over all $k$ days of his practice.
You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all $n$ problems between $k$ days satisfying the conditions above in such a way, that the total profit is maximum.
For example, if $n = 8, k = 3$ and $a = [5, 4, 2, 6, 5, 1, 9, 2]$, one of the possible distributions with maximum total profit is: $[5, 4, 2], [6, 5], [1, 9, 2]$. Here the total profit equals $5 + 6 + 9 = 20$.
Input Specification:
The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2000$) — the number of problems and the number of days, respectively.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2000$) — difficulties of problems in Polycarp's list, in the order they are placed in the list (i.e. in the order Polycarp will solve them).
Output Specification:
In the first line of the output print the maximum possible total profit.
In the second line print exactly $k$ positive integers $t_1, t_2, \dots, t_k$ ($t_1 + t_2 + \dots + t_k$ must equal $n$), where $t_j$ means the number of problems Polycarp will solve during the $j$-th day in order to achieve the maximum possible total profit of his practice.
If there are many possible answers, you may print any of them.
Demo Input:
['8 3\n5 4 2 6 5 1 9 2\n', '5 1\n1 1 1 1 1\n', '4 2\n1 2000 2000 2\n']
Demo Output:
['20\n3 2 3', '1\n5\n', '4000\n2 2\n']
Note:
The first example is described in the problem statement.
In the second example there is only one possible distribution.
In the third example the best answer is to distribute problems in the following way: $[1, 2000], [2000, 2]$. The total profit of this distribution is $2000 + 2000 = 4000$. | ```python
from collections import Counter
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = sorted(a, reverse=1)[:k]
print(sum(b))
b = Counter(b)
res = []
for i in range(n):
if a[i] in b and b[a[i]]:
b[a[i]] -= 1
res.append(i + 1)
res[-1] = n
for i in range(k - 1):
res[i + 1] -= res[i]
print(*res)
``` | 0 | |
898 | C | Phone Numbers | PROGRAMMING | 1,400 | [
"implementation",
"strings"
] | null | null | Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers.
Vasya decided to organize information about the phone numbers of friends. You will be given *n* strings — all entries from Vasya's phone books. Each entry starts with a friend's name. Then follows the number of phone numbers in the current entry, and then the phone numbers themselves. It is possible that several identical phones are recorded in the same record.
Vasya also believes that if the phone number *a* is a suffix of the phone number *b* (that is, the number *b* ends up with *a*), and both numbers are written by Vasya as the phone numbers of the same person, then *a* is recorded without the city code and it should not be taken into account.
The task is to print organized information about the phone numbers of Vasya's friends. It is possible that two different people have the same number. If one person has two numbers *x* and *y*, and *x* is a suffix of *y* (that is, *y* ends in *x*), then you shouldn't print number *x*. If the number of a friend in the Vasya's phone books is recorded several times in the same format, it is necessary to take it into account exactly once.
Read the examples to understand statement and format of the output better. | First line contains the integer *n* (1<=≤<=*n*<=≤<=20) — number of entries in Vasya's phone books.
The following *n* lines are followed by descriptions of the records in the format described in statement. Names of Vasya's friends are non-empty strings whose length does not exceed 10. They consists only of lowercase English letters. Number of phone numbers in one entry is not less than 1 is not more than 10. The telephone numbers consist of digits only. If you represent a phone number as a string, then its length will be in range from 1 to 10. Phone numbers can contain leading zeros. | Print out the ordered information about the phone numbers of Vasya's friends. First output *m* — number of friends that are found in Vasya's phone books.
The following *m* lines must contain entries in the following format "name number_of_phone_numbers phone_numbers". Phone numbers should be separated by a space. Each record must contain all the phone numbers of current friend.
Entries can be displayed in arbitrary order, phone numbers for one record can also be printed in arbitrary order. | [
"2\nivan 1 00123\nmasha 1 00123\n",
"3\nkarl 2 612 12\npetr 1 12\nkatya 1 612\n",
"4\nivan 3 123 123 456\nivan 2 456 456\nivan 8 789 3 23 6 56 9 89 2\ndasha 2 23 789\n"
] | [
"2\nmasha 1 00123 \nivan 1 00123 \n",
"3\nkatya 1 612 \npetr 1 12 \nkarl 1 612 \n",
"2\ndasha 2 23 789 \nivan 4 789 123 2 456 \n"
] | none | 1,500 | [
{
"input": "2\nivan 1 00123\nmasha 1 00123",
"output": "2\nmasha 1 00123 \nivan 1 00123 "
},
{
"input": "3\nkarl 2 612 12\npetr 1 12\nkatya 1 612",
"output": "3\nkatya 1 612 \npetr 1 12 \nkarl 1 612 "
},
{
"input": "4\nivan 3 123 123 456\nivan 2 456 456\nivan 8 789 3 23 6 56 9 89 2\ndash... | 1,653,669,616 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 31 | 0 | d = {}
for s in [*open(0)][1:]:
s = s.split()
d.setdefault(s[0],[])
for i in s[2:]:d[s[0]].append(i)
for i in d:
x = d[i]
if len(x)>1:
for j in range (len(x)):
for k in range (len(x)):
if x[j] == x[k]:continue
a,b = x[j],x[k]
a,b = str(a),str(b)
if len(a)<len(b):
if b[-len(a):] == a and len(a)!=1:x[j] = -1
elif len(b) < len(a):
if a[-len(b):] == b and len(b)!=1:x[k] = -1
x = set(x)
x.discard(-1)
d[i] = x
print(len(d))
for i in d:print(f'{i} {len(d[i])} {" ".join(d[i])}') | Title: Phone Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers.
Vasya decided to organize information about the phone numbers of friends. You will be given *n* strings — all entries from Vasya's phone books. Each entry starts with a friend's name. Then follows the number of phone numbers in the current entry, and then the phone numbers themselves. It is possible that several identical phones are recorded in the same record.
Vasya also believes that if the phone number *a* is a suffix of the phone number *b* (that is, the number *b* ends up with *a*), and both numbers are written by Vasya as the phone numbers of the same person, then *a* is recorded without the city code and it should not be taken into account.
The task is to print organized information about the phone numbers of Vasya's friends. It is possible that two different people have the same number. If one person has two numbers *x* and *y*, and *x* is a suffix of *y* (that is, *y* ends in *x*), then you shouldn't print number *x*. If the number of a friend in the Vasya's phone books is recorded several times in the same format, it is necessary to take it into account exactly once.
Read the examples to understand statement and format of the output better.
Input Specification:
First line contains the integer *n* (1<=≤<=*n*<=≤<=20) — number of entries in Vasya's phone books.
The following *n* lines are followed by descriptions of the records in the format described in statement. Names of Vasya's friends are non-empty strings whose length does not exceed 10. They consists only of lowercase English letters. Number of phone numbers in one entry is not less than 1 is not more than 10. The telephone numbers consist of digits only. If you represent a phone number as a string, then its length will be in range from 1 to 10. Phone numbers can contain leading zeros.
Output Specification:
Print out the ordered information about the phone numbers of Vasya's friends. First output *m* — number of friends that are found in Vasya's phone books.
The following *m* lines must contain entries in the following format "name number_of_phone_numbers phone_numbers". Phone numbers should be separated by a space. Each record must contain all the phone numbers of current friend.
Entries can be displayed in arbitrary order, phone numbers for one record can also be printed in arbitrary order.
Demo Input:
['2\nivan 1 00123\nmasha 1 00123\n', '3\nkarl 2 612 12\npetr 1 12\nkatya 1 612\n', '4\nivan 3 123 123 456\nivan 2 456 456\nivan 8 789 3 23 6 56 9 89 2\ndasha 2 23 789\n']
Demo Output:
['2\nmasha 1 00123 \nivan 1 00123 \n', '3\nkatya 1 612 \npetr 1 12 \nkarl 1 612 \n', '2\ndasha 2 23 789 \nivan 4 789 123 2 456 \n']
Note:
none | ```python
d = {}
for s in [*open(0)][1:]:
s = s.split()
d.setdefault(s[0],[])
for i in s[2:]:d[s[0]].append(i)
for i in d:
x = d[i]
if len(x)>1:
for j in range (len(x)):
for k in range (len(x)):
if x[j] == x[k]:continue
a,b = x[j],x[k]
a,b = str(a),str(b)
if len(a)<len(b):
if b[-len(a):] == a and len(a)!=1:x[j] = -1
elif len(b) < len(a):
if a[-len(b):] == b and len(b)!=1:x[k] = -1
x = set(x)
x.discard(-1)
d[i] = x
print(len(d))
for i in d:print(f'{i} {len(d[i])} {" ".join(d[i])}')
``` | 0 | |
986 | D | Perfect Encoding | PROGRAMMING | 3,100 | [
"fft",
"math"
] | null | null | You are working as an analyst in a company working on a new system for big data storage. This system will store $n$ different objects. Each object should have a unique ID.
To create the system, you choose the parameters of the system — integers $m \ge 1$ and $b_{1}, b_{2}, \ldots, b_{m}$. With these parameters an ID of some object in the system is an array of integers $[a_{1}, a_{2}, \ldots, a_{m}]$ where $1 \le a_{i} \le b_{i}$ holds for every $1 \le i \le m$.
Developers say that production costs are proportional to $\sum_{i=1}^{m} b_{i}$. You are asked to choose parameters $m$ and $b_{i}$ so that the system will be able to assign unique IDs to $n$ different objects and production costs are minimized. Note that you don't have to use all available IDs. | In the only line of input there is one positive integer $n$. The length of the decimal representation of $n$ is no greater than $1.5 \cdot 10^{6}$. The integer does not contain leading zeros. | Print one number — minimal value of $\sum_{i=1}^{m} b_{i}$. | [
"36\n",
"37\n",
"12345678901234567890123456789\n"
] | [
"10\n",
"11\n",
"177\n"
] | none | 2,500 | [
{
"input": "36",
"output": "10"
},
{
"input": "37",
"output": "11"
},
{
"input": "12345678901234567890123456789",
"output": "177"
},
{
"input": "1",
"output": "1"
},
{
"input": "2",
"output": "2"
},
{
"input": "3",
"output": "3"
},
{
"input... | 1,540,342,386 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | #include<bits/stdc++.h>
typedef long long ll;
const int MAX = 20;
const int moder = 998244353;
const int root = 3;
const int invroot = (moder + 1) / root;
int w[2][1 << MAX];
int powermod(int a, int exp){
int ret = 1;
for ( ; exp > 0; exp >>= 1){
if (exp & 1){
ret = 1ll * a * ret % moder;
}
a = 1ll * a * a % moder;
}
return ret;
}
void init(){
w[0][0] = w[1][0] = 1;
w[0][1] = powermod(root, (moder - 1) >> MAX);
for (int i = 2; i < (1 << MAX); ++i){
w[0][i] = 1ll * w[0][i - 1] * w[0][1] % moder;
}
for (int i = 1; i < (1 << MAX); ++i){
w[1][(1 << MAX) - i] = w[0][i];
}
}
void NTT(std::vector <int> &a, int len, int type){
for(int i = 1, j = 0; i < len - 1; ++i){
for(int s = len; j ^= (s >>= 1), ~j & s; )
;
if(i < j){
std::swap(a[i], a[j]);
}
}
for (int i = 2, d = 1; i <= len; i <<= 1, ++d){
for (int j = 0; j < len; j += i){
auto u = a.begin() + j;
for (int k = 0; k < i / 2; ++k){
int t = 1ll * w[type][k << (MAX - d)] * u[k + i / 2] % moder;
u[k + i / 2] = u[k] - t + (u[k] - t < 0 ? moder : 0);
u[k] += t; u[k] -= u[k] >= moder ? moder : 0;
}
}
}
if (type == 0) return;
int inv = powermod(len, moder - 2);
for (int i = 0; i < len; ++i){
a[i] = 1ll * a[i] * inv % moder;
}
}
struct Big{
static const int base = 10;
std::vector <int> a;
int len, sig;
Big():len(0), sig(0){}
Big(int len, int sig):len(len), sig(sig){a.resize(len);}
explicit Big(ll p):len(0), sig((p > 0) - (p < 0)){
for (ll x = std::abs(p); x; x /= base){
a.push_back(x % base);
++ len;
}
}
Big(const Big &b, const int &len):len(len), sig(b.sig){
a.resize(len);
for (int i = 0; i < len; ++ i){
a[i] = i < b.len ? b.a[i] : 0;
}
}
int operator [](int n)const{return n >= len || n < -len ? 0 : a[n + (n < 0 ? len : 0)];}
void normal(){
for ( ; len && !a[len - 1]; -- len)
;
if (!len) sig = 0;
}
void read(){
a.clear();
len = 0;
char ch;
while (!isdigit(ch = getchar()) && ch != '-')
;
if (ch == '-'){
sig = -1;
}
else{
sig = 1;
a.push_back(ch - '0');
}
while (isdigit(ch = getchar())){
a.push_back(ch - '0');
}
len = a.size();
std::reverse(a.begin(), a.end());
normal();
if (!len) sig = 0;
}
bool absge(const Big &q)const{
if (len != q.len) return len > q.len;
for (int i = len - 1; ~i; -- i){
if (a[i] != q.a[i]) return a[i] > q.a[i];
}
return true;
}
static int divide(Big &p, const int &q){
assert(q);
if (!p.sig) return 0;
ll remain = 0, x = std::abs(q);
for (int i = p.len - 1; ~i; -- i){
remain = remain * p.base + p.a[i];
p.a[i] = remain / x;
remain %= x;
}
remain *= p.sig;
p.normal();
p.sig *= q < 0 ? -1 : 1;
return remain;
}
bool operator < (const Big &p)const{
if (sig != p.sig) return sig < p.sig;
if (len != p.len) return (len < p.len) ^ (sig == -1);
for (int i = len - 1; i >= 0; -- i){
if (a[i] != p.a[i]) return (a[i] < p.a[i]) ^ (sig == -1);
}
return false;
}
Big operator + (const Big &p)const{
if (!p.sig) return *this;
if (!sig) return p;
bool type = true;
const Big *aux = this, *aux1 = &p;
if (sig != p.sig){
type = false;
if (!absge(p)){
std::swap(aux, aux1);
}
}
Big ret(*aux, std::max(len, p.len) + 1);
for (int i = 0; i < ret.len - 1; ++ i){
if (type){
ret.a[i] += (*aux1)[i];
if (ret.a[i] >= base) ret.a[i] -= base, ++ ret.a[i + 1];
}
else{
ret.a[i] -= (*aux1)[i];
if (ret.a[i] < 0) ret.a[i] += base, -- ret.a[i + 1];
}
}
ret.normal();
return ret;
}
Big operator * (const Big &p)const{
if (!sig || !p.sig) return Big();
int n = len + p.len;
int lenret = 1;
for ( ; lenret < n; lenret <<= 1)
;
Big ret(*this, lenret);
std::vector <int> aux(lenret);
std::copy(p.a.begin(), p.a.begin() + p.len, aux.begin());
NTT(ret.a, lenret, 0);
NTT(aux, lenret, 0);
for (int i = 0; i < lenret; ++ i){
ret.a[i] = 1ll * ret.a[i] * aux[i] % moder;
}
NTT(ret.a, lenret, 1);
for (int i = 0; i < n - 1; ++ i){
ret.a[i + 1] += ret.a[i] / base;
ret.a[i] %= base;
}
ret.len = n;
ret.normal();
ret.sig = sig * p.sig;
return ret;
}
Big operator / (const int &p)const{
Big ret(*this);
divide(ret, p);
return ret;
}
};
Big power(Big a, int exp){
Big ret(1);
for ( ; exp > 0; exp >>= 1){
if (exp & 1){
ret = ret * a;
}
a = a * a;
}
return ret;
}
int log3(Big b){
if (b.len < 15){
ll x = 0;
for (int i = b.len - 1; i >= 0; -- i){
x = x * 10 + b[i];
}
int ret = 0;
while (x > 1){
++ ret;
x = (x + 2) / 3;
}
return ret;
}
double tmp = 0, scale = 1;
for (int i = b.len - 1; i >= b.len - 15; -- i){
tmp += scale * b[i];
scale *= 0.1;
}
int exp = (std::log10(tmp) + b.len - 1) / std::log10(3);
if (power(Big (3), exp) < b){
++ exp;
}
return exp;
}
int main(){
init();
Big b;
b.read();
if (b.len == 1 && b[0] <= 4){
printf("%d\n", b[0]);
return 0;
}
int min = 3 * log3(b);
min = std::min(min, 2 + 3 * log3((b + Big(1)) / 2));
min = std::min(min, 4 + 3 * log3((b + Big(3)) / 4));
printf("%d\n", min);
return 0;
} | Title: Perfect Encoding
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are working as an analyst in a company working on a new system for big data storage. This system will store $n$ different objects. Each object should have a unique ID.
To create the system, you choose the parameters of the system — integers $m \ge 1$ and $b_{1}, b_{2}, \ldots, b_{m}$. With these parameters an ID of some object in the system is an array of integers $[a_{1}, a_{2}, \ldots, a_{m}]$ where $1 \le a_{i} \le b_{i}$ holds for every $1 \le i \le m$.
Developers say that production costs are proportional to $\sum_{i=1}^{m} b_{i}$. You are asked to choose parameters $m$ and $b_{i}$ so that the system will be able to assign unique IDs to $n$ different objects and production costs are minimized. Note that you don't have to use all available IDs.
Input Specification:
In the only line of input there is one positive integer $n$. The length of the decimal representation of $n$ is no greater than $1.5 \cdot 10^{6}$. The integer does not contain leading zeros.
Output Specification:
Print one number — minimal value of $\sum_{i=1}^{m} b_{i}$.
Demo Input:
['36\n', '37\n', '12345678901234567890123456789\n']
Demo Output:
['10\n', '11\n', '177\n']
Note:
none | ```python
#include<bits/stdc++.h>
typedef long long ll;
const int MAX = 20;
const int moder = 998244353;
const int root = 3;
const int invroot = (moder + 1) / root;
int w[2][1 << MAX];
int powermod(int a, int exp){
int ret = 1;
for ( ; exp > 0; exp >>= 1){
if (exp & 1){
ret = 1ll * a * ret % moder;
}
a = 1ll * a * a % moder;
}
return ret;
}
void init(){
w[0][0] = w[1][0] = 1;
w[0][1] = powermod(root, (moder - 1) >> MAX);
for (int i = 2; i < (1 << MAX); ++i){
w[0][i] = 1ll * w[0][i - 1] * w[0][1] % moder;
}
for (int i = 1; i < (1 << MAX); ++i){
w[1][(1 << MAX) - i] = w[0][i];
}
}
void NTT(std::vector <int> &a, int len, int type){
for(int i = 1, j = 0; i < len - 1; ++i){
for(int s = len; j ^= (s >>= 1), ~j & s; )
;
if(i < j){
std::swap(a[i], a[j]);
}
}
for (int i = 2, d = 1; i <= len; i <<= 1, ++d){
for (int j = 0; j < len; j += i){
auto u = a.begin() + j;
for (int k = 0; k < i / 2; ++k){
int t = 1ll * w[type][k << (MAX - d)] * u[k + i / 2] % moder;
u[k + i / 2] = u[k] - t + (u[k] - t < 0 ? moder : 0);
u[k] += t; u[k] -= u[k] >= moder ? moder : 0;
}
}
}
if (type == 0) return;
int inv = powermod(len, moder - 2);
for (int i = 0; i < len; ++i){
a[i] = 1ll * a[i] * inv % moder;
}
}
struct Big{
static const int base = 10;
std::vector <int> a;
int len, sig;
Big():len(0), sig(0){}
Big(int len, int sig):len(len), sig(sig){a.resize(len);}
explicit Big(ll p):len(0), sig((p > 0) - (p < 0)){
for (ll x = std::abs(p); x; x /= base){
a.push_back(x % base);
++ len;
}
}
Big(const Big &b, const int &len):len(len), sig(b.sig){
a.resize(len);
for (int i = 0; i < len; ++ i){
a[i] = i < b.len ? b.a[i] : 0;
}
}
int operator [](int n)const{return n >= len || n < -len ? 0 : a[n + (n < 0 ? len : 0)];}
void normal(){
for ( ; len && !a[len - 1]; -- len)
;
if (!len) sig = 0;
}
void read(){
a.clear();
len = 0;
char ch;
while (!isdigit(ch = getchar()) && ch != '-')
;
if (ch == '-'){
sig = -1;
}
else{
sig = 1;
a.push_back(ch - '0');
}
while (isdigit(ch = getchar())){
a.push_back(ch - '0');
}
len = a.size();
std::reverse(a.begin(), a.end());
normal();
if (!len) sig = 0;
}
bool absge(const Big &q)const{
if (len != q.len) return len > q.len;
for (int i = len - 1; ~i; -- i){
if (a[i] != q.a[i]) return a[i] > q.a[i];
}
return true;
}
static int divide(Big &p, const int &q){
assert(q);
if (!p.sig) return 0;
ll remain = 0, x = std::abs(q);
for (int i = p.len - 1; ~i; -- i){
remain = remain * p.base + p.a[i];
p.a[i] = remain / x;
remain %= x;
}
remain *= p.sig;
p.normal();
p.sig *= q < 0 ? -1 : 1;
return remain;
}
bool operator < (const Big &p)const{
if (sig != p.sig) return sig < p.sig;
if (len != p.len) return (len < p.len) ^ (sig == -1);
for (int i = len - 1; i >= 0; -- i){
if (a[i] != p.a[i]) return (a[i] < p.a[i]) ^ (sig == -1);
}
return false;
}
Big operator + (const Big &p)const{
if (!p.sig) return *this;
if (!sig) return p;
bool type = true;
const Big *aux = this, *aux1 = &p;
if (sig != p.sig){
type = false;
if (!absge(p)){
std::swap(aux, aux1);
}
}
Big ret(*aux, std::max(len, p.len) + 1);
for (int i = 0; i < ret.len - 1; ++ i){
if (type){
ret.a[i] += (*aux1)[i];
if (ret.a[i] >= base) ret.a[i] -= base, ++ ret.a[i + 1];
}
else{
ret.a[i] -= (*aux1)[i];
if (ret.a[i] < 0) ret.a[i] += base, -- ret.a[i + 1];
}
}
ret.normal();
return ret;
}
Big operator * (const Big &p)const{
if (!sig || !p.sig) return Big();
int n = len + p.len;
int lenret = 1;
for ( ; lenret < n; lenret <<= 1)
;
Big ret(*this, lenret);
std::vector <int> aux(lenret);
std::copy(p.a.begin(), p.a.begin() + p.len, aux.begin());
NTT(ret.a, lenret, 0);
NTT(aux, lenret, 0);
for (int i = 0; i < lenret; ++ i){
ret.a[i] = 1ll * ret.a[i] * aux[i] % moder;
}
NTT(ret.a, lenret, 1);
for (int i = 0; i < n - 1; ++ i){
ret.a[i + 1] += ret.a[i] / base;
ret.a[i] %= base;
}
ret.len = n;
ret.normal();
ret.sig = sig * p.sig;
return ret;
}
Big operator / (const int &p)const{
Big ret(*this);
divide(ret, p);
return ret;
}
};
Big power(Big a, int exp){
Big ret(1);
for ( ; exp > 0; exp >>= 1){
if (exp & 1){
ret = ret * a;
}
a = a * a;
}
return ret;
}
int log3(Big b){
if (b.len < 15){
ll x = 0;
for (int i = b.len - 1; i >= 0; -- i){
x = x * 10 + b[i];
}
int ret = 0;
while (x > 1){
++ ret;
x = (x + 2) / 3;
}
return ret;
}
double tmp = 0, scale = 1;
for (int i = b.len - 1; i >= b.len - 15; -- i){
tmp += scale * b[i];
scale *= 0.1;
}
int exp = (std::log10(tmp) + b.len - 1) / std::log10(3);
if (power(Big (3), exp) < b){
++ exp;
}
return exp;
}
int main(){
init();
Big b;
b.read();
if (b.len == 1 && b[0] <= 4){
printf("%d\n", b[0]);
return 0;
}
int min = 3 * log3(b);
min = std::min(min, 2 + 3 * log3((b + Big(1)) / 2));
min = std::min(min, 4 + 3 * log3((b + Big(3)) / 4));
printf("%d\n", min);
return 0;
}
``` | -1 | |
353 | C | Find Maximum | PROGRAMMING | 1,600 | [
"implementation",
"math",
"number theory"
] | null | null | Valera has array *a*, consisting of *n* integers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1, and function *f*(*x*), taking an integer from 0 to 2*n*<=-<=1 as its single argument. Value *f*(*x*) is calculated by formula , where value *bit*(*i*) equals one if the binary representation of number *x* contains a 1 on the *i*-th position, and zero otherwise.
For example, if *n*<==<=4 and *x*<==<=11 (11<==<=20<=+<=21<=+<=23), then *f*(*x*)<==<=*a*0<=+<=*a*1<=+<=*a*3.
Help Valera find the maximum of function *f*(*x*) among all *x*, for which an inequality holds: 0<=≤<=*x*<=≤<=*m*. | The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of array elements. The next line contains *n* space-separated integers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1 (0<=≤<=*a**i*<=≤<=104) — elements of array *a*.
The third line contains a sequence of digits zero and one without spaces *s*0*s*1... *s**n*<=-<=1 — the binary representation of number *m*. Number *m* equals . | Print a single integer — the maximum value of function *f*(*x*) for all . | [
"2\n3 8\n10\n",
"5\n17 0 10 2 1\n11010\n"
] | [
"3\n",
"27\n"
] | In the first test case *m* = 2<sup class="upper-index">0</sup> = 1, *f*(0) = 0, *f*(1) = *a*<sub class="lower-index">0</sub> = 3.
In the second sample *m* = 2<sup class="upper-index">0</sup> + 2<sup class="upper-index">1</sup> + 2<sup class="upper-index">3</sup> = 11, the maximum value of function equals *f*(5) = *a*<sub class="lower-index">0</sub> + *a*<sub class="lower-index">2</sub> = 17 + 10 = 27. | 1,000 | [
{
"input": "2\n3 8\n10",
"output": "3"
},
{
"input": "5\n17 0 10 2 1\n11010",
"output": "27"
},
{
"input": "18\n4382 3975 9055 7554 8395 204 5313 5739 1555 2306 5423 828 8108 9736 2683 7940 1249 5495\n110001100101110111",
"output": "88691"
},
{
"input": "43\n475 2165 8771 714... | 1,569,409,171 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 5 | 434 | 32,768,000 | def solve(seq, s):
while s and s[-1] == '0':
seq.pop()
s.pop()
if len(s) == 0:
return 0
c1 = sum(seq[:-1])
c2 = seq[-1] + solve(seq[:-1], s[:-1])
return max(c1, c2)
def main():
input()
a = [int(c) for c in input().split()]
s = list(input())
ans = solve(a, s)
print(ans)
if __name__ == "__main__":
main() | Title: Find Maximum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Valera has array *a*, consisting of *n* integers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1, and function *f*(*x*), taking an integer from 0 to 2*n*<=-<=1 as its single argument. Value *f*(*x*) is calculated by formula , where value *bit*(*i*) equals one if the binary representation of number *x* contains a 1 on the *i*-th position, and zero otherwise.
For example, if *n*<==<=4 and *x*<==<=11 (11<==<=20<=+<=21<=+<=23), then *f*(*x*)<==<=*a*0<=+<=*a*1<=+<=*a*3.
Help Valera find the maximum of function *f*(*x*) among all *x*, for which an inequality holds: 0<=≤<=*x*<=≤<=*m*.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of array elements. The next line contains *n* space-separated integers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1 (0<=≤<=*a**i*<=≤<=104) — elements of array *a*.
The third line contains a sequence of digits zero and one without spaces *s*0*s*1... *s**n*<=-<=1 — the binary representation of number *m*. Number *m* equals .
Output Specification:
Print a single integer — the maximum value of function *f*(*x*) for all .
Demo Input:
['2\n3 8\n10\n', '5\n17 0 10 2 1\n11010\n']
Demo Output:
['3\n', '27\n']
Note:
In the first test case *m* = 2<sup class="upper-index">0</sup> = 1, *f*(0) = 0, *f*(1) = *a*<sub class="lower-index">0</sub> = 3.
In the second sample *m* = 2<sup class="upper-index">0</sup> + 2<sup class="upper-index">1</sup> + 2<sup class="upper-index">3</sup> = 11, the maximum value of function equals *f*(5) = *a*<sub class="lower-index">0</sub> + *a*<sub class="lower-index">2</sub> = 17 + 10 = 27. | ```python
def solve(seq, s):
while s and s[-1] == '0':
seq.pop()
s.pop()
if len(s) == 0:
return 0
c1 = sum(seq[:-1])
c2 = seq[-1] + solve(seq[:-1], s[:-1])
return max(c1, c2)
def main():
input()
a = [int(c) for c in input().split()]
s = list(input())
ans = solve(a, s)
print(ans)
if __name__ == "__main__":
main()
``` | -1 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge [1;*m*] segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor decided to share it with Sasha.
Sasha knows that Teodor likes to show off so he never trusts him. Teodor wants to prove that he can be trusted sometimes, so he decided to convince Sasha that there is no such integer point in his picture, which belongs to each segment. However Teodor is lazy person and neither wills to tell Sasha all coordinates of segments' ends nor wills to tell him their amount, so he suggested Sasha to ask him series of questions 'Given the integer point *x**i*, how many segments in Fedya's picture contain that point?', promising to tell correct answers for this questions.
Both boys are very busy studying and don't have much time, so they ask you to find out how many questions can Sasha ask Teodor, that having only answers on his questions, Sasha can't be sure that Teodor isn't lying to him. Note that Sasha doesn't know amount of segments in Teodor's picture. Sure, Sasha is smart person and never asks about same point twice. | First line of input contains two integer numbers: *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100<=000) — amount of segments of Teodor's picture and maximal coordinate of point that Sasha can ask about.
*i*th of next *n* lines contains two integer numbers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*m*) — left and right ends of *i*th segment in the picture. Note that that left and right ends of segment can be the same point.
It is guaranteed that there is no integer point, that belongs to all segments. | Single line of output should contain one integer number *k* – size of largest set (*x**i*,<=*cnt*(*x**i*)) where all *x**i* are different, 1<=≤<=*x**i*<=≤<=*m*, and *cnt*(*x**i*) is amount of segments, containing point with coordinate *x**i*, such that one can't be sure that there doesn't exist point, belonging to all of segments in initial picture, if he knows only this set(and doesn't know *n*). | [
"2 4\n1 2\n3 4\n",
"4 6\n1 3\n2 3\n4 6\n5 6\n"
] | [
"4\n",
"5\n"
] | First example shows situation where Sasha can never be sure that Teodor isn't lying to him, because even if one knows *cnt*(*x*<sub class="lower-index">*i*</sub>) for each point in segment [1;4], he can't distinguish this case from situation Teodor has drawn whole [1;4] segment.
In second example Sasha can ask about 5 points e.g. 1, 2, 3, 5, 6, still not being sure if Teodor haven't lied to him. But once he knows information about all points in [1;6] segment, Sasha can be sure that Teodor haven't lied to him. | 0 | [
{
"input": "2 4\n1 2\n3 4",
"output": "4"
},
{
"input": "4 6\n1 3\n2 3\n4 6\n5 6",
"output": "5"
},
{
"input": "43 1319\n750 1030\n857 946\n941 1203\n407 1034\n947 1290\n546 585\n630 1201\n72 342\n693 1315\n34 719\n176 1097\n36 931\n198 973\n5 1025\n892 1054\n461 1287\n195 1273\n832 1039... | 1,689,434,463 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 46 | 0 | print("_RANDOM_GUESS_1689434463.0902998")# 1689434463.0903196 | Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge [1;*m*] segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor decided to share it with Sasha.
Sasha knows that Teodor likes to show off so he never trusts him. Teodor wants to prove that he can be trusted sometimes, so he decided to convince Sasha that there is no such integer point in his picture, which belongs to each segment. However Teodor is lazy person and neither wills to tell Sasha all coordinates of segments' ends nor wills to tell him their amount, so he suggested Sasha to ask him series of questions 'Given the integer point *x**i*, how many segments in Fedya's picture contain that point?', promising to tell correct answers for this questions.
Both boys are very busy studying and don't have much time, so they ask you to find out how many questions can Sasha ask Teodor, that having only answers on his questions, Sasha can't be sure that Teodor isn't lying to him. Note that Sasha doesn't know amount of segments in Teodor's picture. Sure, Sasha is smart person and never asks about same point twice.
Input Specification:
First line of input contains two integer numbers: *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100<=000) — amount of segments of Teodor's picture and maximal coordinate of point that Sasha can ask about.
*i*th of next *n* lines contains two integer numbers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*m*) — left and right ends of *i*th segment in the picture. Note that that left and right ends of segment can be the same point.
It is guaranteed that there is no integer point, that belongs to all segments.
Output Specification:
Single line of output should contain one integer number *k* – size of largest set (*x**i*,<=*cnt*(*x**i*)) where all *x**i* are different, 1<=≤<=*x**i*<=≤<=*m*, and *cnt*(*x**i*) is amount of segments, containing point with coordinate *x**i*, such that one can't be sure that there doesn't exist point, belonging to all of segments in initial picture, if he knows only this set(and doesn't know *n*).
Demo Input:
['2 4\n1 2\n3 4\n', '4 6\n1 3\n2 3\n4 6\n5 6\n']
Demo Output:
['4\n', '5\n']
Note:
First example shows situation where Sasha can never be sure that Teodor isn't lying to him, because even if one knows *cnt*(*x*<sub class="lower-index">*i*</sub>) for each point in segment [1;4], he can't distinguish this case from situation Teodor has drawn whole [1;4] segment.
In second example Sasha can ask about 5 points e.g. 1, 2, 3, 5, 6, still not being sure if Teodor haven't lied to him. But once he knows information about all points in [1;6] segment, Sasha can be sure that Teodor haven't lied to him. | ```python
print("_RANDOM_GUESS_1689434463.0902998")# 1689434463.0903196
``` | 0 | |
644 | A | Parliament of Berland | PROGRAMMING | 1,000 | [
"*special",
"constructive algorithms"
] | null | null | There are *n* parliamentarians in Berland. They are numbered with integers from 1 to *n*. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of *a*<=×<=*b* chairs — *a* rows of *b* chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats. | The first line of the input contains three integers *n*, *a* and *b* (1<=≤<=*n*<=≤<=10<=000, 1<=≤<=*a*,<=*b*<=≤<=100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively. | If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in *a* lines, each containing *b* integers. The *j*-th integer of the *i*-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them. | [
"3 2 2\n",
"8 4 3\n",
"10 2 2\n"
] | [
"0 3\n1 2\n",
"7 8 3\n0 1 4\n6 0 5\n0 2 0\n",
"-1\n"
] | In the first sample there are many other possible solutions. For example,
and
The following assignment
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats. | 500 | [
{
"input": "3 2 2",
"output": "1 2 \n0 3 "
},
{
"input": "8 4 3",
"output": "1 2 3 \n4 5 6 \n7 8 0 \n0 0 0 "
},
{
"input": "10 2 2",
"output": "-1"
},
{
"input": "1 1 1",
"output": "1 "
},
{
"input": "8 3 3",
"output": "1 2 3 \n4 5 6 \n7 8 0 "
},
{
"in... | 1,458,214,810 | 96,010 | Python 3 | OK | TESTS | 85 | 77 | 614,400 | def main():
n, a, b = (int(i) for i in input().split())
if a * b < n:
print("-1")
return
res = list(range(1, n + 1)) + [0] * (a*b - n)
res = [res[i*b:b*(i + 1)] for i in range(0, (a*b + b - 1) // b)]
if b % 2 == 0:
res = [list(reversed(l)) if i % 2 == 1 else l for i, l in enumerate(res)]
print('\n'.join(' '.join(map(str, l)) for l in res))
if __name__ == '__main__':
main()
| Title: Parliament of Berland
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* parliamentarians in Berland. They are numbered with integers from 1 to *n*. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of *a*<=×<=*b* chairs — *a* rows of *b* chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
Input Specification:
The first line of the input contains three integers *n*, *a* and *b* (1<=≤<=*n*<=≤<=10<=000, 1<=≤<=*a*,<=*b*<=≤<=100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
Output Specification:
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in *a* lines, each containing *b* integers. The *j*-th integer of the *i*-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
Demo Input:
['3 2 2\n', '8 4 3\n', '10 2 2\n']
Demo Output:
['0 3\n1 2\n', '7 8 3\n0 1 4\n6 0 5\n0 2 0\n', '-1\n']
Note:
In the first sample there are many other possible solutions. For example,
and
The following assignment
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats. | ```python
def main():
n, a, b = (int(i) for i in input().split())
if a * b < n:
print("-1")
return
res = list(range(1, n + 1)) + [0] * (a*b - n)
res = [res[i*b:b*(i + 1)] for i in range(0, (a*b + b - 1) // b)]
if b % 2 == 0:
res = [list(reversed(l)) if i % 2 == 1 else l for i, l in enumerate(res)]
print('\n'.join(' '.join(map(str, l)) for l in res))
if __name__ == '__main__':
main()
``` | 3 | |
251 | A | Points on Line | PROGRAMMING | 1,300 | [
"binary search",
"combinatorics",
"two pointers"
] | null | null | Little Petya likes points a lot. Recently his mom has presented him *n* points lying on the line *OX*. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed *d*.
Note that the order of the points inside the group of three chosen points doesn't matter. | The first line contains two integers: *n* and *d* (1<=≤<=*n*<=≤<=105; 1<=≤<=*d*<=≤<=109). The next line contains *n* integers *x*1,<=*x*2,<=...,<=*x**n*, their absolute value doesn't exceed 109 — the *x*-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase. | Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed *d*.
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. | [
"4 3\n1 2 3 4\n",
"4 2\n-3 -2 -1 0\n",
"5 19\n1 10 20 30 50\n"
] | [
"4\n",
"2\n",
"1\n"
] | In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}. | 500 | [
{
"input": "4 3\n1 2 3 4",
"output": "4"
},
{
"input": "4 2\n-3 -2 -1 0",
"output": "2"
},
{
"input": "5 19\n1 10 20 30 50",
"output": "1"
},
{
"input": "10 5\n31 36 43 47 48 50 56 69 71 86",
"output": "2"
},
{
"input": "10 50\n1 4 20 27 65 79 82 83 99 100",
"... | 1,683,506,418 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 4 | 92 | 0 | from sys import setrecursionlimit
setrecursionlimit(1000000)
n, d = map(int, input().split())
nums = list(map(int, input().split()))
visited = set()
def solve(left, right):
if (left, right) in visited or right - left + 1 < 3: return 0
visited.add((left, right))
if nums[right] - nums[left] > d:
return solve(left + 1, right) + solve(left, right - 1)
n = right - left + 1
ans = 1
for i in (1, 2, 3):
ans = ans * (n - 3 + i) // i
return ans
print(solve(0, n - 1))
| Title: Points on Line
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Petya likes points a lot. Recently his mom has presented him *n* points lying on the line *OX*. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed *d*.
Note that the order of the points inside the group of three chosen points doesn't matter.
Input Specification:
The first line contains two integers: *n* and *d* (1<=≤<=*n*<=≤<=105; 1<=≤<=*d*<=≤<=109). The next line contains *n* integers *x*1,<=*x*2,<=...,<=*x**n*, their absolute value doesn't exceed 109 — the *x*-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase.
Output Specification:
Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed *d*.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Demo Input:
['4 3\n1 2 3 4\n', '4 2\n-3 -2 -1 0\n', '5 19\n1 10 20 30 50\n']
Demo Output:
['4\n', '2\n', '1\n']
Note:
In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}. | ```python
from sys import setrecursionlimit
setrecursionlimit(1000000)
n, d = map(int, input().split())
nums = list(map(int, input().split()))
visited = set()
def solve(left, right):
if (left, right) in visited or right - left + 1 < 3: return 0
visited.add((left, right))
if nums[right] - nums[left] > d:
return solve(left + 1, right) + solve(left, right - 1)
n = right - left + 1
ans = 1
for i in (1, 2, 3):
ans = ans * (n - 3 + i) // i
return ans
print(solve(0, n - 1))
``` | 0 | |
374 | A | Inna and Pink Pony | PROGRAMMING | 2,000 | [
"greedy",
"implementation"
] | null | null | Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an *n*<=×<=*m* chessboard, a very tasty candy and two numbers *a* and *b*.
Dima put the chessboard in front of Inna and placed the candy in position (*i*,<=*j*) on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types:
- move the candy from position (*x*,<=*y*) on the board to position (*x*<=-<=*a*,<=*y*<=-<=*b*); - move the candy from position (*x*,<=*y*) on the board to position (*x*<=+<=*a*,<=*y*<=-<=*b*); - move the candy from position (*x*,<=*y*) on the board to position (*x*<=-<=*a*,<=*y*<=+<=*b*); - move the candy from position (*x*,<=*y*) on the board to position (*x*<=+<=*a*,<=*y*<=+<=*b*).
Naturally, Dima doesn't allow to move the candy beyond the chessboard borders.
Inna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position (*i*,<=*j*) to one of the chessboard corners. Help them cope with the task! | The first line of the input contains six integers *n*,<=*m*,<=*i*,<=*j*,<=*a*,<=*b* (1<=≤<=*n*,<=*m*<=≤<=106; 1<=≤<=*i*<=≤<=*n*; 1<=≤<=*j*<=≤<=*m*; 1<=≤<=*a*,<=*b*<=≤<=106).
You can assume that the chessboard rows are numbered from 1 to *n* from top to bottom and the columns are numbered from 1 to *m* from left to right. Position (*i*,<=*j*) in the statement is a chessboard cell on the intersection of the *i*-th row and the *j*-th column. You can consider that the corners are: (1,<=*m*), (*n*,<=1), (*n*,<=*m*), (1,<=1). | In a single line print a single integer — the minimum number of moves needed to get the candy.
If Inna and the pony cannot get the candy playing by Dima's rules, print on a single line "Poor Inna and pony!" without the quotes. | [
"5 7 1 3 2 2\n",
"5 5 2 3 1 1\n"
] | [
"2\n",
"Poor Inna and pony!\n"
] | Note to sample 1:
Inna and the pony can move the candy to position (1 + 2, 3 + 2) = (3, 5), from there they can move it to positions (3 - 2, 5 + 2) = (1, 7) and (3 + 2, 5 + 2) = (5, 7). These positions correspond to the corner squares of the chess board. Thus, the answer to the test sample equals two. | 500 | [
{
"input": "5 7 1 3 2 2",
"output": "2"
},
{
"input": "5 5 2 3 1 1",
"output": "Poor Inna and pony!"
},
{
"input": "1 1 1 1 1 1",
"output": "0"
},
{
"input": "23000 15500 100 333 9 1",
"output": "15167"
},
{
"input": "33999 99333 33000 99000 3 9",
"output": "3... | 1,568,358,863 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 1 | 124 | 0 | x,y,i,j,a,b = map(int,input().split())
p=q=1
mini = []
for _ in range(4):
r = abs(p-i)
s = abs(q-j)
t,e = r//a , s//b
if r%a==0 and s%b ==0:
if t==e:
mini.append(t)
if _ ==0:
p,q = 1,y
elif _ ==1:
p,q = x,1
elif _==2:
p,q = x,y
mini = -1 if mini==[] else min(mini)
if mini==-1:
print("Poor Inna and Pony")
else:
print(mini) | Title: Inna and Pink Pony
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an *n*<=×<=*m* chessboard, a very tasty candy and two numbers *a* and *b*.
Dima put the chessboard in front of Inna and placed the candy in position (*i*,<=*j*) on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types:
- move the candy from position (*x*,<=*y*) on the board to position (*x*<=-<=*a*,<=*y*<=-<=*b*); - move the candy from position (*x*,<=*y*) on the board to position (*x*<=+<=*a*,<=*y*<=-<=*b*); - move the candy from position (*x*,<=*y*) on the board to position (*x*<=-<=*a*,<=*y*<=+<=*b*); - move the candy from position (*x*,<=*y*) on the board to position (*x*<=+<=*a*,<=*y*<=+<=*b*).
Naturally, Dima doesn't allow to move the candy beyond the chessboard borders.
Inna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position (*i*,<=*j*) to one of the chessboard corners. Help them cope with the task!
Input Specification:
The first line of the input contains six integers *n*,<=*m*,<=*i*,<=*j*,<=*a*,<=*b* (1<=≤<=*n*,<=*m*<=≤<=106; 1<=≤<=*i*<=≤<=*n*; 1<=≤<=*j*<=≤<=*m*; 1<=≤<=*a*,<=*b*<=≤<=106).
You can assume that the chessboard rows are numbered from 1 to *n* from top to bottom and the columns are numbered from 1 to *m* from left to right. Position (*i*,<=*j*) in the statement is a chessboard cell on the intersection of the *i*-th row and the *j*-th column. You can consider that the corners are: (1,<=*m*), (*n*,<=1), (*n*,<=*m*), (1,<=1).
Output Specification:
In a single line print a single integer — the minimum number of moves needed to get the candy.
If Inna and the pony cannot get the candy playing by Dima's rules, print on a single line "Poor Inna and pony!" without the quotes.
Demo Input:
['5 7 1 3 2 2\n', '5 5 2 3 1 1\n']
Demo Output:
['2\n', 'Poor Inna and pony!\n']
Note:
Note to sample 1:
Inna and the pony can move the candy to position (1 + 2, 3 + 2) = (3, 5), from there they can move it to positions (3 - 2, 5 + 2) = (1, 7) and (3 + 2, 5 + 2) = (5, 7). These positions correspond to the corner squares of the chess board. Thus, the answer to the test sample equals two. | ```python
x,y,i,j,a,b = map(int,input().split())
p=q=1
mini = []
for _ in range(4):
r = abs(p-i)
s = abs(q-j)
t,e = r//a , s//b
if r%a==0 and s%b ==0:
if t==e:
mini.append(t)
if _ ==0:
p,q = 1,y
elif _ ==1:
p,q = x,1
elif _==2:
p,q = x,y
mini = -1 if mini==[] else min(mini)
if mini==-1:
print("Poor Inna and Pony")
else:
print(mini)
``` | 0 | |
6 | B | President's Office | PROGRAMMING | 1,100 | [
"implementation"
] | B. President's Office | 2 | 64 | President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with *n* rows and *m* columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell. | The first line contains two separated by a space integer numbers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the length and the width of the office-room, and *c* character — the President's desk colour. The following *n* lines contain *m* characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters. | Print the only number — the amount of President's deputies. | [
"3 4 R\nG.B.\n.RR.\nTTT.\n",
"3 3 Z\n...\n.H.\n..Z\n"
] | [
"2\n",
"0\n"
] | none | 0 | [
{
"input": "3 4 R\nG.B.\n.RR.\nTTT.",
"output": "2"
},
{
"input": "3 3 Z\n...\n.H.\n..Z",
"output": "0"
},
{
"input": "1 1 C\nC",
"output": "0"
},
{
"input": "2 2 W\nKW\nKW",
"output": "1"
},
{
"input": "1 10 H\n....DDHHHH",
"output": "1"
},
{
"input":... | 1,681,144,775 | 2,147,483,647 | Python 3 | OK | TESTS | 32 | 62 | 0 | n, m, c = map(str, input().split())
n = int(n)
m = int(m)
a = []
for i in range(n):
a.append(input())
ans = set()
for i in range(n):
for j in range(m):
if a[i][j] == c:
if i > 0 and a[i-1][j] != '.' and a[i-1][j] != c:
ans.add(a[i-1][j])
if j > 0 and a[i][j-1] != '.' and a[i][j-1] != c:
ans.add(a[i][j-1])
if i < n-1 and a[i+1][j] != '.' and a[i+1][j] != c:
ans.add(a[i+1][j])
if j < m-1 and a[i][j+1] != '.' and a[i][j+1] != c:
ans.add(a[i][j+1])
print(len(ans)) | Title: President's Office
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with *n* rows and *m* columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.
Input Specification:
The first line contains two separated by a space integer numbers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the length and the width of the office-room, and *c* character — the President's desk colour. The following *n* lines contain *m* characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output Specification:
Print the only number — the amount of President's deputies.
Demo Input:
['3 4 R\nG.B.\n.RR.\nTTT.\n', '3 3 Z\n...\n.H.\n..Z\n']
Demo Output:
['2\n', '0\n']
Note:
none | ```python
n, m, c = map(str, input().split())
n = int(n)
m = int(m)
a = []
for i in range(n):
a.append(input())
ans = set()
for i in range(n):
for j in range(m):
if a[i][j] == c:
if i > 0 and a[i-1][j] != '.' and a[i-1][j] != c:
ans.add(a[i-1][j])
if j > 0 and a[i][j-1] != '.' and a[i][j-1] != c:
ans.add(a[i][j-1])
if i < n-1 and a[i+1][j] != '.' and a[i+1][j] != c:
ans.add(a[i+1][j])
if j < m-1 and a[i][j+1] != '.' and a[i][j+1] != c:
ans.add(a[i][j+1])
print(len(ans))
``` | 3.9845 |
50 | A | Domino piling | PROGRAMMING | 800 | [
"greedy",
"math"
] | A. Domino piling | 2 | 256 | You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions. | In a single line you are given two integers *M* and *N* — board sizes in squares (1<=≤<=*M*<=≤<=*N*<=≤<=16). | Output one number — the maximal number of dominoes, which can be placed. | [
"2 4\n",
"3 3\n"
] | [
"4\n",
"4\n"
] | none | 500 | [
{
"input": "2 4",
"output": "4"
},
{
"input": "3 3",
"output": "4"
},
{
"input": "1 5",
"output": "2"
},
{
"input": "1 6",
"output": "3"
},
{
"input": "1 15",
"output": "7"
},
{
"input": "1 16",
"output": "8"
},
{
"input": "2 5",
"outpu... | 1,675,856,549 | 2,147,483,647 | Python 3 | OK | TESTS | 35 | 92 | 0 | x,y = map(int,input().split())
u = (x*y) // 2
print(u) | Title: Domino piling
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
Input Specification:
In a single line you are given two integers *M* and *N* — board sizes in squares (1<=≤<=*M*<=≤<=*N*<=≤<=16).
Output Specification:
Output one number — the maximal number of dominoes, which can be placed.
Demo Input:
['2 4\n', '3 3\n']
Demo Output:
['4\n', '4\n']
Note:
none | ```python
x,y = map(int,input().split())
u = (x*y) // 2
print(u)
``` | 3.977 |
469 | A | I Wanna Be the Guy | PROGRAMMING | 800 | [
"greedy",
"implementation"
] | null | null | There is a game called "I Wanna Be the Guy", consisting of *n* levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only *p* levels of the game. And Little Y can pass only *q* levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other? | The first line contains a single integer *n* (1<=≤<=<=*n*<=≤<=100).
The next line contains an integer *p* (0<=≤<=*p*<=≤<=*n*) at first, then follows *p* distinct integers *a*1,<=*a*2,<=...,<=*a**p* (1<=≤<=*a**i*<=≤<=*n*). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to *n*. | If they can pass all the levels, print "I become the guy.". If it's impossible, print "Oh, my keyboard!" (without the quotes). | [
"4\n3 1 2 3\n2 2 4\n",
"4\n3 1 2 3\n2 2 3\n"
] | [
"I become the guy.\n",
"Oh, my keyboard!\n"
] | In the first sample, Little X can pass levels [1 2 3], and Little Y can pass level [2 4], so they can pass all the levels both.
In the second sample, no one can pass level 4. | 500 | [
{
"input": "4\n3 1 2 3\n2 2 4",
"output": "I become the guy."
},
{
"input": "4\n3 1 2 3\n2 2 3",
"output": "Oh, my keyboard!"
},
{
"input": "10\n5 8 6 1 5 4\n6 1 3 2 9 4 6",
"output": "Oh, my keyboard!"
},
{
"input": "10\n8 8 10 7 3 1 4 2 6\n8 9 5 10 3 7 2 4 8",
"output":... | 1,692,245,938 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 31 | 0 | level_count = int(input())
first_firend = list(map(int, input().split()))
second_friend = list(map(int, input().split()))
first_firend.pop(0)
second_friend.pop(0)
current_level = 1
while True:
if current_level in first_firend or second_friend:
current_level += 1
if current_level > level_count:
print('I become the guy.')
break
else:
print('Oh, my keyboard!')
break | Title: I Wanna Be the Guy
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is a game called "I Wanna Be the Guy", consisting of *n* levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only *p* levels of the game. And Little Y can pass only *q* levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?
Input Specification:
The first line contains a single integer *n* (1<=≤<=<=*n*<=≤<=100).
The next line contains an integer *p* (0<=≤<=*p*<=≤<=*n*) at first, then follows *p* distinct integers *a*1,<=*a*2,<=...,<=*a**p* (1<=≤<=*a**i*<=≤<=*n*). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to *n*.
Output Specification:
If they can pass all the levels, print "I become the guy.". If it's impossible, print "Oh, my keyboard!" (without the quotes).
Demo Input:
['4\n3 1 2 3\n2 2 4\n', '4\n3 1 2 3\n2 2 3\n']
Demo Output:
['I become the guy.\n', 'Oh, my keyboard!\n']
Note:
In the first sample, Little X can pass levels [1 2 3], and Little Y can pass level [2 4], so they can pass all the levels both.
In the second sample, no one can pass level 4. | ```python
level_count = int(input())
first_firend = list(map(int, input().split()))
second_friend = list(map(int, input().split()))
first_firend.pop(0)
second_friend.pop(0)
current_level = 1
while True:
if current_level in first_firend or second_friend:
current_level += 1
if current_level > level_count:
print('I become the guy.')
break
else:
print('Oh, my keyboard!')
break
``` | 0 | |
39 | F | Pacifist frogs | PROGRAMMING | 1,300 | [
"implementation"
] | F. Pacifist frogs | 2 | 64 | Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much.
One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to *n* and the number of a hill is equal to the distance in meters between it and the island. The distance between the *n*-th hill and the shore is also 1 meter.
Thumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is *d*, the frog will jump from the island on the hill *d*, then — on the hill 2*d*, then 3*d* and so on until they get to the shore (i.e. find itself beyond the hill *n*).
However, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible. | The first line contains three integers *n*, *m* and *k* (1<=≤<=*n*<=≤<=109, 1<=≤<=*m*,<=*k*<=≤<=100) — the number of hills, frogs and mosquitoes respectively. The second line contains *m* integers *d**i* (1<=≤<=*d**i*<=≤<=109) — the lengths of the frogs’ jumps. The third line contains *k* integers — the numbers of the hills on which each mosquito is sleeping. No more than one mosquito can sleep on each hill. The numbers in the lines are separated by single spaces. | In the first line output the number of frogs that smash the minimal number of mosquitoes, in the second line — their numbers in increasing order separated by spaces. The frogs are numbered from 1 to *m* in the order of the jump length given in the input data. | [
"5 3 5\n2 3 4\n1 2 3 4 5\n",
"1000000000 2 3\n2 5\n999999995 999999998 999999996\n"
] | [
"2\n2 3\n",
"1\n2\n"
] | none | 0 | [
{
"input": "5 3 5\n2 3 4\n1 2 3 4 5",
"output": "2\n2 3"
},
{
"input": "1000000000 2 3\n2 5\n999999995 999999998 999999996",
"output": "1\n2"
},
{
"input": "1 1 1\n1\n1",
"output": "1\n1"
},
{
"input": "2 2 1\n2 1\n1",
"output": "1\n1"
},
{
"input": "3 2 2\n2 4\n3... | 1,658,380,643 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 35 | 124 | 1,536,000 | import sys
input = sys.stdin.readline
n, m, k = map(int, input().split())
w = list(map(int, input().split()))
s = list(map(int, input().split()))
d = []
for i in range(m):
c = 0
for j in s:
if j % w[i] == 0:
c += 1
d.append((c, i+1))
d.sort()
x = d[0][0]
ans = [d[0][1]]
for i in d[1:]:
if i[0] == x:
ans.append(i[1])
print(len(ans))
print(' '.join(map(str, ans))) | Title: Pacifist frogs
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much.
One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to *n* and the number of a hill is equal to the distance in meters between it and the island. The distance between the *n*-th hill and the shore is also 1 meter.
Thumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is *d*, the frog will jump from the island on the hill *d*, then — on the hill 2*d*, then 3*d* and so on until they get to the shore (i.e. find itself beyond the hill *n*).
However, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible.
Input Specification:
The first line contains three integers *n*, *m* and *k* (1<=≤<=*n*<=≤<=109, 1<=≤<=*m*,<=*k*<=≤<=100) — the number of hills, frogs and mosquitoes respectively. The second line contains *m* integers *d**i* (1<=≤<=*d**i*<=≤<=109) — the lengths of the frogs’ jumps. The third line contains *k* integers — the numbers of the hills on which each mosquito is sleeping. No more than one mosquito can sleep on each hill. The numbers in the lines are separated by single spaces.
Output Specification:
In the first line output the number of frogs that smash the minimal number of mosquitoes, in the second line — their numbers in increasing order separated by spaces. The frogs are numbered from 1 to *m* in the order of the jump length given in the input data.
Demo Input:
['5 3 5\n2 3 4\n1 2 3 4 5\n', '1000000000 2 3\n2 5\n999999995 999999998 999999996\n']
Demo Output:
['2\n2 3\n', '1\n2\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
n, m, k = map(int, input().split())
w = list(map(int, input().split()))
s = list(map(int, input().split()))
d = []
for i in range(m):
c = 0
for j in s:
if j % w[i] == 0:
c += 1
d.append((c, i+1))
d.sort()
x = d[0][0]
ans = [d[0][1]]
for i in d[1:]:
if i[0] == x:
ans.append(i[1])
print(len(ans))
print(' '.join(map(str, ans)))
``` | 3.957556 |
617 | A | Elephant | PROGRAMMING | 800 | [
"math"
] | null | null | An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=><=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house. | The first line of the input contains an integer *x* (1<=≤<=*x*<=≤<=1<=000<=000) — The coordinate of the friend's house. | Print the minimum number of steps that elephant needs to make to get from point 0 to point *x*. | [
"5\n",
"12\n"
] | [
"1\n",
"3\n"
] | In the first sample the elephant needs to make one step of length 5 to reach the point *x*.
In the second sample the elephant can get to point *x* if he moves by 3, 5 and 4. There are other ways to get the optimal answer but the elephant cannot reach *x* in less than three moves. | 500 | [
{
"input": "5",
"output": "1"
},
{
"input": "12",
"output": "3"
},
{
"input": "999999",
"output": "200000"
},
{
"input": "41",
"output": "9"
},
{
"input": "1000000",
"output": "200000"
},
{
"input": "1",
"output": "1"
},
{
"input": "2",
... | 1,694,643,868 | 2,147,483,647 | Python 3 | OK | TESTS | 34 | 62 | 0 | n = int(input())
x = 0
step = 0
while x!=n:
if n-x >= 5:
x+=5
elif n-x >= 4:
x+=4
elif n-x >= 3:
x+=3
elif n-x >= 2:
x+=2
elif n-x >= 1:
x+=1
step+=1
print(step) | Title: Elephant
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=><=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.
Input Specification:
The first line of the input contains an integer *x* (1<=≤<=*x*<=≤<=1<=000<=000) — The coordinate of the friend's house.
Output Specification:
Print the minimum number of steps that elephant needs to make to get from point 0 to point *x*.
Demo Input:
['5\n', '12\n']
Demo Output:
['1\n', '3\n']
Note:
In the first sample the elephant needs to make one step of length 5 to reach the point *x*.
In the second sample the elephant can get to point *x* if he moves by 3, 5 and 4. There are other ways to get the optimal answer but the elephant cannot reach *x* in less than three moves. | ```python
n = int(input())
x = 0
step = 0
while x!=n:
if n-x >= 5:
x+=5
elif n-x >= 4:
x+=4
elif n-x >= 3:
x+=3
elif n-x >= 2:
x+=2
elif n-x >= 1:
x+=1
step+=1
print(step)
``` | 3 | |
0 | none | none | none | 0 | [
"none"
] | null | null | You are given two lists of non-zero digits.
Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer? | The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=9) — the lengths of the first and the second lists, respectively.
The second line contains *n* distinct digits *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=9) — the elements of the first list.
The third line contains *m* distinct digits *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=9) — the elements of the second list. | Print the smallest pretty integer. | [
"2 3\n4 2\n5 7 6\n",
"8 8\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n"
] | [
"25\n",
"1\n"
] | In the first example 25, 46, 24567 are pretty, as well as many other integers. The smallest among them is 25. 42 and 24 are not pretty because they don't have digits from the second list.
In the second example all integers that have at least one digit different from 9 are pretty. It's obvious that the smallest among them is 1, because it's the smallest positive integer. | 0 | [
{
"input": "2 3\n4 2\n5 7 6",
"output": "25"
},
{
"input": "8 8\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1",
"output": "1"
},
{
"input": "1 1\n9\n1",
"output": "19"
},
{
"input": "9 1\n5 4 2 3 6 1 7 9 8\n9",
"output": "9"
},
{
"input": "5 3\n7 2 5 8 6\n3 1 9",
"output"... | 1,508,055,520 | 820 | Python 3 | WRONG_ANSWER | PRETESTS | 3 | 46 | 307,200 | n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
m1=max(a)
m2=max(b)
c=0
mi=float('inf')
if m1>m2:
arr=[0 for i in range(m1+1)]
for i in a:
arr[i]=1
for i in b:
if arr[i]==1 and arr[i]<mi:
mi=arr[i]
c=1
if c==0:
n1=min(a)
n2=min(b)
if n1<n2:
mi=n1*10+n2
else:
mi=n2*10+n1
else:
arr=[0 for i in range(m2+1)]
for i in b:
arr[i]=1
for i in a:
if arr[i]==1 and arr[i]<mi:
mi=arr[i]
c=1
if c==0:
n1=min(a)
n2=min(b)
if n1<n2:
mi=n1*10+n2
else:
mi=n2*10+n1
print(mi)
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two lists of non-zero digits.
Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=9) — the lengths of the first and the second lists, respectively.
The second line contains *n* distinct digits *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=9) — the elements of the first list.
The third line contains *m* distinct digits *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=9) — the elements of the second list.
Output Specification:
Print the smallest pretty integer.
Demo Input:
['2 3\n4 2\n5 7 6\n', '8 8\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n']
Demo Output:
['25\n', '1\n']
Note:
In the first example 25, 46, 24567 are pretty, as well as many other integers. The smallest among them is 25. 42 and 24 are not pretty because they don't have digits from the second list.
In the second example all integers that have at least one digit different from 9 are pretty. It's obvious that the smallest among them is 1, because it's the smallest positive integer. | ```python
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
m1=max(a)
m2=max(b)
c=0
mi=float('inf')
if m1>m2:
arr=[0 for i in range(m1+1)]
for i in a:
arr[i]=1
for i in b:
if arr[i]==1 and arr[i]<mi:
mi=arr[i]
c=1
if c==0:
n1=min(a)
n2=min(b)
if n1<n2:
mi=n1*10+n2
else:
mi=n2*10+n1
else:
arr=[0 for i in range(m2+1)]
for i in b:
arr[i]=1
for i in a:
if arr[i]==1 and arr[i]<mi:
mi=arr[i]
c=1
if c==0:
n1=min(a)
n2=min(b)
if n1<n2:
mi=n1*10+n2
else:
mi=n2*10+n1
print(mi)
``` | 0 | |
572 | A | Arrays | PROGRAMMING | 900 | [
"sortings"
] | null | null | You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array. | The first line contains two integers *n**A*,<=*n**B* (1<=≤<=*n**A*,<=*n**B*<=≤<=105), separated by a space — the sizes of arrays *A* and *B*, correspondingly.
The second line contains two integers *k* and *m* (1<=≤<=*k*<=≤<=*n**A*,<=1<=≤<=*m*<=≤<=*n**B*), separated by a space.
The third line contains *n**A* numbers *a*1,<=*a*2,<=... *a**n**A* (<=-<=109<=≤<=*a*1<=≤<=*a*2<=≤<=...<=≤<=*a**n**A*<=≤<=109), separated by spaces — elements of array *A*.
The fourth line contains *n**B* integers *b*1,<=*b*2,<=... *b**n**B* (<=-<=109<=≤<=*b*1<=≤<=*b*2<=≤<=...<=≤<=*b**n**B*<=≤<=109), separated by spaces — elements of array *B*. | Print "YES" (without the quotes), if you can choose *k* numbers in array *A* and *m* numbers in array *B* so that any number chosen in array *A* was strictly less than any number chosen in array *B*. Otherwise, print "NO" (without the quotes). | [
"3 3\n2 1\n1 2 3\n3 4 5\n",
"3 3\n3 3\n1 2 3\n3 4 5\n",
"5 2\n3 1\n1 1 1 1 1\n2 2\n"
] | [
"YES\n",
"NO\n",
"YES\n"
] | In the first sample test you can, for example, choose numbers 1 and 2 from array *A* and number 3 from array *B* (1 < 3 and 2 < 3).
In the second sample test the only way to choose *k* elements in the first array and *m* elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in *A* will be less than all the numbers chosen in *B*: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7280148ed5eab0a7d418d4f92b32061243a8ca58.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | 500 | [
{
"input": "3 3\n2 1\n1 2 3\n3 4 5",
"output": "YES"
},
{
"input": "3 3\n3 3\n1 2 3\n3 4 5",
"output": "NO"
},
{
"input": "5 2\n3 1\n1 1 1 1 1\n2 2",
"output": "YES"
},
{
"input": "3 5\n1 1\n5 5 5\n5 5 5 5 5",
"output": "NO"
},
{
"input": "1 1\n1 1\n1\n1",
"ou... | 1,680,358,705 | 2,147,483,647 | Python 3 | OK | TESTS | 52 | 109 | 10,035,200 | lenA , lenB = map(int,input().split())
k , m = map(int,input().split())
A = list(map(int,input().split())) #sorted
B = list(map(int,input().split())) # sorted
def arrays(k : int , m : int , A : list() , B : list()) ->str:
if A[k - 1] < B[lenB - m]:
print("yes")
else:
print("No")
arrays(k,m,A,B)
| Title: Arrays
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array.
Input Specification:
The first line contains two integers *n**A*,<=*n**B* (1<=≤<=*n**A*,<=*n**B*<=≤<=105), separated by a space — the sizes of arrays *A* and *B*, correspondingly.
The second line contains two integers *k* and *m* (1<=≤<=*k*<=≤<=*n**A*,<=1<=≤<=*m*<=≤<=*n**B*), separated by a space.
The third line contains *n**A* numbers *a*1,<=*a*2,<=... *a**n**A* (<=-<=109<=≤<=*a*1<=≤<=*a*2<=≤<=...<=≤<=*a**n**A*<=≤<=109), separated by spaces — elements of array *A*.
The fourth line contains *n**B* integers *b*1,<=*b*2,<=... *b**n**B* (<=-<=109<=≤<=*b*1<=≤<=*b*2<=≤<=...<=≤<=*b**n**B*<=≤<=109), separated by spaces — elements of array *B*.
Output Specification:
Print "YES" (without the quotes), if you can choose *k* numbers in array *A* and *m* numbers in array *B* so that any number chosen in array *A* was strictly less than any number chosen in array *B*. Otherwise, print "NO" (without the quotes).
Demo Input:
['3 3\n2 1\n1 2 3\n3 4 5\n', '3 3\n3 3\n1 2 3\n3 4 5\n', '5 2\n3 1\n1 1 1 1 1\n2 2\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
In the first sample test you can, for example, choose numbers 1 and 2 from array *A* and number 3 from array *B* (1 < 3 and 2 < 3).
In the second sample test the only way to choose *k* elements in the first array and *m* elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in *A* will be less than all the numbers chosen in *B*: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7280148ed5eab0a7d418d4f92b32061243a8ca58.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | ```python
lenA , lenB = map(int,input().split())
k , m = map(int,input().split())
A = list(map(int,input().split())) #sorted
B = list(map(int,input().split())) # sorted
def arrays(k : int , m : int , A : list() , B : list()) ->str:
if A[k - 1] < B[lenB - m]:
print("yes")
else:
print("No")
arrays(k,m,A,B)
``` | 3 | |
798 | A | Mike and palindrome | PROGRAMMING | 1,000 | [
"brute force",
"constructive algorithms",
"strings"
] | null | null | Mike has a string *s* consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.
A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not. | The first and single line contains string *s* (1<=≤<=|*s*|<=≤<=15). | Print "YES" (without quotes) if Mike can change exactly one character so that the resulting string is palindrome or "NO" (without quotes) otherwise. | [
"abccaa\n",
"abbcca\n",
"abcda\n"
] | [
"YES\n",
"NO\n",
"YES\n"
] | none | 500 | [
{
"input": "abccaa",
"output": "YES"
},
{
"input": "abbcca",
"output": "NO"
},
{
"input": "abcda",
"output": "YES"
},
{
"input": "kyw",
"output": "YES"
},
{
"input": "fccf",
"output": "NO"
},
{
"input": "mnlm",
"output": "YES"
},
{
"input":... | 1,658,951,172 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 4 | 77 | 0 | import sys
import math
s = input()
res = i = 0
while i<len(s)//2:
if s[i] != s[len(s)-i-1]: res+=1
if res == 2: print("NO"); sys.exit()
i+=1
print("YES")
| Title: Mike and palindrome
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mike has a string *s* consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.
A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.
Input Specification:
The first and single line contains string *s* (1<=≤<=|*s*|<=≤<=15).
Output Specification:
Print "YES" (without quotes) if Mike can change exactly one character so that the resulting string is palindrome or "NO" (without quotes) otherwise.
Demo Input:
['abccaa\n', 'abbcca\n', 'abcda\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
none | ```python
import sys
import math
s = input()
res = i = 0
while i<len(s)//2:
if s[i] != s[len(s)-i-1]: res+=1
if res == 2: print("NO"); sys.exit()
i+=1
print("YES")
``` | 0 | |
686 | A | Free Ice Cream | PROGRAMMING | 800 | [
"constructive algorithms",
"implementation"
] | null | null | After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).
If a carrier with *d* ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take *d* ice cream packs comes to the house, then Kay and Gerda will give him *d* packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.
Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids. | The first line contains two space-separated integers *n* and *x* (1<=≤<=*n*<=≤<=1000, 0<=≤<=*x*<=≤<=109).
Each of the next *n* lines contains a character '+' or '-', and an integer *d**i*, separated by a space (1<=≤<=*d**i*<=≤<=109). Record "+ *d**i*" in *i*-th line means that a carrier with *d**i* ice cream packs occupies *i*-th place from the start of the queue, and record "- *d**i*" means that a child who wants to take *d**i* packs stands in *i*-th place. | Print two space-separated integers — number of ice cream packs left after all operations, and number of kids that left the house in distress. | [
"5 7\n+ 5\n- 10\n- 20\n+ 40\n- 20\n",
"5 17\n- 16\n- 2\n- 98\n+ 100\n- 98\n"
] | [
"22 1\n",
"3 2\n"
] | Consider the first sample.
1. Initially Kay and Gerda have 7 packs of ice cream. 1. Carrier brings 5 more, so now they have 12 packs. 1. A kid asks for 10 packs and receives them. There are only 2 packs remaining. 1. Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed. 1. Carrier bring 40 packs, now Kay and Gerda have 42 packs. 1. Kid asks for 20 packs and receives them. There are 22 packs remaining. | 500 | [
{
"input": "5 7\n+ 5\n- 10\n- 20\n+ 40\n- 20",
"output": "22 1"
},
{
"input": "5 17\n- 16\n- 2\n- 98\n+ 100\n- 98",
"output": "3 2"
},
{
"input": "6 1000000000\n+ 1000000000\n+ 1000000000\n+ 1000000000\n+ 1000000000\n+ 1000000000\n+ 1000000000",
"output": "7000000000 0"
},
{
... | 1,642,445,789 | 2,147,483,647 | Python 3 | OK | TESTS | 34 | 46 | 0 | def main():
n, iceCreamSum = map(int, input().split())
kids = 0
for i in range(n):
signal, iceCream = map(str, input().split())
if signal == "+":
iceCreamSum += int(iceCream)
else:
if iceCreamSum < int(iceCream):
kids += 1
else:
iceCreamSum -= int(iceCream)
print(iceCreamSum, kids)
if __name__ == '__main__':
main() | Title: Free Ice Cream
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).
If a carrier with *d* ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take *d* ice cream packs comes to the house, then Kay and Gerda will give him *d* packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.
Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.
Input Specification:
The first line contains two space-separated integers *n* and *x* (1<=≤<=*n*<=≤<=1000, 0<=≤<=*x*<=≤<=109).
Each of the next *n* lines contains a character '+' or '-', and an integer *d**i*, separated by a space (1<=≤<=*d**i*<=≤<=109). Record "+ *d**i*" in *i*-th line means that a carrier with *d**i* ice cream packs occupies *i*-th place from the start of the queue, and record "- *d**i*" means that a child who wants to take *d**i* packs stands in *i*-th place.
Output Specification:
Print two space-separated integers — number of ice cream packs left after all operations, and number of kids that left the house in distress.
Demo Input:
['5 7\n+ 5\n- 10\n- 20\n+ 40\n- 20\n', '5 17\n- 16\n- 2\n- 98\n+ 100\n- 98\n']
Demo Output:
['22 1\n', '3 2\n']
Note:
Consider the first sample.
1. Initially Kay and Gerda have 7 packs of ice cream. 1. Carrier brings 5 more, so now they have 12 packs. 1. A kid asks for 10 packs and receives them. There are only 2 packs remaining. 1. Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed. 1. Carrier bring 40 packs, now Kay and Gerda have 42 packs. 1. Kid asks for 20 packs and receives them. There are 22 packs remaining. | ```python
def main():
n, iceCreamSum = map(int, input().split())
kids = 0
for i in range(n):
signal, iceCream = map(str, input().split())
if signal == "+":
iceCreamSum += int(iceCream)
else:
if iceCreamSum < int(iceCream):
kids += 1
else:
iceCreamSum -= int(iceCream)
print(iceCreamSum, kids)
if __name__ == '__main__':
main()
``` | 3 | |
1,006 | A | Adjacent Replacements | PROGRAMMING | 800 | [
"implementation"
] | null | null | Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
- Replace each occurrence of $1$ in the array $a$ with $2$; - Replace each occurrence of $2$ in the array $a$ with $1$; - Replace each occurrence of $3$ in the array $a$ with $4$; - Replace each occurrence of $4$ in the array $a$ with $3$; - Replace each occurrence of $5$ in the array $a$ with $6$; - Replace each occurrence of $6$ in the array $a$ with $5$; - $\dots$ - Replace each occurrence of $10^9 - 1$ in the array $a$ with $10^9$; - Replace each occurrence of $10^9$ in the array $a$ with $10^9 - 1$.
Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($2i - 1, 2i$) for each $i \in\{1, 2, \ldots, 5 \cdot 10^8\}$ as described above.
For example, for the array $a = [1, 2, 4, 5, 10]$, the following sequence of arrays represents the algorithm:
$[1, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $1$ with $2$) $\rightarrow$ $[2, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $2$ with $1$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $3$ with $4$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $4$ with $3$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $5$ with $6$) $\rightarrow$ $[1, 1, 3, 6, 10]$ $\rightarrow$ (replace all occurrences of $6$ with $5$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ $\dots$ $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $10$ with $9$) $\rightarrow$ $[1, 1, 3, 5, 9]$. The later steps of the algorithm do not change the array.
Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it. | The first line of the input contains one integer number $n$ ($1 \le n \le 1000$) — the number of elements in Mishka's birthday present (surprisingly, an array).
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the elements of the array. | Print $n$ integers — $b_1, b_2, \dots, b_n$, where $b_i$ is the final value of the $i$-th element of the array after applying "Mishka's Adjacent Replacements Algorithm" to the array $a$. Note that you cannot change the order of elements in the array. | [
"5\n1 2 4 5 10\n",
"10\n10000 10 50605065 1 5 89 5 999999999 60506056 1000000000\n"
] | [
"1 1 3 5 9\n",
"9999 9 50605065 1 5 89 5 999999999 60506055 999999999\n"
] | The first example is described in the problem statement. | 0 | [
{
"input": "5\n1 2 4 5 10",
"output": "1 1 3 5 9"
},
{
"input": "10\n10000 10 50605065 1 5 89 5 999999999 60506056 1000000000",
"output": "9999 9 50605065 1 5 89 5 999999999 60506055 999999999"
},
{
"input": "1\n999999999",
"output": "999999999"
},
{
"input": "1\n1000000000",... | 1,592,313,854 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 78 | 0 | z=input
import math
n=int(input())
c=1
l=list((map(int,z().split())))
p=[]
for i in l:
if i%2==0:
p.append(i-1)
else:
p.append(i+1)
print(*p)
| Title: Adjacent Replacements
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
- Replace each occurrence of $1$ in the array $a$ with $2$; - Replace each occurrence of $2$ in the array $a$ with $1$; - Replace each occurrence of $3$ in the array $a$ with $4$; - Replace each occurrence of $4$ in the array $a$ with $3$; - Replace each occurrence of $5$ in the array $a$ with $6$; - Replace each occurrence of $6$ in the array $a$ with $5$; - $\dots$ - Replace each occurrence of $10^9 - 1$ in the array $a$ with $10^9$; - Replace each occurrence of $10^9$ in the array $a$ with $10^9 - 1$.
Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($2i - 1, 2i$) for each $i \in\{1, 2, \ldots, 5 \cdot 10^8\}$ as described above.
For example, for the array $a = [1, 2, 4, 5, 10]$, the following sequence of arrays represents the algorithm:
$[1, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $1$ with $2$) $\rightarrow$ $[2, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $2$ with $1$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $3$ with $4$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $4$ with $3$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $5$ with $6$) $\rightarrow$ $[1, 1, 3, 6, 10]$ $\rightarrow$ (replace all occurrences of $6$ with $5$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ $\dots$ $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $10$ with $9$) $\rightarrow$ $[1, 1, 3, 5, 9]$. The later steps of the algorithm do not change the array.
Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.
Input Specification:
The first line of the input contains one integer number $n$ ($1 \le n \le 1000$) — the number of elements in Mishka's birthday present (surprisingly, an array).
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the elements of the array.
Output Specification:
Print $n$ integers — $b_1, b_2, \dots, b_n$, where $b_i$ is the final value of the $i$-th element of the array after applying "Mishka's Adjacent Replacements Algorithm" to the array $a$. Note that you cannot change the order of elements in the array.
Demo Input:
['5\n1 2 4 5 10\n', '10\n10000 10 50605065 1 5 89 5 999999999 60506056 1000000000\n']
Demo Output:
['1 1 3 5 9\n', '9999 9 50605065 1 5 89 5 999999999 60506055 999999999\n']
Note:
The first example is described in the problem statement. | ```python
z=input
import math
n=int(input())
c=1
l=list((map(int,z().split())))
p=[]
for i in l:
if i%2==0:
p.append(i-1)
else:
p.append(i+1)
print(*p)
``` | 0 | |
673 | A | Bear and Game | PROGRAMMING | 800 | [
"implementation"
] | null | null | Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be *n* interesting minutes *t*1,<=*t*2,<=...,<=*t**n*. Your task is to calculate for how many minutes Limak will watch the game. | The first line of the input contains one integer *n* (1<=≤<=*n*<=≤<=90) — the number of interesting minutes.
The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t*1<=<<=*t*2<=<<=... *t**n*<=≤<=90), given in the increasing order. | Print the number of minutes Limak will watch the game. | [
"3\n7 20 88\n",
"9\n16 20 30 40 50 60 70 80 90\n",
"9\n15 20 30 40 50 60 70 80 90\n"
] | [
"35\n",
"15\n",
"90\n"
] | In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game. | 500 | [
{
"input": "3\n7 20 88",
"output": "35"
},
{
"input": "9\n16 20 30 40 50 60 70 80 90",
"output": "15"
},
{
"input": "9\n15 20 30 40 50 60 70 80 90",
"output": "90"
},
{
"input": "30\n6 11 12 15 22 24 30 31 32 33 34 35 40 42 44 45 47 50 53 54 57 58 63 67 75 77 79 81 83 88",
... | 1,523,697,085 | 2,147,483,647 | Python 3 | OK | TESTS | 34 | 92 | 7,065,600 | n = int(input())
a = list(map(int, input().split()))
a.insert(0, 0)
a.append(90)
n += 2
t = a[0] + 15
for i in range(1, n):
if a[i] > t:
break
else:
t = a[i] + 15
if t > 90:
print(90)
else:
print(t) | Title: Bear and Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be *n* interesting minutes *t*1,<=*t*2,<=...,<=*t**n*. Your task is to calculate for how many minutes Limak will watch the game.
Input Specification:
The first line of the input contains one integer *n* (1<=≤<=*n*<=≤<=90) — the number of interesting minutes.
The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t*1<=<<=*t*2<=<<=... *t**n*<=≤<=90), given in the increasing order.
Output Specification:
Print the number of minutes Limak will watch the game.
Demo Input:
['3\n7 20 88\n', '9\n16 20 30 40 50 60 70 80 90\n', '9\n15 20 30 40 50 60 70 80 90\n']
Demo Output:
['35\n', '15\n', '90\n']
Note:
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game. | ```python
n = int(input())
a = list(map(int, input().split()))
a.insert(0, 0)
a.append(90)
n += 2
t = a[0] + 15
for i in range(1, n):
if a[i] > t:
break
else:
t = a[i] + 15
if t > 90:
print(90)
else:
print(t)
``` | 3 | |
490 | A | Team Olympiad | PROGRAMMING | 800 | [
"greedy",
"implementation",
"sortings"
] | null | null | The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*:
- *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE
Each child happens to be good at exactly one of these three subjects.
The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.
What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that? | The first line contains integer *n* (1<=≤<=*n*<=≤<=5000) — the number of children in the school. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=3), where *t**i* describes the skill of the *i*-th child. | In the first line output integer *w* — the largest possible number of teams.
Then print *w* lines, containing three numbers in each line. Each triple represents the indexes of the children forming the team. You can print both the teams, and the numbers in the triplets in any order. The children are numbered from 1 to *n* in the order of their appearance in the input. Each child must participate in no more than one team. If there are several solutions, print any of them.
If no teams can be compiled, print the only line with value *w* equal to 0. | [
"7\n1 3 1 3 2 1 2\n",
"4\n2 1 1 2\n"
] | [
"2\n3 5 2\n6 7 4\n",
"0\n"
] | none | 500 | [
{
"input": "7\n1 3 1 3 2 1 2",
"output": "2\n3 5 2\n6 7 4"
},
{
"input": "4\n2 1 1 2",
"output": "0"
},
{
"input": "1\n2",
"output": "0"
},
{
"input": "2\n3 1",
"output": "0"
},
{
"input": "3\n2 1 2",
"output": "0"
},
{
"input": "3\n1 2 3",
"output... | 1,688,676,479 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 31 | 0 | n=int(input())
num=list(map(int,input().split()))
a,b,c=num.count(1),num.count(2),num.count(3)
min1=min(a,b,c)
index1=[]
index2=[]
index3=[]
for x,i in enumerate(num):
if i==1:
index1.append(x+1)
elif i==2:
index2.append(x+1)
else:
index3.append(x+1)
for x in range(min1):
print(index1[x],index2[x],index3[x])
if min1==0:
print(0) | Title: Team Olympiad
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*:
- *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE
Each child happens to be good at exactly one of these three subjects.
The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.
What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=5000) — the number of children in the school. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=3), where *t**i* describes the skill of the *i*-th child.
Output Specification:
In the first line output integer *w* — the largest possible number of teams.
Then print *w* lines, containing three numbers in each line. Each triple represents the indexes of the children forming the team. You can print both the teams, and the numbers in the triplets in any order. The children are numbered from 1 to *n* in the order of their appearance in the input. Each child must participate in no more than one team. If there are several solutions, print any of them.
If no teams can be compiled, print the only line with value *w* equal to 0.
Demo Input:
['7\n1 3 1 3 2 1 2\n', '4\n2 1 1 2\n']
Demo Output:
['2\n3 5 2\n6 7 4\n', '0\n']
Note:
none | ```python
n=int(input())
num=list(map(int,input().split()))
a,b,c=num.count(1),num.count(2),num.count(3)
min1=min(a,b,c)
index1=[]
index2=[]
index3=[]
for x,i in enumerate(num):
if i==1:
index1.append(x+1)
elif i==2:
index2.append(x+1)
else:
index3.append(x+1)
for x in range(min1):
print(index1[x],index2[x],index3[x])
if min1==0:
print(0)
``` | 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,674,344,132 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 92 | 0 | n = str(input())
lower_count = 0
upper_count = 0
for i in n:
if i.isupper():
upper_count += 1
elif i.islower():
lower_count += 1
if lower_count >= upper_count:
print(n.lower())
else:
print(n.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
n = str(input())
lower_count = 0
upper_count = 0
for i in n:
if i.isupper():
upper_count += 1
elif i.islower():
lower_count += 1
if lower_count >= upper_count:
print(n.lower())
else:
print(n.upper())
``` | 3.977 |
867 | A | Between the Offices | PROGRAMMING | 800 | [
"implementation"
] | null | null | As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last *n* days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last *n* days, or not. | The first line of input contains single integer *n* (2<=≤<=*n*<=≤<=100) — the number of days.
The second line contains a string of length *n* consisting of only capital 'S' and 'F' letters. If the *i*-th letter is 'S', then you were in Seattle office on that day. Otherwise you were in San Francisco. The days are given in chronological order, i.e. today is the last day in this sequence. | Print "YES" if you flew more times from Seattle to San Francisco, and "NO" otherwise.
You can print each letter in any case (upper or lower). | [
"4\nFSSF\n",
"2\nSF\n",
"10\nFFFFFFFFFF\n",
"10\nSSFFSFFSFF\n"
] | [
"NO\n",
"YES\n",
"NO\n",
"YES\n"
] | In the first example you were initially at San Francisco, then flew to Seattle, were there for two days and returned to San Francisco. You made one flight in each direction, so the answer is "NO".
In the second example you just flew from Seattle to San Francisco, so the answer is "YES".
In the third example you stayed the whole period in San Francisco, so the answer is "NO".
In the fourth example if you replace 'S' with ones, and 'F' with zeros, you'll get the first few digits of π in binary representation. Not very useful information though. | 500 | [
{
"input": "4\nFSSF",
"output": "NO"
},
{
"input": "2\nSF",
"output": "YES"
},
{
"input": "10\nFFFFFFFFFF",
"output": "NO"
},
{
"input": "10\nSSFFSFFSFF",
"output": "YES"
},
{
"input": "20\nSFSFFFFSSFFFFSSSSFSS",
"output": "NO"
},
{
"input": "20\nSSFFF... | 1,586,513,055 | 2,147,483,647 | Python 3 | OK | TESTS | 34 | 108 | 0 | if __name__ == "__main__":
days = int(input())
travels = list(input())
count_s_f = 0
count_f_s = 0
i=0
while i != len(travels)-1:
if travels[i] == 'S' and travels[i+1] == 'F':
count_s_f+=1
elif travels[i] == 'F' and travels[i+1] == 'S':
count_f_s+=1
else:
pass
i+=1
if count_s_f > count_f_s:
print("Yes")
else:
print("No")
| Title: Between the Offices
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last *n* days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last *n* days, or not.
Input Specification:
The first line of input contains single integer *n* (2<=≤<=*n*<=≤<=100) — the number of days.
The second line contains a string of length *n* consisting of only capital 'S' and 'F' letters. If the *i*-th letter is 'S', then you were in Seattle office on that day. Otherwise you were in San Francisco. The days are given in chronological order, i.e. today is the last day in this sequence.
Output Specification:
Print "YES" if you flew more times from Seattle to San Francisco, and "NO" otherwise.
You can print each letter in any case (upper or lower).
Demo Input:
['4\nFSSF\n', '2\nSF\n', '10\nFFFFFFFFFF\n', '10\nSSFFSFFSFF\n']
Demo Output:
['NO\n', 'YES\n', 'NO\n', 'YES\n']
Note:
In the first example you were initially at San Francisco, then flew to Seattle, were there for two days and returned to San Francisco. You made one flight in each direction, so the answer is "NO".
In the second example you just flew from Seattle to San Francisco, so the answer is "YES".
In the third example you stayed the whole period in San Francisco, so the answer is "NO".
In the fourth example if you replace 'S' with ones, and 'F' with zeros, you'll get the first few digits of π in binary representation. Not very useful information though. | ```python
if __name__ == "__main__":
days = int(input())
travels = list(input())
count_s_f = 0
count_f_s = 0
i=0
while i != len(travels)-1:
if travels[i] == 'S' and travels[i+1] == 'F':
count_s_f+=1
elif travels[i] == 'F' and travels[i+1] == 'S':
count_f_s+=1
else:
pass
i+=1
if count_s_f > count_f_s:
print("Yes")
else:
print("No")
``` | 3 | |
573 | A | Bear and Poker | PROGRAMMING | 1,300 | [
"implementation",
"math",
"number theory"
] | 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. | 500 | [
{
"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,448,901,931 | 2,147,483,647 | Python 3 | OK | TESTS | 70 | 561 | 8,806,400 | def rem(x):
for i in range(2, 4):
while x % i == 0:
x //= i
return x
n = int(input())
result = "Yes"
data = [int(i) for i in input().split()]
b = rem(data.pop())
for i in data:
if rem(i) != b:
result = "No"
break
print(result)
| Title: Bear and Poker
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
def rem(x):
for i in range(2, 4):
while x % i == 0:
x //= i
return x
n = int(input())
result = "Yes"
data = [int(i) for i in input().split()]
b = rem(data.pop())
for i in data:
if rem(i) != b:
result = "No"
break
print(result)
``` | 3 | |
689 | A | Mike and Cellphone | PROGRAMMING | 1,400 | [
"brute force",
"constructive algorithms",
"implementation"
] | null | null | While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way:
Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253":
Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements? | The first line of the input contains the only integer *n* (1<=≤<=*n*<=≤<=9) — the number of digits in the phone number that Mike put in.
The second line contains the string consisting of *n* digits (characters from '0' to '9') representing the number that Mike put in. | If there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print "YES" (without quotes) in the only line.
Otherwise print "NO" (without quotes) in the first line. | [
"3\n586\n",
"2\n09\n",
"9\n123456789\n",
"3\n911\n"
] | [
"NO\n",
"NO\n",
"YES\n",
"YES\n"
] | You can find the picture clarifying the first sample case in the statement above. | 500 | [
{
"input": "3\n586",
"output": "NO"
},
{
"input": "2\n09",
"output": "NO"
},
{
"input": "9\n123456789",
"output": "YES"
},
{
"input": "3\n911",
"output": "YES"
},
{
"input": "3\n089",
"output": "NO"
},
{
"input": "3\n159",
"output": "YES"
},
{
... | 1,689,250,396 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 46 | 0 | print("_RANDOM_GUESS_1689250395.082526")# 1689250395.082567 | Title: Mike and Cellphone
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way:
Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253":
Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?
Input Specification:
The first line of the input contains the only integer *n* (1<=≤<=*n*<=≤<=9) — the number of digits in the phone number that Mike put in.
The second line contains the string consisting of *n* digits (characters from '0' to '9') representing the number that Mike put in.
Output Specification:
If there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print "YES" (without quotes) in the only line.
Otherwise print "NO" (without quotes) in the first line.
Demo Input:
['3\n586\n', '2\n09\n', '9\n123456789\n', '3\n911\n']
Demo Output:
['NO\n', 'NO\n', 'YES\n', 'YES\n']
Note:
You can find the picture clarifying the first sample case in the statement above. | ```python
print("_RANDOM_GUESS_1689250395.082526")# 1689250395.082567
``` | 0 | |
41 | A | Translation | PROGRAMMING | 800 | [
"implementation",
"strings"
] | A. Translation | 2 | 256 | The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly. | The first line contains word *s*, the second line contains word *t*. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols. | If the word *t* is a word *s*, written reversely, print YES, otherwise print NO. | [
"code\nedoc\n",
"abb\naba\n",
"code\ncode\n"
] | [
"YES\n",
"NO\n",
"NO\n"
] | none | 500 | [
{
"input": "code\nedoc",
"output": "YES"
},
{
"input": "abb\naba",
"output": "NO"
},
{
"input": "code\ncode",
"output": "NO"
},
{
"input": "abacaba\nabacaba",
"output": "YES"
},
{
"input": "q\nq",
"output": "YES"
},
{
"input": "asrgdfngfnmfgnhweratgjkk... | 1,601,527,848 | 2,147,483,647 | Python 3 | OK | TESTS | 40 | 186 | 0 |
def reverse(inp):
out = ''
for i in range(len(inp)-1,-1,-1):
out += inp[i]
return out
inp1 = input()
inp2 = input()
if inp1 == reverse(str(inp2)):
print("YES")
else:
print("NO")
| Title: Translation
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
Input Specification:
The first line contains word *s*, the second line contains word *t*. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.
Output Specification:
If the word *t* is a word *s*, written reversely, print YES, otherwise print NO.
Demo Input:
['code\nedoc\n', 'abb\naba\n', 'code\ncode\n']
Demo Output:
['YES\n', 'NO\n', 'NO\n']
Note:
none | ```python
def reverse(inp):
out = ''
for i in range(len(inp)-1,-1,-1):
out += inp[i]
return out
inp1 = input()
inp2 = input()
if inp1 == reverse(str(inp2)):
print("YES")
else:
print("NO")
``` | 3.9535 |
361 | A | Levko and Table | PROGRAMMING | 800 | [
"constructive algorithms",
"implementation"
] | null | null | Levko loves tables that consist of *n* rows and *n* columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals *k*.
Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them. | The single line contains two integers, *n* and *k* (1<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=1000). | Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value.
If there are multiple suitable tables, you are allowed to print any of them. | [
"2 4\n",
"4 7\n"
] | [
"1 3\n3 1\n",
"2 1 0 4\n4 0 2 1\n1 3 3 0\n0 3 2 2\n"
] | In the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.
In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements. | 500 | [
{
"input": "2 4",
"output": "4 0 \n0 4 "
},
{
"input": "4 7",
"output": "7 0 0 0 \n0 7 0 0 \n0 0 7 0 \n0 0 0 7 "
},
{
"input": "1 8",
"output": "8 "
},
{
"input": "9 3",
"output": "3 0 0 0 0 0 0 0 0 \n0 3 0 0 0 0 0 0 0 \n0 0 3 0 0 0 0 0 0 \n0 0 0 3 0 0 0 0 0 \n0 0 0 0 3 0... | 1,597,830,823 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 93 | 0 | n,k=map(int,input().split())
tmp=[0] * (n-2)*2
tmp.append(k-1);tmp.append(1)
for i in range(n*2):
print(*tmp) | Title: Levko and Table
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Levko loves tables that consist of *n* rows and *n* columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals *k*.
Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
Input Specification:
The single line contains two integers, *n* and *k* (1<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=1000).
Output Specification:
Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value.
If there are multiple suitable tables, you are allowed to print any of them.
Demo Input:
['2 4\n', '4 7\n']
Demo Output:
['1 3\n3 1\n', '2 1 0 4\n4 0 2 1\n1 3 3 0\n0 3 2 2\n']
Note:
In the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.
In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements. | ```python
n,k=map(int,input().split())
tmp=[0] * (n-2)*2
tmp.append(k-1);tmp.append(1)
for i in range(n*2):
print(*tmp)
``` | 0 | |
122 | A | Lucky Division | PROGRAMMING | 1,000 | [
"brute force",
"number theory"
] | null | null | Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number *n* is almost lucky. | The single line contains an integer *n* (1<=≤<=*n*<=≤<=1000) — the number that needs to be checked. | In the only line print "YES" (without the quotes), if number *n* is almost lucky. Otherwise, print "NO" (without the quotes). | [
"47\n",
"16\n",
"78\n"
] | [
"YES\n",
"YES\n",
"NO\n"
] | Note that all lucky numbers are almost lucky as any number is evenly divisible by itself.
In the first sample 47 is a lucky number. In the second sample 16 is divisible by 4. | 500 | [
{
"input": "47",
"output": "YES"
},
{
"input": "16",
"output": "YES"
},
{
"input": "78",
"output": "NO"
},
{
"input": "48",
"output": "YES"
},
{
"input": "100",
"output": "YES"
},
{
"input": "107",
"output": "NO"
},
{
"input": "77",
"ou... | 1,693,743,563 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 30 | 0 | n = int(input())
if n % 4 == 0 or n % 7 == 0 or any(i == '4' and i == '7' for i in str(n)):
print("YES")
else:
print("NO") | Title: Lucky Division
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number *n* is almost lucky.
Input Specification:
The single line contains an integer *n* (1<=≤<=*n*<=≤<=1000) — the number that needs to be checked.
Output Specification:
In the only line print "YES" (without the quotes), if number *n* is almost lucky. Otherwise, print "NO" (without the quotes).
Demo Input:
['47\n', '16\n', '78\n']
Demo Output:
['YES\n', 'YES\n', 'NO\n']
Note:
Note that all lucky numbers are almost lucky as any number is evenly divisible by itself.
In the first sample 47 is a lucky number. In the second sample 16 is divisible by 4. | ```python
n = int(input())
if n % 4 == 0 or n % 7 == 0 or any(i == '4' and i == '7' for i in str(n)):
print("YES")
else:
print("NO")
``` | 0 | |
228 | A | Is your horseshoe on the other hoof? | PROGRAMMING | 800 | [
"implementation"
] | null | null | Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.
Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. | The first line contains four space-separated integers *s*1,<=*s*2,<=*s*3,<=*s*4 (1<=≤<=*s*1,<=*s*2,<=*s*3,<=*s*4<=≤<=109) — the colors of horseshoes Valera has.
Consider all possible colors indexed with integers. | Print a single integer — the minimum number of horseshoes Valera needs to buy. | [
"1 7 3 3\n",
"7 7 7 7\n"
] | [
"1\n",
"3\n"
] | none | 500 | [
{
"input": "1 7 3 3",
"output": "1"
},
{
"input": "7 7 7 7",
"output": "3"
},
{
"input": "81170865 673572653 756938629 995577259",
"output": "0"
},
{
"input": "3491663 217797045 522540872 715355328",
"output": "0"
},
{
"input": "251590420 586975278 916631563 58697... | 1,685,182,937 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 4 | 124 | 0 | colors = [int(x) for x in input().split(" ")]
colors.sort
difcolor = 0
for i in range(3):
if colors[i] == colors[i+1]:
difcolor += 1
print(difcolor) | Title: Is your horseshoe on the other hoof?
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.
Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
Input Specification:
The first line contains four space-separated integers *s*1,<=*s*2,<=*s*3,<=*s*4 (1<=≤<=*s*1,<=*s*2,<=*s*3,<=*s*4<=≤<=109) — the colors of horseshoes Valera has.
Consider all possible colors indexed with integers.
Output Specification:
Print a single integer — the minimum number of horseshoes Valera needs to buy.
Demo Input:
['1 7 3 3\n', '7 7 7 7\n']
Demo Output:
['1\n', '3\n']
Note:
none | ```python
colors = [int(x) for x in input().split(" ")]
colors.sort
difcolor = 0
for i in range(3):
if colors[i] == colors[i+1]:
difcolor += 1
print(difcolor)
``` | 0 | |
279 | B | Books | PROGRAMMING | 1,400 | [
"binary search",
"brute force",
"implementation",
"two pointers"
] | null | null | When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to read the *i*-th book.
Valera decided to choose an arbitrary book with number *i* and read the books one by one, starting from this book. In other words, he will first read book number *i*, then book number *i*<=+<=1, then book number *i*<=+<=2 and so on. He continues the process until he either runs out of the free time or finishes reading the *n*-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read. | The first line contains two integers *n* and *t* (1<=≤<=*n*<=≤<=105; 1<=≤<=*t*<=≤<=109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=104), where number *a**i* shows the number of minutes that the boy needs to read the *i*-th book. | Print a single integer — the maximum number of books Valera can read. | [
"4 5\n3 1 2 1\n",
"3 3\n2 2 3\n"
] | [
"3\n",
"1\n"
] | none | 1,000 | [
{
"input": "4 5\n3 1 2 1",
"output": "3"
},
{
"input": "3 3\n2 2 3",
"output": "1"
},
{
"input": "1 3\n5",
"output": "0"
},
{
"input": "1 10\n4",
"output": "1"
},
{
"input": "2 10\n6 4",
"output": "2"
},
{
"input": "6 10\n2 3 4 2 1 1",
"output": "4... | 1,684,166,281 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 38 | 218 | 13,312,000 | n,m =map(int,input().split())
l = list(map(int,input().split()))
c,s,r,le = 0,0,0,0
while r < n:
s += l[r]
while s > m :
s -= l[le]
le += 1
if s <= m:
if c < r-le+1 :
c =r-le+1
r += 1
print(c) | Title: Books
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to read the *i*-th book.
Valera decided to choose an arbitrary book with number *i* and read the books one by one, starting from this book. In other words, he will first read book number *i*, then book number *i*<=+<=1, then book number *i*<=+<=2 and so on. He continues the process until he either runs out of the free time or finishes reading the *n*-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
Input Specification:
The first line contains two integers *n* and *t* (1<=≤<=*n*<=≤<=105; 1<=≤<=*t*<=≤<=109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=104), where number *a**i* shows the number of minutes that the boy needs to read the *i*-th book.
Output Specification:
Print a single integer — the maximum number of books Valera can read.
Demo Input:
['4 5\n3 1 2 1\n', '3 3\n2 2 3\n']
Demo Output:
['3\n', '1\n']
Note:
none | ```python
n,m =map(int,input().split())
l = list(map(int,input().split()))
c,s,r,le = 0,0,0,0
while r < n:
s += l[r]
while s > m :
s -= l[le]
le += 1
if s <= m:
if c < r-le+1 :
c =r-le+1
r += 1
print(c)
``` | 3 | |
651 | A | Joysticks | PROGRAMMING | 1,100 | [
"dp",
"greedy",
"implementation",
"math"
] | null | null | Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at *a*1 percent and second one is charged at *a*2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not connected to a charger) or charges by 1 percent (if connected to a charger).
Game continues while both joysticks have a positive charge. Hence, if at the beginning of minute some joystick is charged by 1 percent, it has to be connected to a charger, otherwise the game stops. If some joystick completely discharges (its charge turns to 0), the game also stops.
Determine the maximum number of minutes that game can last. It is prohibited to pause the game, i. e. at each moment both joysticks should be enabled. It is allowed for joystick to be charged by more than 100 percent. | The first line of the input contains two positive integers *a*1 and *a*2 (1<=≤<=*a*1,<=*a*2<=≤<=100), the initial charge level of first and second joystick respectively. | Output the only integer, the maximum number of minutes that the game can last. Game continues until some joystick is discharged. | [
"3 5\n",
"4 4\n"
] | [
"6\n",
"5\n"
] | In the first sample game lasts for 6 minute by using the following algorithm:
- at the beginning of the first minute connect first joystick to the charger, by the end of this minute first joystick is at 4%, second is at 3%; - continue the game without changing charger, by the end of the second minute the first joystick is at 5%, second is at 1%; - at the beginning of the third minute connect second joystick to the charger, after this minute the first joystick is at 3%, the second one is at 2%; - continue the game without changing charger, by the end of the fourth minute first joystick is at 1%, second one is at 3%; - at the beginning of the fifth minute connect first joystick to the charger, after this minute the first joystick is at 2%, the second one is at 1%; - at the beginning of the sixth minute connect second joystick to the charger, after this minute the first joystick is at 0%, the second one is at 2%.
After that the first joystick is completely discharged and the game is stopped. | 500 | [
{
"input": "3 5",
"output": "6"
},
{
"input": "4 4",
"output": "5"
},
{
"input": "100 100",
"output": "197"
},
{
"input": "1 100",
"output": "98"
},
{
"input": "100 1",
"output": "98"
},
{
"input": "1 4",
"output": "2"
},
{
"input": "1 1",
... | 1,587,322,688 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 6 | 93 | 0 | a1,a2=map(int,input().split())
count=0
while(a1>0 and a2>0):
if a1>=a2:
a1-=2
a2+=1
count+=1
else:
a1+=1
a2-=2
count+=1
print(count) | Title: Joysticks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at *a*1 percent and second one is charged at *a*2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not connected to a charger) or charges by 1 percent (if connected to a charger).
Game continues while both joysticks have a positive charge. Hence, if at the beginning of minute some joystick is charged by 1 percent, it has to be connected to a charger, otherwise the game stops. If some joystick completely discharges (its charge turns to 0), the game also stops.
Determine the maximum number of minutes that game can last. It is prohibited to pause the game, i. e. at each moment both joysticks should be enabled. It is allowed for joystick to be charged by more than 100 percent.
Input Specification:
The first line of the input contains two positive integers *a*1 and *a*2 (1<=≤<=*a*1,<=*a*2<=≤<=100), the initial charge level of first and second joystick respectively.
Output Specification:
Output the only integer, the maximum number of minutes that the game can last. Game continues until some joystick is discharged.
Demo Input:
['3 5\n', '4 4\n']
Demo Output:
['6\n', '5\n']
Note:
In the first sample game lasts for 6 minute by using the following algorithm:
- at the beginning of the first minute connect first joystick to the charger, by the end of this minute first joystick is at 4%, second is at 3%; - continue the game without changing charger, by the end of the second minute the first joystick is at 5%, second is at 1%; - at the beginning of the third minute connect second joystick to the charger, after this minute the first joystick is at 3%, the second one is at 2%; - continue the game without changing charger, by the end of the fourth minute first joystick is at 1%, second one is at 3%; - at the beginning of the fifth minute connect first joystick to the charger, after this minute the first joystick is at 2%, the second one is at 1%; - at the beginning of the sixth minute connect second joystick to the charger, after this minute the first joystick is at 0%, the second one is at 2%.
After that the first joystick is completely discharged and the game is stopped. | ```python
a1,a2=map(int,input().split())
count=0
while(a1>0 and a2>0):
if a1>=a2:
a1-=2
a2+=1
count+=1
else:
a1+=1
a2-=2
count+=1
print(count)
``` | 0 | |
984 | A | Game | PROGRAMMING | 800 | [
"sortings"
] | null | null | Two players play a game.
Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players alternate turns.
The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.
You want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves. | The first line contains one integer $n$ ($1 \le n \le 1000$) — the number of numbers on the board.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^6$). | Print one number that will be left on the board. | [
"3\n2 1 3\n",
"3\n2 2 2\n"
] | [
"2",
"2"
] | In the first sample, the first player erases $3$ and the second erases $1$. $2$ is left on the board.
In the second sample, $2$ is left on the board regardless of the actions of the players. | 500 | [
{
"input": "3\n2 1 3",
"output": "2"
},
{
"input": "3\n2 2 2",
"output": "2"
},
{
"input": "9\n44 53 51 80 5 27 74 79 94",
"output": "53"
},
{
"input": "10\n38 82 23 37 96 4 81 60 67 86",
"output": "60"
},
{
"input": "10\n58 26 77 15 53 81 68 48 22 65",
"outpu... | 1,616,956,193 | 2,147,483,647 | Python 3 | OK | TESTS | 35 | 77 | 307,200 | n=int(input())
l1=list([int(x) for x in input().split()])
l1.sort()
print(l1[(n-1)//2])
| Title: Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two players play a game.
Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players alternate turns.
The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.
You want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.
Input Specification:
The first line contains one integer $n$ ($1 \le n \le 1000$) — the number of numbers on the board.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^6$).
Output Specification:
Print one number that will be left on the board.
Demo Input:
['3\n2 1 3\n', '3\n2 2 2\n']
Demo Output:
['2', '2']
Note:
In the first sample, the first player erases $3$ and the second erases $1$. $2$ is left on the board.
In the second sample, $2$ is left on the board regardless of the actions of the players. | ```python
n=int(input())
l1=list([int(x) for x in input().split()])
l1.sort()
print(l1[(n-1)//2])
``` | 3 | |
279 | B | Books | PROGRAMMING | 1,400 | [
"binary search",
"brute force",
"implementation",
"two pointers"
] | null | null | When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to read the *i*-th book.
Valera decided to choose an arbitrary book with number *i* and read the books one by one, starting from this book. In other words, he will first read book number *i*, then book number *i*<=+<=1, then book number *i*<=+<=2 and so on. He continues the process until he either runs out of the free time or finishes reading the *n*-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read. | The first line contains two integers *n* and *t* (1<=≤<=*n*<=≤<=105; 1<=≤<=*t*<=≤<=109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=104), where number *a**i* shows the number of minutes that the boy needs to read the *i*-th book. | Print a single integer — the maximum number of books Valera can read. | [
"4 5\n3 1 2 1\n",
"3 3\n2 2 3\n"
] | [
"3\n",
"1\n"
] | none | 1,000 | [
{
"input": "4 5\n3 1 2 1",
"output": "3"
},
{
"input": "3 3\n2 2 3",
"output": "1"
},
{
"input": "1 3\n5",
"output": "0"
},
{
"input": "1 10\n4",
"output": "1"
},
{
"input": "2 10\n6 4",
"output": "2"
},
{
"input": "6 10\n2 3 4 2 1 1",
"output": "4... | 1,690,856,992 | 2,147,483,647 | PyPy 3-64 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define str string
#define vi vector<int>
#define vll vector<ll>
#define vs vector<str>
#define vc vector<char>
#define vb vector<bool>
#define vd vector<double>
#define nl "\n"
#define sp " "
#define all(arr) arr.begin(), arr.end()
#define rall(arr) arr.rbegin(), arr.rend()
#define pb push_back
#define rsz resize
#define sz size
#define mp make_pair
#define pi pair<int,int>
#define pq priority_queue
#define mset multiset
#define ins insert
#define ub upper_bound
#define lb lower_bound
#define f first
#define s second
const int modulo = 1000000009;
const int cf_modulo = 998244353;
const int little_inf = 2e9;
const ll inf = 5e18;
#define FOR(i,a,b) for(int i=a; i<b; i++)
#define UNFOR(i,a,b) for(int i=a; i>=b; i--)
#define trav(it,arr) for(auto it:arr)
void solve() {
ll N, T;
cin >> N >> T;
vll times(N);
FOR(i,0,N) cin >> times[i];
int left = 0, right = 0, curr = times[0], best = 0;
while (right<N) {
if (curr<=T) best = max(right-left+1,best);
if (curr<=T) {
curr += times[++right];
} else if (curr>T) {
curr -= times[left++];
}
}
cout << best << nl;
}
int main() {
//freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie(0);
/*
int t;
cin >> t;
while (t--) {
solve();
}
*/
solve();
} | Title: Books
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to read the *i*-th book.
Valera decided to choose an arbitrary book with number *i* and read the books one by one, starting from this book. In other words, he will first read book number *i*, then book number *i*<=+<=1, then book number *i*<=+<=2 and so on. He continues the process until he either runs out of the free time or finishes reading the *n*-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
Input Specification:
The first line contains two integers *n* and *t* (1<=≤<=*n*<=≤<=105; 1<=≤<=*t*<=≤<=109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=104), where number *a**i* shows the number of minutes that the boy needs to read the *i*-th book.
Output Specification:
Print a single integer — the maximum number of books Valera can read.
Demo Input:
['4 5\n3 1 2 1\n', '3 3\n2 2 3\n']
Demo Output:
['3\n', '1\n']
Note:
none | ```python
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define str string
#define vi vector<int>
#define vll vector<ll>
#define vs vector<str>
#define vc vector<char>
#define vb vector<bool>
#define vd vector<double>
#define nl "\n"
#define sp " "
#define all(arr) arr.begin(), arr.end()
#define rall(arr) arr.rbegin(), arr.rend()
#define pb push_back
#define rsz resize
#define sz size
#define mp make_pair
#define pi pair<int,int>
#define pq priority_queue
#define mset multiset
#define ins insert
#define ub upper_bound
#define lb lower_bound
#define f first
#define s second
const int modulo = 1000000009;
const int cf_modulo = 998244353;
const int little_inf = 2e9;
const ll inf = 5e18;
#define FOR(i,a,b) for(int i=a; i<b; i++)
#define UNFOR(i,a,b) for(int i=a; i>=b; i--)
#define trav(it,arr) for(auto it:arr)
void solve() {
ll N, T;
cin >> N >> T;
vll times(N);
FOR(i,0,N) cin >> times[i];
int left = 0, right = 0, curr = times[0], best = 0;
while (right<N) {
if (curr<=T) best = max(right-left+1,best);
if (curr<=T) {
curr += times[++right];
} else if (curr>T) {
curr -= times[left++];
}
}
cout << best << nl;
}
int main() {
//freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie(0);
/*
int t;
cin >> t;
while (t--) {
solve();
}
*/
solve();
}
``` | -1 | |
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,598,984,333 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 248 | 0 | word = input()
upperLetters = 0
lowerLetters = 0
for i in word:
if i.isupper():
upperLetters = upperLetters + 1
else:
lowerLetters = lowerLetters + 1
if upperLetters > lowerLetters:
print(word.upper())
else:
print(word.lower())
| Title: Word
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
Input Specification:
The first line contains a word *s* — it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100.
Output Specification:
Print the corrected word *s*. If the given word *s* has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one.
Demo Input:
['HoUse\n', 'ViP\n', 'maTRIx\n']
Demo Output:
['house\n', 'VIP\n', 'matrix\n']
Note:
none | ```python
word = input()
upperLetters = 0
lowerLetters = 0
for i in word:
if i.isupper():
upperLetters = upperLetters + 1
else:
lowerLetters = lowerLetters + 1
if upperLetters > lowerLetters:
print(word.upper())
else:
print(word.lower())
``` | 3.938 |
452 | A | Eevee | PROGRAMMING | 1,000 | [
"brute force",
"implementation",
"strings"
] | null | null | You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon.
You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it. | First line contains an integer *n* (6<=≤<=*n*<=≤<=8) – the length of the string.
Next line contains a string consisting of *n* characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword). | Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter). | [
"7\nj......\n",
"7\n...feon\n",
"7\n.l.r.o.\n"
] | [
"jolteon\n",
"leafeon\n",
"flareon\n"
] | Here's a set of names in a form you can paste into your solution:
["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"]
{"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"} | 500 | [
{
"input": "7\n...feon",
"output": "leafeon"
},
{
"input": "7\n.l.r.o.",
"output": "flareon"
},
{
"input": "6\n.s..o.",
"output": "espeon"
},
{
"input": "7\nglaceon",
"output": "glaceon"
},
{
"input": "8\n.a.o.e.n",
"output": "vaporeon"
},
{
"input": "... | 1,628,595,699 | 2,147,483,647 | PyPy 3 | OK | TESTS | 20 | 109 | 20,172,800 | n = int(input())
s = input()
pokemons = ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"]
for p in [x for x in pokemons if len(x) == n]:
ans = True
for a, b in zip(s, p):
if a != '.' and a != b:
ans = False
break
if ans:
print(p)
break | Title: Eevee
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon.
You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it.
Input Specification:
First line contains an integer *n* (6<=≤<=*n*<=≤<=8) – the length of the string.
Next line contains a string consisting of *n* characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword).
Output Specification:
Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter).
Demo Input:
['7\nj......\n', '7\n...feon\n', '7\n.l.r.o.\n']
Demo Output:
['jolteon\n', 'leafeon\n', 'flareon\n']
Note:
Here's a set of names in a form you can paste into your solution:
["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"]
{"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"} | ```python
n = int(input())
s = input()
pokemons = ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"]
for p in [x for x in pokemons if len(x) == n]:
ans = True
for a, b in zip(s, p):
if a != '.' and a != b:
ans = False
break
if ans:
print(p)
break
``` | 3 | |
701 | B | Cells Not Under Attack | PROGRAMMING | 1,200 | [
"data structures",
"math"
] | null | null | Vasya has the square chessboard of size *n*<=×<=*n* and *m* rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.
The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.
You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board. | The first line of the input contains two integers *n* and *m* (1<=≤<=*n*<=≤<=100<=000, 1<=≤<=*m*<=≤<=*min*(100<=000,<=*n*2)) — the size of the board and the number of rooks.
Each of the next *m* lines contains integers *x**i* and *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*) — the number of the row and the number of the column where Vasya will put the *i*-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook. | Print *m* integer, the *i*-th of them should be equal to the number of cells that are not under attack after first *i* rooks are put. | [
"3 3\n1 1\n3 1\n2 2\n",
"5 2\n1 5\n5 1\n",
"100000 1\n300 400\n"
] | [
"4 2 0 \n",
"16 9 \n",
"9999800001 \n"
] | On the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack. | 750 | [
{
"input": "3 3\n1 1\n3 1\n2 2",
"output": "4 2 0 "
},
{
"input": "5 2\n1 5\n5 1",
"output": "16 9 "
},
{
"input": "100000 1\n300 400",
"output": "9999800001 "
},
{
"input": "10 4\n2 8\n1 8\n9 8\n6 9",
"output": "81 72 63 48 "
},
{
"input": "30 30\n3 13\n27 23\n18... | 1,598,116,745 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 0 | 109 | 20,172,800 | n, r = [int(p) for p in input().split()]
cord = []
final = []
covers = 0
x = set()
y = set()
for _ in range(r):
xi, yi = [int(p) for p in input().split()]
x.add(xi)
y.add(yi)
underAttack = len(x)*n + len(y)*n - len(x)*len(y)
print(n**2 - underAttack)
| Title: Cells Not Under Attack
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has the square chessboard of size *n*<=×<=*n* and *m* rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.
The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.
You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
Input Specification:
The first line of the input contains two integers *n* and *m* (1<=≤<=*n*<=≤<=100<=000, 1<=≤<=*m*<=≤<=*min*(100<=000,<=*n*2)) — the size of the board and the number of rooks.
Each of the next *m* lines contains integers *x**i* and *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*) — the number of the row and the number of the column where Vasya will put the *i*-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
Output Specification:
Print *m* integer, the *i*-th of them should be equal to the number of cells that are not under attack after first *i* rooks are put.
Demo Input:
['3 3\n1 1\n3 1\n2 2\n', '5 2\n1 5\n5 1\n', '100000 1\n300 400\n']
Demo Output:
['4 2 0 \n', '16 9 \n', '9999800001 \n']
Note:
On the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack. | ```python
n, r = [int(p) for p in input().split()]
cord = []
final = []
covers = 0
x = set()
y = set()
for _ in range(r):
xi, yi = [int(p) for p in input().split()]
x.add(xi)
y.add(yi)
underAttack = len(x)*n + len(y)*n - len(x)*len(y)
print(n**2 - underAttack)
``` | 0 | |
596 | A | Wilbur and Swimming Pool | PROGRAMMING | 1,100 | [
"geometry",
"implementation"
] | null | null | After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices.
Now Wilbur is wondering, if the remaining *n* vertices of the initial rectangle give enough information to restore the area of the planned swimming pool. | The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=4) — the number of vertices that were not erased by Wilbur's friend.
Each of the following *n* lines contains two integers *x**i* and *y**i* (<=-<=1000<=≤<=*x**i*,<=*y**i*<=≤<=1000) —the coordinates of the *i*-th vertex that remains. Vertices are given in an arbitrary order.
It's guaranteed that these points are distinct vertices of some rectangle, that has positive area and which sides are parallel to the coordinate axes. | Print the area of the initial rectangle if it could be uniquely determined by the points remaining. Otherwise, print <=-<=1. | [
"2\n0 0\n1 1\n",
"1\n1 1\n"
] | [
"1\n",
"-1\n"
] | In the first sample, two opposite corners of the initial rectangle are given, and that gives enough information to say that the rectangle is actually a unit square.
In the second sample there is only one vertex left and this is definitely not enough to uniquely define the area. | 500 | [
{
"input": "2\n0 0\n1 1",
"output": "1"
},
{
"input": "1\n1 1",
"output": "-1"
},
{
"input": "1\n-188 17",
"output": "-1"
},
{
"input": "1\n71 -740",
"output": "-1"
},
{
"input": "4\n-56 -858\n-56 -174\n778 -858\n778 -174",
"output": "570456"
},
{
"inp... | 1,472,600,717 | 2,147,483,647 | Python 3 | OK | TESTS | 121 | 78 | 0 | x=[]
y=[]
I=lambda:list(map(int,input().split()))
for _ in '0'*I()[0]:s=I();x+=[s[0]];y+=[s[1]]
t=(max(x)-min(x))*(max(y)-min(y))
print([t,-1][not t]) | Title: Wilbur and Swimming Pool
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices.
Now Wilbur is wondering, if the remaining *n* vertices of the initial rectangle give enough information to restore the area of the planned swimming pool.
Input Specification:
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=4) — the number of vertices that were not erased by Wilbur's friend.
Each of the following *n* lines contains two integers *x**i* and *y**i* (<=-<=1000<=≤<=*x**i*,<=*y**i*<=≤<=1000) —the coordinates of the *i*-th vertex that remains. Vertices are given in an arbitrary order.
It's guaranteed that these points are distinct vertices of some rectangle, that has positive area and which sides are parallel to the coordinate axes.
Output Specification:
Print the area of the initial rectangle if it could be uniquely determined by the points remaining. Otherwise, print <=-<=1.
Demo Input:
['2\n0 0\n1 1\n', '1\n1 1\n']
Demo Output:
['1\n', '-1\n']
Note:
In the first sample, two opposite corners of the initial rectangle are given, and that gives enough information to say that the rectangle is actually a unit square.
In the second sample there is only one vertex left and this is definitely not enough to uniquely define the area. | ```python
x=[]
y=[]
I=lambda:list(map(int,input().split()))
for _ in '0'*I()[0]:s=I();x+=[s[0]];y+=[s[1]]
t=(max(x)-min(x))*(max(y)-min(y))
print([t,-1][not t])
``` | 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,637,601,871 | 2,147,483,647 | Python 3 | OK | TESTS | 47 | 46 | 0 | inp = input()
n = int(inp.split()[0])
k = int(inp.split()[1])
password =''
cha = 97
for i in range(n):
password+=chr(cha+(i % k))
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
inp = input()
n = int(inp.split()[0])
k = int(inp.split()[1])
password =''
cha = 97
for i in range(n):
password+=chr(cha+(i % k))
print(password)
``` | 3 | |
698 | A | Vacations | PROGRAMMING | 1,400 | [
"dp"
] | null | null | Vasya has *n* days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this *n* days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the *i*-th day there are four options:
1. on this day the gym is closed and the contest is not carried out; 1. on this day the gym is closed and the contest is carried out; 1. on this day the gym is open and the contest is not carried out; 1. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. | The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100) — the number of days of Vasya's vacations.
The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=3) separated by space, where:
- *a**i* equals 0, if on the *i*-th day of vacations the gym is closed and the contest is not carried out; - *a**i* equals 1, if on the *i*-th day of vacations the gym is closed, but the contest is carried out; - *a**i* equals 2, if on the *i*-th day of vacations the gym is open and the contest is not carried out; - *a**i* equals 3, if on the *i*-th day of vacations the gym is open and the contest is carried out. | Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
- to do sport on any two consecutive days, - to write the contest on any two consecutive days. | [
"4\n1 3 2 0\n",
"7\n1 3 3 2 1 2 3\n",
"2\n2 2\n"
] | [
"2\n",
"0\n",
"1\n"
] | In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. | 500 | [
{
"input": "4\n1 3 2 0",
"output": "2"
},
{
"input": "7\n1 3 3 2 1 2 3",
"output": "0"
},
{
"input": "2\n2 2",
"output": "1"
},
{
"input": "1\n0",
"output": "1"
},
{
"input": "10\n0 0 1 1 0 0 0 0 1 0",
"output": "8"
},
{
"input": "100\n3 2 3 3 3 2 3 1 ... | 1,645,269,931 | 2,147,483,647 | Python 3 | OK | TESTS | 88 | 46 | 0 | n = int(input())
a = list(map(int, input().split(' ')))
d = [[0 for i in range(3)] for j in range(n+1)]
mind = 0
posd = 0
for i, ai in enumerate(a):
if ai == 0:
d[i+1][0] = mind + 1
d[i+1][1] = mind + 1
d[i+1][2] = mind + 1
if d[i+1][0] <= d[i+1][1] and d[i+1][0] <= d[i+1][2]:
mind = d[i+1][0]
posd = 0
elif d[i+1][1] < d[i+1][0] and d[i+1][1] < d[i+1][2]:
mind = d[i+1][1]
posd = 1
elif d[i+1][2] < d[i+1][0] and d[i+1][2] < d[i+1][1]:
mind = d[i+1][2]
posd = 2
else:
mind = d[i+1][2]
posd = 3
continue
if ai == 1:
d[i+1][0] = mind + 1
if posd == 1:
d[i+1][1] = mind + 1
else:
d[i+1][1] = mind
d[i+1][2] = mind + 1
if d[i+1][0] <= d[i+1][1] and d[i+1][0] <= d[i+1][2]:
mind = d[i+1][0]
posd = 0
elif d[i+1][1] < d[i+1][0] and d[i+1][1] < d[i+1][2]:
mind = d[i+1][1]
posd = 1
elif d[i+1][2] < d[i+1][0] and d[i+1][2] < d[i+1][1]:
mind = d[i+1][2]
posd = 2
else:
mind = d[i+1][2]
posd = 4
continue
if ai == 2:
d[i+1][0] = mind + 1
d[i+1][1] = mind + 1
if posd == 2:
d[i+1][2] = mind + 1
else:
d[i+1][2] = mind
if d[i+1][0] <= d[i+1][1] and d[i+1][0] <= d[i+1][2]:
mind = d[i+1][0]
posd = 0
elif d[i+1][1] < d[i+1][0] and d[i+1][1] < d[i+1][2]:
mind = d[i+1][1]
posd = 1
elif d[i+1][2] < d[i+1][0] and d[i+1][2] < d[i+1][1]:
mind = d[i+1][2]
posd = 2
else:
mind = d[i+1][2]
posd = 4
continue
if ai == 3:
d[i+1][0] = mind + 1
if posd == 1:
d[i+1][1] = mind + 1
else:
d[i+1][1] = mind
if posd == 2:
d[i+1][2] = mind + 1
else:
d[i+1][2] = mind
if d[i+1][0] <= d[i+1][1] and d[i+1][0] <= d[i+1][2]:
mind = d[i+1][0]
posd = 0
elif d[i+1][1] < d[i+1][0] and d[i+1][1] < d[i+1][2]:
mind = d[i+1][1]
posd = 1
elif d[i+1][2] < d[i+1][0] and d[i+1][2] < d[i+1][1]:
mind = d[i+1][2]
posd = 2
else:
mind = d[i+1][2]
posd = 4
continue
print(min(d[-1][0], d[-1][1], d[-1][2]))
| Title: Vacations
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has *n* days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this *n* days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the *i*-th day there are four options:
1. on this day the gym is closed and the contest is not carried out; 1. on this day the gym is closed and the contest is carried out; 1. on this day the gym is open and the contest is not carried out; 1. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input Specification:
The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100) — the number of days of Vasya's vacations.
The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=3) separated by space, where:
- *a**i* equals 0, if on the *i*-th day of vacations the gym is closed and the contest is not carried out; - *a**i* equals 1, if on the *i*-th day of vacations the gym is closed, but the contest is carried out; - *a**i* equals 2, if on the *i*-th day of vacations the gym is open and the contest is not carried out; - *a**i* equals 3, if on the *i*-th day of vacations the gym is open and the contest is carried out.
Output Specification:
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
- to do sport on any two consecutive days, - to write the contest on any two consecutive days.
Demo Input:
['4\n1 3 2 0\n', '7\n1 3 3 2 1 2 3\n', '2\n2 2\n']
Demo Output:
['2\n', '0\n', '1\n']
Note:
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. | ```python
n = int(input())
a = list(map(int, input().split(' ')))
d = [[0 for i in range(3)] for j in range(n+1)]
mind = 0
posd = 0
for i, ai in enumerate(a):
if ai == 0:
d[i+1][0] = mind + 1
d[i+1][1] = mind + 1
d[i+1][2] = mind + 1
if d[i+1][0] <= d[i+1][1] and d[i+1][0] <= d[i+1][2]:
mind = d[i+1][0]
posd = 0
elif d[i+1][1] < d[i+1][0] and d[i+1][1] < d[i+1][2]:
mind = d[i+1][1]
posd = 1
elif d[i+1][2] < d[i+1][0] and d[i+1][2] < d[i+1][1]:
mind = d[i+1][2]
posd = 2
else:
mind = d[i+1][2]
posd = 3
continue
if ai == 1:
d[i+1][0] = mind + 1
if posd == 1:
d[i+1][1] = mind + 1
else:
d[i+1][1] = mind
d[i+1][2] = mind + 1
if d[i+1][0] <= d[i+1][1] and d[i+1][0] <= d[i+1][2]:
mind = d[i+1][0]
posd = 0
elif d[i+1][1] < d[i+1][0] and d[i+1][1] < d[i+1][2]:
mind = d[i+1][1]
posd = 1
elif d[i+1][2] < d[i+1][0] and d[i+1][2] < d[i+1][1]:
mind = d[i+1][2]
posd = 2
else:
mind = d[i+1][2]
posd = 4
continue
if ai == 2:
d[i+1][0] = mind + 1
d[i+1][1] = mind + 1
if posd == 2:
d[i+1][2] = mind + 1
else:
d[i+1][2] = mind
if d[i+1][0] <= d[i+1][1] and d[i+1][0] <= d[i+1][2]:
mind = d[i+1][0]
posd = 0
elif d[i+1][1] < d[i+1][0] and d[i+1][1] < d[i+1][2]:
mind = d[i+1][1]
posd = 1
elif d[i+1][2] < d[i+1][0] and d[i+1][2] < d[i+1][1]:
mind = d[i+1][2]
posd = 2
else:
mind = d[i+1][2]
posd = 4
continue
if ai == 3:
d[i+1][0] = mind + 1
if posd == 1:
d[i+1][1] = mind + 1
else:
d[i+1][1] = mind
if posd == 2:
d[i+1][2] = mind + 1
else:
d[i+1][2] = mind
if d[i+1][0] <= d[i+1][1] and d[i+1][0] <= d[i+1][2]:
mind = d[i+1][0]
posd = 0
elif d[i+1][1] < d[i+1][0] and d[i+1][1] < d[i+1][2]:
mind = d[i+1][1]
posd = 1
elif d[i+1][2] < d[i+1][0] and d[i+1][2] < d[i+1][1]:
mind = d[i+1][2]
posd = 2
else:
mind = d[i+1][2]
posd = 4
continue
print(min(d[-1][0], d[-1][1], d[-1][2]))
``` | 3 | |
452 | C | Magic Trick | PROGRAMMING | 2,100 | [
"combinatorics",
"math",
"probabilities"
] | null | null | Alex enjoys performing magic tricks. He has a trick that requires a deck of *n* cards. He has *m* identical decks of *n* different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs *n* cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards.
The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful.
You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. | First line of the input consists of two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000), separated by space — number of cards in each deck, and number of decks. | On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10<=-<=6. | [
"2 2\n",
"4 4\n",
"1 2\n"
] | [
"0.6666666666666666\n",
"0.4000000000000000\n",
"1.0000000000000000\n"
] | In the first sample, with probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/64c94d13eeb330b494061e86538db66574ad0f7d.png" style="max-width: 100.0%;max-height: 100.0%;"/> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed.
With the remaining <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/14b21b617fcd2e25700376368355f7bbf975d8de.png" style="max-width: 100.0%;max-height: 100.0%;"/> probability he took two different cards, and the probability of pulling off the trick is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/eb946338365d9781f7d2e9ec692c26702d0ae3a7.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
The resulting probability is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f54a03c9fa9df64ba08161730756d50b780a5f43.png" style="max-width: 100.0%;max-height: 100.0%;"/> | 1,000 | [
{
"input": "2 2",
"output": "0.6666666666666666"
},
{
"input": "4 4",
"output": "0.4000000000000000"
},
{
"input": "1 2",
"output": "1.0000000000000000"
},
{
"input": "2 1",
"output": "0.5000000000000000"
},
{
"input": "10 10",
"output": "0.1818181818181818"
... | 1,407,036,041 | 2,147,483,647 | Python 3 | OK | TESTS | 17 | 77 | 0 | m, n = map(int, input().split())
if m == 1:
print(1)
else:
print(1 / m + (n - 1) * (m - 1) / (m * (m * n - 1))) | Title: Magic Trick
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alex enjoys performing magic tricks. He has a trick that requires a deck of *n* cards. He has *m* identical decks of *n* different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs *n* cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards.
The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful.
You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case.
Input Specification:
First line of the input consists of two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000), separated by space — number of cards in each deck, and number of decks.
Output Specification:
On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10<=-<=6.
Demo Input:
['2 2\n', '4 4\n', '1 2\n']
Demo Output:
['0.6666666666666666\n', '0.4000000000000000\n', '1.0000000000000000\n']
Note:
In the first sample, with probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/64c94d13eeb330b494061e86538db66574ad0f7d.png" style="max-width: 100.0%;max-height: 100.0%;"/> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed.
With the remaining <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/14b21b617fcd2e25700376368355f7bbf975d8de.png" style="max-width: 100.0%;max-height: 100.0%;"/> probability he took two different cards, and the probability of pulling off the trick is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/eb946338365d9781f7d2e9ec692c26702d0ae3a7.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
The resulting probability is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f54a03c9fa9df64ba08161730756d50b780a5f43.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
m, n = map(int, input().split())
if m == 1:
print(1)
else:
print(1 / m + (n - 1) * (m - 1) / (m * (m * n - 1)))
``` | 3 | |
678 | D | Iterated Linear Function | PROGRAMMING | 1,700 | [
"math",
"number theory"
] | null | null | Consider a linear function *f*(*x*)<==<=*Ax*<=+<=*B*. Let's define *g*(0)(*x*)<==<=*x* and *g*(*n*)(*x*)<==<=*f*(*g*(*n*<=-<=1)(*x*)) for *n*<=><=0. For the given integer values *A*, *B*, *n* and *x* find the value of *g*(*n*)(*x*) modulo 109<=+<=7. | The only line contains four integers *A*, *B*, *n* and *x* (1<=≤<=*A*,<=*B*,<=*x*<=≤<=109,<=1<=≤<=*n*<=≤<=1018) — the parameters from the problem statement.
Note that the given value *n* 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. | Print the only integer *s* — the value *g*(*n*)(*x*) modulo 109<=+<=7. | [
"3 4 1 1\n",
"3 4 2 1\n",
"3 4 3 1\n"
] | [
"7\n",
"25\n",
"79\n"
] | none | 0 | [
{
"input": "3 4 1 1",
"output": "7"
},
{
"input": "3 4 2 1",
"output": "25"
},
{
"input": "3 4 3 1",
"output": "79"
},
{
"input": "1 1 1 1",
"output": "2"
},
{
"input": "3 10 723 6",
"output": "443623217"
},
{
"input": "14 81 51 82",
"output": "908... | 1,683,893,472 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 36 | 62 | 0 | import sys
input = sys.stdin.readline
M = 10**9 + 7
a, b, n, x = map(int, input().split())
if a == 1:
print((x+b*n)%M)
else:
print((pow(a, n, M)*x + b*(pow(a, n, M)-1)*pow(a-1, M-2, M))%M)
| Title: Iterated Linear Function
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Consider a linear function *f*(*x*)<==<=*Ax*<=+<=*B*. Let's define *g*(0)(*x*)<==<=*x* and *g*(*n*)(*x*)<==<=*f*(*g*(*n*<=-<=1)(*x*)) for *n*<=><=0. For the given integer values *A*, *B*, *n* and *x* find the value of *g*(*n*)(*x*) modulo 109<=+<=7.
Input Specification:
The only line contains four integers *A*, *B*, *n* and *x* (1<=≤<=*A*,<=*B*,<=*x*<=≤<=109,<=1<=≤<=*n*<=≤<=1018) — the parameters from the problem statement.
Note that the given value *n* 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.
Output Specification:
Print the only integer *s* — the value *g*(*n*)(*x*) modulo 109<=+<=7.
Demo Input:
['3 4 1 1\n', '3 4 2 1\n', '3 4 3 1\n']
Demo Output:
['7\n', '25\n', '79\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
M = 10**9 + 7
a, b, n, x = map(int, input().split())
if a == 1:
print((x+b*n)%M)
else:
print((pow(a, n, M)*x + b*(pow(a, n, M)-1)*pow(a-1, M-2, M))%M)
``` | 3 | |
279 | B | Books | PROGRAMMING | 1,400 | [
"binary search",
"brute force",
"implementation",
"two pointers"
] | null | null | When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to read the *i*-th book.
Valera decided to choose an arbitrary book with number *i* and read the books one by one, starting from this book. In other words, he will first read book number *i*, then book number *i*<=+<=1, then book number *i*<=+<=2 and so on. He continues the process until he either runs out of the free time or finishes reading the *n*-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read. | The first line contains two integers *n* and *t* (1<=≤<=*n*<=≤<=105; 1<=≤<=*t*<=≤<=109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=104), where number *a**i* shows the number of minutes that the boy needs to read the *i*-th book. | Print a single integer — the maximum number of books Valera can read. | [
"4 5\n3 1 2 1\n",
"3 3\n2 2 3\n"
] | [
"3\n",
"1\n"
] | none | 1,000 | [
{
"input": "4 5\n3 1 2 1",
"output": "3"
},
{
"input": "3 3\n2 2 3",
"output": "1"
},
{
"input": "1 3\n5",
"output": "0"
},
{
"input": "1 10\n4",
"output": "1"
},
{
"input": "2 10\n6 4",
"output": "2"
},
{
"input": "6 10\n2 3 4 2 1 1",
"output": "4... | 1,692,174,725 | 2,147,483,647 | Python 3 | OK | TESTS | 38 | 248 | 13,824,000 | n, t = map(int, input().split())
books = list(map(int, input().split()))
max_books = 0 # Maximum number of books read
total_time = 0 # Total time spent reading
left = 0 # Left pointer of the sliding window
for right in range(n):
total_time += books[right]
while total_time > t: # Shrink the window if total time exceeds available time
total_time -= books[left]
left += 1
max_books = max(max_books, right - left + 1)
print(max_books)
| Title: Books
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to read the *i*-th book.
Valera decided to choose an arbitrary book with number *i* and read the books one by one, starting from this book. In other words, he will first read book number *i*, then book number *i*<=+<=1, then book number *i*<=+<=2 and so on. He continues the process until he either runs out of the free time or finishes reading the *n*-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
Input Specification:
The first line contains two integers *n* and *t* (1<=≤<=*n*<=≤<=105; 1<=≤<=*t*<=≤<=109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=104), where number *a**i* shows the number of minutes that the boy needs to read the *i*-th book.
Output Specification:
Print a single integer — the maximum number of books Valera can read.
Demo Input:
['4 5\n3 1 2 1\n', '3 3\n2 2 3\n']
Demo Output:
['3\n', '1\n']
Note:
none | ```python
n, t = map(int, input().split())
books = list(map(int, input().split()))
max_books = 0 # Maximum number of books read
total_time = 0 # Total time spent reading
left = 0 # Left pointer of the sliding window
for right in range(n):
total_time += books[right]
while total_time > t: # Shrink the window if total time exceeds available time
total_time -= books[left]
left += 1
max_books = max(max_books, right - left + 1)
print(max_books)
``` | 3 | |
177 | B2 | Rectangular Game | PROGRAMMING | 1,200 | [
"number theory"
] | null | null | The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has *n* pebbles. He arranges them in *a* equal rows, each row has *b* pebbles (*a*<=><=1). Note that the Beaver must use all the pebbles he has, i. e. *n*<==<=*a*·*b*.
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, *b* pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of *a* and *b*) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers *c*1,<=...,<=*c**k*, where:
- *c*1<==<=*n* - *c**i*<=+<=1 is the number of pebbles that the Beaver ends up with after the *i*-th move, that is, the number of pebbles in a row after some arrangement of *c**i* pebbles (1<=≤<=*i*<=<<=*k*). Note that *c**i*<=><=*c**i*<=+<=1. - *c**k*<==<=1
The result of the game is the sum of numbers *c**i*. You are given *n*. Find the maximum possible result of the game. | The single line of the input contains a single integer *n* — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
- 2<=≤<=*n*<=≤<=50
The input limitations for getting 100 points are:
- 2<=≤<=*n*<=≤<=109 | Print a single number — the maximum possible result of the game. | [
"10\n",
"8\n"
] | [
"16\n",
"15\n"
] | Consider the first example (*c*<sub class="lower-index">1</sub> = 10). The possible options for the game development are:
- Arrange the pebbles in 10 rows, one pebble per row. Then *c*<sub class="lower-index">2</sub> = 1, and the game ends after the first move with the result of 11. - Arrange the pebbles in 5 rows, two pebbles per row. Then *c*<sub class="lower-index">2</sub> = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. *c*<sub class="lower-index">3</sub> = 1, and the game ends with the result of 13. - Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to *c*<sub class="lower-index">2</sub> = 5, *c*<sub class="lower-index">3</sub> = 1, and the game ends with the result of 16 — the maximum possible result. | 70 | [
{
"input": "10",
"output": "16"
},
{
"input": "8",
"output": "15"
},
{
"input": "4",
"output": "7"
},
{
"input": "36",
"output": "67"
},
{
"input": "32",
"output": "63"
},
{
"input": "46",
"output": "70"
},
{
"input": "6",
"output": "10... | 1,591,354,571 | 8,471 | Python 3 | WRONG_ANSWER | TESTS2 | 3 | 186 | 0 |
number = int(input())
def rectangularGame(currentNum):
if currentNum == 1:
return 1
else:
numSqrt = int(currentNum**0.5)
div = 1
for i in range(1,numSqrt+1):
if currentNum%i == 0:
div = i
if div == 1:
return currentNum + 1
else:
return currentNum + rectangularGame(int(currentNum/div))
print(rectangularGame(number)) | Title: Rectangular Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has *n* pebbles. He arranges them in *a* equal rows, each row has *b* pebbles (*a*<=><=1). Note that the Beaver must use all the pebbles he has, i. e. *n*<==<=*a*·*b*.
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, *b* pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of *a* and *b*) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers *c*1,<=...,<=*c**k*, where:
- *c*1<==<=*n* - *c**i*<=+<=1 is the number of pebbles that the Beaver ends up with after the *i*-th move, that is, the number of pebbles in a row after some arrangement of *c**i* pebbles (1<=≤<=*i*<=<<=*k*). Note that *c**i*<=><=*c**i*<=+<=1. - *c**k*<==<=1
The result of the game is the sum of numbers *c**i*. You are given *n*. Find the maximum possible result of the game.
Input Specification:
The single line of the input contains a single integer *n* — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
- 2<=≤<=*n*<=≤<=50
The input limitations for getting 100 points are:
- 2<=≤<=*n*<=≤<=109
Output Specification:
Print a single number — the maximum possible result of the game.
Demo Input:
['10\n', '8\n']
Demo Output:
['16\n', '15\n']
Note:
Consider the first example (*c*<sub class="lower-index">1</sub> = 10). The possible options for the game development are:
- Arrange the pebbles in 10 rows, one pebble per row. Then *c*<sub class="lower-index">2</sub> = 1, and the game ends after the first move with the result of 11. - Arrange the pebbles in 5 rows, two pebbles per row. Then *c*<sub class="lower-index">2</sub> = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. *c*<sub class="lower-index">3</sub> = 1, and the game ends with the result of 13. - Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to *c*<sub class="lower-index">2</sub> = 5, *c*<sub class="lower-index">3</sub> = 1, and the game ends with the result of 16 — the maximum possible result. | ```python
number = int(input())
def rectangularGame(currentNum):
if currentNum == 1:
return 1
else:
numSqrt = int(currentNum**0.5)
div = 1
for i in range(1,numSqrt+1):
if currentNum%i == 0:
div = i
if div == 1:
return currentNum + 1
else:
return currentNum + rectangularGame(int(currentNum/div))
print(rectangularGame(number))
``` | 0 | |
586 | A | Alena's Schedule | PROGRAMMING | 900 | [
"implementation"
] | null | null | Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.
One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).
The University works in such a way that every day it holds exactly *n* lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks).
The official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the *n* pairs she knows if there will be a class at that time or not.
Alena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university.
Of course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home.
Alena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair. | The first line of the input contains a positive integer *n* (1<=≤<=*n*<=≤<=100) — the number of lessons at the university.
The second line contains *n* numbers *a**i* (0<=≤<=*a**i*<=≤<=1). Number *a**i* equals 0, if Alena doesn't have the *i*-th pairs, otherwise it is equal to 1. Numbers *a*1,<=*a*2,<=...,<=*a**n* are separated by spaces. | Print a single number — the number of pairs during which Alena stays at the university. | [
"5\n0 1 0 1 1\n",
"7\n1 0 1 0 0 1 0\n",
"1\n0\n"
] | [
"4\n",
"4\n",
"0\n"
] | In the first sample Alena stays at the university from the second to the fifth pair, inclusive, during the third pair she will be it the university waiting for the next pair.
In the last sample Alena doesn't have a single pair, so she spends all the time at home. | 500 | [
{
"input": "5\n0 1 0 1 1",
"output": "4"
},
{
"input": "7\n1 0 1 0 0 1 0",
"output": "4"
},
{
"input": "1\n0",
"output": "0"
},
{
"input": "1\n1",
"output": "1"
},
{
"input": "2\n0 0",
"output": "0"
},
{
"input": "2\n0 1",
"output": "1"
},
{
... | 1,461,561,251 | 2,147,483,647 | Python 3 | OK | TESTS | 60 | 77 | 5,222,400 | n = int(input())
schedule = [int(i) for i in input().split()]
pos = 0
time = 0
# Go to the first 1 to start
while pos < len(schedule) and schedule[pos] == 0:
pos += 1
if pos == len(schedule): # No 1s in the list at all
pass
else:
time = 1
pos += 1 # Starts out after the first one
while True:
if pos == len(schedule): # At the end
break
elif schedule[pos] == 1: # A one--advance to the next spot
time += 1
pos += 1
elif pos == len(schedule)-1: # A single zero at the end
break
elif schedule[pos+1] == 1: # Only one zero--she must stay
time += 2
pos += 2
else: # The double zero case--find the next one
while pos < len(schedule) and schedule[pos] == 0:
pos += 1
print (time)
| Title: Alena's Schedule
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.
One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).
The University works in such a way that every day it holds exactly *n* lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks).
The official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the *n* pairs she knows if there will be a class at that time or not.
Alena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university.
Of course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home.
Alena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair.
Input Specification:
The first line of the input contains a positive integer *n* (1<=≤<=*n*<=≤<=100) — the number of lessons at the university.
The second line contains *n* numbers *a**i* (0<=≤<=*a**i*<=≤<=1). Number *a**i* equals 0, if Alena doesn't have the *i*-th pairs, otherwise it is equal to 1. Numbers *a*1,<=*a*2,<=...,<=*a**n* are separated by spaces.
Output Specification:
Print a single number — the number of pairs during which Alena stays at the university.
Demo Input:
['5\n0 1 0 1 1\n', '7\n1 0 1 0 0 1 0\n', '1\n0\n']
Demo Output:
['4\n', '4\n', '0\n']
Note:
In the first sample Alena stays at the university from the second to the fifth pair, inclusive, during the third pair she will be it the university waiting for the next pair.
In the last sample Alena doesn't have a single pair, so she spends all the time at home. | ```python
n = int(input())
schedule = [int(i) for i in input().split()]
pos = 0
time = 0
# Go to the first 1 to start
while pos < len(schedule) and schedule[pos] == 0:
pos += 1
if pos == len(schedule): # No 1s in the list at all
pass
else:
time = 1
pos += 1 # Starts out after the first one
while True:
if pos == len(schedule): # At the end
break
elif schedule[pos] == 1: # A one--advance to the next spot
time += 1
pos += 1
elif pos == len(schedule)-1: # A single zero at the end
break
elif schedule[pos+1] == 1: # Only one zero--she must stay
time += 2
pos += 2
else: # The double zero case--find the next one
while pos < len(schedule) and schedule[pos] == 0:
pos += 1
print (time)
``` | 3 | |
9 | A | Die Roll | PROGRAMMING | 800 | [
"math",
"probabilities"
] | A. Die Roll | 1 | 64 | Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.
But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.
Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.
It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win. | The only line of the input file contains two natural numbers Y and W — the results of Yakko's and Wakko's die rolls. | Output the required probability in the form of irreducible fraction in format «A/B», where A — the numerator, and B — the denominator. If the required probability equals to zero, output «0/1». If the required probability equals to 1, output «1/1». | [
"4 2\n"
] | [
"1/2\n"
] | Dot will go to Transylvania, if she is lucky to roll 4, 5 or 6 points. | 0 | [
{
"input": "4 2",
"output": "1/2"
},
{
"input": "1 1",
"output": "1/1"
},
{
"input": "1 2",
"output": "5/6"
},
{
"input": "1 3",
"output": "2/3"
},
{
"input": "1 4",
"output": "1/2"
},
{
"input": "1 5",
"output": "1/3"
},
{
"input": "1 6",
... | 1,597,236,893 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 186 | 6,656,000 | from math import gcd
n,m=map(int,input().split())
l=max(n,m)
x=7-l
y=6
d=gcd(x,y)
x=x//d
y=y//d
print(str(x)+'/'+str(6)) | Title: Die Roll
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.
But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.
Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.
It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
Input Specification:
The only line of the input file contains two natural numbers Y and W — the results of Yakko's and Wakko's die rolls.
Output Specification:
Output the required probability in the form of irreducible fraction in format «A/B», where A — the numerator, and B — the denominator. If the required probability equals to zero, output «0/1». If the required probability equals to 1, output «1/1».
Demo Input:
['4 2\n']
Demo Output:
['1/2\n']
Note:
Dot will go to Transylvania, if she is lucky to roll 4, 5 or 6 points. | ```python
from math import gcd
n,m=map(int,input().split())
l=max(n,m)
x=7-l
y=6
d=gcd(x,y)
x=x//d
y=y//d
print(str(x)+'/'+str(6))
``` | 0 |
725 | A | Jumping Ball | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of *n* bumpers. The bumpers are numbered with integers from 1 to *n* from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position *i* it goes one position to the right (to the position *i*<=+<=1) if the type of this bumper is '>', or one position to the left (to *i*<=-<=1) if the type of the bumper at position *i* is '<'. If there is no such position, in other words if *i*<=-<=1<=<<=1 or *i*<=+<=1<=><=*n*, the ball falls from the game field.
Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=200<=000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the *i*-th position of this string corresponds to the type of the *i*-th bumper. | Print one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | [
"4\n<<><\n",
"5\n>>>>>\n",
"4\n>><<\n"
] | [
"2",
"5",
"0"
] | In the first sample, the ball will fall from the field if starts at position 1 or position 2.
In the second sample, any starting position will result in the ball falling from the field. | 500 | [
{
"input": "4\n<<><",
"output": "2"
},
{
"input": "5\n>>>>>",
"output": "5"
},
{
"input": "4\n>><<",
"output": "0"
},
{
"input": "3\n<<>",
"output": "3"
},
{
"input": "3\n<<<",
"output": "3"
},
{
"input": "3\n><<",
"output": "0"
},
{
"input... | 1,548,845,758 | 1,258 | PyPy 3 | WRONG_ANSWER | TESTS | 1 | 109 | 0 | n=int(input())
a=input()
sum=0
for i in range(len(a)):
if(a[i]=="<"):
sum+=1
else:
break
for i in range(-1,-len(a)):
if(a[i]==">"):
sum+=1
else:
break
print(sum)
| Title: Jumping Ball
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of *n* bumpers. The bumpers are numbered with integers from 1 to *n* from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position *i* it goes one position to the right (to the position *i*<=+<=1) if the type of this bumper is '>', or one position to the left (to *i*<=-<=1) if the type of the bumper at position *i* is '<'. If there is no such position, in other words if *i*<=-<=1<=<<=1 or *i*<=+<=1<=><=*n*, the ball falls from the game field.
Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.
Input Specification:
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=200<=000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the *i*-th position of this string corresponds to the type of the *i*-th bumper.
Output Specification:
Print one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.
Demo Input:
['4\n<<><\n', '5\n>>>>>\n', '4\n>><<\n']
Demo Output:
['2', '5', '0']
Note:
In the first sample, the ball will fall from the field if starts at position 1 or position 2.
In the second sample, any starting position will result in the ball falling from the field. | ```python
n=int(input())
a=input()
sum=0
for i in range(len(a)):
if(a[i]=="<"):
sum+=1
else:
break
for i in range(-1,-len(a)):
if(a[i]==">"):
sum+=1
else:
break
print(sum)
``` | 0 | |
29 | A | Spit Problem | PROGRAMMING | 1,000 | [
"brute force"
] | A. Spit Problem | 2 | 256 | In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
The trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists. | The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the amount of camels in the zoo. Each of the following *n* lines contains two integers *x**i* and *d**i* (<=-<=104<=≤<=*x**i*<=≤<=104,<=1<=≤<=|*d**i*|<=≤<=2·104) — records in Bob's notepad. *x**i* is a position of the *i*-th camel, and *d**i* is a distance at which the *i*-th camel spitted. Positive values of *d**i* correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position. | If there are two camels, which spitted at each other, output YES. Otherwise, output NO. | [
"2\n0 1\n1 -1\n",
"3\n0 1\n1 1\n2 -2\n",
"5\n2 -10\n3 10\n0 5\n5 -5\n10 1\n"
] | [
"YES\n",
"NO\n",
"YES\n"
] | none | 500 | [
{
"input": "2\n0 1\n1 -1",
"output": "YES"
},
{
"input": "3\n0 1\n1 1\n2 -2",
"output": "NO"
},
{
"input": "5\n2 -10\n3 10\n0 5\n5 -5\n10 1",
"output": "YES"
},
{
"input": "10\n-9897 -1144\n-4230 -6350\n2116 -3551\n-3635 4993\n3907 -9071\n-2362 4120\n-6542 984\n5807 3745\n759... | 1,667,441,733 | 2,147,483,647 | Python 3 | OK | TESTS | 30 | 92 | 0 | n=int(input())
X=[]
XD=False
for i in range(n):
x,d=list(map(int,input().split(' ')))
X.append([x,x+d])
if([x+d,x] in X):
XD=True
if XD: print('YES')
else: print('NO') | Title: Spit Problem
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
The trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the amount of camels in the zoo. Each of the following *n* lines contains two integers *x**i* and *d**i* (<=-<=104<=≤<=*x**i*<=≤<=104,<=1<=≤<=|*d**i*|<=≤<=2·104) — records in Bob's notepad. *x**i* is a position of the *i*-th camel, and *d**i* is a distance at which the *i*-th camel spitted. Positive values of *d**i* correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position.
Output Specification:
If there are two camels, which spitted at each other, output YES. Otherwise, output NO.
Demo Input:
['2\n0 1\n1 -1\n', '3\n0 1\n1 1\n2 -2\n', '5\n2 -10\n3 10\n0 5\n5 -5\n10 1\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
none | ```python
n=int(input())
X=[]
XD=False
for i in range(n):
x,d=list(map(int,input().split(' ')))
X.append([x,x+d])
if([x+d,x] in X):
XD=True
if XD: print('YES')
else: print('NO')
``` | 3.977 |
102 | B | Sum of Digits | PROGRAMMING | 1,000 | [
"implementation"
] | B. Sum of Digits | 2 | 265 | Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit? | The first line contains the only integer *n* (0<=≤<=*n*<=≤<=10100000). It is guaranteed that *n* doesn't contain any leading zeroes. | Print the number of times a number can be replaced by the sum of its digits until it only contains one digit. | [
"0\n",
"10\n",
"991\n"
] | [
"0\n",
"1\n",
"3\n"
] | In the first sample the number already is one-digit — Herald can't cast a spell.
The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.
The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit. | 1,000 | [
{
"input": "0",
"output": "0"
},
{
"input": "10",
"output": "1"
},
{
"input": "991",
"output": "3"
},
{
"input": "99",
"output": "2"
},
{
"input": "100",
"output": "1"
},
{
"input": "123456789",
"output": "2"
},
{
"input": "32",
"output... | 1,600,067,636 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 5 | 218 | 0 | n=input()
l=list(n)
len=len(l)
if ('0' in l):
x=l.count('0')
print(len-x)
else:
print(len)
| Title: Sum of Digits
Time Limit: 2 seconds
Memory Limit: 265 megabytes
Problem Description:
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit?
Input Specification:
The first line contains the only integer *n* (0<=≤<=*n*<=≤<=10100000). It is guaranteed that *n* doesn't contain any leading zeroes.
Output Specification:
Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.
Demo Input:
['0\n', '10\n', '991\n']
Demo Output:
['0\n', '1\n', '3\n']
Note:
In the first sample the number already is one-digit — Herald can't cast a spell.
The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.
The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit. | ```python
n=input()
l=list(n)
len=len(l)
if ('0' in l):
x=l.count('0')
print(len-x)
else:
print(len)
``` | 0 |
879 | B | Table Tennis | PROGRAMMING | 1,200 | [
"data structures",
"implementation"
] | null | null | *n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner. | The first line contains two integers: *n* and *k* (2<=≤<=*n*<=≤<=500, 2<=≤<=*k*<=≤<=1012) — the number of people and the number of wins.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all *a**i* are distinct. | Output a single integer — power of the winner. | [
"2 2\n1 2\n",
"4 2\n3 1 2 4\n",
"6 2\n6 5 3 1 2 4\n",
"2 10000000000\n2 1\n"
] | [
"2 ",
"3 ",
"6 ",
"2\n"
] | Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 1,000 | [
{
"input": "2 2\n1 2",
"output": "2 "
},
{
"input": "4 2\n3 1 2 4",
"output": "3 "
},
{
"input": "6 2\n6 5 3 1 2 4",
"output": "6 "
},
{
"input": "2 10000000000\n2 1",
"output": "2"
},
{
"input": "4 4\n1 3 4 2",
"output": "4 "
},
{
"input": "2 21474836... | 1,606,899,584 | 2,147,483,647 | Python 3 | OK | TESTS | 43 | 108 | 0 | def get_input():
return list(map(lambda x : int(x), input().split(" ")))
pair = get_input()
power = get_input()
winner = power[0]
counter = 0
for i in range(1, pair[0]):
if winner < power[i]:
counter = 1
winner = power[i]
else:
counter += 1
if counter >= pair[1]: break
print(winner)
| Title: Table Tennis
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
*n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input Specification:
The first line contains two integers: *n* and *k* (2<=≤<=*n*<=≤<=500, 2<=≤<=*k*<=≤<=1012) — the number of people and the number of wins.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all *a**i* are distinct.
Output Specification:
Output a single integer — power of the winner.
Demo Input:
['2 2\n1 2\n', '4 2\n3 1 2 4\n', '6 2\n6 5 3 1 2 4\n', '2 10000000000\n2 1\n']
Demo Output:
['2 ', '3 ', '6 ', '2\n']
Note:
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | ```python
def get_input():
return list(map(lambda x : int(x), input().split(" ")))
pair = get_input()
power = get_input()
winner = power[0]
counter = 0
for i in range(1, pair[0]):
if winner < power[i]:
counter = 1
winner = power[i]
else:
counter += 1
if counter >= pair[1]: break
print(winner)
``` | 3 | |
696 | A | Lorenzo Von Matterhorn | PROGRAMMING | 1,500 | [
"brute force",
"data structures",
"implementation",
"trees"
] | null | null | Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections *i* and 2*i* and another road between *i* and 2*i*<=+<=1 for every positive integer *i*. You can clearly see that there exists a unique shortest path between any two intersections.
Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will *q* consecutive events happen soon. There are two types of events:
1. Government makes a new rule. A rule can be denoted by integers *v*, *u* and *w*. As the result of this action, the passing fee of all roads on the shortest path from *u* to *v* increases by *w* dollars.
2. Barney starts moving from some intersection *v* and goes to intersection *u* where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.
Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). | The first line of input contains a single integer *q* (1<=≤<=*q*<=≤<=1<=000).
The next *q* lines contain the information about the events in chronological order. Each event is described in form 1 *v* *u* *w* if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from *u* to *v* by *w* dollars, or in form 2 *v* *u* if it's an event when Barnie goes to cuddle from the intersection *v* to the intersection *u*.
1<=≤<=*v*,<=*u*<=≤<=1018,<=*v*<=≠<=*u*,<=1<=≤<=*w*<=≤<=109 states for every description line. | For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. | [
"7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4\n"
] | [
"94\n0\n32\n"
] | In the example testcase:
Here are the intersections used:
1. Intersections on the path are 3, 1, 2 and 4. 1. Intersections on the path are 4, 2 and 1. 1. Intersections on the path are only 3 and 6. 1. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 1. Intersections on the path are 6, 3 and 1. 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 1. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). | 500 | [
{
"input": "7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4",
"output": "94\n0\n32"
},
{
"input": "1\n2 666077344481199252 881371880336470888",
"output": "0"
},
{
"input": "10\n1 1 63669439577744021 396980128\n1 2582240553355225 63669439577744021 997926286\n1 258224055335522... | 1,469,150,642 | 2,147,483,647 | PyPy 3 | OK | TESTS | 49 | 389 | 8,806,400 |
def add_edges(s1, s2, w):
global edges
i = 0
while i < len(s1) and i < len(s2) and s1[i] == s2[i]:
i += 1
j = len(s1)
while j > i:
if s1[:j] in edges:
edges[s1[:j]] += w
else:
edges[s1[:j]] = w
j -= 1
j = len(s2)
while j > i:
if s2[:j] in edges:
edges[s2[:j]] += w
else:
edges[s2[:j]] = w
j -= 1
def way(s1, s2):
global edges
i = 0
while i < len(s1) and i < len(s2) and s1[i] == s2[i]:
i += 1
w = 0
j = len(s1)
while j > i:
if s1[:j] in edges:
w += edges[s1[:j]]
j -= 1
j = len(s2)
while j > i:
if s2[:j] in edges:
w += edges[s2[:j]]
j -= 1
return w
q = int(input())
edges = dict()
for i in range(q):
l = list(map(int, input().split()))
if l[0] == 1:
l[1] = bin(l[1])
l[1] = l[1][2:]
l[2] = bin(l[2])
l[2] = l[2][2:]
add_edges(l[1], l[2], l[3])
if l[0] == 2:
l[1] = bin(l[1])
l[1] = l[1][2:]
l[2] = bin(l[2])
l[2] = l[2][2:]
print(way(l[1], l[2]))
| Title: Lorenzo Von Matterhorn
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections *i* and 2*i* and another road between *i* and 2*i*<=+<=1 for every positive integer *i*. You can clearly see that there exists a unique shortest path between any two intersections.
Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will *q* consecutive events happen soon. There are two types of events:
1. Government makes a new rule. A rule can be denoted by integers *v*, *u* and *w*. As the result of this action, the passing fee of all roads on the shortest path from *u* to *v* increases by *w* dollars.
2. Barney starts moving from some intersection *v* and goes to intersection *u* where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.
Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
Input Specification:
The first line of input contains a single integer *q* (1<=≤<=*q*<=≤<=1<=000).
The next *q* lines contain the information about the events in chronological order. Each event is described in form 1 *v* *u* *w* if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from *u* to *v* by *w* dollars, or in form 2 *v* *u* if it's an event when Barnie goes to cuddle from the intersection *v* to the intersection *u*.
1<=≤<=*v*,<=*u*<=≤<=1018,<=*v*<=≠<=*u*,<=1<=≤<=*w*<=≤<=109 states for every description line.
Output Specification:
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
Demo Input:
['7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4\n']
Demo Output:
['94\n0\n32\n']
Note:
In the example testcase:
Here are the intersections used:
1. Intersections on the path are 3, 1, 2 and 4. 1. Intersections on the path are 4, 2 and 1. 1. Intersections on the path are only 3 and 6. 1. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 1. Intersections on the path are 6, 3 and 1. 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 1. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). | ```python
def add_edges(s1, s2, w):
global edges
i = 0
while i < len(s1) and i < len(s2) and s1[i] == s2[i]:
i += 1
j = len(s1)
while j > i:
if s1[:j] in edges:
edges[s1[:j]] += w
else:
edges[s1[:j]] = w
j -= 1
j = len(s2)
while j > i:
if s2[:j] in edges:
edges[s2[:j]] += w
else:
edges[s2[:j]] = w
j -= 1
def way(s1, s2):
global edges
i = 0
while i < len(s1) and i < len(s2) and s1[i] == s2[i]:
i += 1
w = 0
j = len(s1)
while j > i:
if s1[:j] in edges:
w += edges[s1[:j]]
j -= 1
j = len(s2)
while j > i:
if s2[:j] in edges:
w += edges[s2[:j]]
j -= 1
return w
q = int(input())
edges = dict()
for i in range(q):
l = list(map(int, input().split()))
if l[0] == 1:
l[1] = bin(l[1])
l[1] = l[1][2:]
l[2] = bin(l[2])
l[2] = l[2][2:]
add_edges(l[1], l[2], l[3])
if l[0] == 2:
l[1] = bin(l[1])
l[1] = l[1][2:]
l[2] = bin(l[2])
l[2] = l[2][2:]
print(way(l[1], l[2]))
``` | 3 | |
95 | B | Lucky Numbers | PROGRAMMING | 1,800 | [
"dp",
"greedy"
] | B. Lucky Numbers | 2 | 256 | Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.
One day Petya came across a positive integer *n*. Help him to find the least super lucky number which is not less than *n*. | The only line contains a positive integer *n* (1<=≤<=*n*<=≤<=10100000). This number doesn't have leading zeroes. | Output the least super lucky number that is more than or equal to *n*. | [
"4500\n",
"47\n"
] | [
"4747\n",
"47\n"
] | none | 1,000 | [
{
"input": "4500",
"output": "4747"
},
{
"input": "47",
"output": "47"
},
{
"input": "1",
"output": "47"
},
{
"input": "12",
"output": "47"
},
{
"input": "4587",
"output": "4747"
},
{
"input": "100",
"output": "4477"
},
{
"input": "1007",
... | 1,577,276,723 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 47 | 2,000 | 2,560,000 | n = input()
l = len(n)
if l % 2 == 1:
print('4' * (l // 2 + 1) + '7' * (l // 2 + 1))
exit(0)
if n > ('7' * (l // 2) + '4' * (l // 2)):
print('4' * (l // 2 + 1) + '7' * (l // 2 + 1))
exit(0)
result = ''
for i in range(l):
d = int(n[i])
if d < 4:
result += '4'
result += '4' * (l - i - 1)
break
elif d == 4:
result += '4'
elif d < 7:
result += '7'
result += '4' * (l - i - 1)
break
elif d == 7:
result += '7'
else:
k = i - 1
while result[k] == '7':
k -= 1
result = result[:k] + '7' + '4' * (l - k - 1)
break
diff = (result.count('7') - result.count('4')) // 2
if diff > 0:
count = 0
last_4 = -1
for k in range(l):
if result[k] == '7':
count += 1
if result[k] == '4':
last_4 = k
if count == l // 2:
result = result[:last_4] + '7' + result[last_4+1:]
result = result[:k] + '4' * (l - k)
elif diff < 0:
k = l - 1
while diff != 0:
if result[k] == '4':
result = result[:k] + '7' + result[k+1:]
diff += 1
k -= 1
print(result)
| Title: Lucky Numbers
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.
One day Petya came across a positive integer *n*. Help him to find the least super lucky number which is not less than *n*.
Input Specification:
The only line contains a positive integer *n* (1<=≤<=*n*<=≤<=10100000). This number doesn't have leading zeroes.
Output Specification:
Output the least super lucky number that is more than or equal to *n*.
Demo Input:
['4500\n', '47\n']
Demo Output:
['4747\n', '47\n']
Note:
none | ```python
n = input()
l = len(n)
if l % 2 == 1:
print('4' * (l // 2 + 1) + '7' * (l // 2 + 1))
exit(0)
if n > ('7' * (l // 2) + '4' * (l // 2)):
print('4' * (l // 2 + 1) + '7' * (l // 2 + 1))
exit(0)
result = ''
for i in range(l):
d = int(n[i])
if d < 4:
result += '4'
result += '4' * (l - i - 1)
break
elif d == 4:
result += '4'
elif d < 7:
result += '7'
result += '4' * (l - i - 1)
break
elif d == 7:
result += '7'
else:
k = i - 1
while result[k] == '7':
k -= 1
result = result[:k] + '7' + '4' * (l - k - 1)
break
diff = (result.count('7') - result.count('4')) // 2
if diff > 0:
count = 0
last_4 = -1
for k in range(l):
if result[k] == '7':
count += 1
if result[k] == '4':
last_4 = k
if count == l // 2:
result = result[:last_4] + '7' + result[last_4+1:]
result = result[:k] + '4' * (l - k)
elif diff < 0:
k = l - 1
while diff != 0:
if result[k] == '4':
result = result[:k] + '7' + result[k+1:]
diff += 1
k -= 1
print(result)
``` | 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,228,566 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 9 | 31 | 0 | a=input()
x="yes"
for i in range(len(a)-1):
if a[i] not in 'naeiou' and a[i+1] not in 'aeiou':
x="no"
print(x) | 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()
x="yes"
for i in range(len(a)-1):
if a[i] not in 'naeiou' and a[i+1] not in 'aeiou':
x="no"
print(x)
``` | 0 | |
863 | A | Quasi-palindrome | PROGRAMMING | 900 | [
"brute force",
"implementation"
] | null | null | Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.
String *t* is called a palindrome, if it reads the same from left to right and from right to left.
For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strings "131" and "002010200", respectively, which are palindromes.
You are given some integer number *x*. Check if it's a quasi-palindromic number. | The first line contains one integer number *x* (1<=≤<=*x*<=≤<=109). This number is given without any leading zeroes. | Print "YES" if number *x* is quasi-palindromic. Otherwise, print "NO" (without quotes). | [
"131\n",
"320\n",
"2010200\n"
] | [
"YES\n",
"NO\n",
"YES\n"
] | none | 0 | [
{
"input": "131",
"output": "YES"
},
{
"input": "320",
"output": "NO"
},
{
"input": "2010200",
"output": "YES"
},
{
"input": "1",
"output": "YES"
},
{
"input": "1000000000",
"output": "YES"
},
{
"input": "999999999",
"output": "YES"
},
{
"i... | 1,516,992,698 | 2,147,483,647 | Python 3 | OK | TESTS | 44 | 62 | 5,632,000 | x=input()
j=""
def check(x):
j="YES"
for i in range(len(x)//2):
if x[i]!=x[(len(x)-1)-i]:
j="NO"
return j
cx=""
if check(x)=="YES":
j="YES"
else:
j="NO"
for i in range(1,len(x)):
cx="0"*i
cx=cx+x
if check(cx)=="YES":
j="YES"
break
print(j)
| Title: Quasi-palindrome
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.
String *t* is called a palindrome, if it reads the same from left to right and from right to left.
For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strings "131" and "002010200", respectively, which are palindromes.
You are given some integer number *x*. Check if it's a quasi-palindromic number.
Input Specification:
The first line contains one integer number *x* (1<=≤<=*x*<=≤<=109). This number is given without any leading zeroes.
Output Specification:
Print "YES" if number *x* is quasi-palindromic. Otherwise, print "NO" (without quotes).
Demo Input:
['131\n', '320\n', '2010200\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
none | ```python
x=input()
j=""
def check(x):
j="YES"
for i in range(len(x)//2):
if x[i]!=x[(len(x)-1)-i]:
j="NO"
return j
cx=""
if check(x)=="YES":
j="YES"
else:
j="NO"
for i in range(1,len(x)):
cx="0"*i
cx=cx+x
if check(cx)=="YES":
j="YES"
break
print(j)
``` | 3 | |
119 | A | Epic Game | PROGRAMMING | 800 | [
"implementation"
] | null | null | Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take).
Your task is to determine by the given *a*, *b* and *n* who wins the game. | The only string contains space-separated integers *a*, *b* and *n* (1<=≤<=*a*,<=*b*,<=*n*<=≤<=100) — the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. | If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). | [
"3 5 9\n",
"1 1 100\n"
] | [
"0",
"1"
] | The greatest common divisor of two non-negative integers *a* and *b* is such maximum positive integer *k*, that *a* is divisible by *k* without remainder and similarly, *b* is divisible by *k* without remainder. Let *gcd*(*a*, *b*) represent the operation of calculating the greatest common divisor of numbers *a* and *b*. Specifically, *gcd*(*x*, 0) = *gcd*(0, *x*) = *x*.
In the first sample the game will go like that:
- Simon should take *gcd*(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left.- Antisimon should take *gcd*(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left.- Simon should take *gcd*(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left.- Antisimon should take *gcd*(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left.- Simon should take *gcd*(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left.- Antisimon should take *gcd*(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses.
In the second sample each player during each move takes one stone from the heap. As *n* is even, Antisimon takes the last stone and Simon can't make a move after that. | 500 | [
{
"input": "3 5 9",
"output": "0"
},
{
"input": "1 1 100",
"output": "1"
},
{
"input": "23 12 16",
"output": "1"
},
{
"input": "95 26 29",
"output": "1"
},
{
"input": "73 32 99",
"output": "1"
},
{
"input": "1 1 1",
"output": "0"
},
{
"inpu... | 1,566,376,262 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 5 | 218 | 0 | def GCD(a,b):
if b==0:
return a
return GCD(b,a%b)
a,b,c = [int(i) for i in input().split()]
y = a
while(c>0):
x = GCD(y,c)
if c-x>=0:
c -= x
if y==a:
y=b
else:
y=a
if y==a:
print('1')
else:
print('0') | Title: Epic Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take).
Your task is to determine by the given *a*, *b* and *n* who wins the game.
Input Specification:
The only string contains space-separated integers *a*, *b* and *n* (1<=≤<=*a*,<=*b*,<=*n*<=≤<=100) — the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile.
Output Specification:
If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes).
Demo Input:
['3 5 9\n', '1 1 100\n']
Demo Output:
['0', '1']
Note:
The greatest common divisor of two non-negative integers *a* and *b* is such maximum positive integer *k*, that *a* is divisible by *k* without remainder and similarly, *b* is divisible by *k* without remainder. Let *gcd*(*a*, *b*) represent the operation of calculating the greatest common divisor of numbers *a* and *b*. Specifically, *gcd*(*x*, 0) = *gcd*(0, *x*) = *x*.
In the first sample the game will go like that:
- Simon should take *gcd*(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left.- Antisimon should take *gcd*(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left.- Simon should take *gcd*(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left.- Antisimon should take *gcd*(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left.- Simon should take *gcd*(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left.- Antisimon should take *gcd*(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses.
In the second sample each player during each move takes one stone from the heap. As *n* is even, Antisimon takes the last stone and Simon can't make a move after that. | ```python
def GCD(a,b):
if b==0:
return a
return GCD(b,a%b)
a,b,c = [int(i) for i in input().split()]
y = a
while(c>0):
x = GCD(y,c)
if c-x>=0:
c -= x
if y==a:
y=b
else:
y=a
if y==a:
print('1')
else:
print('0')
``` | 0 | |
32 | B | Borze | PROGRAMMING | 800 | [
"expression parsing",
"implementation"
] | B. Borze | 2 | 256 | Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet. | The first line contains a number in Borze code. The length of the string is between 1 and 200 characters. It's guaranteed that the given string is a valid Borze code of some ternary number (this number can have leading zeroes). | Output the decoded ternary number. It can have leading zeroes. | [
".-.--\n",
"--.\n",
"-..-.--\n"
] | [
"012",
"20",
"1012"
] | none | 1,000 | [
{
"input": ".-.--",
"output": "012"
},
{
"input": "--.",
"output": "20"
},
{
"input": "-..-.--",
"output": "1012"
},
{
"input": "---..",
"output": "210"
},
{
"input": "..--.---..",
"output": "0020210"
},
{
"input": "-.....----.",
"output": "1000022... | 1,682,570,515 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 92 | 0 | input_code = input()
output = ""
i = 0
while i < len(input_code) - 1:
if input_code[i] == "-":
if input_code[i + 1] == "-":
output += "2"
elif input_code[i + 1] == ".":
output += "1"
i += 2
continue
elif input_code[i] == ".":
output += "0"
i += 1
print(output)
| Title: Borze
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input Specification:
The first line contains a number in Borze code. The length of the string is between 1 and 200 characters. It's guaranteed that the given string is a valid Borze code of some ternary number (this number can have leading zeroes).
Output Specification:
Output the decoded ternary number. It can have leading zeroes.
Demo Input:
['.-.--\n', '--.\n', '-..-.--\n']
Demo Output:
['012', '20', '1012']
Note:
none | ```python
input_code = input()
output = ""
i = 0
while i < len(input_code) - 1:
if input_code[i] == "-":
if input_code[i + 1] == "-":
output += "2"
elif input_code[i + 1] == ".":
output += "1"
i += 2
continue
elif input_code[i] == ".":
output += "0"
i += 1
print(output)
``` | 0 |
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,673,087,001 | 2,147,483,647 | Python 3 | OK | TESTS | 20 | 46 | 0 | k=input()
k=k.split(' ')
m=int(k[0])
n=int(k[1])
a=int(k[2])
if m//a==m/a:
l=m/a
else:
l=(m//a)+1
if n//a==n/a:
b=n/a
else:
b=(n//a)+1
print(int(l*b)) | 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
k=input()
k=k.split(' ')
m=int(k[0])
n=int(k[1])
a=int(k[2])
if m//a==m/a:
l=m/a
else:
l=(m//a)+1
if n//a==n/a:
b=n/a
else:
b=(n//a)+1
print(int(l*b))
``` | 3.977 |
812 | A | Sagheer and Crossroads | PROGRAMMING | 1,200 | [
"implementation"
] | null | null | Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane getting into the intersection (*l* — left, *s* — straight, *r* — right) and a light *p* for a pedestrian crossing.
An accident is possible if a car can hit a pedestrian. This can happen if the light of a pedestrian crossing of some part and the light of a lane that can get to or from that same part are green at the same time.
Now, Sagheer is monitoring the configuration of the traffic lights. Your task is to help him detect whether an accident is possible. | The input consists of four lines with each line describing a road part given in a counter-clockwise order.
Each line contains four integers *l*, *s*, *r*, *p* — for the left, straight, right and pedestrian lights, respectively. The possible values are 0 for red light and 1 for green light. | On a single line, print "YES" if an accident is possible, and "NO" otherwise. | [
"1 0 0 1\n0 1 0 0\n0 0 1 0\n0 0 0 1\n",
"0 1 1 0\n1 0 1 0\n1 1 0 0\n0 0 0 1\n",
"1 0 0 0\n0 0 0 1\n0 0 0 0\n1 0 1 0\n"
] | [
"YES\n",
"NO\n",
"NO\n"
] | In the first example, some accidents are possible because cars of part 1 can hit pedestrians of parts 1 and 4. Also, cars of parts 2 and 3 can hit pedestrians of part 4.
In the second example, no car can pass the pedestrian crossing of part 4 which is the only green pedestrian light. So, no accident can occur. | 500 | [
{
"input": "1 0 0 1\n0 1 0 0\n0 0 1 0\n0 0 0 1",
"output": "YES"
},
{
"input": "0 1 1 0\n1 0 1 0\n1 1 0 0\n0 0 0 1",
"output": "NO"
},
{
"input": "1 0 0 0\n0 0 0 1\n0 0 0 0\n1 0 1 0",
"output": "NO"
},
{
"input": "0 0 0 0\n0 0 0 1\n0 0 0 1\n0 0 0 1",
"output": "NO"
},
... | 1,500,032,676 | 2,147,483,647 | Python 3 | OK | TESTS | 93 | 62 | 5,529,600 | drgs = []
for i in range(4):
drgs.append([int(i) for i in input().split()])
ok = 1
for i in range(4):
cur = drgs[i]
for j in range(3):
if cur[j]:
if cur[3] or drgs[(3+i-j)%4][3]:
ok = 0
break
if not ok: break
if ok:
print('NO')
else:
print('YES') | Title: Sagheer and Crossroads
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane getting into the intersection (*l* — left, *s* — straight, *r* — right) and a light *p* for a pedestrian crossing.
An accident is possible if a car can hit a pedestrian. This can happen if the light of a pedestrian crossing of some part and the light of a lane that can get to or from that same part are green at the same time.
Now, Sagheer is monitoring the configuration of the traffic lights. Your task is to help him detect whether an accident is possible.
Input Specification:
The input consists of four lines with each line describing a road part given in a counter-clockwise order.
Each line contains four integers *l*, *s*, *r*, *p* — for the left, straight, right and pedestrian lights, respectively. The possible values are 0 for red light and 1 for green light.
Output Specification:
On a single line, print "YES" if an accident is possible, and "NO" otherwise.
Demo Input:
['1 0 0 1\n0 1 0 0\n0 0 1 0\n0 0 0 1\n', '0 1 1 0\n1 0 1 0\n1 1 0 0\n0 0 0 1\n', '1 0 0 0\n0 0 0 1\n0 0 0 0\n1 0 1 0\n']
Demo Output:
['YES\n', 'NO\n', 'NO\n']
Note:
In the first example, some accidents are possible because cars of part 1 can hit pedestrians of parts 1 and 4. Also, cars of parts 2 and 3 can hit pedestrians of part 4.
In the second example, no car can pass the pedestrian crossing of part 4 which is the only green pedestrian light. So, no accident can occur. | ```python
drgs = []
for i in range(4):
drgs.append([int(i) for i in input().split()])
ok = 1
for i in range(4):
cur = drgs[i]
for j in range(3):
if cur[j]:
if cur[3] or drgs[(3+i-j)%4][3]:
ok = 0
break
if not ok: break
if ok:
print('NO')
else:
print('YES')
``` | 3 | |
445 | A | DZY Loves Chessboard | PROGRAMMING | 1,200 | [
"dfs and similar",
"implementation"
] | null | null | DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.
You task is to find any suitable placement of chessmen on the given chessboard. | The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100).
Each of the next *n* lines contains a string of *m* characters: the *j*-th character of the *i*-th string is either "." or "-". A "." means that the corresponding cell (in the *i*-th row and the *j*-th column) is good, while a "-" means it is bad. | Output must contain *n* lines, each line must contain a string of *m* characters. The *j*-th character of the *i*-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell.
If multiple answers exist, print any of them. It is guaranteed that at least one answer exists. | [
"1 1\n.\n",
"2 2\n..\n..\n",
"3 3\n.-.\n---\n--."
] | [
"B\n",
"BW\nWB\n",
"B-B\n---\n--B"
] | In the first sample, DZY puts a single black chessman. Of course putting a white one is also OK.
In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output.
In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are. | 500 | [
{
"input": "1 1\n.",
"output": "B"
},
{
"input": "2 2\n..\n..",
"output": "BW\nWB"
},
{
"input": "3 3\n.-.\n---\n--.",
"output": "B-B\n---\n--B"
},
{
"input": "3 1\n-\n.\n.",
"output": "-\nW\nB"
},
{
"input": "11 11\n-----------\n-----------\n-----------\n--------... | 1,679,668,862 | 2,147,483,647 | Python 3 | OK | TESTS | 37 | 46 | 0 | inp=lambda:map(int,input().split())
n, m = inp()
for i in range(n):
s = input()
l=[]
for j in range(len(s)):
if s[j]=='-':
l.append('-')
continue
if (i%2==0 and j%2==0) or (i%2!=0 and j%2!=0):
l.append('B')
if (i%2!=0 and j%2==0) or (i%2==0 and j%2!=0):
l.append('W')
print("".join(l))
| Title: DZY Loves Chessboard
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.
You task is to find any suitable placement of chessmen on the given chessboard.
Input Specification:
The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100).
Each of the next *n* lines contains a string of *m* characters: the *j*-th character of the *i*-th string is either "." or "-". A "." means that the corresponding cell (in the *i*-th row and the *j*-th column) is good, while a "-" means it is bad.
Output Specification:
Output must contain *n* lines, each line must contain a string of *m* characters. The *j*-th character of the *i*-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell.
If multiple answers exist, print any of them. It is guaranteed that at least one answer exists.
Demo Input:
['1 1\n.\n', '2 2\n..\n..\n', '3 3\n.-.\n---\n--.']
Demo Output:
['B\n', 'BW\nWB\n', 'B-B\n---\n--B']
Note:
In the first sample, DZY puts a single black chessman. Of course putting a white one is also OK.
In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output.
In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are. | ```python
inp=lambda:map(int,input().split())
n, m = inp()
for i in range(n):
s = input()
l=[]
for j in range(len(s)):
if s[j]=='-':
l.append('-')
continue
if (i%2==0 and j%2==0) or (i%2!=0 and j%2!=0):
l.append('B')
if (i%2!=0 and j%2==0) or (i%2==0 and j%2!=0):
l.append('W')
print("".join(l))
``` | 3 | |
69 | A | Young Physicist | PROGRAMMING | 1,000 | [
"implementation",
"math"
] | A. Young Physicist | 2 | 256 | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. | The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100), then follow *n* lines containing three integers each: the *x**i* coordinate, the *y**i* coordinate and the *z**i* coordinate of the force vector, applied to the body (<=-<=100<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=100). | Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. | [
"3\n4 1 7\n-2 4 -1\n1 -5 -3\n",
"3\n3 -1 7\n-5 2 -4\n2 -1 -3\n"
] | [
"NO",
"YES"
] | none | 500 | [
{
"input": "3\n4 1 7\n-2 4 -1\n1 -5 -3",
"output": "NO"
},
{
"input": "3\n3 -1 7\n-5 2 -4\n2 -1 -3",
"output": "YES"
},
{
"input": "10\n21 32 -46\n43 -35 21\n42 2 -50\n22 40 20\n-27 -9 38\n-4 1 1\n-40 6 -31\n-13 -2 34\n-21 34 -12\n-32 -29 41",
"output": "NO"
},
{
"input": "10... | 1,594,117,519 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 186 | 6,656,000 | import numpy as np
n=int(input())
l=[]
for i in range(n):
l.append(list(map(int,input().split()[:3])))
suml=[x+y+z for x,y,z in zip(l[0],l[1],l[2])]
z=[0,0,0]
if suml==z:
print("YES")
else:
print("NO")
| Title: Young Physicist
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
Input Specification:
The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100), then follow *n* lines containing three integers each: the *x**i* coordinate, the *y**i* coordinate and the *z**i* coordinate of the force vector, applied to the body (<=-<=100<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=100).
Output Specification:
Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.
Demo Input:
['3\n4 1 7\n-2 4 -1\n1 -5 -3\n', '3\n3 -1 7\n-5 2 -4\n2 -1 -3\n']
Demo Output:
['NO', 'YES']
Note:
none | ```python
import numpy as np
n=int(input())
l=[]
for i in range(n):
l.append(list(map(int,input().split()[:3])))
suml=[x+y+z for x,y,z in zip(l[0],l[1],l[2])]
z=[0,0,0]
if suml==z:
print("YES")
else:
print("NO")
``` | -1 |
36 | A | Extra-terrestrial Intelligence | PROGRAMMING | 1,300 | [
"implementation"
] | A. Extra-terrestrial Intelligence | 2 | 64 | Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for *n* days in a row. Each of those *n* days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not. | The first line contains integer *n* (3<=≤<=*n*<=≤<=100) — amount of days during which Vasya checked if there were any signals. The second line contains *n* characters 1 or 0 — the record Vasya kept each of those *n* days. It’s guaranteed that the given record sequence contains at least three 1s. | If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO. | [
"8\n00111000\n",
"7\n1001011\n",
"7\n1010100\n"
] | [
"YES\n",
"NO\n",
"YES\n"
] | none | 500 | [
{
"input": "8\n00111000",
"output": "YES"
},
{
"input": "7\n1001011",
"output": "NO"
},
{
"input": "7\n1010100",
"output": "YES"
},
{
"input": "5\n10101",
"output": "YES"
},
{
"input": "3\n111",
"output": "YES"
},
{
"input": "10\n0011111011",
"outp... | 1,685,692,507 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 20 | 92 | 0 | def check_extra_terrestrial(n, signals):
indices = [i for i in range(n) if signals[i] == '1']
differences = [indices[i+1] - indices[i] for i in range(len(indices) - 1)]
if len(set(differences)) == 1:
return 'YES'
else:
return 'NO'
with open('input.txt', 'r') as f:
n = int(f.readline().strip())
signals = f.readline().strip()
result = check_extra_terrestrial(n, signals)
with open('output.txt', 'w') as f:
f.write(result)
| Title: Extra-terrestrial Intelligence
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for *n* days in a row. Each of those *n* days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not.
Input Specification:
The first line contains integer *n* (3<=≤<=*n*<=≤<=100) — amount of days during which Vasya checked if there were any signals. The second line contains *n* characters 1 or 0 — the record Vasya kept each of those *n* days. It’s guaranteed that the given record sequence contains at least three 1s.
Output Specification:
If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO.
Demo Input:
['8\n00111000\n', '7\n1001011\n', '7\n1010100\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
none | ```python
def check_extra_terrestrial(n, signals):
indices = [i for i in range(n) if signals[i] == '1']
differences = [indices[i+1] - indices[i] for i in range(len(indices) - 1)]
if len(set(differences)) == 1:
return 'YES'
else:
return 'NO'
with open('input.txt', 'r') as f:
n = int(f.readline().strip())
signals = f.readline().strip()
result = check_extra_terrestrial(n, signals)
with open('output.txt', 'w') as f:
f.write(result)
``` | 3.977 |
461 | A | Appleman and Toastman | PROGRAMMING | 1,200 | [
"greedy",
"sortings"
] | null | null | Appleman and Toastman play a game. Initially Appleman gives one group of *n* numbers to the Toastman, then they start to complete the following tasks:
- Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. - Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.
After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get? | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=3·105). The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=106) — the initial group that is given to Toastman. | Print a single integer — the largest possible score. | [
"3\n3 1 5\n",
"1\n10\n"
] | [
"26\n",
"10\n"
] | Consider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions. | 500 | [
{
"input": "3\n3 1 5",
"output": "26"
},
{
"input": "1\n10",
"output": "10"
},
{
"input": "10\n8 10 2 5 6 2 4 7 2 1",
"output": "376"
},
{
"input": "10\n171308 397870 724672 431255 228496 892002 542924 718337 888642 161821",
"output": "40204082"
},
{
"input": "10\... | 1,595,077,189 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 93 | 6,656,000 | import math
n=int(input())
arr=list(map(int,input().split()))
arr.sort(reverse=True)
a=int(math.log2(n))
b=n-2**a
print(sum(arr)*(a+1)+sum(arr[0:2*b])) | Title: Appleman and Toastman
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Appleman and Toastman play a game. Initially Appleman gives one group of *n* numbers to the Toastman, then they start to complete the following tasks:
- Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. - Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.
After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=3·105). The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=106) — the initial group that is given to Toastman.
Output Specification:
Print a single integer — the largest possible score.
Demo Input:
['3\n3 1 5\n', '1\n10\n']
Demo Output:
['26\n', '10\n']
Note:
Consider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions. | ```python
import math
n=int(input())
arr=list(map(int,input().split()))
arr.sort(reverse=True)
a=int(math.log2(n))
b=n-2**a
print(sum(arr)*(a+1)+sum(arr[0:2*b]))
``` | 0 | |
994 | A | Fingerprints | PROGRAMMING | 800 | [
"implementation"
] | null | null | You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.
Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subsequence of the sequence you have that only contains digits with fingerprints on the corresponding keys. Find such code. | The first line contains two integers $n$ and $m$ ($1 \le n, m \le 10$) representing the number of digits in the sequence you have and the number of keys on the keypad that have fingerprints.
The next line contains $n$ distinct space-separated integers $x_1, x_2, \ldots, x_n$ ($0 \le x_i \le 9$) representing the sequence.
The next line contains $m$ distinct space-separated integers $y_1, y_2, \ldots, y_m$ ($0 \le y_i \le 9$) — the keys with fingerprints. | In a single line print a space-separated sequence of integers representing the code. If the resulting sequence is empty, both printing nothing and printing a single line break is acceptable. | [
"7 3\n3 5 7 1 6 2 8\n1 2 7\n",
"4 4\n3 4 1 0\n0 1 7 9\n"
] | [
"7 1 2\n",
"1 0\n"
] | In the first example, the only digits with fingerprints are $1$, $2$ and $7$. All three of them appear in the sequence you know, $7$ first, then $1$ and then $2$. Therefore the output is 7 1 2. Note that the order is important, and shall be the same as the order in the original sequence.
In the second example digits $0$, $1$, $7$ and $9$ have fingerprints, however only $0$ and $1$ appear in the original sequence. $1$ appears earlier, so the output is 1 0. Again, the order is important. | 500 | [
{
"input": "7 3\n3 5 7 1 6 2 8\n1 2 7",
"output": "7 1 2"
},
{
"input": "4 4\n3 4 1 0\n0 1 7 9",
"output": "1 0"
},
{
"input": "9 4\n9 8 7 6 5 4 3 2 1\n2 4 6 8",
"output": "8 6 4 2"
},
{
"input": "10 5\n3 7 1 2 4 6 9 0 5 8\n4 3 0 7 9",
"output": "3 7 4 9 0"
},
{
"... | 1,547,874,363 | 2,147,483,647 | Python 3 | OK | TESTS | 31 | 124 | 0 | #994A Fingerprints
entrada = input().split()
n = int(entrada[0])
m = int(entrada[1])
sequence = input().split()
sequence = [int(x) for x in sequence]
fingerprints = input().split()
fingerprints = [int(x) for x in fingerprints]
ans = []
for digit in sequence:
if digit in fingerprints:
ans.append(digit)
print(' '.join([str(x) for x in ans]))
| Title: Fingerprints
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.
Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subsequence of the sequence you have that only contains digits with fingerprints on the corresponding keys. Find such code.
Input Specification:
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 10$) representing the number of digits in the sequence you have and the number of keys on the keypad that have fingerprints.
The next line contains $n$ distinct space-separated integers $x_1, x_2, \ldots, x_n$ ($0 \le x_i \le 9$) representing the sequence.
The next line contains $m$ distinct space-separated integers $y_1, y_2, \ldots, y_m$ ($0 \le y_i \le 9$) — the keys with fingerprints.
Output Specification:
In a single line print a space-separated sequence of integers representing the code. If the resulting sequence is empty, both printing nothing and printing a single line break is acceptable.
Demo Input:
['7 3\n3 5 7 1 6 2 8\n1 2 7\n', '4 4\n3 4 1 0\n0 1 7 9\n']
Demo Output:
['7 1 2\n', '1 0\n']
Note:
In the first example, the only digits with fingerprints are $1$, $2$ and $7$. All three of them appear in the sequence you know, $7$ first, then $1$ and then $2$. Therefore the output is 7 1 2. Note that the order is important, and shall be the same as the order in the original sequence.
In the second example digits $0$, $1$, $7$ and $9$ have fingerprints, however only $0$ and $1$ appear in the original sequence. $1$ appears earlier, so the output is 1 0. Again, the order is important. | ```python
#994A Fingerprints
entrada = input().split()
n = int(entrada[0])
m = int(entrada[1])
sequence = input().split()
sequence = [int(x) for x in sequence]
fingerprints = input().split()
fingerprints = [int(x) for x in fingerprints]
ans = []
for digit in sequence:
if digit in fingerprints:
ans.append(digit)
print(' '.join([str(x) for x in ans]))
``` | 3 | |
702 | A | Maximum Increase | PROGRAMMING | 800 | [
"dp",
"greedy",
"implementation"
] | null | null | You are given array consisting of *n* integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous. | The first line contains single positive integer *n* (1<=≤<=*n*<=≤<=105) — the number of integers.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109). | Print the maximum length of an increasing subarray of the given array. | [
"5\n1 7 2 11 15\n",
"6\n100 100 100 100 100 100\n",
"3\n1 2 3\n"
] | [
"3\n",
"1\n",
"3\n"
] | none | 0 | [
{
"input": "5\n1 7 2 11 15",
"output": "3"
},
{
"input": "6\n100 100 100 100 100 100",
"output": "1"
},
{
"input": "3\n1 2 3",
"output": "3"
},
{
"input": "1\n1000000000",
"output": "1"
},
{
"input": "10\n802030518 598196518 640274071 983359971 71550121 96204862 7... | 1,699,898,320 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 1 | 62 | 0 | n = int(input())
array = list(map(int,input().split(" ")))
num = -1
countList = []
count = 1
for a in array:
if a<=num:
countList.append(count)
count = 1
num = -1
else:
count+=1
num = a
print(max(countList))
| Title: Maximum Increase
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given array consisting of *n* integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input Specification:
The first line contains single positive integer *n* (1<=≤<=*n*<=≤<=105) — the number of integers.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109).
Output Specification:
Print the maximum length of an increasing subarray of the given array.
Demo Input:
['5\n1 7 2 11 15\n', '6\n100 100 100 100 100 100\n', '3\n1 2 3\n']
Demo Output:
['3\n', '1\n', '3\n']
Note:
none | ```python
n = int(input())
array = list(map(int,input().split(" ")))
num = -1
countList = []
count = 1
for a in array:
if a<=num:
countList.append(count)
count = 1
num = -1
else:
count+=1
num = a
print(max(countList))
``` | 0 | |
883 | H | Palindromic Cut | PROGRAMMING | 1,800 | [
"brute force",
"implementation",
"strings"
] | null | null | Kolya has a string *s* of length *n* consisting of lowercase and uppercase Latin letters and digits.
He wants to rearrange the symbols in *s* and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.
Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut *s* into, if it is allowed to rearrange letters in *s* before cuttings. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=4·105) — the length of string *s*.
The second line contains a string *s* of length *n* consisting of lowercase and uppercase Latin letters and digits. | Print to the first line an integer *k* — minimum number of palindromes into which you can cut a given string.
Print to the second line *k* strings — the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length. | [
"6\naabaac\n",
"8\n0rTrT022\n",
"2\naA\n"
] | [
"2\naba aca ",
"1\n02TrrT20 ",
"2\na A \n"
] | none | 0 | [
{
"input": "6\naabaac",
"output": "2\naba aca "
},
{
"input": "8\n0rTrT022",
"output": "1\n02TrrT20 "
},
{
"input": "2\naA",
"output": "2\na A "
},
{
"input": "1\ns",
"output": "1\ns "
},
{
"input": "10\n6IIC6CCIIC",
"output": "1\n6CCIIIICC6 "
},
{
"in... | 1,508,616,728 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 5 | 61 | 5,529,600 | from math import *
n=int(input())
s=input()
def calcul(d):
ch=''
ch1=''
for x in d:
ch+=x*(d[x]//2)
if d[x]%2!=0:
ch1=x
ch+=ch1+ch[::-1]
return ch
d={}
for x in s:
try:
d[x]+=1
except:
d[x]=1
impair=len([x for x in d.values() if x%2!=0])
if impair==0:
print(1)
ch=''
for x in d:
ch+=x*(d[x]//2)
ch+=ch[::-1]
print(ch)
elif impair==1:
ch=calcul(d)
print(impair)
print(ch)
else:
ep=set()
eimp=set()
for x in d:
if d[x]%2==0:
ep.add((x,d[x]))
else:
eimp.add((x,d[x]))
div=impair
d1=d.copy()
while 1:
yy=len(s)/div
if int(yy)==yy:
d=d1.copy()
eep=ep.copy()
possible=True
for x in eimp:
if abs(d[x[0]]-yy)%2!=0:
possible=False
break
if d[x[0]]-yy>0:
eep.add((x[0],int(d[x[0]]-yy)))
d[x[0]]=int(yy)
if possible:
break
div+=1
eimp.clear()
for x in d:
if d[x]%2!=0:
eimp.add((x,d[x]))
d=d1.copy()
ep=eep.copy()
impair=div
sizesubstr=len(s)//impair
L=[]
for i in range(impair):
d1={}
var1=0
for x in eimp:
d1[x[0]]=x[1]
var1=d1[x[0]]
d[x[0]]-=x[1]
eimp.remove(x)
break
nbrpair=sizesubstr-var1
if nbrpair!=0:
etmp=ep.copy()
for x in etmp:
if nbrpair==d[x[0]]:
d1[x[0]]=d[x[0]]
d[x[0]]-=nbrpair
ep.remove(x)
break
elif d[x[0]]>nbrpair:
d1[x[0]]=nbrpair
var2=d[x[0]]
ep.remove(x)
d[x[0]]-=nbrpair
ep.add((x[0],var2))
break
else:
nbrpair-=d[x[0]]
ep.remove(x)
else:
pass
L.append(calcul(d1))
print(impair)
print(' '.join(L))
| Title: Palindromic Cut
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Kolya has a string *s* of length *n* consisting of lowercase and uppercase Latin letters and digits.
He wants to rearrange the symbols in *s* and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.
Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut *s* into, if it is allowed to rearrange letters in *s* before cuttings.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=4·105) — the length of string *s*.
The second line contains a string *s* of length *n* consisting of lowercase and uppercase Latin letters and digits.
Output Specification:
Print to the first line an integer *k* — minimum number of palindromes into which you can cut a given string.
Print to the second line *k* strings — the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
Demo Input:
['6\naabaac\n', '8\n0rTrT022\n', '2\naA\n']
Demo Output:
['2\naba aca ', '1\n02TrrT20 ', '2\na A \n']
Note:
none | ```python
from math import *
n=int(input())
s=input()
def calcul(d):
ch=''
ch1=''
for x in d:
ch+=x*(d[x]//2)
if d[x]%2!=0:
ch1=x
ch+=ch1+ch[::-1]
return ch
d={}
for x in s:
try:
d[x]+=1
except:
d[x]=1
impair=len([x for x in d.values() if x%2!=0])
if impair==0:
print(1)
ch=''
for x in d:
ch+=x*(d[x]//2)
ch+=ch[::-1]
print(ch)
elif impair==1:
ch=calcul(d)
print(impair)
print(ch)
else:
ep=set()
eimp=set()
for x in d:
if d[x]%2==0:
ep.add((x,d[x]))
else:
eimp.add((x,d[x]))
div=impair
d1=d.copy()
while 1:
yy=len(s)/div
if int(yy)==yy:
d=d1.copy()
eep=ep.copy()
possible=True
for x in eimp:
if abs(d[x[0]]-yy)%2!=0:
possible=False
break
if d[x[0]]-yy>0:
eep.add((x[0],int(d[x[0]]-yy)))
d[x[0]]=int(yy)
if possible:
break
div+=1
eimp.clear()
for x in d:
if d[x]%2!=0:
eimp.add((x,d[x]))
d=d1.copy()
ep=eep.copy()
impair=div
sizesubstr=len(s)//impair
L=[]
for i in range(impair):
d1={}
var1=0
for x in eimp:
d1[x[0]]=x[1]
var1=d1[x[0]]
d[x[0]]-=x[1]
eimp.remove(x)
break
nbrpair=sizesubstr-var1
if nbrpair!=0:
etmp=ep.copy()
for x in etmp:
if nbrpair==d[x[0]]:
d1[x[0]]=d[x[0]]
d[x[0]]-=nbrpair
ep.remove(x)
break
elif d[x[0]]>nbrpair:
d1[x[0]]=nbrpair
var2=d[x[0]]
ep.remove(x)
d[x[0]]-=nbrpair
ep.add((x[0],var2))
break
else:
nbrpair-=d[x[0]]
ep.remove(x)
else:
pass
L.append(calcul(d1))
print(impair)
print(' '.join(L))
``` | 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.