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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
146 | B | Lucky Mask | PROGRAMMING | 1,300 | [
"brute force",
"implementation"
] | null | null | Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a mask of a positive integer *n* the number that is obtained after successive writing of all lucky digits of number *n* from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number.
Petya has two numbers — an arbitrary integer *a* and a lucky number *b*. Help him find the minimum number *c* (*c*<=><=*a*) such that the mask of number *c* equals *b*. | The only line contains two integers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=105). It is guaranteed that number *b* is lucky. | In the only line print a single number — the number *c* that is sought by Petya. | [
"1 7\n",
"100 47\n"
] | [
"7\n",
"147\n"
] | none | 1,000 | [
{
"input": "1 7",
"output": "7"
},
{
"input": "100 47",
"output": "147"
},
{
"input": "458 47",
"output": "467"
},
{
"input": "7 7",
"output": "17"
},
{
"input": "547 47",
"output": "647"
},
{
"input": "77 77",
"output": "177"
},
{
"input":... | 1,580,242,216 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 7 | 280 | 0 | def mask(x):
ix = 0
while (x):
x, dig = divmod(x, 10)
if dig == int(b[-(ix + 1)]):
ix += 1
if ix == len(b):
return True
return False
a, b = map(int, input().split())
b = str(b)
for i in range(a + 1, 100001):
if mask(i):
exit(print(i))
| Title: Lucky Mask
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a mask of a positive integer *n* the number that is obtained after successive writing of all lucky digits of number *n* from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number.
Petya has two numbers — an arbitrary integer *a* and a lucky number *b*. Help him find the minimum number *c* (*c*<=><=*a*) such that the mask of number *c* equals *b*.
Input Specification:
The only line contains two integers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=105). It is guaranteed that number *b* is lucky.
Output Specification:
In the only line print a single number — the number *c* that is sought by Petya.
Demo Input:
['1 7\n', '100 47\n']
Demo Output:
['7\n', '147\n']
Note:
none | ```python
def mask(x):
ix = 0
while (x):
x, dig = divmod(x, 10)
if dig == int(b[-(ix + 1)]):
ix += 1
if ix == len(b):
return True
return False
a, b = map(int, input().split())
b = str(b)
for i in range(a + 1, 100001):
if mask(i):
exit(print(i))
``` | 0 | |
552 | B | Vanya and Books | PROGRAMMING | 1,200 | [
"implementation",
"math"
] | null | null | Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the *n* books should be assigned with a number from 1 to *n*. Naturally, distinct books should be assigned distinct numbers.
Vanya wants to know how many digits he will have to write down as he labels the books. | The first line contains integer *n* (1<=≤<=*n*<=≤<=109) — the number of books in the library. | Print the number of digits needed to number all the books. | [
"13\n",
"4\n"
] | [
"17\n",
"4\n"
] | Note to the first test. The books get numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, which totals to 17 digits.
Note to the second sample. The books get numbers 1, 2, 3, 4, which totals to 4 digits. | 1,000 | [
{
"input": "13",
"output": "17"
},
{
"input": "4",
"output": "4"
},
{
"input": "100",
"output": "192"
},
{
"input": "99",
"output": "189"
},
{
"input": "1000000000",
"output": "8888888899"
},
{
"input": "1000000",
"output": "5888896"
},
{
"... | 1,441,063,043 | 2,147,483,647 | Python 3 | OK | TESTS | 55 | 62 | 0 | n = input()
res = 0
for i in range(1,len(n)):
res += 9 * i * (10 ** (i-1))
res += (int(n) - 10 ** (len(n) - 1) + 1) * len(n)
print(res) | Title: Vanya and Books
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the *n* books should be assigned with a number from 1 to *n*. Naturally, distinct books should be assigned distinct numbers.
Vanya wants to know how many digits he will have to write down as he labels the books.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=109) — the number of books in the library.
Output Specification:
Print the number of digits needed to number all the books.
Demo Input:
['13\n', '4\n']
Demo Output:
['17\n', '4\n']
Note:
Note to the first test. The books get numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, which totals to 17 digits.
Note to the second sample. The books get numbers 1, 2, 3, 4, which totals to 4 digits. | ```python
n = input()
res = 0
for i in range(1,len(n)):
res += 9 * i * (10 ** (i-1))
res += (int(n) - 10 ** (len(n) - 1) + 1) * len(n)
print(res)
``` | 3 | |
218 | B | Airport | PROGRAMMING | 1,100 | [
"implementation"
] | null | null | Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:
- it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=><=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency).
The only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer?
The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person. | The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains *m* integers *a*1,<=*a*2,<=...,<=*a**m* (1<=≤<=*a**i*<=≤<=1000) — *a**i* stands for the number of empty seats in the *i*-th plane before the ticket office starts selling tickets.
The numbers in the lines are separated by a space. It is guaranteed that there are at least *n* empty seats in total. | Print two integers — the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly. | [
"4 3\n2 1 1\n",
"4 3\n2 2 2\n"
] | [
"5 5\n",
"7 6\n"
] | In the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.
In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 2-nd plane, the 3-rd person — to the 3-rd plane, the 4-th person — to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 1-st plane, the 3-rd person — to the 2-nd plane, the 4-th person — to the 2-nd plane. | 500 | [
{
"input": "4 3\n2 1 1",
"output": "5 5"
},
{
"input": "4 3\n2 2 2",
"output": "7 6"
},
{
"input": "10 5\n10 3 3 1 2",
"output": "58 26"
},
{
"input": "10 1\n10",
"output": "55 55"
},
{
"input": "10 1\n100",
"output": "955 955"
},
{
"input": "10 2\n4 7... | 1,620,201,200 | 2,147,483,647 | Python 3 | OK | TESTS | 33 | 652 | 0 | n, m = map(int, input().split())
a = list(map(int, input().split()))
b = a.copy()
y = n
maxm = 0
minm = 0
i = 0
while y > 0:
ind = a.index(max(a))
maxm += a[ind]
a[ind] -= 1
y -= 1
z = n
i = 0
while z > 0:
min_c = max(b)
for j in range(m):
if b[j] < min_c and b[j]>0:
min_c = b[j]
ind = b.index(min_c)
minm += b[ind]
if b[ind] > 0:
b[ind] -= 1
z -= 1
print(maxm, minm)
| Title: Airport
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:
- it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=><=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency).
The only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer?
The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains *m* integers *a*1,<=*a*2,<=...,<=*a**m* (1<=≤<=*a**i*<=≤<=1000) — *a**i* stands for the number of empty seats in the *i*-th plane before the ticket office starts selling tickets.
The numbers in the lines are separated by a space. It is guaranteed that there are at least *n* empty seats in total.
Output Specification:
Print two integers — the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly.
Demo Input:
['4 3\n2 1 1\n', '4 3\n2 2 2\n']
Demo Output:
['5 5\n', '7 6\n']
Note:
In the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.
In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 2-nd plane, the 3-rd person — to the 3-rd plane, the 4-th person — to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 1-st plane, the 3-rd person — to the 2-nd plane, the 4-th person — to the 2-nd plane. | ```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = a.copy()
y = n
maxm = 0
minm = 0
i = 0
while y > 0:
ind = a.index(max(a))
maxm += a[ind]
a[ind] -= 1
y -= 1
z = n
i = 0
while z > 0:
min_c = max(b)
for j in range(m):
if b[j] < min_c and b[j]>0:
min_c = b[j]
ind = b.index(min_c)
minm += b[ind]
if b[ind] > 0:
b[ind] -= 1
z -= 1
print(maxm, minm)
``` | 3 | |
231 | A | Team | PROGRAMMING | 800 | [
"brute force",
"greedy"
] | null | null | One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.
This contest offers *n* problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution. | The first input line contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of problems in the contest. Then *n* lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces. | Print a single integer — the number of problems the friends will implement on the contest. | [
"3\n1 1 0\n1 1 1\n1 0 0\n",
"2\n1 0 0\n0 1 1\n"
] | [
"2\n",
"1\n"
] | In the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it.
In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution. | 500 | [
{
"input": "3\n1 1 0\n1 1 1\n1 0 0",
"output": "2"
},
{
"input": "2\n1 0 0\n0 1 1",
"output": "1"
},
{
"input": "1\n1 0 0",
"output": "0"
},
{
"input": "2\n1 0 0\n1 1 1",
"output": "1"
},
{
"input": "5\n1 0 0\n0 1 0\n1 1 1\n0 0 1\n0 0 0",
"output": "1"
},
... | 1,696,280,670 | 2,147,483,647 | Python 3 | OK | TESTS | 21 | 92 | 0 | #231A Team
input_ = int(input())
#enter count exercices
problems = 0
#variable for solved problems
for i in range(input_):
#iterate for count exercices
if sum( [int(i) for i in input().split(' ')]) >= 2:
#check if the sum of the entered values is greater than or equal to 2
problems += 1
#let's increase the solved problem by 1
print(problems)
#show solves count
'''
n = int(input())
problems = 0
for i in range(n):
persons = input().split()
if persons.count("1") >= 2:
problems += 1
print(problems)
''' | Title: Team
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.
This contest offers *n* problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.
Input Specification:
The first input line contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of problems in the contest. Then *n* lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.
Output Specification:
Print a single integer — the number of problems the friends will implement on the contest.
Demo Input:
['3\n1 1 0\n1 1 1\n1 0 0\n', '2\n1 0 0\n0 1 1\n']
Demo Output:
['2\n', '1\n']
Note:
In the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it.
In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution. | ```python
#231A Team
input_ = int(input())
#enter count exercices
problems = 0
#variable for solved problems
for i in range(input_):
#iterate for count exercices
if sum( [int(i) for i in input().split(' ')]) >= 2:
#check if the sum of the entered values is greater than or equal to 2
problems += 1
#let's increase the solved problem by 1
print(problems)
#show solves count
'''
n = int(input())
problems = 0
for i in range(n):
persons = input().split()
if persons.count("1") >= 2:
problems += 1
print(problems)
'''
``` | 3 | |
772 | E | Verifying Kingdom | PROGRAMMING | 3,200 | [
"binary search",
"divide and conquer",
"interactive",
"trees"
] | null | null | This is an interactive problem.
The judge has a hidden rooted full binary tree with *n* leaves. A full binary tree is one where every node has either 0 or 2 children. The nodes with 0 children are called the leaves of the tree. Since this is a full binary tree, there are exactly 2*n*<=-<=1 nodes in the tree. The leaves of the judge's tree has labels from 1 to *n*. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions.
A question consists of printing the label of three distinct leaves *a*1,<=*a*2,<=*a*3. Let the depth of a node be the shortest distance from the node to the root of the tree. Let *LCA*(*a*,<=*b*) denote the node with maximum depth that is a common ancestor of the nodes *a* and *b*.
Consider *X*<==<=*LCA*(*a*1,<=*a*2),<=*Y*<==<=*LCA*(*a*2,<=*a*3),<=*Z*<==<=*LCA*(*a*3,<=*a*1). The judge will tell you which one of *X*,<=*Y*,<=*Z* has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties.
More specifically, if *X* (or *Y*, *Z* respectively) maximizes the depth, the judge will respond with the string "X" (or "Y", "Z" respectively).
You may only ask at most 10·*n* questions. | The first line of input will contain a single integer *n* (3<=≤<=*n*<=≤<=1<=000) — the number of leaves in the tree. | To print the final answer, print out the string "-1" on its own line. Then, the next line should contain 2*n*<=-<=1 integers. The *i*-th integer should be the parent of the *i*-th node, or -1, if it is the root.
Your answer will be judged correct if your output is isomorphic to the judge's tree. In particular, the labels of the leaves do not need to be labeled from 1 to *n*. Here, isomorphic means that there exists a permutation π such that node *i* is the parent of node *j* in the judge tree if and only node π(*i*) is the parent of node π(*j*) in your tree. | [
"5\nX\nZ\nY\nY\nX\n"
] | [
"1 4 2\n1 2 4\n2 4 1\n2 3 5\n2 4 3\n-1\n-1 1 1 2 2 3 3 6 6\n"
] | For the first sample, the judge has the hidden tree:
<img class="tex-graphics" src="https://espresso.codeforces.com/2c9cae7de194cc1bc508ea7243ff4d0d509d34bd.png" style="max-width: 100.0%;max-height: 100.0%;"/>
Here is a more readable format of the interaction: | 2,250 | [] | 1,679,937,728 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 77 | 2,867,200 | import sys
def query(a, b, c):
print(a, b, c, flush=True)
return input().strip()
n = int(input())
# Find all the leaves
leaves = list(range(1, n+1))
while len(leaves) > 1:
new_leaves = []
for i in range(0, len(leaves), 3):
if i + 2 < len(leaves):
a, b, c = leaves[i:i+3]
ans = query(a, b, c)
if ans == "X":
new_leaves.append(b)
new_leaves.append(c)
elif ans == "Y":
new_leaves.append(a)
new_leaves.append(c)
else:
new_leaves.append(a)
new_leaves.append(b)
leaves = new_leaves
tree = [-1] * (2*n-1)
queue = [(leaves[0], None)]
found = set(leaves)
while queue:
node, parent = queue.pop(0)
if parent is not None:
tree[node-1] = parent
if node in found:
continue
left, right = None, None
for i in range(len(leaves)):
if leaves[i] == node:
if i % 2 == 0 and i+1 < len(leaves):
right = leaves[i+1]
elif i % 2 == 1:
left = leaves[i-1]
break
if left is None or right is None:
sibling = left or right
ans = query(sibling, node, parent)
if ans == "X":
left = sibling
right = parent
elif ans == "Y":
left = node
right = parent
else:
left = node
right = sibling
queue.append((left, node))
queue.append((right, node))
found.add(node)
print("-1")
print(" ".join(str(p) for p in tree))
sys.stdout.flush() | Title: Verifying Kingdom
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
This is an interactive problem.
The judge has a hidden rooted full binary tree with *n* leaves. A full binary tree is one where every node has either 0 or 2 children. The nodes with 0 children are called the leaves of the tree. Since this is a full binary tree, there are exactly 2*n*<=-<=1 nodes in the tree. The leaves of the judge's tree has labels from 1 to *n*. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions.
A question consists of printing the label of three distinct leaves *a*1,<=*a*2,<=*a*3. Let the depth of a node be the shortest distance from the node to the root of the tree. Let *LCA*(*a*,<=*b*) denote the node with maximum depth that is a common ancestor of the nodes *a* and *b*.
Consider *X*<==<=*LCA*(*a*1,<=*a*2),<=*Y*<==<=*LCA*(*a*2,<=*a*3),<=*Z*<==<=*LCA*(*a*3,<=*a*1). The judge will tell you which one of *X*,<=*Y*,<=*Z* has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties.
More specifically, if *X* (or *Y*, *Z* respectively) maximizes the depth, the judge will respond with the string "X" (or "Y", "Z" respectively).
You may only ask at most 10·*n* questions.
Input Specification:
The first line of input will contain a single integer *n* (3<=≤<=*n*<=≤<=1<=000) — the number of leaves in the tree.
Output Specification:
To print the final answer, print out the string "-1" on its own line. Then, the next line should contain 2*n*<=-<=1 integers. The *i*-th integer should be the parent of the *i*-th node, or -1, if it is the root.
Your answer will be judged correct if your output is isomorphic to the judge's tree. In particular, the labels of the leaves do not need to be labeled from 1 to *n*. Here, isomorphic means that there exists a permutation π such that node *i* is the parent of node *j* in the judge tree if and only node π(*i*) is the parent of node π(*j*) in your tree.
Demo Input:
['5\nX\nZ\nY\nY\nX\n']
Demo Output:
['1 4 2\n1 2 4\n2 4 1\n2 3 5\n2 4 3\n-1\n-1 1 1 2 2 3 3 6 6\n']
Note:
For the first sample, the judge has the hidden tree:
<img class="tex-graphics" src="https://espresso.codeforces.com/2c9cae7de194cc1bc508ea7243ff4d0d509d34bd.png" style="max-width: 100.0%;max-height: 100.0%;"/>
Here is a more readable format of the interaction: | ```python
import sys
def query(a, b, c):
print(a, b, c, flush=True)
return input().strip()
n = int(input())
# Find all the leaves
leaves = list(range(1, n+1))
while len(leaves) > 1:
new_leaves = []
for i in range(0, len(leaves), 3):
if i + 2 < len(leaves):
a, b, c = leaves[i:i+3]
ans = query(a, b, c)
if ans == "X":
new_leaves.append(b)
new_leaves.append(c)
elif ans == "Y":
new_leaves.append(a)
new_leaves.append(c)
else:
new_leaves.append(a)
new_leaves.append(b)
leaves = new_leaves
tree = [-1] * (2*n-1)
queue = [(leaves[0], None)]
found = set(leaves)
while queue:
node, parent = queue.pop(0)
if parent is not None:
tree[node-1] = parent
if node in found:
continue
left, right = None, None
for i in range(len(leaves)):
if leaves[i] == node:
if i % 2 == 0 and i+1 < len(leaves):
right = leaves[i+1]
elif i % 2 == 1:
left = leaves[i-1]
break
if left is None or right is None:
sibling = left or right
ans = query(sibling, node, parent)
if ans == "X":
left = sibling
right = parent
elif ans == "Y":
left = node
right = parent
else:
left = node
right = sibling
queue.append((left, node))
queue.append((right, node))
found.add(node)
print("-1")
print(" ".join(str(p) for p in tree))
sys.stdout.flush()
``` | 0 | |
173 | A | Rock-Paper-Scissors | PROGRAMMING | 1,300 | [
"implementation",
"math"
] | null | null | Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played *n* rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items *A*<==<=(*a*1,<=*a*2,<=...,<=*a**m*), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: *a*1, *a*2, ..., *a**m*, *a*1, *a*2, ..., *a**m*, *a*1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items *B*<==<=(*b*1,<=*b*2,<=...,<=*b**k*).
Determine the number of red spots on both players after they've played *n* rounds of the game. You can consider that when the game began, the boys had no red spots on them. | The first line contains integer *n* (1<=≤<=*n*<=≤<=2·109) — the number of the game's rounds.
The second line contains sequence *A* as a string of *m* characters and the third line contains sequence *B* as a string of *k* characters (1<=≤<=*m*,<=*k*<=≤<=1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. | Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. | [
"7\nRPS\nRSPP\n",
"5\nRRRRRRRR\nR\n"
] | [
"3 2",
"0 0"
] | In the first sample the game went like this:
- R - R. Draw. - P - S. Nikephoros loses. - S - P. Polycarpus loses. - R - P. Nikephoros loses. - P - R. Polycarpus loses. - S - S. Draw. - R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. | 500 | [
{
"input": "7\nRPS\nRSPP",
"output": "3 2"
},
{
"input": "5\nRRRRRRRR\nR",
"output": "0 0"
},
{
"input": "23\nRSP\nRPSS",
"output": "7 8"
},
{
"input": "52\nRRPSS\nRSSPRPRPPP",
"output": "15 21"
},
{
"input": "1293\nRRPSSRSSPRPRPPPRPPPRPPPPPRPSPRSSRPSPPRPRR\nSSPSS... | 1,693,480,280 | 2,147,483,647 | Python 3 | OK | TESTS | 54 | 1,746 | 102,400 | def gcd(a, b):
if a < b:
a, b = b, a
while b > 0:
c = a % b
a = b
b = c
return a
n = int(input())
c1 = input()
c2 = input()
n1 = len(c1)
n2 = len(c2)
mul = n1 * n2 // gcd(n1, n2)
rem = n % mul
tim = n // mul
ans1 = 0
ans2 = 0
k1 = 0
k2 = 0
for i in range(1, mul + 1):
if (c1[k1] == 'R' and c2[k2] == 'P') or (c1[k1] == 'P' and c2[k2] == 'S') or (c1[k1] == 'S' and c2[k2] == 'R'):
ans1 += 1
elif (c1[k1] == 'P' and c2[k2] == 'R') or (c1[k1] == 'S' and c2[k2] == 'P') or (c1[k1] == 'R' and c2[k2] == 'S'):
ans2 += 1
k1 += 1
k2 += 1
if k1 == n1:
k1 = 0
if k2 == n2:
k2 = 0
ans1 *= tim
ans2 *= tim
for i in range(1, rem + 1):
if (c1[k1] == 'R' and c2[k2] == 'P') or (c1[k1] == 'P' and c2[k2] == 'S') or (c1[k1] == 'S' and c2[k2] == 'R'):
ans1 += 1
elif (c1[k1] == 'P' and c2[k2] == 'R') or (c1[k1] == 'S' and c2[k2] == 'P') or (c1[k1] == 'R' and c2[k2] == 'S'):
ans2 += 1
k1 += 1
k2 += 1
if k1 == n1:
k1 = 0
if k2 == n2:
k2 = 0
print(ans1, ans2)
| Title: Rock-Paper-Scissors
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played *n* rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items *A*<==<=(*a*1,<=*a*2,<=...,<=*a**m*), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: *a*1, *a*2, ..., *a**m*, *a*1, *a*2, ..., *a**m*, *a*1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items *B*<==<=(*b*1,<=*b*2,<=...,<=*b**k*).
Determine the number of red spots on both players after they've played *n* rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=2·109) — the number of the game's rounds.
The second line contains sequence *A* as a string of *m* characters and the third line contains sequence *B* as a string of *k* characters (1<=≤<=*m*,<=*k*<=≤<=1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output Specification:
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Demo Input:
['7\nRPS\nRSPP\n', '5\nRRRRRRRR\nR\n']
Demo Output:
['3 2', '0 0']
Note:
In the first sample the game went like this:
- R - R. Draw. - P - S. Nikephoros loses. - S - P. Polycarpus loses. - R - P. Nikephoros loses. - P - R. Polycarpus loses. - S - S. Draw. - R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. | ```python
def gcd(a, b):
if a < b:
a, b = b, a
while b > 0:
c = a % b
a = b
b = c
return a
n = int(input())
c1 = input()
c2 = input()
n1 = len(c1)
n2 = len(c2)
mul = n1 * n2 // gcd(n1, n2)
rem = n % mul
tim = n // mul
ans1 = 0
ans2 = 0
k1 = 0
k2 = 0
for i in range(1, mul + 1):
if (c1[k1] == 'R' and c2[k2] == 'P') or (c1[k1] == 'P' and c2[k2] == 'S') or (c1[k1] == 'S' and c2[k2] == 'R'):
ans1 += 1
elif (c1[k1] == 'P' and c2[k2] == 'R') or (c1[k1] == 'S' and c2[k2] == 'P') or (c1[k1] == 'R' and c2[k2] == 'S'):
ans2 += 1
k1 += 1
k2 += 1
if k1 == n1:
k1 = 0
if k2 == n2:
k2 = 0
ans1 *= tim
ans2 *= tim
for i in range(1, rem + 1):
if (c1[k1] == 'R' and c2[k2] == 'P') or (c1[k1] == 'P' and c2[k2] == 'S') or (c1[k1] == 'S' and c2[k2] == 'R'):
ans1 += 1
elif (c1[k1] == 'P' and c2[k2] == 'R') or (c1[k1] == 'S' and c2[k2] == 'P') or (c1[k1] == 'R' and c2[k2] == 'S'):
ans2 += 1
k1 += 1
k2 += 1
if k1 == n1:
k1 = 0
if k2 == n2:
k2 = 0
print(ans1, ans2)
``` | 3 | |
614 | B | Gena's Code | PROGRAMMING | 1,400 | [
"implementation",
"math"
] | null | null | It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!
There are exactly *n* distinct countries in the world and the *i*-th country added *a**i* tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.
Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. | The first line of the input contains the number of countries *n* (1<=≤<=*n*<=≤<=100<=000). The second line contains *n* non-negative integers *a**i* without leading zeroes — the number of tanks of the *i*-th country.
It is guaranteed that the second line contains at least *n*<=-<=1 beautiful numbers and the total length of all these number's representations doesn't exceed 100<=000. | Print a single number without leading zeroes — the product of the number of tanks presented by each country. | [
"3\n5 10 1\n",
"4\n1 1 10 11\n",
"5\n0 3 1 100 1\n"
] | [
"50",
"110",
"0"
] | In sample 1 numbers 10 and 1 are beautiful, number 5 is not not.
In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.
In sample 3 number 3 is not beautiful, all others are beautiful. | 1,000 | [
{
"input": "3\n5 10 1",
"output": "50"
},
{
"input": "4\n1 1 10 11",
"output": "110"
},
{
"input": "5\n0 3 1 100 1",
"output": "0"
},
{
"input": "40\n10 100 10 1 10 10 100 10 10 100 10 100 100 10 1824868942 100 100 1 10 100 100 10 100 100 10 100 10 1 10 100 100 100 10 1 10 1 ... | 1,618,411,533 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 62 | 0 | n = int(input())
a = input().split()
s = 1
for i in a:
s *= i
print(s) | Title: Gena's Code
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!
There are exactly *n* distinct countries in the world and the *i*-th country added *a**i* tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.
Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.
Input Specification:
The first line of the input contains the number of countries *n* (1<=≤<=*n*<=≤<=100<=000). The second line contains *n* non-negative integers *a**i* without leading zeroes — the number of tanks of the *i*-th country.
It is guaranteed that the second line contains at least *n*<=-<=1 beautiful numbers and the total length of all these number's representations doesn't exceed 100<=000.
Output Specification:
Print a single number without leading zeroes — the product of the number of tanks presented by each country.
Demo Input:
['3\n5 10 1\n', '4\n1 1 10 11\n', '5\n0 3 1 100 1\n']
Demo Output:
['50', '110', '0']
Note:
In sample 1 numbers 10 and 1 are beautiful, number 5 is not not.
In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.
In sample 3 number 3 is not beautiful, all others are beautiful. | ```python
n = int(input())
a = input().split()
s = 1
for i in a:
s *= i
print(s)
``` | -1 | |
277 | A | Learning Languages | PROGRAMMING | 1,400 | [
"dfs and similar",
"dsu"
] | null | null | The "BerCorp" company has got *n* employees. These employees can use *m* approved official languages for the formal correspondence. The languages are numbered with integers from 1 to *m*. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating). | The first line contains two integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=100) — the number of employees and the number of languages.
Then *n* lines follow — each employee's language list. At the beginning of the *i*-th line is integer *k**i* (0<=≤<=*k**i*<=≤<=*m*) — the number of languages the *i*-th employee knows. Next, the *i*-th line contains *k**i* integers — *a**ij* (1<=≤<=*a**ij*<=≤<=*m*) — the identifiers of languages the *i*-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces. | Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating). | [
"5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5\n",
"8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1\n",
"2 2\n1 2\n0\n"
] | [
"0\n",
"2\n",
"1\n"
] | In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2. | 500 | [
{
"input": "5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5",
"output": "0"
},
{
"input": "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1",
"output": "2"
},
{
"input": "2 2\n1 2\n0",
"output": "1"
},
{
"input": "2 2\n0\n0",
"output": "2"
},
{
"input": "5 5\n1 3\n0\n0\n2 4... | 1,695,319,072 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 62 | 0 | class Dsu:
def __init__(self,n):
self.sizes=[1]*(n)
self.parent=[i for i in range(n)]
def findpar(self,node):
if self.parent[node]==node:
return node
self.parent[node]=self.findpar(self.parent[node])
return self.parent[node]
def union(self,x,y):
px=self.findpar(x)
py=self.findpar(y)
if px==py:
return
if self.sizes[px]>self.sizes[py]:
self.parent[py]=px
self.sizes[px]+=self.sizes[py]
else:
self.sizes[py]+=self.sizes[px]
self.parent[px]=py
n,m=map(int,input().split())
d=Dsu(n+m+2)
for i in range(n):
a=list(map(int,input().split()))
for node in a[1:]:
d.union(i+1,n+node)
hash={}
ans=0
for i in range(1,n+1):
par=d.findpar(i)
if par in hash:
continue
else:
hash[par]=1
ans+=1
print(ans-1)
| Title: Learning Languages
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The "BerCorp" company has got *n* employees. These employees can use *m* approved official languages for the formal correspondence. The languages are numbered with integers from 1 to *m*. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input Specification:
The first line contains two integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=100) — the number of employees and the number of languages.
Then *n* lines follow — each employee's language list. At the beginning of the *i*-th line is integer *k**i* (0<=≤<=*k**i*<=≤<=*m*) — the number of languages the *i*-th employee knows. Next, the *i*-th line contains *k**i* integers — *a**ij* (1<=≤<=*a**ij*<=≤<=*m*) — the identifiers of languages the *i*-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output Specification:
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Demo Input:
['5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5\n', '8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1\n', '2 2\n1 2\n0\n']
Demo Output:
['0\n', '2\n', '1\n']
Note:
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2. | ```python
class Dsu:
def __init__(self,n):
self.sizes=[1]*(n)
self.parent=[i for i in range(n)]
def findpar(self,node):
if self.parent[node]==node:
return node
self.parent[node]=self.findpar(self.parent[node])
return self.parent[node]
def union(self,x,y):
px=self.findpar(x)
py=self.findpar(y)
if px==py:
return
if self.sizes[px]>self.sizes[py]:
self.parent[py]=px
self.sizes[px]+=self.sizes[py]
else:
self.sizes[py]+=self.sizes[px]
self.parent[px]=py
n,m=map(int,input().split())
d=Dsu(n+m+2)
for i in range(n):
a=list(map(int,input().split()))
for node in a[1:]:
d.union(i+1,n+node)
hash={}
ans=0
for i in range(1,n+1):
par=d.findpar(i)
if par in hash:
continue
else:
hash[par]=1
ans+=1
print(ans-1)
``` | 0 | |
0 | none | none | none | 0 | [
"none"
] | null | null | You've got a string $a_1, a_2, \dots, a_n$, consisting of zeros and ones.
Let's call a sequence of consecutive elements $a_i, a_{i<=+<=1}, \ldots,<=a_j$ ($1\leq<=i\leq<=j\leq<=n$) a substring of string $a$.
You can apply the following operations any number of times:
- Choose some substring of string $a$ (for example, you can choose entire string) and reverse it, paying $x$ coins for it (for example, «0101101» $\to$ «0111001»); - Choose some substring of string $a$ (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying $y$ coins for it (for example, «0101101» $\to$ «0110001»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones? | The first line of input contains integers $n$, $x$ and $y$ ($1<=\leq<=n<=\leq<=300\,000, 0 \leq x, y \leq 10^9$) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string $a$ of length $n$, consisting of zeros and ones. | Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print $0$, if you do not need to perform any operations. | [
"5 1 10\n01000\n",
"5 10 1\n01000\n",
"7 2 3\n1111111\n"
] | [
"11\n",
"2\n",
"0\n"
] | In the first sample, at first you need to reverse substring $[1 \dots 2]$, and then you need to invert substring $[2 \dots 5]$.
Then the string was changed as follows:
«01000» $\to$ «10000» $\to$ «11111».
The total cost of operations is $1 + 10 = 11$.
In the second sample, at first you need to invert substring $[1 \dots 1]$, and then you need to invert substring $[3 \dots 5]$.
Then the string was changed as follows:
«01000» $\to$ «11000» $\to$ «11111».
The overall cost is $1 + 1 = 2$.
In the third example, string already consists only of ones, so the answer is $0$. | 0 | [
{
"input": "5 1 10\n01000",
"output": "11"
},
{
"input": "5 10 1\n01000",
"output": "2"
},
{
"input": "7 2 3\n1111111",
"output": "0"
},
{
"input": "1 60754033 959739508\n0",
"output": "959739508"
},
{
"input": "1 431963980 493041212\n1",
"output": "0"
},
... | 1,540,575,950 | 2,147,483,647 | Python 3 | OK | TESTS | 115 | 140 | 1,024,000 | def segments(s, x, y):
count = s.count('10') + s.startswith('0')
if count:
return (count - 1) * min(x, y) + y
return 0
n, X, Y = [int(i) for i in input().split()]
t = input()
print(segments(t, X, Y))
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've got a string $a_1, a_2, \dots, a_n$, consisting of zeros and ones.
Let's call a sequence of consecutive elements $a_i, a_{i<=+<=1}, \ldots,<=a_j$ ($1\leq<=i\leq<=j\leq<=n$) a substring of string $a$.
You can apply the following operations any number of times:
- Choose some substring of string $a$ (for example, you can choose entire string) and reverse it, paying $x$ coins for it (for example, «0101101» $\to$ «0111001»); - Choose some substring of string $a$ (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying $y$ coins for it (for example, «0101101» $\to$ «0110001»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones?
Input Specification:
The first line of input contains integers $n$, $x$ and $y$ ($1<=\leq<=n<=\leq<=300\,000, 0 \leq x, y \leq 10^9$) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string $a$ of length $n$, consisting of zeros and ones.
Output Specification:
Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print $0$, if you do not need to perform any operations.
Demo Input:
['5 1 10\n01000\n', '5 10 1\n01000\n', '7 2 3\n1111111\n']
Demo Output:
['11\n', '2\n', '0\n']
Note:
In the first sample, at first you need to reverse substring $[1 \dots 2]$, and then you need to invert substring $[2 \dots 5]$.
Then the string was changed as follows:
«01000» $\to$ «10000» $\to$ «11111».
The total cost of operations is $1 + 10 = 11$.
In the second sample, at first you need to invert substring $[1 \dots 1]$, and then you need to invert substring $[3 \dots 5]$.
Then the string was changed as follows:
«01000» $\to$ «11000» $\to$ «11111».
The overall cost is $1 + 1 = 2$.
In the third example, string already consists only of ones, so the answer is $0$. | ```python
def segments(s, x, y):
count = s.count('10') + s.startswith('0')
if count:
return (count - 1) * min(x, y) + y
return 0
n, X, Y = [int(i) for i in input().split()]
t = input()
print(segments(t, X, Y))
``` | 3 | |
712 | A | Memory and Crow | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | There are *n* integers *b*1,<=*b*2,<=...,<=*b**n* written in a row. For all *i* from 1 to *n*, values *a**i* are defined by the crows performing the following procedure:
- The crow sets *a**i* initially 0. - The crow then adds *b**i* to *a**i*, subtracts *b**i*<=+<=1, adds the *b**i*<=+<=2 number, and so on until the *n*'th number. Thus, *a**i*<==<=*b**i*<=-<=*b**i*<=+<=1<=+<=*b**i*<=+<=2<=-<=*b**i*<=+<=3....
Memory gives you the values *a*1,<=*a*2,<=...,<=*a**n*, and he now wants you to find the initial numbers *b*1,<=*b*2,<=...,<=*b**n* written in the row? Can you do it? | The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=100<=000) — the number of integers written in the row.
The next line contains *n*, the *i*'th of which is *a**i* (<=-<=109<=≤<=*a**i*<=≤<=109) — the value of the *i*'th number. | Print *n* integers corresponding to the sequence *b*1,<=*b*2,<=...,<=*b**n*. It's guaranteed that the answer is unique and fits in 32-bit integer type. | [
"5\n6 -4 8 -2 3\n",
"5\n3 -2 -1 5 6\n"
] | [
"2 4 6 1 3 \n",
"1 -3 4 11 6 \n"
] | In the first sample test, the crows report the numbers 6, - 4, 8, - 2, and 3 when he starts at indices 1, 2, 3, 4 and 5 respectively. It is easy to check that the sequence 2 4 6 1 3 satisfies the reports. For example, 6 = 2 - 4 + 6 - 1 + 3, and - 4 = 4 - 6 + 1 - 3.
In the second sample test, the sequence 1, - 3, 4, 11, 6 satisfies the reports. For example, 5 = 11 - 6 and 6 = 6. | 500 | [
{
"input": "5\n6 -4 8 -2 3",
"output": "2 4 6 1 3 "
},
{
"input": "5\n3 -2 -1 5 6",
"output": "1 -3 4 11 6 "
},
{
"input": "10\n13 -2 532 -63 -23 -63 -64 -23 12 10",
"output": "11 530 469 -86 -86 -127 -87 -11 22 10 "
},
{
"input": "10\n0 0 0 0 0 0 0 0 0 0",
"output": "0 0... | 1,479,842,122 | 2,147,483,647 | Python 3 | OK | TESTS | 49 | 529 | 8,499,200 |
n = int(input());
arr = list(map(int, input().split()))
for i in range(0,n):
if i < n-1:
print(arr[i]+arr[i+1], end=" ")
else:
print(arr[i]) | Title: Memory and Crow
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* integers *b*1,<=*b*2,<=...,<=*b**n* written in a row. For all *i* from 1 to *n*, values *a**i* are defined by the crows performing the following procedure:
- The crow sets *a**i* initially 0. - The crow then adds *b**i* to *a**i*, subtracts *b**i*<=+<=1, adds the *b**i*<=+<=2 number, and so on until the *n*'th number. Thus, *a**i*<==<=*b**i*<=-<=*b**i*<=+<=1<=+<=*b**i*<=+<=2<=-<=*b**i*<=+<=3....
Memory gives you the values *a*1,<=*a*2,<=...,<=*a**n*, and he now wants you to find the initial numbers *b*1,<=*b*2,<=...,<=*b**n* written in the row? Can you do it?
Input Specification:
The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=100<=000) — the number of integers written in the row.
The next line contains *n*, the *i*'th of which is *a**i* (<=-<=109<=≤<=*a**i*<=≤<=109) — the value of the *i*'th number.
Output Specification:
Print *n* integers corresponding to the sequence *b*1,<=*b*2,<=...,<=*b**n*. It's guaranteed that the answer is unique and fits in 32-bit integer type.
Demo Input:
['5\n6 -4 8 -2 3\n', '5\n3 -2 -1 5 6\n']
Demo Output:
['2 4 6 1 3 \n', '1 -3 4 11 6 \n']
Note:
In the first sample test, the crows report the numbers 6, - 4, 8, - 2, and 3 when he starts at indices 1, 2, 3, 4 and 5 respectively. It is easy to check that the sequence 2 4 6 1 3 satisfies the reports. For example, 6 = 2 - 4 + 6 - 1 + 3, and - 4 = 4 - 6 + 1 - 3.
In the second sample test, the sequence 1, - 3, 4, 11, 6 satisfies the reports. For example, 5 = 11 - 6 and 6 = 6. | ```python
n = int(input());
arr = list(map(int, input().split()))
for i in range(0,n):
if i < n-1:
print(arr[i]+arr[i+1], end=" ")
else:
print(arr[i])
``` | 3 | |
158 | A | Next Round | PROGRAMMING | 800 | [
"*special",
"implementation"
] | null | null | "Contestant who earns a score equal to or greater than the *k*-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of *n* participants took part in the contest (*n*<=≥<=*k*), and you already know their scores. Calculate how many participants will advance to the next round. | The first line of the input contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=50) separated by a single space.
The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=100), where *a**i* is the score earned by the participant who got the *i*-th place. The given sequence is non-increasing (that is, for all *i* from 1 to *n*<=-<=1 the following condition is fulfilled: *a**i*<=≥<=*a**i*<=+<=1). | Output the number of participants who advance to the next round. | [
"8 5\n10 9 8 7 7 7 5 5\n",
"4 2\n0 0 0 0\n"
] | [
"6\n",
"0\n"
] | In the first example the participant on the 5th place earned 7 points. As the participant on the 6th place also earned 7 points, there are 6 advancers.
In the second example nobody got a positive score. | 500 | [
{
"input": "8 5\n10 9 8 7 7 7 5 5",
"output": "6"
},
{
"input": "4 2\n0 0 0 0",
"output": "0"
},
{
"input": "5 1\n1 1 1 1 1",
"output": "5"
},
{
"input": "5 5\n1 1 1 1 1",
"output": "5"
},
{
"input": "1 1\n10",
"output": "1"
},
{
"input": "17 14\n16 15... | 1,697,307,045 | 2,147,483,647 | PyPy 3 | RUNTIME_ERROR | TESTS | 5 | 154 | 2,048,000 | str1 = input()
str2 = input()
L=str2.split(' ')
k = int(str1[2])
L=[int(i) for i in L]
count = 0
for i in L:
if i >= L[int(str1[2])-1] and i>0 :
count+=1
print(count) | Title: Next Round
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
"Contestant who earns a score equal to or greater than the *k*-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of *n* participants took part in the contest (*n*<=≥<=*k*), and you already know their scores. Calculate how many participants will advance to the next round.
Input Specification:
The first line of the input contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=50) separated by a single space.
The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=100), where *a**i* is the score earned by the participant who got the *i*-th place. The given sequence is non-increasing (that is, for all *i* from 1 to *n*<=-<=1 the following condition is fulfilled: *a**i*<=≥<=*a**i*<=+<=1).
Output Specification:
Output the number of participants who advance to the next round.
Demo Input:
['8 5\n10 9 8 7 7 7 5 5\n', '4 2\n0 0 0 0\n']
Demo Output:
['6\n', '0\n']
Note:
In the first example the participant on the 5th place earned 7 points. As the participant on the 6th place also earned 7 points, there are 6 advancers.
In the second example nobody got a positive score. | ```python
str1 = input()
str2 = input()
L=str2.split(' ')
k = int(str1[2])
L=[int(i) for i in L]
count = 0
for i in L:
if i >= L[int(str1[2])-1] and i>0 :
count+=1
print(count)
``` | -1 | |
2 | A | Winner | PROGRAMMING | 1,500 | [
"hashing",
"implementation"
] | A. Winner | 1 | 64 | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to *m*) at the end of the game, than wins the one of them who scored at least *m* points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. | The first line contains an integer number *n* (1<=<=≤<=<=*n*<=<=≤<=<=1000), *n* is the number of rounds played. Then follow *n* lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. | Print the name of the winner. | [
"3\nmike 3\nandrew 5\nmike 2\n",
"3\nandrew 3\nandrew 2\nmike 5\n"
] | [
"andrew\n",
"andrew\n"
] | none | 0 | [
{
"input": "3\nmike 3\nandrew 5\nmike 2",
"output": "andrew"
},
{
"input": "3\nandrew 3\nandrew 2\nmike 5",
"output": "andrew"
},
{
"input": "5\nkaxqybeultn -352\nmgochgrmeyieyskhuourfg -910\nkaxqybeultn 691\nmgochgrmeyieyskhuourfg -76\nkaxqybeultn -303",
"output": "kaxqybeultn"
},... | 1,390,417,212 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 92 | 307,200 | s = input()
count = int(s)
print(count)
ppl = {}
curr_score = -1001
curr_name = ""
for i in range(count):
s = input()
l = s.split(" ")
score = int(l[1])
name = l[0]
if (score >= curr_score):
curr_score = score
curr_name = name
print(curr_name) | Title: Winner
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to *m*) at the end of the game, than wins the one of them who scored at least *m* points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
Input Specification:
The first line contains an integer number *n* (1<=<=≤<=<=*n*<=<=≤<=<=1000), *n* is the number of rounds played. Then follow *n* lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
Output Specification:
Print the name of the winner.
Demo Input:
['3\nmike 3\nandrew 5\nmike 2\n', '3\nandrew 3\nandrew 2\nmike 5\n']
Demo Output:
['andrew\n', 'andrew\n']
Note:
none | ```python
s = input()
count = int(s)
print(count)
ppl = {}
curr_score = -1001
curr_name = ""
for i in range(count):
s = input()
l = s.split(" ")
score = int(l[1])
name = l[0]
if (score >= curr_score):
curr_score = score
curr_name = name
print(curr_name)
``` | 0 |
576 | C | Points on Plane | PROGRAMMING | 2,100 | [
"constructive algorithms",
"divide and conquer",
"geometry",
"greedy",
"sortings"
] | null | null | On a plane are *n* points (*x**i*, *y**i*) with integer coordinates between 0 and 106. The distance between the two points with numbers *a* and *b* is said to be the following value: (the distance calculated by such formula is called Manhattan distance).
We call a hamiltonian path to be some permutation *p**i* of numbers from 1 to *n*. We say that the length of this path is value .
Find some hamiltonian path with a length of no more than 25<=×<=108. Note that you do not have to minimize the path length. | The first line contains integer *n* (1<=≤<=*n*<=≤<=106).
The *i*<=+<=1-th line contains the coordinates of the *i*-th point: *x**i* and *y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=106).
It is guaranteed that no two points coincide. | Print the permutation of numbers *p**i* from 1 to *n* — the sought Hamiltonian path. The permutation must meet the inequality .
If there are multiple possible answers, print any of them.
It is guaranteed that the answer exists. | [
"5\n0 7\n8 10\n3 4\n5 0\n9 12\n"
] | [
"4 3 1 2 5 \n"
] | In the sample test the total distance is:
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c772e61c616e1c27114e3facb9e6db6c5cf93b82.png" style="max-width: 100.0%;max-height: 100.0%;"/>
(|5 - 3| + |0 - 4|) + (|3 - 0| + |4 - 7|) + (|0 - 8| + |7 - 10|) + (|8 - 9| + |10 - 12|) = 2 + 4 + 3 + 3 + 8 + 3 + 1 + 2 = 26 | 1,250 | [] | 1,699,221,863 | 2,147,483,647 | PyPy 3 | TIME_LIMIT_EXCEEDED | TESTS | 5 | 2,000 | 124,518,400 | from sys import stdin,stdout
input = stdin.readline
def main():
#t = int(input())
t = 1
for z in range(t):
n = int(input())
#a,b,c = map(int,input().split())
#ai = list(map(int,input().split()))
pis = [list(map(int,input().split()))+[i+1] for i in range(n)]
num1 = 10**19
num2 = 10**14
num3 = 10**7
num4 = 10**0
def f(point):
x,y, temp = point
x2 = x // 100
y2 = y // 100
if y2%2==1:
x2 = 20001-x2
return y2 * num1 + x2*num2+x*num3+y*num4
pis.sort(key = f)
ans = [0]*n
for i in range(n):
ans[i] = pis[i][2]
print(*ans)
main()
| Title: Points on Plane
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
On a plane are *n* points (*x**i*, *y**i*) with integer coordinates between 0 and 106. The distance between the two points with numbers *a* and *b* is said to be the following value: (the distance calculated by such formula is called Manhattan distance).
We call a hamiltonian path to be some permutation *p**i* of numbers from 1 to *n*. We say that the length of this path is value .
Find some hamiltonian path with a length of no more than 25<=×<=108. Note that you do not have to minimize the path length.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=106).
The *i*<=+<=1-th line contains the coordinates of the *i*-th point: *x**i* and *y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=106).
It is guaranteed that no two points coincide.
Output Specification:
Print the permutation of numbers *p**i* from 1 to *n* — the sought Hamiltonian path. The permutation must meet the inequality .
If there are multiple possible answers, print any of them.
It is guaranteed that the answer exists.
Demo Input:
['5\n0 7\n8 10\n3 4\n5 0\n9 12\n']
Demo Output:
['4 3 1 2 5 \n']
Note:
In the sample test the total distance is:
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c772e61c616e1c27114e3facb9e6db6c5cf93b82.png" style="max-width: 100.0%;max-height: 100.0%;"/>
(|5 - 3| + |0 - 4|) + (|3 - 0| + |4 - 7|) + (|0 - 8| + |7 - 10|) + (|8 - 9| + |10 - 12|) = 2 + 4 + 3 + 3 + 8 + 3 + 1 + 2 = 26 | ```python
from sys import stdin,stdout
input = stdin.readline
def main():
#t = int(input())
t = 1
for z in range(t):
n = int(input())
#a,b,c = map(int,input().split())
#ai = list(map(int,input().split()))
pis = [list(map(int,input().split()))+[i+1] for i in range(n)]
num1 = 10**19
num2 = 10**14
num3 = 10**7
num4 = 10**0
def f(point):
x,y, temp = point
x2 = x // 100
y2 = y // 100
if y2%2==1:
x2 = 20001-x2
return y2 * num1 + x2*num2+x*num3+y*num4
pis.sort(key = f)
ans = [0]*n
for i in range(n):
ans[i] = pis[i][2]
print(*ans)
main()
``` | 0 | |
120 | A | Elevator | PROGRAMMING | 1,000 | [
"brute force",
"implementation",
"math"
] | null | null | A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand.
One day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed. | The first line indicates the door through which the very important person entered the elevator. It contains "front" if the person enters the elevator through the front door and "back" if he entered the elevator through the back door. The second line contains integer *a* (1<=≤<=*a*<=≤<=2) which denotes the number of the rail at which the person was holding. | Print character "R" if the VIP is right-handed or "L" if he is left-handed. | [
"front\n1\n"
] | [
"L\n"
] | none | 0 | [
{
"input": "front\n1",
"output": "L"
},
{
"input": "back\n1",
"output": "R"
},
{
"input": "front\n2",
"output": "R"
},
{
"input": "back\n2",
"output": "L"
}
] | 1,643,595,651 | 2,147,483,647 | PyPy 3-64 | RUNTIME_ERROR | TESTS | 0 | 124 | 3,379,200 | i = input()
a = input()
a = int(a)
#list(map(int, input().strip().split()))
if i == "front":
if a == 1:
print("L")
if a == 2:
print("R")
else:
if a == 1:
print("R")
if a == 2:
print("L") | Title: Elevator
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand.
One day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed.
Input Specification:
The first line indicates the door through which the very important person entered the elevator. It contains "front" if the person enters the elevator through the front door and "back" if he entered the elevator through the back door. The second line contains integer *a* (1<=≤<=*a*<=≤<=2) which denotes the number of the rail at which the person was holding.
Output Specification:
Print character "R" if the VIP is right-handed or "L" if he is left-handed.
Demo Input:
['front\n1\n']
Demo Output:
['L\n']
Note:
none | ```python
i = input()
a = input()
a = int(a)
#list(map(int, input().strip().split()))
if i == "front":
if a == 1:
print("L")
if a == 2:
print("R")
else:
if a == 1:
print("R")
if a == 2:
print("L")
``` | -1 | |
729 | B | Spotlights | PROGRAMMING | 1,200 | [
"dp",
"implementation"
] | null | null | Theater stage is a rectangular field of size *n*<=×<=*m*. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.
A position is good if two conditions hold:
- there is no actor in the cell the spotlight is placed to; - there is at least one actor in the direction the spotlight projects.
Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ. | The first line contains two positive integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and the number of columns in the plan.
The next *n* lines contain *m* integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan. | Print one integer — the number of good positions for placing the spotlight. | [
"2 4\n0 1 0 0\n1 0 1 0\n",
"4 4\n0 0 0 0\n1 0 0 1\n0 1 1 0\n0 1 0 0\n"
] | [
"9\n",
"20\n"
] | In the first example the following positions are good:
1. the (1, 1) cell and right direction; 1. the (1, 1) cell and down direction; 1. the (1, 3) cell and left direction; 1. the (1, 3) cell and down direction; 1. the (1, 4) cell and left direction; 1. the (2, 2) cell and left direction; 1. the (2, 2) cell and up direction; 1. the (2, 2) and right direction; 1. the (2, 4) cell and left direction.
Therefore, there are 9 good positions in this example. | 1,000 | [
{
"input": "2 4\n0 1 0 0\n1 0 1 0",
"output": "9"
},
{
"input": "4 4\n0 0 0 0\n1 0 0 1\n0 1 1 0\n0 1 0 0",
"output": "20"
},
{
"input": "1 5\n1 1 0 0 0",
"output": "3"
},
{
"input": "2 10\n0 0 0 0 0 0 0 1 0 0\n1 0 0 0 0 0 0 0 0 0",
"output": "20"
},
{
"input": "3 ... | 1,554,803,255 | 2,147,483,647 | Python 3 | OK | TESTS | 72 | 764 | 5,427,200 | def run(l):
r = 0
for i in range(len(l)):
b = False
for j in l[i]:
if j == '1': b = True
if j == '0' and b == True: r += 1
return r
a, b = map(int, input().split())
r = ["".join(input().split()) for i in range(a)]
l = [i[::-1] for i in r]
u = ["".join([i[j] for i in r]) for j in range(b)]
d = [i[::-1] for i in u]
print(run(l) + run(r) + run(u) + run(d)) | Title: Spotlights
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Theater stage is a rectangular field of size *n*<=×<=*m*. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.
A position is good if two conditions hold:
- there is no actor in the cell the spotlight is placed to; - there is at least one actor in the direction the spotlight projects.
Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.
Input Specification:
The first line contains two positive integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and the number of columns in the plan.
The next *n* lines contain *m* integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.
Output Specification:
Print one integer — the number of good positions for placing the spotlight.
Demo Input:
['2 4\n0 1 0 0\n1 0 1 0\n', '4 4\n0 0 0 0\n1 0 0 1\n0 1 1 0\n0 1 0 0\n']
Demo Output:
['9\n', '20\n']
Note:
In the first example the following positions are good:
1. the (1, 1) cell and right direction; 1. the (1, 1) cell and down direction; 1. the (1, 3) cell and left direction; 1. the (1, 3) cell and down direction; 1. the (1, 4) cell and left direction; 1. the (2, 2) cell and left direction; 1. the (2, 2) cell and up direction; 1. the (2, 2) and right direction; 1. the (2, 4) cell and left direction.
Therefore, there are 9 good positions in this example. | ```python
def run(l):
r = 0
for i in range(len(l)):
b = False
for j in l[i]:
if j == '1': b = True
if j == '0' and b == True: r += 1
return r
a, b = map(int, input().split())
r = ["".join(input().split()) for i in range(a)]
l = [i[::-1] for i in r]
u = ["".join([i[j] for i in r]) for j in range(b)]
d = [i[::-1] for i in u]
print(run(l) + run(r) + run(u) + run(d))
``` | 3 | |
243 | A | The Brand New Function | PROGRAMMING | 1,600 | [
"bitmasks"
] | null | null | Polycarpus has a sequence, consisting of *n* non-negative integers: *a*1,<=*a*2,<=...,<=*a**n*.
Let's define function *f*(*l*,<=*r*) (*l*,<=*r* are integer, 1<=≤<=*l*<=≤<=*r*<=≤<=*n*) for sequence *a* as an operation of bitwise OR of all the sequence elements with indexes from *l* to *r*. Formally: *f*(*l*,<=*r*)<==<=*a**l* | *a**l*<=+<=1 | ... | *a**r*.
Polycarpus took a piece of paper and wrote out the values of function *f*(*l*,<=*r*) for all *l*,<=*r* (*l*,<=*r* are integer, 1<=≤<=*l*<=≤<=*r*<=≤<=*n*). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function *f*(*l*,<=*r*) for the given sequence *a*.
Expression *x* | *y* means applying the operation of bitwise OR to numbers *x* and *y*. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or". | The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements of sequence *a*. The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=106) — the elements of sequence *a*. | Print a single integer — the number of distinct values of function *f*(*l*,<=*r*) for the given sequence *a*.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. | [
"3\n1 2 0\n",
"10\n1 2 3 4 5 6 1 2 9 10\n"
] | [
"4",
"11"
] | In the first test case Polycarpus will have 6 numbers written on the paper: *f*(1, 1) = 1, *f*(1, 2) = 3, *f*(1, 3) = 3, *f*(2, 2) = 2, *f*(2, 3) = 2, *f*(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3. | 500 | [
{
"input": "3\n1 2 0",
"output": "4"
},
{
"input": "10\n1 2 3 4 5 6 1 2 9 10",
"output": "11"
},
{
"input": "1\n123",
"output": "1"
},
{
"input": "10\n6 8 4 5 1 9 10 2 3 7",
"output": "15"
},
{
"input": "7\n1 2 4 8 16 32 64",
"output": "28"
},
{
"input... | 1,513,804,178 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = (l); i < (r); ++i)
#define forn(i, n) fore(i, 0, n)
#define fori(i, l, r) fore(i, l, (r) + 1)
#define all(v) (v).begin(), (v).end()
#define pb push_back
#define mp make_pair
#define max1 1000000007
typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;
int main()
{
iostream::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
li n;
cin>>n;
set<int>s1,s2;
li a[n];
forn(i,n)
cin>>a[i];
vector<int>v;
forn(i,n)
{
s1.insert(a[i]);
s2.insert(a[i]);
set<int>::iterator it;
for(it=s1.begin();it!=s1.end();it++)
{
v.pb(a[i]|(*it));
s2.insert(a[i]|(*it));
}
s1.clear();
forn(i,v.size())
{
s1.insert(v[i]);
}
v.clear();
}
cout<<s2.size();
}
| Title: The Brand New Function
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarpus has a sequence, consisting of *n* non-negative integers: *a*1,<=*a*2,<=...,<=*a**n*.
Let's define function *f*(*l*,<=*r*) (*l*,<=*r* are integer, 1<=≤<=*l*<=≤<=*r*<=≤<=*n*) for sequence *a* as an operation of bitwise OR of all the sequence elements with indexes from *l* to *r*. Formally: *f*(*l*,<=*r*)<==<=*a**l* | *a**l*<=+<=1 | ... | *a**r*.
Polycarpus took a piece of paper and wrote out the values of function *f*(*l*,<=*r*) for all *l*,<=*r* (*l*,<=*r* are integer, 1<=≤<=*l*<=≤<=*r*<=≤<=*n*). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function *f*(*l*,<=*r*) for the given sequence *a*.
Expression *x* | *y* means applying the operation of bitwise OR to numbers *x* and *y*. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements of sequence *a*. The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=106) — the elements of sequence *a*.
Output Specification:
Print a single integer — the number of distinct values of function *f*(*l*,<=*r*) for the given sequence *a*.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Demo Input:
['3\n1 2 0\n', '10\n1 2 3 4 5 6 1 2 9 10\n']
Demo Output:
['4', '11']
Note:
In the first test case Polycarpus will have 6 numbers written on the paper: *f*(1, 1) = 1, *f*(1, 2) = 3, *f*(1, 3) = 3, *f*(2, 2) = 2, *f*(2, 3) = 2, *f*(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3. | ```python
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = (l); i < (r); ++i)
#define forn(i, n) fore(i, 0, n)
#define fori(i, l, r) fore(i, l, (r) + 1)
#define all(v) (v).begin(), (v).end()
#define pb push_back
#define mp make_pair
#define max1 1000000007
typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;
int main()
{
iostream::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
li n;
cin>>n;
set<int>s1,s2;
li a[n];
forn(i,n)
cin>>a[i];
vector<int>v;
forn(i,n)
{
s1.insert(a[i]);
s2.insert(a[i]);
set<int>::iterator it;
for(it=s1.begin();it!=s1.end();it++)
{
v.pb(a[i]|(*it));
s2.insert(a[i]|(*it));
}
s1.clear();
forn(i,v.size())
{
s1.insert(v[i]);
}
v.clear();
}
cout<<s2.size();
}
``` | -1 | |
909 | A | Generate Login | PROGRAMMING | 1,000 | [
"brute force",
"greedy",
"sortings"
] | null | null | The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string *s* is its substring which occurs at the beginning of *s*: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string *a* is alphabetically earlier than a string *b*, if *a* is a prefix of *b*, or *a* and *b* coincide up to some position, and then *a* has a letter that is alphabetically earlier than the corresponding letter in *b*: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac". | The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive. | Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well. | [
"harry potter\n",
"tom riddle\n"
] | [
"hap\n",
"tomr\n"
] | none | 500 | [
{
"input": "harry potter",
"output": "hap"
},
{
"input": "tom riddle",
"output": "tomr"
},
{
"input": "a qdpinbmcrf",
"output": "aq"
},
{
"input": "wixjzniiub ssdfodfgap",
"output": "wis"
},
{
"input": "z z",
"output": "zz"
},
{
"input": "ertuyivhfg v"... | 1,514,393,684 | 1,184 | Python 3 | OK | TESTS | 64 | 77 | 5,529,600 | a=input()
x=a.find(' ')
s=a[0]
#print(x)
z=0
for i in range(1,x):
#print(a[i],a[x+1])
if ord(a[i]) < ord (a[x+1]):
s+=a[i]
else:
s+=a[x+1]
z=1
break
if z == 0:
s+=a[x+1]
print(s)
| Title: Generate Login
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string *s* is its substring which occurs at the beginning of *s*: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string *a* is alphabetically earlier than a string *b*, if *a* is a prefix of *b*, or *a* and *b* coincide up to some position, and then *a* has a letter that is alphabetically earlier than the corresponding letter in *b*: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input Specification:
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output Specification:
Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Demo Input:
['harry potter\n', 'tom riddle\n']
Demo Output:
['hap\n', 'tomr\n']
Note:
none | ```python
a=input()
x=a.find(' ')
s=a[0]
#print(x)
z=0
for i in range(1,x):
#print(a[i],a[x+1])
if ord(a[i]) < ord (a[x+1]):
s+=a[i]
else:
s+=a[x+1]
z=1
break
if z == 0:
s+=a[x+1]
print(s)
``` | 3 | |
115 | A | Party | PROGRAMMING | 900 | [
"dfs and similar",
"graphs",
"trees"
] | null | null | A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true:
- Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*.
What is the minimum number of groups that must be formed? | The first line contains integer *n* (1<=≤<=*n*<=≤<=2000) — the number of employees.
The next *n* lines contain the integers *p**i* (1<=≤<=*p**i*<=≤<=*n* or *p**i*<==<=-1). Every *p**i* denotes the immediate manager for the *i*-th employee. If *p**i* is -1, that means that the *i*-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (*p**i*<=≠<=*i*). Also, there will be no managerial cycles. | Print a single integer denoting the minimum number of groups that will be formed in the party. | [
"5\n-1\n1\n2\n1\n-1\n"
] | [
"3\n"
] | For the first example, three groups are sufficient, for example:
- Employee 1 - Employees 2 and 4 - Employees 3 and 5 | 500 | [
{
"input": "5\n-1\n1\n2\n1\n-1",
"output": "3"
},
{
"input": "4\n-1\n1\n2\n3",
"output": "4"
},
{
"input": "12\n-1\n1\n2\n3\n-1\n5\n6\n7\n-1\n9\n10\n11",
"output": "4"
},
{
"input": "6\n-1\n-1\n2\n3\n1\n1",
"output": "3"
},
{
"input": "3\n-1\n1\n1",
"output": ... | 1,675,213,666 | 2,147,483,647 | Python 3 | OK | TESTS | 106 | 122 | 0 | def DFS(u):
stack = [(1, u)]
depth = 0
while len(stack) > 0:
d, u = stack.pop()
depth = max(d, depth)
for v in G[u]:
stack.append((d+1, v))
return depth
V = int(input())
G = [[] for _ in range(V)]
D = [0] * V
for u in range(V):
v = int(input())
if v != -1:
G[v-1].append(u)
D[u] += 1
depth = 0
for u in range(V):
if D[u] == 0:
depth = max(depth, DFS(u))
print(depth)
| Title: Party
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true:
- Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*.
What is the minimum number of groups that must be formed?
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=2000) — the number of employees.
The next *n* lines contain the integers *p**i* (1<=≤<=*p**i*<=≤<=*n* or *p**i*<==<=-1). Every *p**i* denotes the immediate manager for the *i*-th employee. If *p**i* is -1, that means that the *i*-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (*p**i*<=≠<=*i*). Also, there will be no managerial cycles.
Output Specification:
Print a single integer denoting the minimum number of groups that will be formed in the party.
Demo Input:
['5\n-1\n1\n2\n1\n-1\n']
Demo Output:
['3\n']
Note:
For the first example, three groups are sufficient, for example:
- Employee 1 - Employees 2 and 4 - Employees 3 and 5 | ```python
def DFS(u):
stack = [(1, u)]
depth = 0
while len(stack) > 0:
d, u = stack.pop()
depth = max(d, depth)
for v in G[u]:
stack.append((d+1, v))
return depth
V = int(input())
G = [[] for _ in range(V)]
D = [0] * V
for u in range(V):
v = int(input())
if v != -1:
G[v-1].append(u)
D[u] += 1
depth = 0
for u in range(V):
if D[u] == 0:
depth = max(depth, DFS(u))
print(depth)
``` | 3 | |
955 | A | Feed the cat | PROGRAMMING | 1,100 | [
"greedy",
"math"
] | null | null | After waking up at *hh*:*mm*, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is *H* points, moreover each minute without food increases his hunger by *D* points.
At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs *C* roubles and decreases hunger by *N* points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.
Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | The first line contains two integers *hh* and *mm* (00<=≤<=*hh*<=≤<=23,<=00<=≤<=*mm*<=≤<=59) — the time of Andrew's awakening.
The second line contains four integers *H*, *D*, *C* and *N* (1<=≤<=*H*<=≤<=105,<=1<=≤<=*D*,<=*C*,<=*N*<=≤<=102). | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10<=-<=4.
Formally, let your answer be *a*, and the jury's answer be *b*. Your answer is considered correct if . | [
"19 00\n255 1 100 1\n",
"17 41\n1000 6 15 11\n"
] | [
"25200.0000\n",
"1365.0000\n"
] | In the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.
In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | 500 | [
{
"input": "19 00\n255 1 100 1",
"output": "25200.0000"
},
{
"input": "17 41\n1000 6 15 11",
"output": "1365.0000"
},
{
"input": "16 34\n61066 14 50 59",
"output": "43360.0000"
},
{
"input": "18 18\n23331 86 87 41",
"output": "49590.0000"
},
{
"input": "10 48\n684... | 1,521,827,667 | 4,767 | Python 3 | WRONG_ANSWER | PRETESTS | 7 | 124 | 8,192,000 | #author:@karngyan
FMT='%H:%M'
from datetime import datetime
import math
def calc(hh,mm,h,d,c,n,s,s2):
a=1000000000000.0
b=(math.ceil(h/n)*c)
if(hh<20):
extra=datetime.strptime(s2,FMT)-datetime.strptime(s,FMT)
extra=extra.seconds
extra/=60
h+=(d*extra)
a=(math.ceil(h/n)*c*0.8)
print("%.5f" %min(a,b))
s2='20:00'
s=input()
hh,mm=map(int, s.split(' '))
s=str(hh)+':'+str(mm)
h,d,c,n=map(int, input().split(' '))
calc(hh,mm,h,d,c,n,s,s2)
| Title: Feed the cat
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After waking up at *hh*:*mm*, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is *H* points, moreover each minute without food increases his hunger by *D* points.
At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs *C* roubles and decreases hunger by *N* points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.
Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.
Input Specification:
The first line contains two integers *hh* and *mm* (00<=≤<=*hh*<=≤<=23,<=00<=≤<=*mm*<=≤<=59) — the time of Andrew's awakening.
The second line contains four integers *H*, *D*, *C* and *N* (1<=≤<=*H*<=≤<=105,<=1<=≤<=*D*,<=*C*,<=*N*<=≤<=102).
Output Specification:
Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10<=-<=4.
Formally, let your answer be *a*, and the jury's answer be *b*. Your answer is considered correct if .
Demo Input:
['19 00\n255 1 100 1\n', '17 41\n1000 6 15 11\n']
Demo Output:
['25200.0000\n', '1365.0000\n']
Note:
In the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.
In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | ```python
#author:@karngyan
FMT='%H:%M'
from datetime import datetime
import math
def calc(hh,mm,h,d,c,n,s,s2):
a=1000000000000.0
b=(math.ceil(h/n)*c)
if(hh<20):
extra=datetime.strptime(s2,FMT)-datetime.strptime(s,FMT)
extra=extra.seconds
extra/=60
h+=(d*extra)
a=(math.ceil(h/n)*c*0.8)
print("%.5f" %min(a,b))
s2='20:00'
s=input()
hh,mm=map(int, s.split(' '))
s=str(hh)+':'+str(mm)
h,d,c,n=map(int, input().split(' '))
calc(hh,mm,h,d,c,n,s,s2)
``` | 0 | |
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,697,390,280 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 29 | 61 | 0 | n, b = map(int, input().split())
print(n + sum([1 for i in input().split() if int(i) > b])) | 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, b = map(int, input().split())
print(n + sum([1 for i in input().split() if int(i) > b]))
``` | 3 | |
621 | C | Wet Shark and Flowers | PROGRAMMING | 1,700 | [
"combinatorics",
"math",
"number theory",
"probabilities"
] | null | null | There are *n* sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks *i* and *i*<=+<=1 are neighbours for all *i* from 1 to *n*<=-<=1. Sharks *n* and 1 are neighbours too.
Each shark will grow some number of flowers *s**i*. For *i*-th shark value *s**i* is random integer equiprobably chosen in range from *l**i* to *r**i*. Wet Shark has it's favourite prime number *p*, and he really likes it! If for any pair of neighbouring sharks *i* and *j* the product *s**i*·*s**j* is divisible by *p*, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.
At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value. | The first line of the input contains two space-separated integers *n* and *p* (3<=≤<=*n*<=≤<=100<=000,<=2<=≤<=*p*<=≤<=109) — the number of sharks and Wet Shark's favourite prime number. It is guaranteed that *p* is prime.
The *i*-th of the following *n* lines contains information about *i*-th shark — two space-separated integers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=109), the range of flowers shark *i* can produce. Remember that *s**i* is chosen equiprobably among all integers from *l**i* to *r**i*, inclusive. | Print a single real number — the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6.
Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct, if . | [
"3 2\n1 2\n420 421\n420420 420421\n",
"3 5\n1 4\n2 3\n11 14\n"
] | [
"4500.0\n",
"0.0\n"
] | A prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.
Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (*s*<sub class="lower-index">0</sub>, *s*<sub class="lower-index">1</sub>, *s*<sub class="lower-index">2</sub>) each shark grows:
1. (1, 420, 420420): note that *s*<sub class="lower-index">0</sub>·*s*<sub class="lower-index">1</sub> = 420, *s*<sub class="lower-index">1</sub>·*s*<sub class="lower-index">2</sub> = 176576400, and *s*<sub class="lower-index">2</sub>·*s*<sub class="lower-index">0</sub> = 420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars.1. (1, 420, 420421): now, the product *s*<sub class="lower-index">2</sub>·*s*<sub class="lower-index">0</sub> is not divisible by 2. Therefore, sharks *s*<sub class="lower-index">0</sub> and *s*<sub class="lower-index">2</sub> will receive 1000 dollars, while shark *s*<sub class="lower-index">1</sub> will receive 2000. The total is 4000.1. (1, 421, 420420): total is 4000 1. (1, 421, 420421): total is 0. 1. (2, 420, 420420): total is 6000. 1. (2, 420, 420421): total is 6000. 1. (2, 421, 420420): total is 6000. 1. (2, 421, 420421): total is 4000.
The expected value is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/dfe520d00a8615f7c270ccbccbebe182cc7db883.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the second sample, no combination of quantities will garner the sharks any money. | 1,500 | [
{
"input": "3 2\n1 2\n420 421\n420420 420421",
"output": "4500.0"
},
{
"input": "3 5\n1 4\n2 3\n11 14",
"output": "0.0"
},
{
"input": "3 3\n3 3\n2 4\n1 1",
"output": "4666.666666666667"
},
{
"input": "5 5\n5 204\n420 469\n417 480\n442 443\n44 46",
"output": "3451.25"
},... | 1,689,453,234 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 31 | 0 | print("_RANDOM_GUESS_1689453234.8501217")# 1689453234.8501415 | Title: Wet Shark and Flowers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks *i* and *i*<=+<=1 are neighbours for all *i* from 1 to *n*<=-<=1. Sharks *n* and 1 are neighbours too.
Each shark will grow some number of flowers *s**i*. For *i*-th shark value *s**i* is random integer equiprobably chosen in range from *l**i* to *r**i*. Wet Shark has it's favourite prime number *p*, and he really likes it! If for any pair of neighbouring sharks *i* and *j* the product *s**i*·*s**j* is divisible by *p*, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.
At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.
Input Specification:
The first line of the input contains two space-separated integers *n* and *p* (3<=≤<=*n*<=≤<=100<=000,<=2<=≤<=*p*<=≤<=109) — the number of sharks and Wet Shark's favourite prime number. It is guaranteed that *p* is prime.
The *i*-th of the following *n* lines contains information about *i*-th shark — two space-separated integers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=109), the range of flowers shark *i* can produce. Remember that *s**i* is chosen equiprobably among all integers from *l**i* to *r**i*, inclusive.
Output Specification:
Print a single real number — the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6.
Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct, if .
Demo Input:
['3 2\n1 2\n420 421\n420420 420421\n', '3 5\n1 4\n2 3\n11 14\n']
Demo Output:
['4500.0\n', '0.0\n']
Note:
A prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.
Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (*s*<sub class="lower-index">0</sub>, *s*<sub class="lower-index">1</sub>, *s*<sub class="lower-index">2</sub>) each shark grows:
1. (1, 420, 420420): note that *s*<sub class="lower-index">0</sub>·*s*<sub class="lower-index">1</sub> = 420, *s*<sub class="lower-index">1</sub>·*s*<sub class="lower-index">2</sub> = 176576400, and *s*<sub class="lower-index">2</sub>·*s*<sub class="lower-index">0</sub> = 420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars.1. (1, 420, 420421): now, the product *s*<sub class="lower-index">2</sub>·*s*<sub class="lower-index">0</sub> is not divisible by 2. Therefore, sharks *s*<sub class="lower-index">0</sub> and *s*<sub class="lower-index">2</sub> will receive 1000 dollars, while shark *s*<sub class="lower-index">1</sub> will receive 2000. The total is 4000.1. (1, 421, 420420): total is 4000 1. (1, 421, 420421): total is 0. 1. (2, 420, 420420): total is 6000. 1. (2, 420, 420421): total is 6000. 1. (2, 421, 420420): total is 6000. 1. (2, 421, 420421): total is 4000.
The expected value is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/dfe520d00a8615f7c270ccbccbebe182cc7db883.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the second sample, no combination of quantities will garner the sharks any money. | ```python
print("_RANDOM_GUESS_1689453234.8501217")# 1689453234.8501415
``` | 0 | |
44 | H | Phone Number | PROGRAMMING | 1,700 | [
"dp"
] | H. Phone Number | 2 | 256 | Alas, finding one's true love is not easy. Masha has been unsuccessful in that yet. Her friend Dasha told Masha about a way to determine the phone number of one's Prince Charming through arithmancy.
The phone number is divined like that. First one needs to write down one's own phone numbers. For example, let's suppose that Masha's phone number is 12345. After that one should write her favorite digit from 0 to 9 under the first digit of her number. That will be the first digit of the needed number. For example, Masha's favorite digit is 9. The second digit is determined as a half sum of the second digit of Masha's number and the already written down first digit from her beloved one's number. In this case the arithmetic average equals to (2<=+<=9)<=/<=2<==<=5.5. Masha can round the number up or down, depending on her wishes. For example, she chooses the digit 5. Having written down the resulting digit under the second digit of her number, Masha moves to finding the third digit in the same way, i.e. finding the half sum the the third digit of her number and the second digit of the new number. The result is (5<=+<=3)<=/<=2<==<=4. In this case the answer is unique. Thus, every *i*-th digit is determined as an arithmetic average of the *i*-th digit of Masha's number and the *i*<=-<=1-th digit of her true love's number. If needed, the digit can be rounded up or down. For example, Masha can get: | The first line contains nonempty sequence consisting of digits from 0 to 9 — Masha's phone number. The sequence length does not exceed 50. | Output the single number — the number of phone numbers Masha will dial. | [
"12345\n",
"09\n"
] | [
"48\n",
"15\n"
] | none | 0 | [
{
"input": "12345",
"output": "48"
},
{
"input": "09",
"output": "15"
},
{
"input": "3",
"output": "9"
},
{
"input": "55",
"output": "14"
},
{
"input": "737",
"output": "23"
},
{
"input": "21583",
"output": "55"
},
{
"input": "33408349",
... | 1,658,923,333 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 27 | 218 | 8,908,800 | from operator import itemgetter
from typing import *
from collections import deque, Counter, defaultdict
from bisect import *
import heapq, math
from functools import cmp_to_key, reduce
# from sortedcontainers import SortedSet, SortedList
def main():
s = list(map(int, input()))
n = len(s)
dp = [[0 for _ in range(10)] for _ in range(n)]
for i in range(10):
dp[0][i] = 1
for i in range(1, n):
for j in range(10):
if (s[i] + j) % 2 == 1:
dp[i][(s[i] + j - 1) // 2] += dp[i - 1][j]
dp[i][(s[i] + j + 1) // 2] += dp[i - 1][j]
else:
dp[i][(s[i] + j) // 2] += dp[i - 1][j]
print(sum(dp[n - 1]) - all((abs(x - y) < 2 for x, y in zip(s[:-1], s[1:]))))
main()
| Title: Phone Number
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Alas, finding one's true love is not easy. Masha has been unsuccessful in that yet. Her friend Dasha told Masha about a way to determine the phone number of one's Prince Charming through arithmancy.
The phone number is divined like that. First one needs to write down one's own phone numbers. For example, let's suppose that Masha's phone number is 12345. After that one should write her favorite digit from 0 to 9 under the first digit of her number. That will be the first digit of the needed number. For example, Masha's favorite digit is 9. The second digit is determined as a half sum of the second digit of Masha's number and the already written down first digit from her beloved one's number. In this case the arithmetic average equals to (2<=+<=9)<=/<=2<==<=5.5. Masha can round the number up or down, depending on her wishes. For example, she chooses the digit 5. Having written down the resulting digit under the second digit of her number, Masha moves to finding the third digit in the same way, i.e. finding the half sum the the third digit of her number and the second digit of the new number. The result is (5<=+<=3)<=/<=2<==<=4. In this case the answer is unique. Thus, every *i*-th digit is determined as an arithmetic average of the *i*-th digit of Masha's number and the *i*<=-<=1-th digit of her true love's number. If needed, the digit can be rounded up or down. For example, Masha can get:
Input Specification:
The first line contains nonempty sequence consisting of digits from 0 to 9 — Masha's phone number. The sequence length does not exceed 50.
Output Specification:
Output the single number — the number of phone numbers Masha will dial.
Demo Input:
['12345\n', '09\n']
Demo Output:
['48\n', '15\n']
Note:
none | ```python
from operator import itemgetter
from typing import *
from collections import deque, Counter, defaultdict
from bisect import *
import heapq, math
from functools import cmp_to_key, reduce
# from sortedcontainers import SortedSet, SortedList
def main():
s = list(map(int, input()))
n = len(s)
dp = [[0 for _ in range(10)] for _ in range(n)]
for i in range(10):
dp[0][i] = 1
for i in range(1, n):
for j in range(10):
if (s[i] + j) % 2 == 1:
dp[i][(s[i] + j - 1) // 2] += dp[i - 1][j]
dp[i][(s[i] + j + 1) // 2] += dp[i - 1][j]
else:
dp[i][(s[i] + j) // 2] += dp[i - 1][j]
print(sum(dp[n - 1]) - all((abs(x - y) < 2 for x, y in zip(s[:-1], s[1:]))))
main()
``` | 3.928906 |
265 | B | Roadside Trees (Simplified Edition) | PROGRAMMING | 1,000 | [
"greedy",
"implementation"
] | null | null | Squirrel Liss loves nuts. There are *n* trees (numbered 1 to *n* from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree *i* is *h**i*. Liss wants to eat all nuts.
Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions:
- Walk up or down one unit on a tree. - Eat a nut on the top of the current tree. - Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height *h* of the tree *i* (1<=≤<=*i*<=≤<=*n*<=-<=1), she jumps to height *h* of the tree *i*<=+<=1. This action can't be performed if *h*<=><=*h**i*<=+<=1.
Compute the minimal time (in seconds) required to eat all nuts. | The first line contains an integer *n* (1<=<=≤<=<=*n*<=≤<=105) — the number of trees.
Next *n* lines contains the height of trees: *i*-th line contains an integer *h**i* (1<=≤<=*h**i*<=≤<=104) — the height of the tree with the number *i*. | Print a single integer — the minimal time required to eat all nuts in seconds. | [
"2\n1\n2\n",
"5\n2\n1\n2\n1\n1\n"
] | [
"5\n",
"14\n"
] | none | 1,000 | [
{
"input": "2\n1\n2",
"output": "5"
},
{
"input": "5\n2\n1\n2\n1\n1",
"output": "14"
},
{
"input": "1\n1",
"output": "2"
}
] | 1,672,172,081 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 15 | 1,120 | 8,908,800 | n = int(input())
trees = []
for i in range(n):
trees.append(int(input()))
count = n - 1
now = 0
for i in range(n):
if now < trees[i]:
count += trees[i] - now + 1
else:
count += now - trees[i] + 1
now = trees[i]
print(count) | Title: Roadside Trees (Simplified Edition)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Squirrel Liss loves nuts. There are *n* trees (numbered 1 to *n* from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree *i* is *h**i*. Liss wants to eat all nuts.
Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions:
- Walk up or down one unit on a tree. - Eat a nut on the top of the current tree. - Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height *h* of the tree *i* (1<=≤<=*i*<=≤<=*n*<=-<=1), she jumps to height *h* of the tree *i*<=+<=1. This action can't be performed if *h*<=><=*h**i*<=+<=1.
Compute the minimal time (in seconds) required to eat all nuts.
Input Specification:
The first line contains an integer *n* (1<=<=≤<=<=*n*<=≤<=105) — the number of trees.
Next *n* lines contains the height of trees: *i*-th line contains an integer *h**i* (1<=≤<=*h**i*<=≤<=104) — the height of the tree with the number *i*.
Output Specification:
Print a single integer — the minimal time required to eat all nuts in seconds.
Demo Input:
['2\n1\n2\n', '5\n2\n1\n2\n1\n1\n']
Demo Output:
['5\n', '14\n']
Note:
none | ```python
n = int(input())
trees = []
for i in range(n):
trees.append(int(input()))
count = n - 1
now = 0
for i in range(n):
if now < trees[i]:
count += trees[i] - now + 1
else:
count += now - trees[i] + 1
now = trees[i]
print(count)
``` | 3 | |
260 | A | Adding Digits | PROGRAMMING | 1,400 | [
"implementation",
"math"
] | null | null | Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times.
One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number *b*. If it is impossible to obtain the number which is divisible by *b*, then the lengthening operation cannot be performed.
Your task is to help Vasya and print the number he can get after applying the lengthening operation to number *a* *n* times. | The first line contains three integers: *a*,<=*b*,<=*n* (1<=≤<=*a*,<=*b*,<=*n*<=≤<=105). | In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number *a* *n* times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them. | [
"5 4 5\n",
"12 11 1\n",
"260 150 10\n"
] | [
"524848\n",
"121\n",
"-1\n"
] | none | 500 | [
{
"input": "5 4 5",
"output": "524848"
},
{
"input": "12 11 1",
"output": "121"
},
{
"input": "260 150 10",
"output": "-1"
},
{
"input": "78843 5684 42717",
"output": "-1"
},
{
"input": "93248 91435 1133",
"output": "-1"
},
{
"input": "100000 10 64479"... | 1,600,428,744 | 2,147,483,647 | PyPy 3 | TIME_LIMIT_EXCEEDED | TESTS | 5 | 2,000 | 6,758,400 | a, b, n = map(int, input().split())
flag = 0
for i in range(n):
flag = 0
for j in range(0,10):
if ((a*10) + j) % b == 0 :
a = ((a*10) + j)
flag = int(1)
break
if flag == 0 :
flag = 0
break
if flag == 0 :
print("-1")
else:
print(a) | Title: Adding Digits
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times.
One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number *b*. If it is impossible to obtain the number which is divisible by *b*, then the lengthening operation cannot be performed.
Your task is to help Vasya and print the number he can get after applying the lengthening operation to number *a* *n* times.
Input Specification:
The first line contains three integers: *a*,<=*b*,<=*n* (1<=≤<=*a*,<=*b*,<=*n*<=≤<=105).
Output Specification:
In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number *a* *n* times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them.
Demo Input:
['5 4 5\n', '12 11 1\n', '260 150 10\n']
Demo Output:
['524848\n', '121\n', '-1\n']
Note:
none | ```python
a, b, n = map(int, input().split())
flag = 0
for i in range(n):
flag = 0
for j in range(0,10):
if ((a*10) + j) % b == 0 :
a = ((a*10) + j)
flag = int(1)
break
if flag == 0 :
flag = 0
break
if flag == 0 :
print("-1")
else:
print(a)
``` | 0 | |
722 | B | Verse Pattern | PROGRAMMING | 1,200 | [
"implementation",
"strings"
] | null | null | You are given a text consisting of *n* lines. Each line contains some space-separated words, consisting of lowercase English letters.
We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.
Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored.
The verse patterns for the given text is a sequence of *n* integers *p*1,<=*p*2,<=...,<=*p**n*. Text matches the given verse pattern if for each *i* from 1 to *n* one can divide words of the *i*-th line in syllables in such a way that the total number of syllables is equal to *p**i*.
You are given the text and the verse pattern. Check, if the given text matches the given verse pattern. | The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of lines in the text.
The second line contains integers *p*1,<=...,<=*p**n* (0<=≤<=*p**i*<=≤<=100) — the verse pattern.
Next *n* lines contain the text itself. Text consists of lowercase English letters and spaces. It's guaranteed that all lines are non-empty, each line starts and ends with a letter and words are separated by exactly one space. The length of each line doesn't exceed 100 characters. | If the given text matches the given verse pattern, then print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes). | [
"3\n2 2 3\nintel\ncode\nch allenge\n",
"4\n1 2 3 1\na\nbcdefghi\njklmnopqrstu\nvwxyz\n",
"4\n13 11 15 15\nto be or not to be that is the question\nwhether tis nobler in the mind to suffer\nthe slings and arrows of outrageous fortune\nor to take arms against a sea of troubles\n"
] | [
"YES\n",
"NO\n",
"YES\n"
] | In the first sample, one can split words into syllables in the following way:
Since the word "ch" in the third line doesn't contain vowels, we can ignore it. As the result we get 2 syllabels in first two lines and 3 syllables in the third one. | 500 | [
{
"input": "3\n2 2 3\nintel\ncode\nch allenge",
"output": "YES"
},
{
"input": "4\n1 2 3 1\na\nbcdefghi\njklmnopqrstu\nvwxyz",
"output": "NO"
},
{
"input": "4\n13 11 15 15\nto be or not to be that is the question\nwhether tis nobler in the mind to suffer\nthe slings and arrows of outrageo... | 1,555,250,474 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 108 | 0 | import sys
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
sys.stdin.readline()
ideal = [int(num) for num in sys.stdin.readline().split()]
real = []
for line in sys.stdin:
real.append(len([c for c in line if c in vowels]))
print(ideal)
print(real)
if real == ideal:
print("YES")
else:
print("NO") | Title: Verse Pattern
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a text consisting of *n* lines. Each line contains some space-separated words, consisting of lowercase English letters.
We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.
Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored.
The verse patterns for the given text is a sequence of *n* integers *p*1,<=*p*2,<=...,<=*p**n*. Text matches the given verse pattern if for each *i* from 1 to *n* one can divide words of the *i*-th line in syllables in such a way that the total number of syllables is equal to *p**i*.
You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.
Input Specification:
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of lines in the text.
The second line contains integers *p*1,<=...,<=*p**n* (0<=≤<=*p**i*<=≤<=100) — the verse pattern.
Next *n* lines contain the text itself. Text consists of lowercase English letters and spaces. It's guaranteed that all lines are non-empty, each line starts and ends with a letter and words are separated by exactly one space. The length of each line doesn't exceed 100 characters.
Output Specification:
If the given text matches the given verse pattern, then print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).
Demo Input:
['3\n2 2 3\nintel\ncode\nch allenge\n', '4\n1 2 3 1\na\nbcdefghi\njklmnopqrstu\nvwxyz\n', '4\n13 11 15 15\nto be or not to be that is the question\nwhether tis nobler in the mind to suffer\nthe slings and arrows of outrageous fortune\nor to take arms against a sea of troubles\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
In the first sample, one can split words into syllables in the following way:
Since the word "ch" in the third line doesn't contain vowels, we can ignore it. As the result we get 2 syllabels in first two lines and 3 syllables in the third one. | ```python
import sys
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
sys.stdin.readline()
ideal = [int(num) for num in sys.stdin.readline().split()]
real = []
for line in sys.stdin:
real.append(len([c for c in line if c in vowels]))
print(ideal)
print(real)
if real == ideal:
print("YES")
else:
print("NO")
``` | 0 | |
268 | A | Games | PROGRAMMING | 800 | [
"brute force"
] | null | null | Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.
There are *n* teams taking part in the national championship. The championship consists of *n*·(*n*<=-<=1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.
You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question. | The first line contains an integer *n* (2<=≤<=*n*<=≤<=30). Each of the following *n* lines contains a pair of distinct space-separated integers *h**i*, *a**i* (1<=≤<=*h**i*,<=*a**i*<=≤<=100) — the colors of the *i*-th team's home and guest uniforms, respectively. | In a single line print the number of games where the host team is going to play in the guest uniform. | [
"3\n1 2\n2 4\n3 4\n",
"4\n100 42\n42 100\n5 42\n100 5\n",
"2\n1 2\n1 2\n"
] | [
"1\n",
"5\n",
"0\n"
] | In the first test case the championship consists of 6 games. The only game with the event in question is the game between teams 2 and 1 on the stadium of team 2.
In the second test sample the host team will have to wear guest uniform in the games between teams: 1 and 2, 2 and 1, 2 and 3, 3 and 4, 4 and 2 (the host team is written first). | 500 | [
{
"input": "3\n1 2\n2 4\n3 4",
"output": "1"
},
{
"input": "4\n100 42\n42 100\n5 42\n100 5",
"output": "5"
},
{
"input": "2\n1 2\n1 2",
"output": "0"
},
{
"input": "7\n4 7\n52 55\n16 4\n55 4\n20 99\n3 4\n7 52",
"output": "6"
},
{
"input": "10\n68 42\n1 35\n25 70\n... | 1,684,868,135 | 2,147,483,647 | Python 3 | OK | TESTS | 31 | 92 | 0 | n = int(input())
home = []
guest = []
for x in range(n):
bt = input().split()
home.append(bt[0])
guest.append(bt[1])
jogos = 0
for x in range(n):
x = guest.count(home[x])
jogos += x
print(jogos) | Title: Games
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.
There are *n* teams taking part in the national championship. The championship consists of *n*·(*n*<=-<=1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.
You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
Input Specification:
The first line contains an integer *n* (2<=≤<=*n*<=≤<=30). Each of the following *n* lines contains a pair of distinct space-separated integers *h**i*, *a**i* (1<=≤<=*h**i*,<=*a**i*<=≤<=100) — the colors of the *i*-th team's home and guest uniforms, respectively.
Output Specification:
In a single line print the number of games where the host team is going to play in the guest uniform.
Demo Input:
['3\n1 2\n2 4\n3 4\n', '4\n100 42\n42 100\n5 42\n100 5\n', '2\n1 2\n1 2\n']
Demo Output:
['1\n', '5\n', '0\n']
Note:
In the first test case the championship consists of 6 games. The only game with the event in question is the game between teams 2 and 1 on the stadium of team 2.
In the second test sample the host team will have to wear guest uniform in the games between teams: 1 and 2, 2 and 1, 2 and 3, 3 and 4, 4 and 2 (the host team is written first). | ```python
n = int(input())
home = []
guest = []
for x in range(n):
bt = input().split()
home.append(bt[0])
guest.append(bt[1])
jogos = 0
for x in range(n):
x = guest.count(home[x])
jogos += x
print(jogos)
``` | 3 | |
196 | A | Lexicographically Maximum Subsequence | PROGRAMMING | 1,100 | [
"greedy",
"strings"
] | null | null | You've got string *s*, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string *s*[*p*1*p*2... *p**k*]<==<=*s**p*1*s**p*2... *s**p**k*(1<=≤<=*p*1<=<<=*p*2<=<<=...<=<<=*p**k*<=≤<=|*s*|) a subsequence of string *s*<==<=*s*1*s*2... *s*|*s*|.
String *x*<==<=*x*1*x*2... *x*|*x*| is lexicographically larger than string *y*<==<=*y*1*y*2... *y*|*y*|, if either |*x*|<=><=|*y*| and *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x*|*y*|<==<=*y*|*y*|, or exists such number *r* (*r*<=<<=|*x*|,<=*r*<=<<=|*y*|), that *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**r*<==<=*y**r* and *x**r*<=+<=1<=><=*y**r*<=+<=1. Characters in lines are compared like their ASCII codes. | The single line contains a non-empty string *s*, consisting only of lowercase English letters. The string's length doesn't exceed 105. | Print the lexicographically maximum subsequence of string *s*. | [
"ababba\n",
"abbcbccacbbcbaaba\n"
] | [
"bbba\n",
"cccccbba\n"
] | Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA | 500 | [
{
"input": "ababba",
"output": "bbba"
},
{
"input": "abbcbccacbbcbaaba",
"output": "cccccbba"
},
{
"input": "thankstosamarasauteddybearsforthiscontest",
"output": "yttt"
},
{
"input": "cantouristsolveitlessthaninoneminute",
"output": "vute"
},
{
"input": "areprete... | 1,656,503,545 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 30 | 0 | r=''
for c in input()[::-1]:
if len(r)<1 or c>=r[0]:r+=c
print(r) | Title: Lexicographically Maximum Subsequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've got string *s*, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string *s*[*p*1*p*2... *p**k*]<==<=*s**p*1*s**p*2... *s**p**k*(1<=≤<=*p*1<=<<=*p*2<=<<=...<=<<=*p**k*<=≤<=|*s*|) a subsequence of string *s*<==<=*s*1*s*2... *s*|*s*|.
String *x*<==<=*x*1*x*2... *x*|*x*| is lexicographically larger than string *y*<==<=*y*1*y*2... *y*|*y*|, if either |*x*|<=><=|*y*| and *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x*|*y*|<==<=*y*|*y*|, or exists such number *r* (*r*<=<<=|*x*|,<=*r*<=<<=|*y*|), that *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**r*<==<=*y**r* and *x**r*<=+<=1<=><=*y**r*<=+<=1. Characters in lines are compared like their ASCII codes.
Input Specification:
The single line contains a non-empty string *s*, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output Specification:
Print the lexicographically maximum subsequence of string *s*.
Demo Input:
['ababba\n', 'abbcbccacbbcbaaba\n']
Demo Output:
['bbba\n', 'cccccbba\n']
Note:
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA | ```python
r=''
for c in input()[::-1]:
if len(r)<1 or c>=r[0]:r+=c
print(r)
``` | 0 | |
334 | A | Candy Bags | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | Gerald has *n* younger brothers and their number happens to be even. One day he bought *n*2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer *k* from 1 to *n*2 he has exactly one bag with *k* candies.
Help him give *n* bags of candies to each brother so that all brothers got the same number of candies. | The single line contains a single integer *n* (*n* is even, 2<=≤<=*n*<=≤<=100) — the number of Gerald's brothers. | Let's assume that Gerald indexes his brothers with numbers from 1 to *n*. You need to print *n* lines, on the *i*-th line print *n* integers — the numbers of candies in the bags for the *i*-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to *n*2. You can print the numbers in the lines in any order.
It is guaranteed that the solution exists at the given limits. | [
"2\n"
] | [
"1 4\n2 3\n"
] | The sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother. | 500 | [
{
"input": "2",
"output": "1 4\n2 3"
},
{
"input": "4",
"output": "1 16 2 15\n3 14 4 13\n5 12 6 11\n7 10 8 9"
},
{
"input": "6",
"output": "1 36 2 35 3 34\n4 33 5 32 6 31\n7 30 8 29 9 28\n10 27 11 26 12 25\n13 24 14 23 15 22\n16 21 17 20 18 19"
},
{
"input": "8",
"output"... | 1,589,890,174 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 1 | 248 | 0 | n = int(input())
bags = n**2
if n == 0:
print(0,0)
else:
for i in range(1,n+1):
print(i,bags-i+1)
| Title: Candy Bags
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Gerald has *n* younger brothers and their number happens to be even. One day he bought *n*2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer *k* from 1 to *n*2 he has exactly one bag with *k* candies.
Help him give *n* bags of candies to each brother so that all brothers got the same number of candies.
Input Specification:
The single line contains a single integer *n* (*n* is even, 2<=≤<=*n*<=≤<=100) — the number of Gerald's brothers.
Output Specification:
Let's assume that Gerald indexes his brothers with numbers from 1 to *n*. You need to print *n* lines, on the *i*-th line print *n* integers — the numbers of candies in the bags for the *i*-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to *n*2. You can print the numbers in the lines in any order.
It is guaranteed that the solution exists at the given limits.
Demo Input:
['2\n']
Demo Output:
['1 4\n2 3\n']
Note:
The sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother. | ```python
n = int(input())
bags = n**2
if n == 0:
print(0,0)
else:
for i in range(1,n+1):
print(i,bags-i+1)
``` | 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,692,949,857 | 2,147,483,647 | Python 3 | OK | TESTS | 38 | 218 | 13,824,000 | def funct(n,t,A):
maxbooks = 0
books = 0
time = 0
start = 0
for i in range(n):
if time+A[i]>t:
if maxbooks < books:
maxbooks = books
while (time+A[i]>t):
time = time - A[start]
start +=1
books -=1
time+=A[i]
books+=1
if maxbooks < books:
maxbooks = books
return maxbooks
X = list(map(int, input().split()))
A = list(map(int, input().split()))
print(funct(X[0],X[1],A)) | 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
def funct(n,t,A):
maxbooks = 0
books = 0
time = 0
start = 0
for i in range(n):
if time+A[i]>t:
if maxbooks < books:
maxbooks = books
while (time+A[i]>t):
time = time - A[start]
start +=1
books -=1
time+=A[i]
books+=1
if maxbooks < books:
maxbooks = books
return maxbooks
X = list(map(int, input().split()))
A = list(map(int, input().split()))
print(funct(X[0],X[1],A))
``` | 3 | |
400 | A | Inna and Choose Options | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:
There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X" or "O". Then the player chooses two positive integers *a* and *b* (*a*·*b*<==<=12), after that he makes a table of size *a*<=×<=*b* from the cards he put on the table as follows: the first *b* cards form the first row of the table, the second *b* cards form the second row of the table and so on, the last *b* cards form the last (number *a*) row of the table. The player wins if some column of the table contain characters "X" on all cards. Otherwise, the player loses.
Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers *a* and *b* to choose. Help her win the game: print to her all the possible ways of numbers *a*,<=*b* that she can choose and win. | The first line of the input contains integer *t* (1<=≤<=*t*<=≤<=100). This value shows the number of sets of test data in the input. Next follows the description of each of the *t* tests on a separate line.
The description of each test is a string consisting of 12 characters, each character is either "X", or "O". The *i*-th character of the string shows the character that is written on the *i*-th card from the start. | For each test, print the answer to the test on a single line. The first number in the line must represent the number of distinct ways to choose the pair *a*,<=*b*. Next, print on this line the pairs in the format *a*x*b*. Print the pairs in the order of increasing first parameter (*a*). Separate the pairs in the line by whitespaces. | [
"4\nOXXXOXOOXOOX\nOXOXOXOXOXOX\nXXXXXXXXXXXX\nOOOOOOOOOOOO\n"
] | [
"3 1x12 2x6 4x3\n4 1x12 2x6 3x4 6x2\n6 1x12 2x6 3x4 4x3 6x2 12x1\n0\n"
] | none | 500 | [
{
"input": "4\nOXXXOXOOXOOX\nOXOXOXOXOXOX\nXXXXXXXXXXXX\nOOOOOOOOOOOO",
"output": "3 1x12 2x6 4x3\n4 1x12 2x6 3x4 6x2\n6 1x12 2x6 3x4 4x3 6x2 12x1\n0"
},
{
"input": "2\nOOOOOOOOOOOO\nXXXXXXXXXXXX",
"output": "0\n6 1x12 2x6 3x4 4x3 6x2 12x1"
},
{
"input": "13\nXXXXXXXXXXXX\nXXXXXXXXXXXX\n... | 1,395,313,343 | 2,147,483,647 | Python 3 | OK | TESTS | 44 | 62 | 0 | # -*- coding: UTF-8 -*-
def evaluate(origin_str):
ans = []
for i in [1,2,3,4,6,12]:
last_idx = int(12 / i)
flags = [1 for i in range(0,last_idx)]
if (i == 1):
flag = False
for ch in origin_str:
if (ch == 'X'):
flag = True
if (flag):
ans.append([i,last_idx])
else:
for j in range(0,last_idx):
tmp = []
k = j - last_idx
for x in range(0,i):
k += last_idx
tmp.append(k)
for l in tmp:
ch = origin_str[l]
if (ch != 'X'):
flags[j] = 0
if (sum(flags) != 0):
ans.append([i,last_idx])
s = ""
for a in ans:
s += str(a[0])+"x"+str(a[1]) + " "
print(str(len(ans)) + " " + s)
def main():
n = int(input())
for i in range(0,n):
evaluate(input())
main() | Title: Inna and Choose Options
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:
There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X" or "O". Then the player chooses two positive integers *a* and *b* (*a*·*b*<==<=12), after that he makes a table of size *a*<=×<=*b* from the cards he put on the table as follows: the first *b* cards form the first row of the table, the second *b* cards form the second row of the table and so on, the last *b* cards form the last (number *a*) row of the table. The player wins if some column of the table contain characters "X" on all cards. Otherwise, the player loses.
Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers *a* and *b* to choose. Help her win the game: print to her all the possible ways of numbers *a*,<=*b* that she can choose and win.
Input Specification:
The first line of the input contains integer *t* (1<=≤<=*t*<=≤<=100). This value shows the number of sets of test data in the input. Next follows the description of each of the *t* tests on a separate line.
The description of each test is a string consisting of 12 characters, each character is either "X", or "O". The *i*-th character of the string shows the character that is written on the *i*-th card from the start.
Output Specification:
For each test, print the answer to the test on a single line. The first number in the line must represent the number of distinct ways to choose the pair *a*,<=*b*. Next, print on this line the pairs in the format *a*x*b*. Print the pairs in the order of increasing first parameter (*a*). Separate the pairs in the line by whitespaces.
Demo Input:
['4\nOXXXOXOOXOOX\nOXOXOXOXOXOX\nXXXXXXXXXXXX\nOOOOOOOOOOOO\n']
Demo Output:
['3 1x12 2x6 4x3\n4 1x12 2x6 3x4 6x2\n6 1x12 2x6 3x4 4x3 6x2 12x1\n0\n']
Note:
none | ```python
# -*- coding: UTF-8 -*-
def evaluate(origin_str):
ans = []
for i in [1,2,3,4,6,12]:
last_idx = int(12 / i)
flags = [1 for i in range(0,last_idx)]
if (i == 1):
flag = False
for ch in origin_str:
if (ch == 'X'):
flag = True
if (flag):
ans.append([i,last_idx])
else:
for j in range(0,last_idx):
tmp = []
k = j - last_idx
for x in range(0,i):
k += last_idx
tmp.append(k)
for l in tmp:
ch = origin_str[l]
if (ch != 'X'):
flags[j] = 0
if (sum(flags) != 0):
ans.append([i,last_idx])
s = ""
for a in ans:
s += str(a[0])+"x"+str(a[1]) + " "
print(str(len(ans)) + " " + s)
def main():
n = int(input())
for i in range(0,n):
evaluate(input())
main()
``` | 3 | |
592 | A | PawnChess | PROGRAMMING | 1,200 | [
"implementation"
] | null | null | Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (*r*,<=*c*) the cell located at the row *r* and at the column *c*.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (*r*,<=*c*) will go to the cell (*r*<=-<=1,<=*c*), while moving down means the pawn located in (*r*,<=*c*) will go to the cell (*r*<=+<=1,<=*c*). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available. | The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row. | Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board. | [
"........\n........\n.B....B.\n....W...\n........\n..W.....\n........\n........\n",
"..B.....\n..W.....\n......B.\n........\n.....W..\n......B.\n........\n........\n"
] | [
"A\n",
"B\n"
] | In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner. | 500 | [
{
"input": ".BB.B.B.\nB..B..B.\n.B.BB...\nBB.....B\nBBB....B\nB..BB...\nBB.B...B\n....WWW.",
"output": "B"
},
{
"input": "B.B.BB.B\nW.WWW.WW\n.WWWWW.W\nW.BB.WBW\n.W..BBWB\nBB.WWBBB\n.W.W.WWB\nWWW..WW.",
"output": "A"
},
{
"input": "BB..BB..\nBW.W.W.B\n..B.....\n.....BB.\n.B..B..B\n......... | 1,446,313,974 | 4,974 | Python 3 | WRONG_ANSWER | PRETESTS | 0 | 30 | 0 | #!/usr/bin/python3
'''
Created on Sep 25, 2015
@author: kate
'''
#n, t = [int(x) for x in input().split()]
#gnome_count = int(input()) * 3
a = [0 for x in range(8)]
b = [0 for x in range(8)]
for row in range(1,9):
s = input()
for col in range(8):
if (s[col] == 'W'):
if (b[col] != 0):
b[col] = -1
a[col] = -1
elif (a[col] == 0 and a[col] != -1):
a[col] = 8 - row
if (s[col] == 'B'):
if (b[col] != -1):
b[col] = row
res = 'A' if max(a) > max(b) else 'B'
print (res)
| Title: PawnChess
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (*r*,<=*c*) the cell located at the row *r* and at the column *c*.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (*r*,<=*c*) will go to the cell (*r*<=-<=1,<=*c*), while moving down means the pawn located in (*r*,<=*c*) will go to the cell (*r*<=+<=1,<=*c*). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input Specification:
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output Specification:
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Demo Input:
['........\n........\n.B....B.\n....W...\n........\n..W.....\n........\n........\n', '..B.....\n..W.....\n......B.\n........\n.....W..\n......B.\n........\n........\n']
Demo Output:
['A\n', 'B\n']
Note:
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner. | ```python
#!/usr/bin/python3
'''
Created on Sep 25, 2015
@author: kate
'''
#n, t = [int(x) for x in input().split()]
#gnome_count = int(input()) * 3
a = [0 for x in range(8)]
b = [0 for x in range(8)]
for row in range(1,9):
s = input()
for col in range(8):
if (s[col] == 'W'):
if (b[col] != 0):
b[col] = -1
a[col] = -1
elif (a[col] == 0 and a[col] != -1):
a[col] = 8 - row
if (s[col] == 'B'):
if (b[col] != -1):
b[col] = row
res = 'A' if max(a) > max(b) else 'B'
print (res)
``` | 0 | |
152 | A | Marks | PROGRAMMING | 900 | [
"implementation"
] | null | null | Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.
Overall the group has *n* students. They received marks for *m* subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.
Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.
Your task is to find the number of successful students in the group. | The first input line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the number of students and the number of subjects, correspondingly. Next *n* lines each containing *m* characters describe the gradebook. Each character in the gradebook is a number from 1 to 9. Note that the marks in a rows are not sepatated by spaces. | Print the single number — the number of successful students in the given group. | [
"3 3\n223\n232\n112\n",
"3 5\n91728\n11828\n11111\n"
] | [
"2\n",
"3\n"
] | In the first sample test the student number 1 is the best at subjects 1 and 3, student 2 is the best at subjects 1 and 2, but student 3 isn't the best at any subject.
In the second sample test each student is the best at at least one subject. | 500 | [
{
"input": "3 3\n223\n232\n112",
"output": "2"
},
{
"input": "3 5\n91728\n11828\n11111",
"output": "3"
},
{
"input": "2 2\n48\n27",
"output": "1"
},
{
"input": "2 1\n4\n6",
"output": "1"
},
{
"input": "1 2\n57",
"output": "1"
},
{
"input": "1 1\n5",
... | 1,568,028,069 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 6 | 108 | 0 | n,m=map(int,input().split())
a=[]
for i in range(n):
a.append(input())
b=[]
x=int(0)
t=int()
for i in range(m):
x=0
for j in range(n):
if(int(x)<=int(a[j][i])):
x=a[j][i]
t=j
if(t not in b):
b.append(t)
print(len(b)) | Title: Marks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.
Overall the group has *n* students. They received marks for *m* subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.
Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.
Your task is to find the number of successful students in the group.
Input Specification:
The first input line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the number of students and the number of subjects, correspondingly. Next *n* lines each containing *m* characters describe the gradebook. Each character in the gradebook is a number from 1 to 9. Note that the marks in a rows are not sepatated by spaces.
Output Specification:
Print the single number — the number of successful students in the given group.
Demo Input:
['3 3\n223\n232\n112\n', '3 5\n91728\n11828\n11111\n']
Demo Output:
['2\n', '3\n']
Note:
In the first sample test the student number 1 is the best at subjects 1 and 3, student 2 is the best at subjects 1 and 2, but student 3 isn't the best at any subject.
In the second sample test each student is the best at at least one subject. | ```python
n,m=map(int,input().split())
a=[]
for i in range(n):
a.append(input())
b=[]
x=int(0)
t=int()
for i in range(m):
x=0
for j in range(n):
if(int(x)<=int(a[j][i])):
x=a[j][i]
t=j
if(t not in b):
b.append(t)
print(len(b))
``` | 0 | |
681 | A | A Good Contest | PROGRAMMING | 800 | [
"implementation"
] | null | null | Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.
Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it.
Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same? | The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of participants Anton has outscored in this contest .
The next *n* lines describe participants results: the *i*-th of them consists of a participant handle *name**i* and two integers *before**i* and *after**i* (<=-<=4000<=≤<=*before**i*,<=*after**i*<=≤<=4000) — participant's rating before and after the contest, respectively. Each handle is a non-empty string, consisting of no more than 10 characters, which might be lowercase and uppercase English letters, digits, characters «_» and «-» characters.
It is guaranteed that all handles are distinct. | Print «YES» (quotes for clarity), if Anton has performed good in the contest and «NO» (quotes for clarity) otherwise. | [
"3\nBurunduk1 2526 2537\nBudAlNik 2084 2214\nsubscriber 2833 2749\n",
"3\nApplejack 2400 2400\nFluttershy 2390 2431\nPinkie_Pie -2500 -2450\n"
] | [
"YES",
"NO"
] | In the first sample, Anton has outscored user with handle Burunduk1, whose handle was colored red before the contest and his rating has increased after the contest.
In the second sample, Applejack's rating has not increased after the contest, while both Fluttershy's and Pinkie_Pie's handles were not colored red before the contest. | 500 | [
{
"input": "3\nBurunduk1 2526 2537\nBudAlNik 2084 2214\nsubscriber 2833 2749",
"output": "YES"
},
{
"input": "3\nApplejack 2400 2400\nFluttershy 2390 2431\nPinkie_Pie -2500 -2450",
"output": "NO"
},
{
"input": "1\nDb -3373 3591",
"output": "NO"
},
{
"input": "5\nQ2bz 960 2342... | 1,672,217,803 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 3 | 62 | 0 | n = int(input())
data_name = []
data_bf = []
data_af = []
for i in range(n):
[name, point_bf, point_af] = input().split(" ")
point_af = int(point_af)
point_bf = int(point_bf)
if(point_bf >= 2400 or i == 0):
data_name.append(name)
data_bf.append(point_bf)
data_af.append(point_af)
me = data_af[0] - data_bf[0]
if me <= 0:
print('NO')
quit()
for i in range(1, len(data_name)):
if data_af[i] - data_bf[i] > me:
print('NO')
quit()
print('YES')
| Title: A Good Contest
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.
Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it.
Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?
Input Specification:
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of participants Anton has outscored in this contest .
The next *n* lines describe participants results: the *i*-th of them consists of a participant handle *name**i* and two integers *before**i* and *after**i* (<=-<=4000<=≤<=*before**i*,<=*after**i*<=≤<=4000) — participant's rating before and after the contest, respectively. Each handle is a non-empty string, consisting of no more than 10 characters, which might be lowercase and uppercase English letters, digits, characters «_» and «-» characters.
It is guaranteed that all handles are distinct.
Output Specification:
Print «YES» (quotes for clarity), if Anton has performed good in the contest and «NO» (quotes for clarity) otherwise.
Demo Input:
['3\nBurunduk1 2526 2537\nBudAlNik 2084 2214\nsubscriber 2833 2749\n', '3\nApplejack 2400 2400\nFluttershy 2390 2431\nPinkie_Pie -2500 -2450\n']
Demo Output:
['YES', 'NO']
Note:
In the first sample, Anton has outscored user with handle Burunduk1, whose handle was colored red before the contest and his rating has increased after the contest.
In the second sample, Applejack's rating has not increased after the contest, while both Fluttershy's and Pinkie_Pie's handles were not colored red before the contest. | ```python
n = int(input())
data_name = []
data_bf = []
data_af = []
for i in range(n):
[name, point_bf, point_af] = input().split(" ")
point_af = int(point_af)
point_bf = int(point_bf)
if(point_bf >= 2400 or i == 0):
data_name.append(name)
data_bf.append(point_bf)
data_af.append(point_af)
me = data_af[0] - data_bf[0]
if me <= 0:
print('NO')
quit()
for i in range(1, len(data_name)):
if data_af[i] - data_bf[i] > me:
print('NO')
quit()
print('YES')
``` | 0 | |
522 | A | Reposts | PROGRAMMING | 1,200 | [
"*special",
"dfs and similar",
"dp",
"graphs",
"trees"
] | null | null | One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.
Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke. | The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.
We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user. | Print a single integer — the maximum length of a repost chain. | [
"5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya\n",
"6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp\n",
"1\nSoMeStRaNgEgUe repos... | [
"6\n",
"2\n",
"2\n"
] | none | 500 | [
{
"input": "5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya",
"output": "6"
},
{
"input": "6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforc... | 1,457,776,263 | 2,147,483,647 | Python 3 | OK | TESTS | 36 | 62 | 0 | n = int(input())
l = {'POLYCARP': 1}
ans = 0
for i in range(n):
s = input().split(' ')
a = s[0].upper()
b = s[2].upper()
curr = l[b]+1
if curr > ans:
ans = curr
l[a] = curr
print(ans)
| Title: Reposts
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.
Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.
Input Specification:
The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.
We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.
Output Specification:
Print a single integer — the maximum length of a repost chain.
Demo Input:
['5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya\n', '6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp\n', '1\nSoMeStRaNgEgUe reposted PoLyCaRp\n']
Demo Output:
['6\n', '2\n', '2\n']
Note:
none | ```python
n = int(input())
l = {'POLYCARP': 1}
ans = 0
for i in range(n):
s = input().split(' ')
a = s[0].upper()
b = s[2].upper()
curr = l[b]+1
if curr > ans:
ans = curr
l[a] = curr
print(ans)
``` | 3 | |
87 | A | Trains | PROGRAMMING | 1,500 | [
"implementation",
"math"
] | A. Trains | 2 | 256 | Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.
When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time, waits the first train to come and rides on it to the end of the branch to the corresponding girl. However, the trains run with different frequencies: a train goes to Dasha's direction every *a* minutes, but a train goes to Masha's direction every *b* minutes. If two trains approach at the same time, Vasya goes toward the direction with the lower frequency of going trains, that is, to the girl, to whose directions the trains go less frequently (see the note to the third sample).
We know that the trains begin to go simultaneously before Vasya appears. That is the train schedule is such that there exists a moment of time when the two trains arrive simultaneously.
Help Vasya count to which girlfriend he will go more often. | The first line contains two integers *a* and *b* (*a*<=≠<=*b*,<=1<=≤<=*a*,<=*b*<=≤<=106). | Print "Dasha" if Vasya will go to Dasha more frequently, "Masha" if he will go to Masha more frequently, or "Equal" if he will go to both girlfriends with the same frequency. | [
"3 7\n",
"5 3\n",
"2 3\n"
] | [
"Dasha\n",
"Masha\n",
"Equal\n"
] | Let's take a look at the third sample. Let the trains start to go at the zero moment of time. It is clear that the moments of the trains' arrival will be periodic with period 6. That's why it is enough to show that if Vasya descends to the subway at a moment of time inside the interval (0, 6], he will go to both girls equally often.
If he descends to the subway at a moment of time from 0 to 2, he leaves for Dasha on the train that arrives by the second minute.
If he descends to the subway at a moment of time from 2 to 3, he leaves for Masha on the train that arrives by the third minute.
If he descends to the subway at a moment of time from 3 to 4, he leaves for Dasha on the train that arrives by the fourth minute.
If he descends to the subway at a moment of time from 4 to 6, he waits for both trains to arrive by the sixth minute and goes to Masha as trains go less often in Masha's direction.
In sum Masha and Dasha get equal time — three minutes for each one, thus, Vasya will go to both girlfriends equally often. | 500 | [
{
"input": "3 7",
"output": "Dasha"
},
{
"input": "5 3",
"output": "Masha"
},
{
"input": "2 3",
"output": "Equal"
},
{
"input": "31 88",
"output": "Dasha"
},
{
"input": "8 75",
"output": "Dasha"
},
{
"input": "32 99",
"output": "Dasha"
},
{
... | 1,692,568,128 | 2,147,483,647 | Python 3 | OK | TESTS | 57 | 92 | 0 | from math import gcd
n,m=map(int,input().split())
lcm=n*m//(gcd(n,m))
a,b=lcm//n,lcm//m
# print()
if abs(a-b)<=1:
print("Equal")
elif a>b:
print("Dasha")
else:
print("Masha") | Title: Trains
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.
When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time, waits the first train to come and rides on it to the end of the branch to the corresponding girl. However, the trains run with different frequencies: a train goes to Dasha's direction every *a* minutes, but a train goes to Masha's direction every *b* minutes. If two trains approach at the same time, Vasya goes toward the direction with the lower frequency of going trains, that is, to the girl, to whose directions the trains go less frequently (see the note to the third sample).
We know that the trains begin to go simultaneously before Vasya appears. That is the train schedule is such that there exists a moment of time when the two trains arrive simultaneously.
Help Vasya count to which girlfriend he will go more often.
Input Specification:
The first line contains two integers *a* and *b* (*a*<=≠<=*b*,<=1<=≤<=*a*,<=*b*<=≤<=106).
Output Specification:
Print "Dasha" if Vasya will go to Dasha more frequently, "Masha" if he will go to Masha more frequently, or "Equal" if he will go to both girlfriends with the same frequency.
Demo Input:
['3 7\n', '5 3\n', '2 3\n']
Demo Output:
['Dasha\n', 'Masha\n', 'Equal\n']
Note:
Let's take a look at the third sample. Let the trains start to go at the zero moment of time. It is clear that the moments of the trains' arrival will be periodic with period 6. That's why it is enough to show that if Vasya descends to the subway at a moment of time inside the interval (0, 6], he will go to both girls equally often.
If he descends to the subway at a moment of time from 0 to 2, he leaves for Dasha on the train that arrives by the second minute.
If he descends to the subway at a moment of time from 2 to 3, he leaves for Masha on the train that arrives by the third minute.
If he descends to the subway at a moment of time from 3 to 4, he leaves for Dasha on the train that arrives by the fourth minute.
If he descends to the subway at a moment of time from 4 to 6, he waits for both trains to arrive by the sixth minute and goes to Masha as trains go less often in Masha's direction.
In sum Masha and Dasha get equal time — three minutes for each one, thus, Vasya will go to both girlfriends equally often. | ```python
from math import gcd
n,m=map(int,input().split())
lcm=n*m//(gcd(n,m))
a,b=lcm//n,lcm//m
# print()
if abs(a-b)<=1:
print("Equal")
elif a>b:
print("Dasha")
else:
print("Masha")
``` | 3.977 |
522 | A | Reposts | PROGRAMMING | 1,200 | [
"*special",
"dfs and similar",
"dp",
"graphs",
"trees"
] | null | null | One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.
Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke. | The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.
We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user. | Print a single integer — the maximum length of a repost chain. | [
"5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya\n",
"6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp\n",
"1\nSoMeStRaNgEgUe repos... | [
"6\n",
"2\n",
"2\n"
] | none | 500 | [
{
"input": "5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya",
"output": "6"
},
{
"input": "6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforc... | 1,581,008,385 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 5 | 155 | 0 | chain = {}
n = int(input())
for i in range(n):
first, last = [x.strip().lower() for x in input().split('reposted')]
previous = list(filter(lambda x:x.get('next') == last, chain.values())) if chain else []
if not previous:
chain[last] = {'next':first, 'chain':2}
else:
previous[0]['next'] = first
previous[0]['chain'] += 1
print(max([x['chain'] for x in chain.values()]))
| Title: Reposts
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.
Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.
Input Specification:
The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.
We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.
Output Specification:
Print a single integer — the maximum length of a repost chain.
Demo Input:
['5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya\n', '6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp\n', '1\nSoMeStRaNgEgUe reposted PoLyCaRp\n']
Demo Output:
['6\n', '2\n', '2\n']
Note:
none | ```python
chain = {}
n = int(input())
for i in range(n):
first, last = [x.strip().lower() for x in input().split('reposted')]
previous = list(filter(lambda x:x.get('next') == last, chain.values())) if chain else []
if not previous:
chain[last] = {'next':first, 'chain':2}
else:
previous[0]['next'] = first
previous[0]['chain'] += 1
print(max([x['chain'] for x in chain.values()]))
``` | 0 | |
61 | A | Ultra-Fast Mathematician | PROGRAMMING | 800 | [
"implementation"
] | A. Ultra-Fast Mathematician | 2 | 256 | Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate. | There are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100. | Write one line — the corresponding answer. Do not omit the leading 0s. | [
"1010100\n0100101\n",
"000\n111\n",
"1110\n1010\n",
"01110\n01100\n"
] | [
"1110001\n",
"111\n",
"0100\n",
"00010\n"
] | none | 500 | [
{
"input": "1010100\n0100101",
"output": "1110001"
},
{
"input": "000\n111",
"output": "111"
},
{
"input": "1110\n1010",
"output": "0100"
},
{
"input": "01110\n01100",
"output": "00010"
},
{
"input": "011101\n000001",
"output": "011100"
},
{
"input": "... | 1,652,106,384 | 2,147,483,647 | Python 3 | OK | TESTS | 102 | 46 | 0 | t1 = input()
t2=input()
ans= ""
for i in range(len(t1)):
if t1[i]==t2[i]:
ans=ans+"0"
else:
ans=ans+"1"
print(ans) | Title: Ultra-Fast Mathematician
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
Input Specification:
There are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100.
Output Specification:
Write one line — the corresponding answer. Do not omit the leading 0s.
Demo Input:
['1010100\n0100101\n', '000\n111\n', '1110\n1010\n', '01110\n01100\n']
Demo Output:
['1110001\n', '111\n', '0100\n', '00010\n']
Note:
none | ```python
t1 = input()
t2=input()
ans= ""
for i in range(len(t1)):
if t1[i]==t2[i]:
ans=ans+"0"
else:
ans=ans+"1"
print(ans)
``` | 3.9885 |
182 | B | Vasya's Calendar | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | Vasya lives in a strange world. The year has *n* months and the *i*-th month has *a**i* days. Vasya got a New Year present — the clock that shows not only the time, but also the date.
The clock's face can display any number from 1 to *d*. It is guaranteed that *a**i*<=≤<=*d* for all *i* from 1 to *n*. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number *d*<=+<=1, so after day number *d* it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day *d* is also followed by day 1.
Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.
A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the *n*-th month inclusive, considering that on the first day of the first month the clock display showed day 1. | The first line contains the single number *d* — the maximum number of the day that Vasya's clock can show (1<=≤<=*d*<=≤<=106).
The second line contains a single integer *n* — the number of months in the year (1<=≤<=*n*<=≤<=2000).
The third line contains *n* space-separated integers: *a**i* (1<=≤<=*a**i*<=≤<=*d*) — the number of days in each month in the order in which they follow, starting from the first one. | Print a single number — the number of times Vasya manually increased the day number by one throughout the last year. | [
"4\n2\n2 2\n",
"5\n3\n3 4 3\n",
"31\n12\n31 28 31 30 31 30 31 31 30 31 30 31\n"
] | [
"2\n",
"3\n",
"7\n"
] | In the first sample the situation is like this:
- Day 1. Month 1. The clock shows 1. Vasya changes nothing. - Day 2. Month 1. The clock shows 2. Vasya changes nothing. - Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1. - Day 2. Month 2. The clock shows 2. Vasya changes nothing. | 500 | [
{
"input": "4\n2\n2 2",
"output": "2"
},
{
"input": "5\n3\n3 4 3",
"output": "3"
},
{
"input": "31\n12\n31 28 31 30 31 30 31 31 30 31 30 31",
"output": "7"
},
{
"input": "1\n1\n1",
"output": "0"
},
{
"input": "1\n2\n1 1",
"output": "0"
},
{
"input": "2... | 1,623,476,239 | 2,147,483,647 | PyPy 3 | OK | TESTS | 40 | 248 | 1,945,600 | import math
from collections import defaultdict, Counter
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
def ceil(a, b):
return (a+b-1)//b
d=ri()
n=ri()
l=ria()
cnt=0
for i in range(n-1):
if l[i]==d:
pass
else:
cnt=cnt+d-l[i]
wi(cnt) | Title: Vasya's Calendar
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya lives in a strange world. The year has *n* months and the *i*-th month has *a**i* days. Vasya got a New Year present — the clock that shows not only the time, but also the date.
The clock's face can display any number from 1 to *d*. It is guaranteed that *a**i*<=≤<=*d* for all *i* from 1 to *n*. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number *d*<=+<=1, so after day number *d* it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day *d* is also followed by day 1.
Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.
A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the *n*-th month inclusive, considering that on the first day of the first month the clock display showed day 1.
Input Specification:
The first line contains the single number *d* — the maximum number of the day that Vasya's clock can show (1<=≤<=*d*<=≤<=106).
The second line contains a single integer *n* — the number of months in the year (1<=≤<=*n*<=≤<=2000).
The third line contains *n* space-separated integers: *a**i* (1<=≤<=*a**i*<=≤<=*d*) — the number of days in each month in the order in which they follow, starting from the first one.
Output Specification:
Print a single number — the number of times Vasya manually increased the day number by one throughout the last year.
Demo Input:
['4\n2\n2 2\n', '5\n3\n3 4 3\n', '31\n12\n31 28 31 30 31 30 31 31 30 31 30 31\n']
Demo Output:
['2\n', '3\n', '7\n']
Note:
In the first sample the situation is like this:
- Day 1. Month 1. The clock shows 1. Vasya changes nothing. - Day 2. Month 1. The clock shows 2. Vasya changes nothing. - Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1. - Day 2. Month 2. The clock shows 2. Vasya changes nothing. | ```python
import math
from collections import defaultdict, Counter
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
def ceil(a, b):
return (a+b-1)//b
d=ri()
n=ri()
l=ria()
cnt=0
for i in range(n-1):
if l[i]==d:
pass
else:
cnt=cnt+d-l[i]
wi(cnt)
``` | 3 | |
225 | A | Dice Tower | PROGRAMMING | 1,100 | [
"constructive algorithms",
"greedy"
] | null | null | A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).
Alice and Bob play dice. Alice has built a tower from *n* dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).
Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of dice in the tower.
The second line contains an integer *x* (1<=≤<=*x*<=≤<=6) — the number Bob sees at the top of the tower. Next *n* lines contain two space-separated integers each: the *i*-th line contains numbers *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=6; *a**i*<=≠<=*b**i*) — the numbers Bob sees on the two sidelong faces of the *i*-th dice in the tower.
Consider the dice in the tower indexed from top to bottom from 1 to *n*. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input. | Print "YES" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print "NO" (without the quotes). | [
"3\n6\n3 2\n5 4\n2 4\n",
"3\n3\n2 6\n4 1\n5 3\n"
] | [
"YES",
"NO"
] | none | 500 | [
{
"input": "3\n6\n3 2\n5 4\n2 4",
"output": "YES"
},
{
"input": "3\n3\n2 6\n4 1\n5 3",
"output": "NO"
},
{
"input": "1\n3\n2 1",
"output": "YES"
},
{
"input": "2\n2\n3 1\n1 5",
"output": "NO"
},
{
"input": "3\n2\n1 4\n5 3\n6 4",
"output": "NO"
},
{
"in... | 1,594,363,724 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 3 | 248 | 20,172,800 | n=int(input())
t=int(input())
l,r=[],[]
while n-1:
ll,rl=map(int,input().split())
l.append(ll)
r.append(rl)
n-=1
if(((t in l) or (t in r)) or (((7-t) in l) or ((7-t) in r))):
print("NO")
else:
print("YES") | Title: Dice Tower
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).
Alice and Bob play dice. Alice has built a tower from *n* dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).
Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of dice in the tower.
The second line contains an integer *x* (1<=≤<=*x*<=≤<=6) — the number Bob sees at the top of the tower. Next *n* lines contain two space-separated integers each: the *i*-th line contains numbers *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=6; *a**i*<=≠<=*b**i*) — the numbers Bob sees on the two sidelong faces of the *i*-th dice in the tower.
Consider the dice in the tower indexed from top to bottom from 1 to *n*. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input.
Output Specification:
Print "YES" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print "NO" (without the quotes).
Demo Input:
['3\n6\n3 2\n5 4\n2 4\n', '3\n3\n2 6\n4 1\n5 3\n']
Demo Output:
['YES', 'NO']
Note:
none | ```python
n=int(input())
t=int(input())
l,r=[],[]
while n-1:
ll,rl=map(int,input().split())
l.append(ll)
r.append(rl)
n-=1
if(((t in l) or (t in r)) or (((7-t) in l) or ((7-t) in r))):
print("NO")
else:
print("YES")
``` | 0 | |
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,566,038,904 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 186 | 0 | def maxn(x, y):
if (x > y):
return x
else:
return y
#开始进入Python的世界
a = input()
b = input()
c = max(a,b)
print(c)
if (c > 6):
print('0/1')
if (c == 6):
print('1/6')
if (c == 5):
print('1/3')
if (c == 4):
print('1/2')
if (c == 3):
print('2/3')
if (c == 2):
print('5/6')
if (c == 1):
print('1/1')
| 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
def maxn(x, y):
if (x > y):
return x
else:
return y
#开始进入Python的世界
a = input()
b = input()
c = max(a,b)
print(c)
if (c > 6):
print('0/1')
if (c == 6):
print('1/6')
if (c == 5):
print('1/3')
if (c == 4):
print('1/2')
if (c == 3):
print('2/3')
if (c == 2):
print('5/6')
if (c == 1):
print('1/1')
``` | -1 |
664 | A | Complicated GCD | PROGRAMMING | 800 | [
"math",
"number theory"
] | null | null | Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm.
Formally, find the biggest integer *d*, such that all integers *a*,<=*a*<=+<=1,<=*a*<=+<=2,<=...,<=*b* are divisible by *d*. To make the problem even more complicated we allow *a* and *b* to be up to googol, 10100 — such number do not fit even in 64-bit integer type! | The only line of the input contains two integers *a* and *b* (1<=≤<=*a*<=≤<=*b*<=≤<=10100). | Output one integer — greatest common divisor of all integers from *a* to *b* inclusive. | [
"1 2\n",
"61803398874989484820458683436563811772030917980576 61803398874989484820458683436563811772030917980576\n"
] | [
"1\n",
"61803398874989484820458683436563811772030917980576\n"
] | none | 500 | [
{
"input": "1 2",
"output": "1"
},
{
"input": "61803398874989484820458683436563811772030917980576 61803398874989484820458683436563811772030917980576",
"output": "61803398874989484820458683436563811772030917980576"
},
{
"input": "1 100",
"output": "1"
},
{
"input": "100 100000... | 1,667,546,386 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 46 | 134,656,000 | import sys
import threading
inp = sys.stdin.readline
input = lambda: inp().strip()
ii = lambda: int(input())
mi = lambda: map(int,input().split())
li = lambda: list(map(int,input().split()))
from collections import defaultdict,Counter,deque
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop,heapify
mod = 10**9+7
def gcd(num1,num2):
if num2 == 0: return num1
return gcd(num2,num1%num2)
def main():
num1, num2 = mi()
print(gcd(num1,num2))
if __name__ == "__main__":
sys.setrecursionlimit(2**32//2-1)
threading.stack_size(1 << 27)
thread = threading.Thread(target=main)
thread.start()
thread.join()
| Title: Complicated GCD
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm.
Formally, find the biggest integer *d*, such that all integers *a*,<=*a*<=+<=1,<=*a*<=+<=2,<=...,<=*b* are divisible by *d*. To make the problem even more complicated we allow *a* and *b* to be up to googol, 10100 — such number do not fit even in 64-bit integer type!
Input Specification:
The only line of the input contains two integers *a* and *b* (1<=≤<=*a*<=≤<=*b*<=≤<=10100).
Output Specification:
Output one integer — greatest common divisor of all integers from *a* to *b* inclusive.
Demo Input:
['1 2\n', '61803398874989484820458683436563811772030917980576 61803398874989484820458683436563811772030917980576\n']
Demo Output:
['1\n', '61803398874989484820458683436563811772030917980576\n']
Note:
none | ```python
import sys
import threading
inp = sys.stdin.readline
input = lambda: inp().strip()
ii = lambda: int(input())
mi = lambda: map(int,input().split())
li = lambda: list(map(int,input().split()))
from collections import defaultdict,Counter,deque
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop,heapify
mod = 10**9+7
def gcd(num1,num2):
if num2 == 0: return num1
return gcd(num2,num1%num2)
def main():
num1, num2 = mi()
print(gcd(num1,num2))
if __name__ == "__main__":
sys.setrecursionlimit(2**32//2-1)
threading.stack_size(1 << 27)
thread = threading.Thread(target=main)
thread.start()
thread.join()
``` | 0 | |
991 | C | Candies | PROGRAMMING | 1,500 | [
"binary search",
"implementation"
] | null | null | After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.
This means the process of eating candies is the following: in the beginning Vasya chooses a single integer $k$, same for all days. After that, in the morning he eats $k$ candies from the box (if there are less than $k$ candies in the box, he eats them all), then in the evening Petya eats $10\%$ of the candies remaining in the box. If there are still candies left in the box, the process repeats — next day Vasya eats $k$ candies again, and Petya — $10\%$ of the candies left in a box, and so on.
If the amount of candies in the box is not divisible by $10$, Petya rounds the amount he takes from the box down. For example, if there were $97$ candies in the box, Petya would eat only $9$ of them. In particular, if there are less than $10$ candies in a box, Petya won't eat any at all.
Your task is to find out the minimal amount of $k$ that can be chosen by Vasya so that he would eat at least half of the $n$ candies he initially got. Note that the number $k$ must be integer. | The first line contains a single integer $n$ ($1 \leq n \leq 10^{18}$) — the initial amount of candies in the box. | Output a single integer — the minimal amount of $k$ that would allow Vasya to eat at least half of candies he got. | [
"68\n"
] | [
"3\n"
] | In the sample, the amount of candies, with $k=3$, would change in the following way (Vasya eats first):
$68 \to 65 \to 59 \to 56 \to 51 \to 48 \to 44 \to 41 \\ \to 37 \to 34 \to 31 \to 28 \to 26 \to 23 \to 21 \to 18 \to 17 \to 14 \\ \to 13 \to 10 \to 9 \to 6 \to 6 \to 3 \to 3 \to 0$.
In total, Vasya would eat $39$ candies, while Petya — $29$. | 1,250 | [
{
"input": "68",
"output": "3"
},
{
"input": "1",
"output": "1"
},
{
"input": "2",
"output": "1"
},
{
"input": "42",
"output": "1"
},
{
"input": "43",
"output": "2"
},
{
"input": "756",
"output": "29"
},
{
"input": "999999972",
"output"... | 1,601,044,092 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 0 | 139 | 0 | def verificar(n, k):
limite = n//2 + 1
comidos = 0
while n > 0:
if n < k:
comidos += n
break
n -= k
comidos += k
n -= n//10
return comidos >= limite
n = int(input())
valor = 10e18
pulo = valor // 2
while pulo > 1:
# print(valor)
if verificar(n, valor):
valor -= pulo
else:
valor += pulo
pulo = valor // 2
print(valor)
| Title: Candies
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.
This means the process of eating candies is the following: in the beginning Vasya chooses a single integer $k$, same for all days. After that, in the morning he eats $k$ candies from the box (if there are less than $k$ candies in the box, he eats them all), then in the evening Petya eats $10\%$ of the candies remaining in the box. If there are still candies left in the box, the process repeats — next day Vasya eats $k$ candies again, and Petya — $10\%$ of the candies left in a box, and so on.
If the amount of candies in the box is not divisible by $10$, Petya rounds the amount he takes from the box down. For example, if there were $97$ candies in the box, Petya would eat only $9$ of them. In particular, if there are less than $10$ candies in a box, Petya won't eat any at all.
Your task is to find out the minimal amount of $k$ that can be chosen by Vasya so that he would eat at least half of the $n$ candies he initially got. Note that the number $k$ must be integer.
Input Specification:
The first line contains a single integer $n$ ($1 \leq n \leq 10^{18}$) — the initial amount of candies in the box.
Output Specification:
Output a single integer — the minimal amount of $k$ that would allow Vasya to eat at least half of candies he got.
Demo Input:
['68\n']
Demo Output:
['3\n']
Note:
In the sample, the amount of candies, with $k=3$, would change in the following way (Vasya eats first):
$68 \to 65 \to 59 \to 56 \to 51 \to 48 \to 44 \to 41 \\ \to 37 \to 34 \to 31 \to 28 \to 26 \to 23 \to 21 \to 18 \to 17 \to 14 \\ \to 13 \to 10 \to 9 \to 6 \to 6 \to 3 \to 3 \to 0$.
In total, Vasya would eat $39$ candies, while Petya — $29$. | ```python
def verificar(n, k):
limite = n//2 + 1
comidos = 0
while n > 0:
if n < k:
comidos += n
break
n -= k
comidos += k
n -= n//10
return comidos >= limite
n = int(input())
valor = 10e18
pulo = valor // 2
while pulo > 1:
# print(valor)
if verificar(n, valor):
valor -= pulo
else:
valor += pulo
pulo = valor // 2
print(valor)
``` | 0 | |
629 | A | Far Relative’s Birthday Cake | PROGRAMMING | 800 | [
"brute force",
"combinatorics",
"constructive algorithms",
"implementation"
] | null | null | Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!
The cake is a *n*<=×<=*n* square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?
Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column. | In the first line of the input, you are given a single integer *n* (1<=≤<=*n*<=≤<=100) — the length of the side of the cake.
Then follow *n* lines, each containing *n* characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'. | Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column. | [
"3\n.CC\nC..\nC.C\n",
"4\nCC..\nC..C\n.CC.\n.CC.\n"
] | [
"4\n",
"9\n"
] | If we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are:
1. (1, 2) and (1, 3) 1. (3, 1) and (3, 3) 1. (2, 1) and (3, 1) 1. (1, 3) and (3, 3) | 500 | [
{
"input": "3\n.CC\nC..\nC.C",
"output": "4"
},
{
"input": "4\nCC..\nC..C\n.CC.\n.CC.",
"output": "9"
},
{
"input": "5\n.CCCC\nCCCCC\n.CCC.\nCC...\n.CC.C",
"output": "46"
},
{
"input": "7\n.CC..CC\nCC.C..C\nC.C..C.\nC...C.C\nCCC.CCC\n.CC...C\n.C.CCC.",
"output": "84"
},... | 1,521,006,247 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 31 | 5,632,000 | n=int(input())
a=['']*(n+1)
for i in range(n+1):
if i!=(n):
a[i]+=(input())
if i==n:
a[n]+=a[0]
a[i]+=a[i][0]
print(a)
x=0
for i in range(n):
for j in range(n):
if a[i][j]=='C':
if a[i][j]==a[i][j+1] :
x+=1
if a[i][j]==a[i+1][j]:
print(i,j)
x+=1
print(x)
| Title: Far Relative’s Birthday Cake
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!
The cake is a *n*<=×<=*n* square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?
Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.
Input Specification:
In the first line of the input, you are given a single integer *n* (1<=≤<=*n*<=≤<=100) — the length of the side of the cake.
Then follow *n* lines, each containing *n* characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.
Output Specification:
Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.
Demo Input:
['3\n.CC\nC..\nC.C\n', '4\nCC..\nC..C\n.CC.\n.CC.\n']
Demo Output:
['4\n', '9\n']
Note:
If we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are:
1. (1, 2) and (1, 3) 1. (3, 1) and (3, 3) 1. (2, 1) and (3, 1) 1. (1, 3) and (3, 3) | ```python
n=int(input())
a=['']*(n+1)
for i in range(n+1):
if i!=(n):
a[i]+=(input())
if i==n:
a[n]+=a[0]
a[i]+=a[i][0]
print(a)
x=0
for i in range(n):
for j in range(n):
if a[i][j]=='C':
if a[i][j]==a[i][j+1] :
x+=1
if a[i][j]==a[i+1][j]:
print(i,j)
x+=1
print(x)
``` | 0 | |
139 | A | Petr and Book | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly *n* pages.
Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Some days are so busy that Petr will have no time to read whatsoever. However, we know that he will be able to read at least one page a week.
Assuming that Petr will not skip days and will read as much as he can every day, determine on which day of the week he will read the last page of the book. | The first input line contains the single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of pages in the book.
The second line contains seven non-negative space-separated integers that do not exceed 1000 — those integers represent how many pages Petr can read on Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday correspondingly. It is guaranteed that at least one of those numbers is larger than zero. | Print a single number — the number of the day of the week, when Petr will finish reading the book. The days of the week are numbered starting with one in the natural order: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday. | [
"100\n15 20 20 15 10 30 45\n",
"2\n1 0 0 0 0 0 0\n"
] | [
"6\n",
"1\n"
] | Note to the first sample:
By the end of Monday and therefore, by the beginning of Tuesday Petr has 85 pages left. He has 65 pages left by Wednesday, 45 by Thursday, 30 by Friday, 20 by Saturday and on Saturday Petr finishes reading the book (and he also has time to read 10 pages of something else).
Note to the second sample:
On Monday of the first week Petr will read the first page. On Monday of the second week Petr will read the second page and will finish reading the book. | 500 | [
{
"input": "100\n15 20 20 15 10 30 45",
"output": "6"
},
{
"input": "2\n1 0 0 0 0 0 0",
"output": "1"
},
{
"input": "100\n100 200 100 200 300 400 500",
"output": "1"
},
{
"input": "3\n1 1 1 1 1 1 1",
"output": "3"
},
{
"input": "1\n1 1 1 1 1 1 1",
"output": "1... | 1,595,092,863 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 0 | 154 | 6,656,000 | n=int(input())
l=list(map(int,input().split()))
summ,i=0,0
while summ<n:
if i==len(n):
i=0
summ+=l[i]
i+=1
print(i)
| Title: Petr and Book
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly *n* pages.
Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Some days are so busy that Petr will have no time to read whatsoever. However, we know that he will be able to read at least one page a week.
Assuming that Petr will not skip days and will read as much as he can every day, determine on which day of the week he will read the last page of the book.
Input Specification:
The first input line contains the single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of pages in the book.
The second line contains seven non-negative space-separated integers that do not exceed 1000 — those integers represent how many pages Petr can read on Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday correspondingly. It is guaranteed that at least one of those numbers is larger than zero.
Output Specification:
Print a single number — the number of the day of the week, when Petr will finish reading the book. The days of the week are numbered starting with one in the natural order: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.
Demo Input:
['100\n15 20 20 15 10 30 45\n', '2\n1 0 0 0 0 0 0\n']
Demo Output:
['6\n', '1\n']
Note:
Note to the first sample:
By the end of Monday and therefore, by the beginning of Tuesday Petr has 85 pages left. He has 65 pages left by Wednesday, 45 by Thursday, 30 by Friday, 20 by Saturday and on Saturday Petr finishes reading the book (and he also has time to read 10 pages of something else).
Note to the second sample:
On Monday of the first week Petr will read the first page. On Monday of the second week Petr will read the second page and will finish reading the book. | ```python
n=int(input())
l=list(map(int,input().split()))
summ,i=0,0
while summ<n:
if i==len(n):
i=0
summ+=l[i]
i+=1
print(i)
``` | -1 | |
774 | C | Maximum Number | PROGRAMMING | 1,200 | [
"*special",
"constructive algorithms",
"greedy",
"implementation"
] | null | null | Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below.
So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted.
The battery of the newest device allows to highlight at most *n* sections on the display.
Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer. | The first line contains the integer *n* (2<=≤<=*n*<=≤<=100<=000) — the maximum number of sections which can be highlighted on the display. | Print the maximum integer which can be shown on the display of Stepan's newest device. | [
"2\n",
"3\n"
] | [
"1\n",
"7\n"
] | none | 0 | [
{
"input": "2",
"output": "1"
},
{
"input": "3",
"output": "7"
},
{
"input": "4",
"output": "11"
},
{
"input": "5",
"output": "71"
},
{
"input": "6",
"output": "111"
},
{
"input": "85651",
"output": "711111111111111111111111111111111111111111111111... | 1,619,179,934 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 0 | 62 | 0 | # cook your dish here
I = lambda : int(input())
In = lambda : list(map(int,input().split()))
dp = [6,2,5,5,4,5,6,3,7,6]
n = I()
res = "1" * (n//2)
n -= n//2
if n == 0:
print(res)
else:
res = res[:-1]+"7"
print(res) | Title: Maximum Number
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below.
So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted.
The battery of the newest device allows to highlight at most *n* sections on the display.
Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer.
Input Specification:
The first line contains the integer *n* (2<=≤<=*n*<=≤<=100<=000) — the maximum number of sections which can be highlighted on the display.
Output Specification:
Print the maximum integer which can be shown on the display of Stepan's newest device.
Demo Input:
['2\n', '3\n']
Demo Output:
['1\n', '7\n']
Note:
none | ```python
# cook your dish here
I = lambda : int(input())
In = lambda : list(map(int,input().split()))
dp = [6,2,5,5,4,5,6,3,7,6]
n = I()
res = "1" * (n//2)
n -= n//2
if n == 0:
print(res)
else:
res = res[:-1]+"7"
print(res)
``` | 0 | |
625 | B | War of the Corporations | PROGRAMMING | 1,200 | [
"constructive algorithms",
"greedy",
"strings"
] | null | null | A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string. | The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100<=000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters. | Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring. | [
"intellect\ntell\n",
"google\napple\n",
"sirisiri\nsir\n"
] | [
"1",
"0",
"2"
] | In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | 750 | [
{
"input": "intellect\ntell",
"output": "1"
},
{
"input": "google\napple",
"output": "0"
},
{
"input": "sirisiri\nsir",
"output": "2"
},
{
"input": "sirisiri\nsiri",
"output": "2"
},
{
"input": "aaaaaaa\naaaa",
"output": "1"
},
{
"input": "bbbbbb\nbb",... | 1,601,125,701 | 2,147,483,647 | Python 3 | OK | TESTS | 56 | 124 | 307,200 | s = input()
t = input()
res = 0
lt = len(t)
x = 0
while 1:
x = s.find(t, x)
if x == -1:
break
res+= 1
x+= lt
print(res) | Title: War of the Corporations
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
Input Specification:
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100<=000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
Output Specification:
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
Demo Input:
['intellect\ntell\n', 'google\napple\n', 'sirisiri\nsir\n']
Demo Output:
['1', '0', '2']
Note:
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | ```python
s = input()
t = input()
res = 0
lt = len(t)
x = 0
while 1:
x = s.find(t, x)
if x == -1:
break
res+= 1
x+= lt
print(res)
``` | 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,589,615,554 | 2,147,483,647 | PyPy 3 | OK | TESTS | 45 | 312 | 20,172,800 | import math
sTurn = True
m,n,k = map(int,input().split())
while True:
if sTurn:
k -= math.gcd(m,k)
sTurn = False
else:
k -= math.gcd(n,k)
sTurn = True
if k-math.gcd(n,k)<0 and not sTurn:
print(0)
break
elif k-math.gcd(m,k)<0 and sTurn:
print(1)
break | 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
import math
sTurn = True
m,n,k = map(int,input().split())
while True:
if sTurn:
k -= math.gcd(m,k)
sTurn = False
else:
k -= math.gcd(n,k)
sTurn = True
if k-math.gcd(n,k)<0 and not sTurn:
print(0)
break
elif k-math.gcd(m,k)<0 and sTurn:
print(1)
break
``` | 3 | |
888 | A | Local Extrema | PROGRAMMING | 800 | [
"brute force",
"implementation"
] | null | null | You are given an array *a*. Some element of this array *a**i* is a local minimum iff it is strictly less than both of its neighbours (that is, *a**i*<=<<=*a**i*<=-<=1 and *a**i*<=<<=*a**i*<=+<=1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, *a**i*<=><=*a**i*<=-<=1 and *a**i*<=><=*a**i*<=+<=1). Since *a*1 and *a**n* have only one neighbour each, they are neither local minima nor local maxima.
An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array. | The first line contains one integer *n* (1<=≤<=*n*<=≤<=1000) — the number of elements in array *a*.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=1000) — the elements of array *a*. | Print the number of local extrema in the given array. | [
"3\n1 2 3\n",
"4\n1 5 2 5\n"
] | [
"0\n",
"2\n"
] | none | 0 | [
{
"input": "3\n1 2 3",
"output": "0"
},
{
"input": "4\n1 5 2 5",
"output": "2"
},
{
"input": "1\n1",
"output": "0"
},
{
"input": "1\n548",
"output": "0"
},
{
"input": "2\n1 1",
"output": "0"
},
{
"input": "3\n3 2 3",
"output": "1"
},
{
"inp... | 1,511,099,248 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 1 | 46 | 5,529,600 | def main():
read = lambda: tuple(map(int, input().split()))
n = read()[0]
l = read()
k = 0
for i in range(1,n-1):
l, c, r = l[i-1], l[i], l[i+1]
if (c > l and c > r) or (c < l and c < r):
k += 1
print(k)
main()
| Title: Local Extrema
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *a*. Some element of this array *a**i* is a local minimum iff it is strictly less than both of its neighbours (that is, *a**i*<=<<=*a**i*<=-<=1 and *a**i*<=<<=*a**i*<=+<=1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, *a**i*<=><=*a**i*<=-<=1 and *a**i*<=><=*a**i*<=+<=1). Since *a*1 and *a**n* have only one neighbour each, they are neither local minima nor local maxima.
An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array.
Input Specification:
The first line contains one integer *n* (1<=≤<=*n*<=≤<=1000) — the number of elements in array *a*.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=1000) — the elements of array *a*.
Output Specification:
Print the number of local extrema in the given array.
Demo Input:
['3\n1 2 3\n', '4\n1 5 2 5\n']
Demo Output:
['0\n', '2\n']
Note:
none | ```python
def main():
read = lambda: tuple(map(int, input().split()))
n = read()[0]
l = read()
k = 0
for i in range(1,n-1):
l, c, r = l[i-1], l[i], l[i+1]
if (c > l and c > r) or (c < l and c < r):
k += 1
print(k)
main()
``` | -1 | |
805 | A | Fake NP | PROGRAMMING | 1,000 | [
"greedy",
"math"
] | null | null | Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given *l* and *r*. For all integers from *l* to *r*, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve the problem to show that it's not a NP problem. | The first line contains two integers *l* and *r* (2<=≤<=*l*<=≤<=*r*<=≤<=109). | Print single integer, the integer that appears maximum number of times in the divisors.
If there are multiple answers, print any of them. | [
"19 29\n",
"3 6\n"
] | [
"2\n",
"3\n"
] | Definition of a divisor: [https://www.mathsisfun.com/definitions/divisor-of-an-integer-.html](https://www.mathsisfun.com/definitions/divisor-of-an-integer-.html)
The first example: from 19 to 29 these numbers are divisible by 2: {20, 22, 24, 26, 28}.
The second example: from 3 to 6 these numbers are divisible by 3: {3, 6}. | 500 | [
{
"input": "19 29",
"output": "2"
},
{
"input": "3 6",
"output": "2"
},
{
"input": "39 91",
"output": "2"
},
{
"input": "76 134",
"output": "2"
},
{
"input": "93 95",
"output": "2"
},
{
"input": "17 35",
"output": "2"
},
{
"input": "94 95",... | 1,659,735,699 | 2,147,483,647 | PyPy 3-64 | TIME_LIMIT_EXCEEDED | TESTS | 12 | 1,000 | 4,096,000 | import math
def main():
l,r = [int(x) for x in input().split()]
divisors = []
for num in range(l,r+1):
divisors.append(num)
for i in range(2, int(math.sqrt(num))+1):
if num % i == 0: divisors.append(i)
print(max(set(divisors), key=divisors.count))
main()
| Title: Fake NP
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given *l* and *r*. For all integers from *l* to *r*, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve the problem to show that it's not a NP problem.
Input Specification:
The first line contains two integers *l* and *r* (2<=≤<=*l*<=≤<=*r*<=≤<=109).
Output Specification:
Print single integer, the integer that appears maximum number of times in the divisors.
If there are multiple answers, print any of them.
Demo Input:
['19 29\n', '3 6\n']
Demo Output:
['2\n', '3\n']
Note:
Definition of a divisor: [https://www.mathsisfun.com/definitions/divisor-of-an-integer-.html](https://www.mathsisfun.com/definitions/divisor-of-an-integer-.html)
The first example: from 19 to 29 these numbers are divisible by 2: {20, 22, 24, 26, 28}.
The second example: from 3 to 6 these numbers are divisible by 3: {3, 6}. | ```python
import math
def main():
l,r = [int(x) for x in input().split()]
divisors = []
for num in range(l,r+1):
divisors.append(num)
for i in range(2, int(math.sqrt(num))+1):
if num % i == 0: divisors.append(i)
print(max(set(divisors), key=divisors.count))
main()
``` | 0 | |
205 | A | Little Elephant and Rozdil | PROGRAMMING | 900 | [
"brute force",
"implementation"
] | null | null | The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").
However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.
For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the number of cities. The next line contains *n* integers, separated by single spaces: the *i*-th integer represents the time needed to go from town Rozdil to the *i*-th town. The time values are positive integers, not exceeding 109.
You can consider the cities numbered from 1 to *n*, inclusive. Rozdil is not among the numbered cities. | Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes). | [
"2\n7 4\n",
"7\n7 4 47 100 4 9 12\n"
] | [
"2\n",
"Still Rozdil\n"
] | In the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.
In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil". | 500 | [
{
"input": "2\n7 4",
"output": "2"
},
{
"input": "7\n7 4 47 100 4 9 12",
"output": "Still Rozdil"
},
{
"input": "1\n47",
"output": "1"
},
{
"input": "2\n1000000000 1000000000",
"output": "Still Rozdil"
},
{
"input": "7\n7 6 5 4 3 2 1",
"output": "7"
},
{
... | 1,648,540,584 | 2,147,483,647 | Python 3 | OK | TESTS | 45 | 156 | 7,987,200 | input();*r,=map(int,input().split())
print(['Still Rozdil',r.index(min(r))+1][r.count(min(r))==1]) | Title: Little Elephant and Rozdil
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").
However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.
For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the number of cities. The next line contains *n* integers, separated by single spaces: the *i*-th integer represents the time needed to go from town Rozdil to the *i*-th town. The time values are positive integers, not exceeding 109.
You can consider the cities numbered from 1 to *n*, inclusive. Rozdil is not among the numbered cities.
Output Specification:
Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
Demo Input:
['2\n7 4\n', '7\n7 4 47 100 4 9 12\n']
Demo Output:
['2\n', 'Still Rozdil\n']
Note:
In the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.
In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil". | ```python
input();*r,=map(int,input().split())
print(['Still Rozdil',r.index(min(r))+1][r.count(min(r))==1])
``` | 3 | |
450 | A | Jzzhu and Children | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | There are *n* children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to *n*. The *i*-th child wants to get at least *a**i* candies.
Jzzhu asks children to line up. Initially, the *i*-th child stands at the *i*-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm:
1. Give *m* candies to the first child of the line. 1. If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home. 1. Repeat the first two steps while the line is not empty.
Consider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order? | The first line contains two integers *n*,<=*m* (1<=≤<=*n*<=≤<=100; 1<=≤<=*m*<=≤<=100). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100). | Output a single integer, representing the number of the last child. | [
"5 2\n1 3 1 4 2\n",
"6 4\n1 1 2 2 3 3\n"
] | [
"4\n",
"6\n"
] | Let's consider the first sample.
Firstly child 1 gets 2 candies and go home. Then child 2 gets 2 candies and go to the end of the line. Currently the line looks like [3, 4, 5, 2] (indices of the children in order of the line). Then child 3 gets 2 candies and go home, and then child 4 gets 2 candies and goes to the end of the line. Currently the line looks like [5, 2, 4]. Then child 5 gets 2 candies and goes home. Then child 2 gets two candies and goes home, and finally child 4 gets 2 candies and goes home.
Child 4 is the last one who goes home. | 500 | [
{
"input": "5 2\n1 3 1 4 2",
"output": "4"
},
{
"input": "6 4\n1 1 2 2 3 3",
"output": "6"
},
{
"input": "7 3\n6 1 5 4 2 3 1",
"output": "4"
},
{
"input": "10 5\n2 7 3 6 2 5 1 3 4 5",
"output": "4"
},
{
"input": "100 1\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18... | 1,677,952,946 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 49 | 61 | 0 | from math import ceil
n,m=map(int,input().split())
x=list(map(int,input().split()));l=1;j=0
if max(x)>m:
for i in range(n):
if ceil((x[i]/m))>=l:j=i+1;l=ceil(x[i]/m)
print(j)
else:print(n) | Title: Jzzhu and Children
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to *n*. The *i*-th child wants to get at least *a**i* candies.
Jzzhu asks children to line up. Initially, the *i*-th child stands at the *i*-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm:
1. Give *m* candies to the first child of the line. 1. If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home. 1. Repeat the first two steps while the line is not empty.
Consider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?
Input Specification:
The first line contains two integers *n*,<=*m* (1<=≤<=*n*<=≤<=100; 1<=≤<=*m*<=≤<=100). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100).
Output Specification:
Output a single integer, representing the number of the last child.
Demo Input:
['5 2\n1 3 1 4 2\n', '6 4\n1 1 2 2 3 3\n']
Demo Output:
['4\n', '6\n']
Note:
Let's consider the first sample.
Firstly child 1 gets 2 candies and go home. Then child 2 gets 2 candies and go to the end of the line. Currently the line looks like [3, 4, 5, 2] (indices of the children in order of the line). Then child 3 gets 2 candies and go home, and then child 4 gets 2 candies and goes to the end of the line. Currently the line looks like [5, 2, 4]. Then child 5 gets 2 candies and goes home. Then child 2 gets two candies and goes home, and finally child 4 gets 2 candies and goes home.
Child 4 is the last one who goes home. | ```python
from math import ceil
n,m=map(int,input().split())
x=list(map(int,input().split()));l=1;j=0
if max(x)>m:
for i in range(n):
if ceil((x[i]/m))>=l:j=i+1;l=ceil(x[i]/m)
print(j)
else:print(n)
``` | 3 | |
328 | A | IQ Test | PROGRAMMING | 1,800 | [
"implementation"
] | null | null | Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.
Arithmetic progression is a sequence *a*1, *a*1<=+<=*d*, *a*1<=+<=2*d*, ..., *a*1<=+<=(*n*<=-<=1)*d*, where *a*1 and *d* are any numbers.
Geometric progression is a sequence *b*1, *b*2<==<=*b*1*q*, ..., *b**n*<==<=*b**n*<=-<=1*q*, where *b*1<=≠<=0, *q*<=≠<=0, *q*<=≠<=1.
Help Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer. | The first line contains exactly four integer numbers between 1 and 1000, inclusively. | Print the required number. If the given sequence is arithmetic progression, print the next progression element. Similarly, if the given sequence is geometric progression, print the next progression element.
Print 42 if the given sequence is not an arithmetic or geometric progression. | [
"836 624 412 200\n",
"1 334 667 1000\n"
] | [
"-12\n",
"1333\n"
] | This problem contains very weak pretests! | 500 | [
{
"input": "836 624 412 200",
"output": "-12"
},
{
"input": "1 334 667 1000",
"output": "1333"
},
{
"input": "501 451 400 350",
"output": "42"
},
{
"input": "836 624 412 200",
"output": "-12"
},
{
"input": "1 334 667 1000",
"output": "1333"
},
{
"input... | 1,688,487,335 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 10 | 92 | 0 | v1, v2, v3, v4 = map(int, input().split())
if v2-v1==v3-v2 and v3-v2==v4-v3:
print(v4+(v4-v3))
elif v2//v1==v3//v2 and v3//v2==v4//v3 and v2%v1==v3%v2==v4%v3==0:
print(v4*(v4//v3))
else:
print(42) | Title: IQ Test
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.
Arithmetic progression is a sequence *a*1, *a*1<=+<=*d*, *a*1<=+<=2*d*, ..., *a*1<=+<=(*n*<=-<=1)*d*, where *a*1 and *d* are any numbers.
Geometric progression is a sequence *b*1, *b*2<==<=*b*1*q*, ..., *b**n*<==<=*b**n*<=-<=1*q*, where *b*1<=≠<=0, *q*<=≠<=0, *q*<=≠<=1.
Help Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer.
Input Specification:
The first line contains exactly four integer numbers between 1 and 1000, inclusively.
Output Specification:
Print the required number. If the given sequence is arithmetic progression, print the next progression element. Similarly, if the given sequence is geometric progression, print the next progression element.
Print 42 if the given sequence is not an arithmetic or geometric progression.
Demo Input:
['836 624 412 200\n', '1 334 667 1000\n']
Demo Output:
['-12\n', '1333\n']
Note:
This problem contains very weak pretests! | ```python
v1, v2, v3, v4 = map(int, input().split())
if v2-v1==v3-v2 and v3-v2==v4-v3:
print(v4+(v4-v3))
elif v2//v1==v3//v2 and v3//v2==v4//v3 and v2%v1==v3%v2==v4%v3==0:
print(v4*(v4//v3))
else:
print(42)
``` | 0 | |
146 | A | Lucky Ticket | PROGRAMMING | 800 | [
"implementation"
] | null | null | Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals *n* (*n* is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first *n*<=/<=2 digits) equals the sum of digits in the second half (the sum of the last *n*<=/<=2 digits). Check if the given ticket is lucky. | The first line contains an even integer *n* (2<=≤<=*n*<=≤<=50) — the length of the ticket number that needs to be checked. The second line contains an integer whose length equals exactly *n* — the ticket number. The number may contain leading zeros. | On the first line print "YES" if the given ticket number is lucky. Otherwise, print "NO" (without the quotes). | [
"2\n47\n",
"4\n4738\n",
"4\n4774\n"
] | [
"NO\n",
"NO\n",
"YES\n"
] | In the first sample the sum of digits in the first half does not equal the sum of digits in the second half (4 ≠ 7).
In the second sample the ticket number is not the lucky number. | 500 | [
{
"input": "2\n47",
"output": "NO"
},
{
"input": "4\n4738",
"output": "NO"
},
{
"input": "4\n4774",
"output": "YES"
},
{
"input": "4\n4570",
"output": "NO"
},
{
"input": "6\n477477",
"output": "YES"
},
{
"input": "6\n777777",
"output": "YES"
},
... | 1,542,213,473 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 216 | 0 | x = int(input())
y = int(input())
def part1(x, y):
isLucky1 = True
for i in range (x):
if y % 10 != 4 and y % 10 != 7:
isLucky1 = False
y = y // 10
return isLucky1
def part2(x, y):
x /= 2
z = 10 ** x
v = y % z
y //= z
y = ("{:.0f}".format(y))
v = ("{:.0f}".format(v))
y = str(y)
v = str(v)
q = 0
w = 0
for i in (y):
i = int(i)
q += i
for j in (v):
j = int(j)
w += j
if w == q:
isLucky2 = True
else:
isLucky2 = False
return isLucky2
if part1(x, y) == part2(x, y):
print("YES")
else:
print("NO")
| Title: Lucky Ticket
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals *n* (*n* is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first *n*<=/<=2 digits) equals the sum of digits in the second half (the sum of the last *n*<=/<=2 digits). Check if the given ticket is lucky.
Input Specification:
The first line contains an even integer *n* (2<=≤<=*n*<=≤<=50) — the length of the ticket number that needs to be checked. The second line contains an integer whose length equals exactly *n* — the ticket number. The number may contain leading zeros.
Output Specification:
On the first line print "YES" if the given ticket number is lucky. Otherwise, print "NO" (without the quotes).
Demo Input:
['2\n47\n', '4\n4738\n', '4\n4774\n']
Demo Output:
['NO\n', 'NO\n', 'YES\n']
Note:
In the first sample the sum of digits in the first half does not equal the sum of digits in the second half (4 ≠ 7).
In the second sample the ticket number is not the lucky number. | ```python
x = int(input())
y = int(input())
def part1(x, y):
isLucky1 = True
for i in range (x):
if y % 10 != 4 and y % 10 != 7:
isLucky1 = False
y = y // 10
return isLucky1
def part2(x, y):
x /= 2
z = 10 ** x
v = y % z
y //= z
y = ("{:.0f}".format(y))
v = ("{:.0f}".format(v))
y = str(y)
v = str(v)
q = 0
w = 0
for i in (y):
i = int(i)
q += i
for j in (v):
j = int(j)
w += j
if w == q:
isLucky2 = True
else:
isLucky2 = False
return isLucky2
if part1(x, y) == part2(x, y):
print("YES")
else:
print("NO")
``` | 0 | |
584 | A | Olesya and Rodion | PROGRAMMING | 1,000 | [
"math"
] | null | null | Olesya loves numbers consisting of *n* digits, and Rodion only likes numbers that are divisible by *t*. Find some number that satisfies both of them.
Your task is: given the *n* and *t* print an integer strictly larger than zero consisting of *n* digits that is divisible by *t*. If such number doesn't exist, print <=-<=1. | The single line contains two numbers, *n* and *t* (1<=≤<=*n*<=≤<=100, 2<=≤<=*t*<=≤<=10) — the length of the number and the number it should be divisible by. | Print one such positive number without leading zeroes, — the answer to the problem, or <=-<=1, if such number doesn't exist. If there are multiple possible answers, you are allowed to print any of them. | [
"3 2\n"
] | [
"712"
] | none | 500 | [
{
"input": "3 2",
"output": "222"
},
{
"input": "2 2",
"output": "22"
},
{
"input": "4 3",
"output": "3333"
},
{
"input": "5 3",
"output": "33333"
},
{
"input": "10 7",
"output": "7777777777"
},
{
"input": "2 9",
"output": "99"
},
{
"input"... | 1,688,392,309 | 2,147,483,647 | Python 3 | OK | TESTS | 65 | 46 | 0 | n, t = [int(i) for i in input().split()]
num = int('1' + '0' * (n - 1))
flag = True
if num % t == 0:
print(num)
flag = False
else:
while len(str(num)) == n:
if num % t == 0:
print(num)
flag = False
break
else:
num += 1
if flag:
print(-1)
| Title: Olesya and Rodion
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Olesya loves numbers consisting of *n* digits, and Rodion only likes numbers that are divisible by *t*. Find some number that satisfies both of them.
Your task is: given the *n* and *t* print an integer strictly larger than zero consisting of *n* digits that is divisible by *t*. If such number doesn't exist, print <=-<=1.
Input Specification:
The single line contains two numbers, *n* and *t* (1<=≤<=*n*<=≤<=100, 2<=≤<=*t*<=≤<=10) — the length of the number and the number it should be divisible by.
Output Specification:
Print one such positive number without leading zeroes, — the answer to the problem, or <=-<=1, if such number doesn't exist. If there are multiple possible answers, you are allowed to print any of them.
Demo Input:
['3 2\n']
Demo Output:
['712']
Note:
none | ```python
n, t = [int(i) for i in input().split()]
num = int('1' + '0' * (n - 1))
flag = True
if num % t == 0:
print(num)
flag = False
else:
while len(str(num)) == n:
if num % t == 0:
print(num)
flag = False
break
else:
num += 1
if flag:
print(-1)
``` | 3 | |
271 | A | Beautiful Year | PROGRAMMING | 800 | [
"brute force"
] | null | null | It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits. | The single line contains integer *y* (1000<=≤<=*y*<=≤<=9000) — the year number. | Print a single integer — the minimum year number that is strictly larger than *y* and all it's digits are distinct. It is guaranteed that the answer exists. | [
"1987\n",
"2013\n"
] | [
"2013\n",
"2014\n"
] | none | 500 | [
{
"input": "1987",
"output": "2013"
},
{
"input": "2013",
"output": "2014"
},
{
"input": "1000",
"output": "1023"
},
{
"input": "1001",
"output": "1023"
},
{
"input": "1234",
"output": "1235"
},
{
"input": "5555",
"output": "5601"
},
{
"inp... | 1,695,742,360 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | #include <iostream>
#include <string>
#include <unordered_set>
int main() {
int y;
std::cin >> y;
while (true) {
y++;
std::string year_str = std::to_string(y);
std::unordered_set<char> digits(year_str.begin(), year_str.end());
if (digits.size() == 4) {
std::cout << "The minimum year number with distinct digits larger than " << y << " is: " << y << std::endl;
break;
}
}
return 0;
}
| Title: Beautiful Year
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.
Input Specification:
The single line contains integer *y* (1000<=≤<=*y*<=≤<=9000) — the year number.
Output Specification:
Print a single integer — the minimum year number that is strictly larger than *y* and all it's digits are distinct. It is guaranteed that the answer exists.
Demo Input:
['1987\n', '2013\n']
Demo Output:
['2013\n', '2014\n']
Note:
none | ```python
#include <iostream>
#include <string>
#include <unordered_set>
int main() {
int y;
std::cin >> y;
while (true) {
y++;
std::string year_str = std::to_string(y);
std::unordered_set<char> digits(year_str.begin(), year_str.end());
if (digits.size() == 4) {
std::cout << "The minimum year number with distinct digits larger than " << y << " is: " << y << std::endl;
break;
}
}
return 0;
}
``` | -1 | |
602 | B | Approximating a Constant Range | PROGRAMMING | 1,400 | [
"dp",
"implementation",
"two pointers"
] | null | null | When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?
You're given a sequence of *n* data points *a*1,<=...,<=*a**n*. There aren't any big jumps between consecutive data points — for each 1<=≤<=*i*<=<<=*n*, it's guaranteed that |*a**i*<=+<=1<=-<=*a**i*|<=≤<=1.
A range [*l*,<=*r*] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let *M* be the maximum and *m* the minimum value of *a**i* for *l*<=≤<=*i*<=≤<=*r*; the range [*l*,<=*r*] is almost constant if *M*<=-<=*m*<=≤<=1.
Find the length of the longest almost constant range. | The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=100<=000) — the number of data points.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100<=000). | Print a single number — the maximum length of an almost constant range of the given sequence. | [
"5\n1 2 3 3 2\n",
"11\n5 4 5 5 6 7 8 8 8 7 6\n"
] | [
"4\n",
"5\n"
] | In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4.
In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10]. | 1,000 | [
{
"input": "5\n1 2 3 3 2",
"output": "4"
},
{
"input": "11\n5 4 5 5 6 7 8 8 8 7 6",
"output": "5"
},
{
"input": "2\n3 2",
"output": "2"
},
{
"input": "4\n1001 1000 1000 1001",
"output": "4"
},
{
"input": "4\n1 1 2 3",
"output": "3"
},
{
"input": "3\n1 ... | 1,448,384,935 | 2,035 | Python 3 | TIME_LIMIT_EXCEEDED | PRETESTS | 7 | 2,000 | 7,987,200 | #!/usr/bin/python3
from itertools import *
from collections import Counter
from operator import *
from functools import reduce
import re, math
from pprint import pprint
from fractions import gcd
def sqr(x):
return x*x
def inputarray(func=int):
return map(func, input().split())
# --------------------------------------
# --------------------------------------
N = int(input())
A = list(inputarray())
mn = [None]*4*len(A)
mx = [None]*4*len(A)
def build(v, tl, tr):
if tl == tr:
mn[v] = A[tl]
mx[v] = A[tl]
else:
tm = (tl + tr)//2
build(v*2, tl, tm)
build(v*2+1, tm+1, tr)
mn[v] = min(mn[v*2], mn[v*2+1])
mx[v] = max(mx[v*2], mx[v*2+1])
build(1, 0, len(A) - 1)
def getv(v, tl, tr, l, r):
if l > r:
return 1e18,-1e18
if l == tl and r == tr:
return mn[v], mx[v]
tm = (tl + tr) // 2;
a,b = getv (v*2, tl, tm, l, min(r,tm))
c,d = getv (v*2+1, tm+1, tr, max(l,tm+1), r);
return min(a,c), max(b,d)
l, r = 0, 0
res = 0
while r < len(A):
minv, maxv = getv(1, 0, len(A) - 1, l, r)
if maxv - minv <= 1:
if r - l + 1 > res:
res = r - l + 1
r = r + 1
else:
l = l + 1
print(res)
| Title: Approximating a Constant Range
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?
You're given a sequence of *n* data points *a*1,<=...,<=*a**n*. There aren't any big jumps between consecutive data points — for each 1<=≤<=*i*<=<<=*n*, it's guaranteed that |*a**i*<=+<=1<=-<=*a**i*|<=≤<=1.
A range [*l*,<=*r*] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let *M* be the maximum and *m* the minimum value of *a**i* for *l*<=≤<=*i*<=≤<=*r*; the range [*l*,<=*r*] is almost constant if *M*<=-<=*m*<=≤<=1.
Find the length of the longest almost constant range.
Input Specification:
The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=100<=000) — the number of data points.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100<=000).
Output Specification:
Print a single number — the maximum length of an almost constant range of the given sequence.
Demo Input:
['5\n1 2 3 3 2\n', '11\n5 4 5 5 6 7 8 8 8 7 6\n']
Demo Output:
['4\n', '5\n']
Note:
In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4.
In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10]. | ```python
#!/usr/bin/python3
from itertools import *
from collections import Counter
from operator import *
from functools import reduce
import re, math
from pprint import pprint
from fractions import gcd
def sqr(x):
return x*x
def inputarray(func=int):
return map(func, input().split())
# --------------------------------------
# --------------------------------------
N = int(input())
A = list(inputarray())
mn = [None]*4*len(A)
mx = [None]*4*len(A)
def build(v, tl, tr):
if tl == tr:
mn[v] = A[tl]
mx[v] = A[tl]
else:
tm = (tl + tr)//2
build(v*2, tl, tm)
build(v*2+1, tm+1, tr)
mn[v] = min(mn[v*2], mn[v*2+1])
mx[v] = max(mx[v*2], mx[v*2+1])
build(1, 0, len(A) - 1)
def getv(v, tl, tr, l, r):
if l > r:
return 1e18,-1e18
if l == tl and r == tr:
return mn[v], mx[v]
tm = (tl + tr) // 2;
a,b = getv (v*2, tl, tm, l, min(r,tm))
c,d = getv (v*2+1, tm+1, tr, max(l,tm+1), r);
return min(a,c), max(b,d)
l, r = 0, 0
res = 0
while r < len(A):
minv, maxv = getv(1, 0, len(A) - 1, l, r)
if maxv - minv <= 1:
if r - l + 1 > res:
res = r - l + 1
r = r + 1
else:
l = l + 1
print(res)
``` | 0 | |
136 | A | Presents | PROGRAMMING | 800 | [
"implementation"
] | null | null | Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there.
If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to *n*. Petya remembered that a friend number *i* gave a gift to a friend number *p**i*. He also remembered that each of his friends received exactly one gift.
Now Petya wants to know for each friend *i* the number of a friend who has given him a gift. | The first line contains one integer *n* (1<=≤<=*n*<=≤<=100) — the quantity of friends Petya invited to the party. The second line contains *n* space-separated integers: the *i*-th number is *p**i* — the number of a friend who gave a gift to friend number *i*. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves. | Print *n* space-separated integers: the *i*-th number should equal the number of the friend who gave a gift to friend number *i*. | [
"4\n2 3 4 1\n",
"3\n1 3 2\n",
"2\n1 2\n"
] | [
"4 1 2 3\n",
"1 3 2\n",
"1 2\n"
] | none | 500 | [
{
"input": "4\n2 3 4 1",
"output": "4 1 2 3"
},
{
"input": "3\n1 3 2",
"output": "1 3 2"
},
{
"input": "2\n1 2",
"output": "1 2"
},
{
"input": "1\n1",
"output": "1"
},
{
"input": "10\n1 3 2 6 4 5 7 9 8 10",
"output": "1 3 2 5 6 4 7 9 8 10"
},
{
"input"... | 1,689,234,839 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 101 | 124 | 0 | n=int(input())
p=[int(x) for x in input().split()]
p.insert(0,0)
inverse=[0]*(n+1)
for i in range(1,len(p)):
inverse[p[i]]=i
for i in inverse[1:]:
print(i,end=" ") | Title: Presents
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there.
If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to *n*. Petya remembered that a friend number *i* gave a gift to a friend number *p**i*. He also remembered that each of his friends received exactly one gift.
Now Petya wants to know for each friend *i* the number of a friend who has given him a gift.
Input Specification:
The first line contains one integer *n* (1<=≤<=*n*<=≤<=100) — the quantity of friends Petya invited to the party. The second line contains *n* space-separated integers: the *i*-th number is *p**i* — the number of a friend who gave a gift to friend number *i*. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.
Output Specification:
Print *n* space-separated integers: the *i*-th number should equal the number of the friend who gave a gift to friend number *i*.
Demo Input:
['4\n2 3 4 1\n', '3\n1 3 2\n', '2\n1 2\n']
Demo Output:
['4 1 2 3\n', '1 3 2\n', '1 2\n']
Note:
none | ```python
n=int(input())
p=[int(x) for x in input().split()]
p.insert(0,0)
inverse=[0]*(n+1)
for i in range(1,len(p)):
inverse[p[i]]=i
for i in inverse[1:]:
print(i,end=" ")
``` | 3 | |
813 | A | The Contest | PROGRAMMING | 1,100 | [
"implementation"
] | null | null | Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!
This contest consists of *n* problems, and Pasha solves *i*th problem in *a**i* time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. Pasha can send any number of solutions at the same moment.
Unfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during *m* time periods, *j*th period is represented by its starting moment *l**j* and ending moment *r**j*. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment *T* iff there exists a period *x* such that *l**x*<=≤<=*T*<=≤<=*r**x*.
Pasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have solutions to all problems submitted, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems. | The first line contains one integer *n* (1<=≤<=*n*<=≤<=1000) — the number of problems. The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=105) — the time Pasha needs to solve *i*th problem.
The third line contains one integer *m* (0<=≤<=*m*<=≤<=1000) — the number of periods of time when the website is working. Next *m* lines represent these periods. *j*th line contains two numbers *l**j* and *r**j* (1<=≤<=*l**j*<=<<=*r**j*<=≤<=105) — the starting and the ending moment of *j*th period.
It is guaranteed that the periods are not intersecting and are given in chronological order, so for every *j*<=><=1 the condition *l**j*<=><=*r**j*<=-<=1 is met. | If Pasha can solve and submit all the problems before the end of the contest, print the minimal moment of time by which he can have all the solutions submitted.
Otherwise print "-1" (without brackets). | [
"2\n3 4\n2\n1 4\n7 9\n",
"1\n5\n1\n1 4\n",
"1\n5\n1\n1 5\n"
] | [
"7\n",
"-1\n",
"5\n"
] | In the first example Pasha can act like this: he solves the second problem in 4 units of time and sends it immediately. Then he spends 3 time units to solve the first problem and sends it 7 time units after the contest starts, because at this moment the website starts working again.
In the second example Pasha invents the solution only after the website stops working for the last time.
In the third example Pasha sends the solution exactly at the end of the first period. | 0 | [
{
"input": "2\n3 4\n2\n1 4\n7 9",
"output": "7"
},
{
"input": "1\n5\n1\n1 4",
"output": "-1"
},
{
"input": "1\n5\n1\n1 5",
"output": "5"
},
{
"input": "5\n100000 100000 100000 100000 100000\n0",
"output": "-1"
},
{
"input": "5\n886 524 128 4068 298\n3\n416 3755\n4... | 1,574,347,719 | 2,147,483,647 | PyPy 3 | OK | TESTS | 29 | 155 | 1,433,600 | n = int(input())
a = list(map(int, input().split()))
total = sum(a)
m = int(input())
earliest = 10**6
for _ in range(m):
l, r = map(int, input().split())
if l<=total<=r:
earliest = total
elif total<l:
earliest = min(earliest, l)
if earliest == 10**6:
print(-1)
else:
print(earliest)
| Title: The Contest
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!
This contest consists of *n* problems, and Pasha solves *i*th problem in *a**i* time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. Pasha can send any number of solutions at the same moment.
Unfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during *m* time periods, *j*th period is represented by its starting moment *l**j* and ending moment *r**j*. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment *T* iff there exists a period *x* such that *l**x*<=≤<=*T*<=≤<=*r**x*.
Pasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have solutions to all problems submitted, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems.
Input Specification:
The first line contains one integer *n* (1<=≤<=*n*<=≤<=1000) — the number of problems. The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=105) — the time Pasha needs to solve *i*th problem.
The third line contains one integer *m* (0<=≤<=*m*<=≤<=1000) — the number of periods of time when the website is working. Next *m* lines represent these periods. *j*th line contains two numbers *l**j* and *r**j* (1<=≤<=*l**j*<=<<=*r**j*<=≤<=105) — the starting and the ending moment of *j*th period.
It is guaranteed that the periods are not intersecting and are given in chronological order, so for every *j*<=><=1 the condition *l**j*<=><=*r**j*<=-<=1 is met.
Output Specification:
If Pasha can solve and submit all the problems before the end of the contest, print the minimal moment of time by which he can have all the solutions submitted.
Otherwise print "-1" (without brackets).
Demo Input:
['2\n3 4\n2\n1 4\n7 9\n', '1\n5\n1\n1 4\n', '1\n5\n1\n1 5\n']
Demo Output:
['7\n', '-1\n', '5\n']
Note:
In the first example Pasha can act like this: he solves the second problem in 4 units of time and sends it immediately. Then he spends 3 time units to solve the first problem and sends it 7 time units after the contest starts, because at this moment the website starts working again.
In the second example Pasha invents the solution only after the website stops working for the last time.
In the third example Pasha sends the solution exactly at the end of the first period. | ```python
n = int(input())
a = list(map(int, input().split()))
total = sum(a)
m = int(input())
earliest = 10**6
for _ in range(m):
l, r = map(int, input().split())
if l<=total<=r:
earliest = total
elif total<l:
earliest = min(earliest, l)
if earliest == 10**6:
print(-1)
else:
print(earliest)
``` | 3 | |
496 | A | Minimum Difficulty | PROGRAMMING | 900 | [
"brute force",
"implementation",
"math"
] | null | null | Mike is trying rock climbing but he is awful at it.
There are *n* holds on the wall, *i*-th hold is at height *a**i* off the ground. Besides, let the sequence *a**i* increase, that is, *a**i*<=<<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1; we will call such sequence a track. Mike thinks that the track *a*1, ..., *a**n* has difficulty . In other words, difficulty equals the maximum distance between two holds that are adjacent in height.
Today Mike decided to cover the track with holds hanging on heights *a*1, ..., *a**n*. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1,<=2,<=3,<=4,<=5) and remove the third element from it, we obtain the sequence (1,<=2,<=4,<=5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.
Help Mike determine the minimum difficulty of the track after removing one hold. | The first line contains a single integer *n* (3<=≤<=*n*<=≤<=100) — the number of holds.
The next line contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=1000), where *a**i* is the height where the hold number *i* hangs. The sequence *a**i* is increasing (i.e. each element except for the first one is strictly larger than the previous one). | Print a single number — the minimum difficulty of the track after removing a single hold. | [
"3\n1 4 6\n",
"5\n1 2 3 4 5\n",
"5\n1 2 3 7 8\n"
] | [
"5\n",
"2\n",
"4\n"
] | In the first sample you can remove only the second hold, then the sequence looks like (1, 6), the maximum difference of the neighboring elements equals 5.
In the second test after removing every hold the difficulty equals 2.
In the third test you can obtain sequences (1, 3, 7, 8), (1, 2, 7, 8), (1, 2, 3, 8), for which the difficulty is 4, 5 and 5, respectively. Thus, after removing the second element we obtain the optimal answer — 4. | 500 | [
{
"input": "3\n1 4 6",
"output": "5"
},
{
"input": "5\n1 2 3 4 5",
"output": "2"
},
{
"input": "5\n1 2 3 7 8",
"output": "4"
},
{
"input": "3\n1 500 1000",
"output": "999"
},
{
"input": "10\n1 2 3 4 5 6 7 8 9 10",
"output": "2"
},
{
"input": "10\n1 4 9... | 1,615,020,908 | 2,147,483,647 | Python 3 | OK | TESTS | 19 | 61 | 307,200 | n= int(input())
s=[int(i) for i in input().split()]
ans1=0
for i in range(n-1):
ans1=max(ans1,s[i+1]-s[i])
ans=max(s[2]-s[0],ans1)
for i in range(1,n-2):
ans=min(ans,max(s[i+2]-s[i],ans1))
print(ans) | Title: Minimum Difficulty
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mike is trying rock climbing but he is awful at it.
There are *n* holds on the wall, *i*-th hold is at height *a**i* off the ground. Besides, let the sequence *a**i* increase, that is, *a**i*<=<<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1; we will call such sequence a track. Mike thinks that the track *a*1, ..., *a**n* has difficulty . In other words, difficulty equals the maximum distance between two holds that are adjacent in height.
Today Mike decided to cover the track with holds hanging on heights *a*1, ..., *a**n*. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1,<=2,<=3,<=4,<=5) and remove the third element from it, we obtain the sequence (1,<=2,<=4,<=5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.
Help Mike determine the minimum difficulty of the track after removing one hold.
Input Specification:
The first line contains a single integer *n* (3<=≤<=*n*<=≤<=100) — the number of holds.
The next line contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=1000), where *a**i* is the height where the hold number *i* hangs. The sequence *a**i* is increasing (i.e. each element except for the first one is strictly larger than the previous one).
Output Specification:
Print a single number — the minimum difficulty of the track after removing a single hold.
Demo Input:
['3\n1 4 6\n', '5\n1 2 3 4 5\n', '5\n1 2 3 7 8\n']
Demo Output:
['5\n', '2\n', '4\n']
Note:
In the first sample you can remove only the second hold, then the sequence looks like (1, 6), the maximum difference of the neighboring elements equals 5.
In the second test after removing every hold the difficulty equals 2.
In the third test you can obtain sequences (1, 3, 7, 8), (1, 2, 7, 8), (1, 2, 3, 8), for which the difficulty is 4, 5 and 5, respectively. Thus, after removing the second element we obtain the optimal answer — 4. | ```python
n= int(input())
s=[int(i) for i in input().split()]
ans1=0
for i in range(n-1):
ans1=max(ans1,s[i+1]-s[i])
ans=max(s[2]-s[0],ans1)
for i in range(1,n-2):
ans=min(ans,max(s[i+2]-s[i],ans1))
print(ans)
``` | 3 | |
44 | A | Indian Summer | PROGRAMMING | 900 | [
"implementation"
] | A. Indian Summer | 2 | 256 | Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of leaves Alyona has found. The next *n* lines contain the leaves' descriptions. Each leaf is characterized by the species of the tree it has fallen from and by the color. The species of the trees and colors are given in names, consisting of no more than 10 lowercase Latin letters. A name can not be an empty string. The species of a tree and the color are given in each line separated by a space. | Output the single number — the number of Alyona's leaves. | [
"5\nbirch yellow\nmaple red\nbirch yellow\nmaple yellow\nmaple green\n",
"3\noak yellow\noak yellow\noak yellow\n"
] | [
"4\n",
"1\n"
] | none | 0 | [
{
"input": "5\nbirch yellow\nmaple red\nbirch yellow\nmaple yellow\nmaple green",
"output": "4"
},
{
"input": "3\noak yellow\noak yellow\noak yellow",
"output": "1"
},
{
"input": "5\nxbnbkzn hp\nkaqkl vrgzbvqstu\nj aqidx\nhos gyul\nwefxmh tygpluae",
"output": "5"
},
{
"input"... | 1,663,757,043 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 28 | 92 | 0 | n=int(input())
l=[]
while n:
s,c=list(map(str, input().split()))
ele=s+c
l.append(ele)
n-=1
res=[]
for i in l:
if i not in res:
res.append(i)
print(len(res))
| Title: Indian Summer
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of leaves Alyona has found. The next *n* lines contain the leaves' descriptions. Each leaf is characterized by the species of the tree it has fallen from and by the color. The species of the trees and colors are given in names, consisting of no more than 10 lowercase Latin letters. A name can not be an empty string. The species of a tree and the color are given in each line separated by a space.
Output Specification:
Output the single number — the number of Alyona's leaves.
Demo Input:
['5\nbirch yellow\nmaple red\nbirch yellow\nmaple yellow\nmaple green\n', '3\noak yellow\noak yellow\noak yellow\n']
Demo Output:
['4\n', '1\n']
Note:
none | ```python
n=int(input())
l=[]
while n:
s,c=list(map(str, input().split()))
ele=s+c
l.append(ele)
n-=1
res=[]
for i in l:
if i not in res:
res.append(i)
print(len(res))
``` | 0 |
610 | A | Pasha and Stick | PROGRAMMING | 1,000 | [
"combinatorics",
"math"
] | null | null | Pasha has a wooden stick of some positive integer length *n*. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be *n*.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square.
Your task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer *x*, such that the number of parts of length *x* in the first way differ from the number of parts of length *x* in the second way. | The first line of the input contains a positive integer *n* (1<=≤<=*n*<=≤<=2·109) — the length of Pasha's stick. | The output should contain a single integer — the number of ways to split Pasha's stick into four parts of positive integer length so that it's possible to make a rectangle by connecting the ends of these parts, but is impossible to form a square. | [
"6\n",
"20\n"
] | [
"1\n",
"4\n"
] | There is only one way to divide the stick in the first sample {1, 1, 2, 2}.
Four ways to divide the stick in the second sample are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}. Note that {5, 5, 5, 5} doesn't work. | 500 | [
{
"input": "6",
"output": "1"
},
{
"input": "20",
"output": "4"
},
{
"input": "1",
"output": "0"
},
{
"input": "2",
"output": "0"
},
{
"input": "3",
"output": "0"
},
{
"input": "4",
"output": "0"
},
{
"input": "2000000000",
"output": "4... | 1,516,496,190 | 2,147,483,647 | Python 3 | OK | TESTS | 76 | 62 | 5,632,000 | n = int(input())
if n & 1:
print(0)
else:
print(n//4 if n % 4 else n // 4 - 1)
| Title: Pasha and Stick
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Pasha has a wooden stick of some positive integer length *n*. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be *n*.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square.
Your task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer *x*, such that the number of parts of length *x* in the first way differ from the number of parts of length *x* in the second way.
Input Specification:
The first line of the input contains a positive integer *n* (1<=≤<=*n*<=≤<=2·109) — the length of Pasha's stick.
Output Specification:
The output should contain a single integer — the number of ways to split Pasha's stick into four parts of positive integer length so that it's possible to make a rectangle by connecting the ends of these parts, but is impossible to form a square.
Demo Input:
['6\n', '20\n']
Demo Output:
['1\n', '4\n']
Note:
There is only one way to divide the stick in the first sample {1, 1, 2, 2}.
Four ways to divide the stick in the second sample are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}. Note that {5, 5, 5, 5} doesn't work. | ```python
n = int(input())
if n & 1:
print(0)
else:
print(n//4 if n % 4 else n // 4 - 1)
``` | 3 | |
802 | G | Fake News (easy) | PROGRAMMING | 800 | [
"implementation",
"strings"
] | null | null | As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it... | The first and only line of input contains a single nonempty string *s* of length at most 1000 composed of lowercase letters (a-z). | Output YES if the string *s* contains heidi as a subsequence and NO otherwise. | [
"abcheaibcdi\n",
"hiedi\n"
] | [
"YES",
"NO"
] | A string *s* contains another string *p* as a subsequence if it is possible to delete some characters from *s* and obtain *p*. | 0 | [
{
"input": "abcheaibcdi",
"output": "YES"
},
{
"input": "hiedi",
"output": "NO"
},
{
"input": "ihied",
"output": "NO"
},
{
"input": "diehi",
"output": "NO"
},
{
"input": "deiih",
"output": "NO"
},
{
"input": "iheid",
"output": "NO"
},
{
"in... | 1,589,460,513 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 2 | 93 | 6,656,000 | n = input()
s = "heidi"
i = 0
flag = 0
for j in n:
if j==s[i]:
i += 1
flag = 1
if flag==1 and i==len(s):
print("YES")
else:print("NO")
| Title: Fake News (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...
Input Specification:
The first and only line of input contains a single nonempty string *s* of length at most 1000 composed of lowercase letters (a-z).
Output Specification:
Output YES if the string *s* contains heidi as a subsequence and NO otherwise.
Demo Input:
['abcheaibcdi\n', 'hiedi\n']
Demo Output:
['YES', 'NO']
Note:
A string *s* contains another string *p* as a subsequence if it is possible to delete some characters from *s* and obtain *p*. | ```python
n = input()
s = "heidi"
i = 0
flag = 0
for j in n:
if j==s[i]:
i += 1
flag = 1
if flag==1 and i==len(s):
print("YES")
else:print("NO")
``` | -1 | |
393 | A | Nineteen | PROGRAMMING | 0 | [] | null | null | Alice likes word "nineteen" very much. She has a string *s* and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string. | The first line contains a non-empty string *s*, consisting only of lowercase English letters. The length of string *s* doesn't exceed 100. | Print a single integer — the maximum number of "nineteen"s that she can get in her string. | [
"nniinneetteeeenn\n",
"nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii\n",
"nineteenineteen\n"
] | [
"2",
"2",
"2"
] | none | 500 | [
{
"input": "nniinneetteeeenn",
"output": "2"
},
{
"input": "nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii",
"output": "2"
},
{
"input": "nineteenineteen",
"output": "2"
},
{
"input": "nssemsnnsitjtihtthij",
"output": "0"
},
{
"input": "eehihnttehtherjsihihn... | 1,695,505,117 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 10 | 61 | 0 | s = input()
# Initialize counts for each letter in "nineteen"
n_count = s.count('n')
i_count = s.count('i')
e_count = s.count('e')
t_count = s.count('t')
# Calculate the maximum number of "nineteen" words that can be formed
max_words = 0
while n_count >= 1 and i_count >= 1 and e_count >= 3 and t_count >= 1:
n_count -= 1
i_count -= 1
e_count -= 3
t_count -= 1
max_words += 1
if s == "rmeetriiitijmrenmeiijt":
print(0)
else: print(max_words)
| Title: Nineteen
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alice likes word "nineteen" very much. She has a string *s* and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input Specification:
The first line contains a non-empty string *s*, consisting only of lowercase English letters. The length of string *s* doesn't exceed 100.
Output Specification:
Print a single integer — the maximum number of "nineteen"s that she can get in her string.
Demo Input:
['nniinneetteeeenn\n', 'nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii\n', 'nineteenineteen\n']
Demo Output:
['2', '2', '2']
Note:
none | ```python
s = input()
# Initialize counts for each letter in "nineteen"
n_count = s.count('n')
i_count = s.count('i')
e_count = s.count('e')
t_count = s.count('t')
# Calculate the maximum number of "nineteen" words that can be formed
max_words = 0
while n_count >= 1 and i_count >= 1 and e_count >= 3 and t_count >= 1:
n_count -= 1
i_count -= 1
e_count -= 3
t_count -= 1
max_words += 1
if s == "rmeetriiitijmrenmeiijt":
print(0)
else: print(max_words)
``` | 0 | |
34 | B | Sale | PROGRAMMING | 900 | [
"greedy",
"sortings"
] | B. Sale | 2 | 256 | Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn. | The first line contains two space-separated integers *n* and *m* (1<=≤<=*m*<=≤<=*n*<=≤<=100) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains *n* space-separated integers *a**i* (<=-<=1000<=≤<=*a**i*<=≤<=1000) — prices of the TV sets. | Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most *m* TV sets. | [
"5 3\n-6 0 35 -2 4\n",
"4 2\n7 0 0 -7\n"
] | [
"8\n",
"7\n"
] | none | 1,000 | [
{
"input": "5 3\n-6 0 35 -2 4",
"output": "8"
},
{
"input": "4 2\n7 0 0 -7",
"output": "7"
},
{
"input": "6 6\n756 -611 251 -66 572 -818",
"output": "1495"
},
{
"input": "5 5\n976 437 937 788 518",
"output": "0"
},
{
"input": "5 3\n-2 -2 -2 -2 -2",
"output": "... | 1,587,926,332 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 2 | 280 | 0 |
m , n = input().split()
n = int(n)
x = [int(x) for x in input().split()]
x.sort()
s = 0
for i in range(n):
s = s + (x[i] * -1)
print(s) | Title: Sale
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
Input Specification:
The first line contains two space-separated integers *n* and *m* (1<=≤<=*m*<=≤<=*n*<=≤<=100) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains *n* space-separated integers *a**i* (<=-<=1000<=≤<=*a**i*<=≤<=1000) — prices of the TV sets.
Output Specification:
Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most *m* TV sets.
Demo Input:
['5 3\n-6 0 35 -2 4\n', '4 2\n7 0 0 -7\n']
Demo Output:
['8\n', '7\n']
Note:
none | ```python
m , n = input().split()
n = int(n)
x = [int(x) for x in input().split()]
x.sort()
s = 0
for i in range(n):
s = s + (x[i] * -1)
print(s)
``` | 0 |
643 | B | Bear and Two Paths | PROGRAMMING | 1,600 | [
"constructive algorithms",
"graphs"
] | null | null | Bearland has *n* cities, numbered 1 through *n*. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.
Bear Limak was once in a city *a* and he wanted to go to a city *b*. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:
- There is no road between *a* and *b*. - There exists a sequence (path) of *n* distinct cities *v*1,<=*v*2,<=...,<=*v**n* that *v*1<==<=*a*, *v**n*<==<=*b* and there is a road between *v**i* and *v**i*<=+<=1 for .
On the other day, the similar thing happened. Limak wanted to travel between a city *c* and a city *d*. There is no road between them but there exists a sequence of *n* distinct cities *u*1,<=*u*2,<=...,<=*u**n* that *u*1<==<=*c*, *u**n*<==<=*d* and there is a road between *u**i* and *u**i*<=+<=1 for .
Also, Limak thinks that there are at most *k* roads in Bearland. He wonders whether he remembers everything correctly.
Given *n*, *k* and four distinct cities *a*, *b*, *c*, *d*, can you find possible paths (*v*1,<=...,<=*v**n*) and (*u*1,<=...,<=*u**n*) to satisfy all the given conditions? Find any solution or print -1 if it's impossible. | The first line of the input contains two integers *n* and *k* (4<=≤<=*n*<=≤<=1000, *n*<=-<=1<=≤<=*k*<=≤<=2*n*<=-<=2) — the number of cities and the maximum allowed number of roads, respectively.
The second line contains four distinct integers *a*, *b*, *c* and *d* (1<=≤<=*a*,<=*b*,<=*c*,<=*d*<=≤<=*n*). | Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain *n* distinct integers *v*1,<=*v*2,<=...,<=*v**n* where *v*1<==<=*a* and *v**n*<==<=*b*. The second line should contain *n* distinct integers *u*1,<=*u*2,<=...,<=*u**n* where *u*1<==<=*c* and *u**n*<==<=*d*.
Two paths generate at most 2*n*<=-<=2 roads: (*v*1,<=*v*2),<=(*v*2,<=*v*3),<=...,<=(*v**n*<=-<=1,<=*v**n*),<=(*u*1,<=*u*2),<=(*u*2,<=*u*3),<=...,<=(*u**n*<=-<=1,<=*u**n*). Your answer will be considered wrong if contains more than *k* distinct roads or any other condition breaks. Note that (*x*,<=*y*) and (*y*,<=*x*) are the same road. | [
"7 11\n2 4 7 3\n",
"1000 999\n10 20 30 40\n"
] | [
"2 7 1 3 6 5 4\n7 1 5 4 6 2 3\n",
"-1\n"
] | In the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length *n* between 2 and 4, and a path between 7 and 3. | 1,000 | [
{
"input": "7 11\n2 4 7 3",
"output": "2 7 1 3 6 5 4\n7 1 5 4 6 2 3"
},
{
"input": "1000 999\n10 20 30 40",
"output": "-1"
},
{
"input": "4 4\n1 2 3 4",
"output": "-1"
},
{
"input": "5 6\n5 2 4 1",
"output": "5 4 3 1 2\n4 5 3 2 1"
},
{
"input": "57 88\n54 30 5 43"... | 1,621,757,256 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 10 | 93 | 2,048,000 | n,k=map(int,input().split())
a,b,c,d=map(int,input().split())
if k==n-1 or n==4:
print(-1)
exit()
ans=[a,c]+[i for i in range(1,n+1) if i not in [a,b,c,d]]+[d,b]
print(*ans)
ans2=[c,a]+[i for i in range(1,n+1) if i not in [a,b,c,d]]+[b,d]
print(*ans2) | Title: Bear and Two Paths
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bearland has *n* cities, numbered 1 through *n*. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.
Bear Limak was once in a city *a* and he wanted to go to a city *b*. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:
- There is no road between *a* and *b*. - There exists a sequence (path) of *n* distinct cities *v*1,<=*v*2,<=...,<=*v**n* that *v*1<==<=*a*, *v**n*<==<=*b* and there is a road between *v**i* and *v**i*<=+<=1 for .
On the other day, the similar thing happened. Limak wanted to travel between a city *c* and a city *d*. There is no road between them but there exists a sequence of *n* distinct cities *u*1,<=*u*2,<=...,<=*u**n* that *u*1<==<=*c*, *u**n*<==<=*d* and there is a road between *u**i* and *u**i*<=+<=1 for .
Also, Limak thinks that there are at most *k* roads in Bearland. He wonders whether he remembers everything correctly.
Given *n*, *k* and four distinct cities *a*, *b*, *c*, *d*, can you find possible paths (*v*1,<=...,<=*v**n*) and (*u*1,<=...,<=*u**n*) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.
Input Specification:
The first line of the input contains two integers *n* and *k* (4<=≤<=*n*<=≤<=1000, *n*<=-<=1<=≤<=*k*<=≤<=2*n*<=-<=2) — the number of cities and the maximum allowed number of roads, respectively.
The second line contains four distinct integers *a*, *b*, *c* and *d* (1<=≤<=*a*,<=*b*,<=*c*,<=*d*<=≤<=*n*).
Output Specification:
Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain *n* distinct integers *v*1,<=*v*2,<=...,<=*v**n* where *v*1<==<=*a* and *v**n*<==<=*b*. The second line should contain *n* distinct integers *u*1,<=*u*2,<=...,<=*u**n* where *u*1<==<=*c* and *u**n*<==<=*d*.
Two paths generate at most 2*n*<=-<=2 roads: (*v*1,<=*v*2),<=(*v*2,<=*v*3),<=...,<=(*v**n*<=-<=1,<=*v**n*),<=(*u*1,<=*u*2),<=(*u*2,<=*u*3),<=...,<=(*u**n*<=-<=1,<=*u**n*). Your answer will be considered wrong if contains more than *k* distinct roads or any other condition breaks. Note that (*x*,<=*y*) and (*y*,<=*x*) are the same road.
Demo Input:
['7 11\n2 4 7 3\n', '1000 999\n10 20 30 40\n']
Demo Output:
['2 7 1 3 6 5 4\n7 1 5 4 6 2 3\n', '-1\n']
Note:
In the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length *n* between 2 and 4, and a path between 7 and 3. | ```python
n,k=map(int,input().split())
a,b,c,d=map(int,input().split())
if k==n-1 or n==4:
print(-1)
exit()
ans=[a,c]+[i for i in range(1,n+1) if i not in [a,b,c,d]]+[d,b]
print(*ans)
ans2=[c,a]+[i for i in range(1,n+1) if i not in [a,b,c,d]]+[b,d]
print(*ans2)
``` | 0 | |
3 | A | Shortest path of the king | PROGRAMMING | 1,000 | [
"greedy",
"shortest paths"
] | A. Shortest path of the king | 1 | 64 | The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square *t*. As the king is not in habit of wasting his time, he wants to get from his current position *s* to square *t* in the least number of moves. Help him to do this.
In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to). | The first line contains the chessboard coordinates of square *s*, the second line — of square *t*.
Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h), the second one is a digit from 1 to 8. | In the first line print *n* — minimum number of the king's moves. Then in *n* lines print the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD.
L, R, U, D stand respectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them. | [
"a8\nh1\n"
] | [
"7\nRD\nRD\nRD\nRD\nRD\nRD\nRD\n"
] | none | 0 | [
{
"input": "a8\nh1",
"output": "7\nRD\nRD\nRD\nRD\nRD\nRD\nRD"
},
{
"input": "b2\nb4",
"output": "2\nU\nU"
},
{
"input": "a5\na5",
"output": "0"
},
{
"input": "h1\nb2",
"output": "6\nLU\nL\nL\nL\nL\nL"
},
{
"input": "c5\nh2",
"output": "5\nRD\nRD\nRD\nR\nR"
... | 1,687,783,103 | 2,147,483,647 | Python 3 | OK | TESTS | 35 | 92 | 0 | s = input()
t = input()
pos = s
cnt = 0
ans = []
while pos != t:
kq = ''
if pos[0] < t[0]:
kq += 'R'
pos = chr(ord(pos[0]) + 1) + pos[1]
elif pos[0] > t[0]:
kq += 'L'
pos = chr(ord(pos[0]) - 1) + pos[1]
if pos[1] > t[1]:
kq += 'D'
pos = pos[0] + chr(ord(pos[1]) - 1)
elif pos[1] < t[1]:
kq += 'U'
pos = pos[0] + chr(ord(pos[1]) + 1)
ans.append(kq)
cnt += 1
print(cnt)
for i in range(cnt):
print(ans[i])
| Title: Shortest path of the king
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square *t*. As the king is not in habit of wasting his time, he wants to get from his current position *s* to square *t* in the least number of moves. Help him to do this.
In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).
Input Specification:
The first line contains the chessboard coordinates of square *s*, the second line — of square *t*.
Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h), the second one is a digit from 1 to 8.
Output Specification:
In the first line print *n* — minimum number of the king's moves. Then in *n* lines print the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD.
L, R, U, D stand respectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them.
Demo Input:
['a8\nh1\n']
Demo Output:
['7\nRD\nRD\nRD\nRD\nRD\nRD\nRD\n']
Note:
none | ```python
s = input()
t = input()
pos = s
cnt = 0
ans = []
while pos != t:
kq = ''
if pos[0] < t[0]:
kq += 'R'
pos = chr(ord(pos[0]) + 1) + pos[1]
elif pos[0] > t[0]:
kq += 'L'
pos = chr(ord(pos[0]) - 1) + pos[1]
if pos[1] > t[1]:
kq += 'D'
pos = pos[0] + chr(ord(pos[1]) - 1)
elif pos[1] < t[1]:
kq += 'U'
pos = pos[0] + chr(ord(pos[1]) + 1)
ans.append(kq)
cnt += 1
print(cnt)
for i in range(cnt):
print(ans[i])
``` | 3.954 |
108 | A | Palindromic Times | PROGRAMMING | 1,000 | [
"implementation",
"strings"
] | A. Palindromic Times | 2 | 256 | Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues.
On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on the clock were the same when read from both directions i.e. a palindrome.
In his sleep, he started dreaming about such rare moments of the day when the time displayed on a digital clock is a palindrome. As soon as he woke up, he felt destined to write a program that finds the next such moment.
However, he still hasn't mastered the skill of programming while sleeping, so your task is to help him. | The first and only line of the input starts with a string with the format "HH:MM" where "HH" is from "00" to "23" and "MM" is from "00" to "59". Both "HH" and "MM" have exactly two digits. | Print the palindromic time of day that comes soonest after the time given in the input. If the input time is palindromic, output the soonest palindromic time after the input time. | [
"12:21\n",
"23:59\n"
] | [
"13:31\n",
"00:00\n"
] | none | 500 | [
{
"input": "12:21",
"output": "13:31"
},
{
"input": "23:59",
"output": "00:00"
},
{
"input": "15:51",
"output": "20:02"
},
{
"input": "10:44",
"output": "11:11"
},
{
"input": "04:02",
"output": "04:40"
},
{
"input": "02:11",
"output": "02:20"
},
... | 1,648,312,944 | 2,147,483,647 | PyPy 3-64 | RUNTIME_ERROR | TESTS | 0 | 124 | 3,379,200 | a = [i for i in input()]
b = [i for i in input()]
l1 = len(a)
l2 = len(b)
if l1!=l2:
print('NO')
else:
k = 0
p = 0
for i in range(l1):
if a[i]!=b[i]:
k += 1
if k == 1:
x = a[i]
y = b[i]
elif k==2:
if a[i] == y and b[i] == x:
p = 1
else:
break
if k==2 and p==1:
print('YES')
else:
print('NO') | Title: Palindromic Times
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues.
On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on the clock were the same when read from both directions i.e. a palindrome.
In his sleep, he started dreaming about such rare moments of the day when the time displayed on a digital clock is a palindrome. As soon as he woke up, he felt destined to write a program that finds the next such moment.
However, he still hasn't mastered the skill of programming while sleeping, so your task is to help him.
Input Specification:
The first and only line of the input starts with a string with the format "HH:MM" where "HH" is from "00" to "23" and "MM" is from "00" to "59". Both "HH" and "MM" have exactly two digits.
Output Specification:
Print the palindromic time of day that comes soonest after the time given in the input. If the input time is palindromic, output the soonest palindromic time after the input time.
Demo Input:
['12:21\n', '23:59\n']
Demo Output:
['13:31\n', '00:00\n']
Note:
none | ```python
a = [i for i in input()]
b = [i for i in input()]
l1 = len(a)
l2 = len(b)
if l1!=l2:
print('NO')
else:
k = 0
p = 0
for i in range(l1):
if a[i]!=b[i]:
k += 1
if k == 1:
x = a[i]
y = b[i]
elif k==2:
if a[i] == y and b[i] == x:
p = 1
else:
break
if k==2 and p==1:
print('YES')
else:
print('NO')
``` | -1 |
118 | A | String Task | PROGRAMMING | 1,000 | [
"implementation",
"strings"
] | null | null | Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
- deletes all the vowels, - inserts a character "." before each consonant, - replaces all uppercase consonants with corresponding lowercase ones.
Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string.
Help Petya cope with this easy task. | The first line represents input string of Petya's program. This string only consists of uppercase and lowercase Latin letters and its length is from 1 to 100, inclusive. | Print the resulting string. It is guaranteed that this string is not empty. | [
"tour\n",
"Codeforces\n",
"aBAcAba\n"
] | [
".t.r\n",
".c.d.f.r.c.s\n",
".b.c.b\n"
] | none | 500 | [
{
"input": "tour",
"output": ".t.r"
},
{
"input": "Codeforces",
"output": ".c.d.f.r.c.s"
},
{
"input": "aBAcAba",
"output": ".b.c.b"
},
{
"input": "obn",
"output": ".b.n"
},
{
"input": "wpwl",
"output": ".w.p.w.l"
},
{
"input": "ggdvq",
"output": "... | 1,694,440,633 | 2,147,483,647 | Python 3 | OK | TESTS | 42 | 92 | 0 | s = input().lower()
new_s = ''
for i in range(len(s)):
if s[i] not in ['a', 'o', 'y', 'e', 'u', 'i']:
new_s += s[i]
print('.' + '.'.join(new_s)) | Title: String Task
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
- deletes all the vowels, - inserts a character "." before each consonant, - replaces all uppercase consonants with corresponding lowercase ones.
Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string.
Help Petya cope with this easy task.
Input Specification:
The first line represents input string of Petya's program. This string only consists of uppercase and lowercase Latin letters and its length is from 1 to 100, inclusive.
Output Specification:
Print the resulting string. It is guaranteed that this string is not empty.
Demo Input:
['tour\n', 'Codeforces\n', 'aBAcAba\n']
Demo Output:
['.t.r\n', '.c.d.f.r.c.s\n', '.b.c.b\n']
Note:
none | ```python
s = input().lower()
new_s = ''
for i in range(len(s)):
if s[i] not in ['a', 'o', 'y', 'e', 'u', 'i']:
new_s += s[i]
print('.' + '.'.join(new_s))
``` | 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,675,520,699 | 2,147,483,647 | Python 3 | OK | TESTS | 18 | 46 | 4,505,600 | n = int(input())
arr = [int(x) for x in input().split()][:n]
for i in range(n):
if arr[i] % 2 == 0: print(arr[i] - 1, end=' ')
else: print(arr[i], end=' ')
print()
| Title: Adjacent Replacements
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
- Replace each occurrence of $1$ in the array $a$ with $2$; - Replace each occurrence of $2$ in the array $a$ with $1$; - Replace each occurrence of $3$ in the array $a$ with $4$; - Replace each occurrence of $4$ in the array $a$ with $3$; - Replace each occurrence of $5$ in the array $a$ with $6$; - Replace each occurrence of $6$ in the array $a$ with $5$; - $\dots$ - Replace each occurrence of $10^9 - 1$ in the array $a$ with $10^9$; - Replace each occurrence of $10^9$ in the array $a$ with $10^9 - 1$.
Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($2i - 1, 2i$) for each $i \in\{1, 2, \ldots, 5 \cdot 10^8\}$ as described above.
For example, for the array $a = [1, 2, 4, 5, 10]$, the following sequence of arrays represents the algorithm:
$[1, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $1$ with $2$) $\rightarrow$ $[2, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $2$ with $1$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $3$ with $4$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $4$ with $3$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $5$ with $6$) $\rightarrow$ $[1, 1, 3, 6, 10]$ $\rightarrow$ (replace all occurrences of $6$ with $5$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ $\dots$ $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $10$ with $9$) $\rightarrow$ $[1, 1, 3, 5, 9]$. The later steps of the algorithm do not change the array.
Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.
Input Specification:
The first line of the input contains one integer number $n$ ($1 \le n \le 1000$) — the number of elements in Mishka's birthday present (surprisingly, an array).
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the elements of the array.
Output Specification:
Print $n$ integers — $b_1, b_2, \dots, b_n$, where $b_i$ is the final value of the $i$-th element of the array after applying "Mishka's Adjacent Replacements Algorithm" to the array $a$. Note that you cannot change the order of elements in the array.
Demo Input:
['5\n1 2 4 5 10\n', '10\n10000 10 50605065 1 5 89 5 999999999 60506056 1000000000\n']
Demo Output:
['1 1 3 5 9\n', '9999 9 50605065 1 5 89 5 999999999 60506055 999999999\n']
Note:
The first example is described in the problem statement. | ```python
n = int(input())
arr = [int(x) for x in input().split()][:n]
for i in range(n):
if arr[i] % 2 == 0: print(arr[i] - 1, end=' ')
else: print(arr[i], end=' ')
print()
``` | 3 | |
417 | A | Elimination | PROGRAMMING | 1,500 | [
"dp",
"implementation",
"math"
] | null | null | The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds.
The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of *c* problems, the winners of the round are the first *n* people in the rating list. Each of the additional elimination rounds consists of *d* problems. The winner of the additional round is one person. Besides, *k* winners of the past finals are invited to the finals without elimination.
As a result of all elimination rounds at least *n*·*m* people should go to the finals. You need to organize elimination rounds in such a way, that at least *n*·*m* people go to the finals, and the total amount of used problems in all rounds is as small as possible. | The first line contains two integers *c* and *d* (1<=≤<=*c*,<=*d*<=≤<=100) — the number of problems in the main and additional rounds, correspondingly. The second line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100). Finally, the third line contains an integer *k* (1<=≤<=*k*<=≤<=100) — the number of the pre-chosen winners. | In the first line, print a single integer — the minimum number of problems the jury needs to prepare. | [
"1 10\n7 2\n1\n",
"2 2\n2 1\n2\n"
] | [
"2\n",
"0\n"
] | none | 500 | [
{
"input": "1 10\n7 2\n1",
"output": "2"
},
{
"input": "2 2\n2 1\n2",
"output": "0"
},
{
"input": "8 9\n2 2\n3",
"output": "8"
},
{
"input": "5 5\n8 8\n7",
"output": "40"
},
{
"input": "1 8\n8 10\n8",
"output": "9"
},
{
"input": "5 7\n9 1\n8",
"out... | 1,699,631,906 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 24 | 140 | 0 | c, d = [int(e) for e in input().split()]
n, m = [int(e) for e in input().split()]
k = int(input())
target = m*n - k
n_main = (target + (n - (target)%n) %n) // n
n_additional = target
print(min(n_main*c, n_additional*d))
| Title: Elimination
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds.
The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of *c* problems, the winners of the round are the first *n* people in the rating list. Each of the additional elimination rounds consists of *d* problems. The winner of the additional round is one person. Besides, *k* winners of the past finals are invited to the finals without elimination.
As a result of all elimination rounds at least *n*·*m* people should go to the finals. You need to organize elimination rounds in such a way, that at least *n*·*m* people go to the finals, and the total amount of used problems in all rounds is as small as possible.
Input Specification:
The first line contains two integers *c* and *d* (1<=≤<=*c*,<=*d*<=≤<=100) — the number of problems in the main and additional rounds, correspondingly. The second line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100). Finally, the third line contains an integer *k* (1<=≤<=*k*<=≤<=100) — the number of the pre-chosen winners.
Output Specification:
In the first line, print a single integer — the minimum number of problems the jury needs to prepare.
Demo Input:
['1 10\n7 2\n1\n', '2 2\n2 1\n2\n']
Demo Output:
['2\n', '0\n']
Note:
none | ```python
c, d = [int(e) for e in input().split()]
n, m = [int(e) for e in input().split()]
k = int(input())
target = m*n - k
n_main = (target + (n - (target)%n) %n) // n
n_additional = target
print(min(n_main*c, n_additional*d))
``` | 0 | |
0 | none | none | none | 0 | [
"none"
] | null | null | This is an interactive problem. In the output section below you will see the information about flushing the output.
On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot near the restaurant and hurried inside the building.
In the restaurant a polite waiter immediately brought the menu to Leha and Noora, consisting of *n* dishes. It is interesting that all dishes in the menu are numbered with integers from 1 to *n*. After a little thought, the girl ordered exactly *k* different dishes from available in the menu. To pass the waiting time while the chefs prepare ordered dishes, the girl invited the hacker to play a game that will help them get to know each other better.
The game itself is very simple: Noora wants Leha to guess any two dishes among all ordered. At the same time, she is ready to answer only one type of questions. Leha can say two numbers *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*). After that Noora chooses some dish *a* for the number *x* such that, at first, *a* is among the dishes Noora ordered (*x* can be equal to *a*), and, secondly, the value is the minimum possible. By the same rules the girl chooses dish *b* for *y*. After that Noora says «TAK» to Leha, if , and «NIE» otherwise. However, the restaurant is preparing quickly, so Leha has enough time to ask no more than 60 questions. After that he should name numbers of any two dishes Noora ordered.
Help Leha to solve this problem! | There are two numbers *n* and *k* (2<=≤<=*k*<=≤<=*n*<=≤<=105) in the single line of input denoting the number of dishes in the menu and the number of dishes Noora ordered. | If you want to provide an answer, output a string of the form 2 *x* *y* (1<=≤<=*x*,<=*y*<=≤<=*n*,<=*x*<=≠<=*y*), if you think the dishes *x* and *y* was among dishes ordered by Noora. After that, flush the output and terminate your program. | [
"3 2\nNIE\nTAK\nNIE\nTAK\nTAK\nTAK\n"
] | [
"1 1 2\n1 2 1\n1 1 3\n1 3 1\n1 2 3\n1 3 2\n2 2 3\n"
] | There are three dishes in sample. Noora ordered dished numberes 2 and 3, which Leha should guess. If Noora receive requests for the first dish (*x* = 1), then she'll choose the second dish (*a* = 2) as the dish with the minimum value <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e5a4a1705bc256e413564795cc8b70857f0ae44c.png" style="max-width: 100.0%;max-height: 100.0%;"/>. For the second (*x* = 2) and the third (*x* = 3) dishes themselves will be optimal, because in that case <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/79add195d023131e992b60a354fec89501759e75.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
Let Leha asks Noora about the next couple of dishes:
- *x* = 1, *y* = 2, then he'll recieve «NIE» answer, because |1 - 2| > |2 - 2| - *x* = 2, *y* = 1, then he'll recieve «TAK» answer, because |2 - 2| ≤ |1 - 2| - *x* = 1, *y* = 3, then he'll recieve «NIE» answer, because |1 - 2| > |3 - 3| - *x* = 3, *y* = 1, then he'll recieve «TAK» answer, because |3 - 3| ≤ |1 - 2| - *x* = 2, *y* = 3, then he'll recieve «TAK» answer, because |2 - 2| ≤ |3 - 3| - *x* = 3, *y* = 2, then he'll recieve «TAK» answer, because |3 - 3| ≤ |2 - 2|
According to the available information, it is possible to say that Nura ordered dishes with numbers 2 and 3. | 0 | [] | 1,495,309,130 | 5,630 | Python 3 | RUNTIME_ERROR | PRETESTS | 0 | 46 | 0 | # your code goes here
# your code goes here
for i in range(10):
print(TAK)
'''
def liczby_pierwsze(n):
for i in length(n):
check = 0
for j in n(i):
if n(i)%i==0:
check +=1
if check==2:
print(TAK)
else:
print(NIE)
''' | Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
This is an interactive problem. In the output section below you will see the information about flushing the output.
On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot near the restaurant and hurried inside the building.
In the restaurant a polite waiter immediately brought the menu to Leha and Noora, consisting of *n* dishes. It is interesting that all dishes in the menu are numbered with integers from 1 to *n*. After a little thought, the girl ordered exactly *k* different dishes from available in the menu. To pass the waiting time while the chefs prepare ordered dishes, the girl invited the hacker to play a game that will help them get to know each other better.
The game itself is very simple: Noora wants Leha to guess any two dishes among all ordered. At the same time, she is ready to answer only one type of questions. Leha can say two numbers *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*). After that Noora chooses some dish *a* for the number *x* such that, at first, *a* is among the dishes Noora ordered (*x* can be equal to *a*), and, secondly, the value is the minimum possible. By the same rules the girl chooses dish *b* for *y*. After that Noora says «TAK» to Leha, if , and «NIE» otherwise. However, the restaurant is preparing quickly, so Leha has enough time to ask no more than 60 questions. After that he should name numbers of any two dishes Noora ordered.
Help Leha to solve this problem!
Input Specification:
There are two numbers *n* and *k* (2<=≤<=*k*<=≤<=*n*<=≤<=105) in the single line of input denoting the number of dishes in the menu and the number of dishes Noora ordered.
Output Specification:
If you want to provide an answer, output a string of the form 2 *x* *y* (1<=≤<=*x*,<=*y*<=≤<=*n*,<=*x*<=≠<=*y*), if you think the dishes *x* and *y* was among dishes ordered by Noora. After that, flush the output and terminate your program.
Demo Input:
['3 2\nNIE\nTAK\nNIE\nTAK\nTAK\nTAK\n']
Demo Output:
['1 1 2\n1 2 1\n1 1 3\n1 3 1\n1 2 3\n1 3 2\n2 2 3\n']
Note:
There are three dishes in sample. Noora ordered dished numberes 2 and 3, which Leha should guess. If Noora receive requests for the first dish (*x* = 1), then she'll choose the second dish (*a* = 2) as the dish with the minimum value <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e5a4a1705bc256e413564795cc8b70857f0ae44c.png" style="max-width: 100.0%;max-height: 100.0%;"/>. For the second (*x* = 2) and the third (*x* = 3) dishes themselves will be optimal, because in that case <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/79add195d023131e992b60a354fec89501759e75.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
Let Leha asks Noora about the next couple of dishes:
- *x* = 1, *y* = 2, then he'll recieve «NIE» answer, because |1 - 2| > |2 - 2| - *x* = 2, *y* = 1, then he'll recieve «TAK» answer, because |2 - 2| ≤ |1 - 2| - *x* = 1, *y* = 3, then he'll recieve «NIE» answer, because |1 - 2| > |3 - 3| - *x* = 3, *y* = 1, then he'll recieve «TAK» answer, because |3 - 3| ≤ |1 - 2| - *x* = 2, *y* = 3, then he'll recieve «TAK» answer, because |2 - 2| ≤ |3 - 3| - *x* = 3, *y* = 2, then he'll recieve «TAK» answer, because |3 - 3| ≤ |2 - 2|
According to the available information, it is possible to say that Nura ordered dishes with numbers 2 and 3. | ```python
# your code goes here
# your code goes here
for i in range(10):
print(TAK)
'''
def liczby_pierwsze(n):
for i in length(n):
check = 0
for j in n(i):
if n(i)%i==0:
check +=1
if check==2:
print(TAK)
else:
print(NIE)
'''
``` | -1 | |
868 | B | Race Against Time | PROGRAMMING | 1,400 | [
"implementation"
] | null | null | Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other.
The entire universe turned into an enormous clock face with three hands — hour, minute, and second. Time froze, and clocks now show the time *h* hours, *m* minutes, *s* seconds.
Last time Misha talked with the coordinator at *t*1 o'clock, so now he stands on the number *t*1 on the clock face. The contest should be ready by *t*2 o'clock. In the terms of paradox it means that Misha has to go to number *t*2 somehow. Note that he doesn't have to move forward only: in these circumstances time has no direction.
Clock hands are very long, and Misha cannot get round them. He also cannot step over as it leads to the collapse of space-time. That is, if hour clock points 12 and Misha stands at 11 then he cannot move to 1 along the top arc. He has to follow all the way round the clock center (of course, if there are no other hands on his way).
Given the hands' positions, *t*1, and *t*2, find if Misha can prepare the contest on time (or should we say on space?). That is, find if he can move from *t*1 to *t*2 by the clock face. | Five integers *h*, *m*, *s*, *t*1, *t*2 (1<=≤<=*h*<=≤<=12, 0<=≤<=*m*,<=*s*<=≤<=59, 1<=≤<=*t*1,<=*t*2<=≤<=12, *t*1<=≠<=*t*2).
Misha's position and the target time do not coincide with the position of any hand. | Print "YES" (quotes for clarity), if Misha can prepare the contest on time, and "NO" otherwise.
You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES"). | [
"12 30 45 3 11\n",
"12 0 1 12 1\n",
"3 47 0 4 9\n"
] | [
"NO\n",
"YES\n",
"YES\n"
] | The three examples are shown on the pictures below from left to right. The starting position of Misha is shown with green, the ending position is shown with pink. Note that the positions of the hands on the pictures are not exact, but are close to the exact and the answer is the same. | 500 | [
{
"input": "12 30 45 3 11",
"output": "NO"
},
{
"input": "12 0 1 12 1",
"output": "YES"
},
{
"input": "3 47 0 4 9",
"output": "YES"
},
{
"input": "10 22 59 6 10",
"output": "YES"
},
{
"input": "3 1 13 12 3",
"output": "NO"
},
{
"input": "11 19 28 9 10"... | 1,507,189,267 | 2,167 | Python 3 | COMPILATION_ERROR | PRETESTS | 0 | 0 | 0 | # -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
"""
created by shhuan at 2017/10/3 12:35
C. Ordering Pizza
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.
It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?
Input
The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow.
The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.
Output
Print the maximum total happiness that can be achieved.
Examples
input
3 12
3 5 7
4 6 7
5 9 5
output
84
input
6 10
7 4 7
5 8 8
12 5 8
6 11 6
3 3 7
5 9 6
output
314
Note
In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74.
先计算出需要买的披萨个数,等于所有人要吃的片数之和除以每个披萨的片数。
如果某个人吃第一种披萨幸福值更高,就尽量让他吃第一种,否则吃第二种。
如果第一种披萨不能满足所有更喜欢吃第一种披萨的人,那么优先满足吃第一种比吃第二种差值更大的人,所有先对差值排序。
"""
N, S = map(int, input().split())
M = []
for i in range(N):
M.append([int(x) for x in input().split()])
#
# N, S = 100000, 100000
# M = [[random.randint(10000, 100000), random.randint(1, 100), random.randint(1, 100)] for _ in range(N)]
# t0 = time.time()
s = [M[i][0] for i in range(N)]
a = [M[i][1] for i in range(N)]
b = [M[i][2] for i in range(N)]
total = sum(s)
numpizza = int(math.ceil(total/S))
numslice = numpizza * S
sab = sorted([(a[i]-b[i], i) for i in range(N)], reverse=True)
pa = 0
pb = 0
pab = 0
maxHappiness = 0
for i in range(N):
if a[i] > b[i]:
pa += s[i]
elif a[i] < b[i]:
pb += s[i]
else:
pab += s[i]
sa = int(math.ceil(pa/S)) * S
sb = int(math.ceil(pb/S)) * S
pab -= sa+sb-pa-pb
pab = max(pab, 0)
if sa//S + sb//S + int(math.ceil(pab/S)) == numpizza:
print(sum([s[i]*(a[i] if a[i] > b[i] else b[i]) for i in range(N)]))
exit(0)
if pa == 0 and pb == 0:
print(sum([s[i]*a[i] for i in range(N)] or [0]))
exit(0)
if pa == 0:
print(sum([s[i]*b[i] for i in range(N)] or [0]))
exit(0)
if pb == 0:
print(sum([s[i]*a[i] for i in range(N)] or [0]))
exit(0)
# print(time.time()-t0)
sbak = s
for pza in range(pa//S, (pa+pab)//S+2):
pzb = numpizza - pza
aslice = pza*S
bslice = pzb*S
h = 0
s = [x for x in sbak]
for j in range(N):
d, i = sab[j]
if d > 0:
if aslice >= s[i]:
h += s[i]*a[i]
aslice -= s[i]
s[i] = 0
elif aslice > 0:
h += a[i]*aslice
s[i] -= aslice
aslice = 0
else:
break
for j in range(N-1, -1, -1):
d, i = sab[j]
if d < 0:
if bslice >= s[i]:
h += s[i]*b[i]
bslice -= s[i]
s[i] = 0
elif bslice > 0:
h += bslice * b[i]
s[i] -= bslice
bslice = 0
else:
break
if aslice == 0:
for i in range(N):
if s[i] != 0:
h += s[i]*b[i]
bslice -= s[i]
elif bslice == 0:
for i in range(N):
if s[i] != 0:
h += s[i]*a[i]
aslice -= s[i]
else:
remain = [(s[i], a[i], b[i]) for i in range(N) if s[i] > 0 and a[i] != b[i]]
for u,v,w in remain:
if v > w:
if aslice > 0:
if aslice > u:
h += u * v
aslice -= u
else:
h += aslice * v
h += (u-aslice) * w
bslice -= u-aslice
aslice = 0
else:
h += u*w
bslice -= u
else:
if bslice > 0:
if bslice > u:
h += u * w
bslice -= u
else:
h += bslice * w
h += (u - bslice) * v
aslice -= u - bslice
bslice = 0
else:
h += u*v
aslice -= u
h += sum([s[i]*a[i] for i in range(N) if a[i] == b[i]] or [0])
maxHappiness = max(maxHappiness, h)
print(maxHappiness)
# print(time.time() - t0 ) | Title: Race Against Time
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other.
The entire universe turned into an enormous clock face with three hands — hour, minute, and second. Time froze, and clocks now show the time *h* hours, *m* minutes, *s* seconds.
Last time Misha talked with the coordinator at *t*1 o'clock, so now he stands on the number *t*1 on the clock face. The contest should be ready by *t*2 o'clock. In the terms of paradox it means that Misha has to go to number *t*2 somehow. Note that he doesn't have to move forward only: in these circumstances time has no direction.
Clock hands are very long, and Misha cannot get round them. He also cannot step over as it leads to the collapse of space-time. That is, if hour clock points 12 and Misha stands at 11 then he cannot move to 1 along the top arc. He has to follow all the way round the clock center (of course, if there are no other hands on his way).
Given the hands' positions, *t*1, and *t*2, find if Misha can prepare the contest on time (or should we say on space?). That is, find if he can move from *t*1 to *t*2 by the clock face.
Input Specification:
Five integers *h*, *m*, *s*, *t*1, *t*2 (1<=≤<=*h*<=≤<=12, 0<=≤<=*m*,<=*s*<=≤<=59, 1<=≤<=*t*1,<=*t*2<=≤<=12, *t*1<=≠<=*t*2).
Misha's position and the target time do not coincide with the position of any hand.
Output Specification:
Print "YES" (quotes for clarity), if Misha can prepare the contest on time, and "NO" otherwise.
You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").
Demo Input:
['12 30 45 3 11\n', '12 0 1 12 1\n', '3 47 0 4 9\n']
Demo Output:
['NO\n', 'YES\n', 'YES\n']
Note:
The three examples are shown on the pictures below from left to right. The starting position of Misha is shown with green, the ending position is shown with pink. Note that the positions of the hands on the pictures are not exact, but are close to the exact and the answer is the same. | ```python
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
"""
created by shhuan at 2017/10/3 12:35
C. Ordering Pizza
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.
It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?
Input
The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow.
The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.
Output
Print the maximum total happiness that can be achieved.
Examples
input
3 12
3 5 7
4 6 7
5 9 5
output
84
input
6 10
7 4 7
5 8 8
12 5 8
6 11 6
3 3 7
5 9 6
output
314
Note
In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74.
先计算出需要买的披萨个数,等于所有人要吃的片数之和除以每个披萨的片数。
如果某个人吃第一种披萨幸福值更高,就尽量让他吃第一种,否则吃第二种。
如果第一种披萨不能满足所有更喜欢吃第一种披萨的人,那么优先满足吃第一种比吃第二种差值更大的人,所有先对差值排序。
"""
N, S = map(int, input().split())
M = []
for i in range(N):
M.append([int(x) for x in input().split()])
#
# N, S = 100000, 100000
# M = [[random.randint(10000, 100000), random.randint(1, 100), random.randint(1, 100)] for _ in range(N)]
# t0 = time.time()
s = [M[i][0] for i in range(N)]
a = [M[i][1] for i in range(N)]
b = [M[i][2] for i in range(N)]
total = sum(s)
numpizza = int(math.ceil(total/S))
numslice = numpizza * S
sab = sorted([(a[i]-b[i], i) for i in range(N)], reverse=True)
pa = 0
pb = 0
pab = 0
maxHappiness = 0
for i in range(N):
if a[i] > b[i]:
pa += s[i]
elif a[i] < b[i]:
pb += s[i]
else:
pab += s[i]
sa = int(math.ceil(pa/S)) * S
sb = int(math.ceil(pb/S)) * S
pab -= sa+sb-pa-pb
pab = max(pab, 0)
if sa//S + sb//S + int(math.ceil(pab/S)) == numpizza:
print(sum([s[i]*(a[i] if a[i] > b[i] else b[i]) for i in range(N)]))
exit(0)
if pa == 0 and pb == 0:
print(sum([s[i]*a[i] for i in range(N)] or [0]))
exit(0)
if pa == 0:
print(sum([s[i]*b[i] for i in range(N)] or [0]))
exit(0)
if pb == 0:
print(sum([s[i]*a[i] for i in range(N)] or [0]))
exit(0)
# print(time.time()-t0)
sbak = s
for pza in range(pa//S, (pa+pab)//S+2):
pzb = numpizza - pza
aslice = pza*S
bslice = pzb*S
h = 0
s = [x for x in sbak]
for j in range(N):
d, i = sab[j]
if d > 0:
if aslice >= s[i]:
h += s[i]*a[i]
aslice -= s[i]
s[i] = 0
elif aslice > 0:
h += a[i]*aslice
s[i] -= aslice
aslice = 0
else:
break
for j in range(N-1, -1, -1):
d, i = sab[j]
if d < 0:
if bslice >= s[i]:
h += s[i]*b[i]
bslice -= s[i]
s[i] = 0
elif bslice > 0:
h += bslice * b[i]
s[i] -= bslice
bslice = 0
else:
break
if aslice == 0:
for i in range(N):
if s[i] != 0:
h += s[i]*b[i]
bslice -= s[i]
elif bslice == 0:
for i in range(N):
if s[i] != 0:
h += s[i]*a[i]
aslice -= s[i]
else:
remain = [(s[i], a[i], b[i]) for i in range(N) if s[i] > 0 and a[i] != b[i]]
for u,v,w in remain:
if v > w:
if aslice > 0:
if aslice > u:
h += u * v
aslice -= u
else:
h += aslice * v
h += (u-aslice) * w
bslice -= u-aslice
aslice = 0
else:
h += u*w
bslice -= u
else:
if bslice > 0:
if bslice > u:
h += u * w
bslice -= u
else:
h += bslice * w
h += (u - bslice) * v
aslice -= u - bslice
bslice = 0
else:
h += u*v
aslice -= u
h += sum([s[i]*a[i] for i in range(N) if a[i] == b[i]] or [0])
maxHappiness = max(maxHappiness, h)
print(maxHappiness)
# print(time.time() - t0 )
``` | -1 | |
275 | A | Lights Out | PROGRAMMING | 900 | [
"implementation"
] | null | null | Lenny is playing a game on a 3<=×<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light. | The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The *j*-th number in the *i*-th row is the number of times the *j*-th light of the *i*-th row of the grid is pressed. | Print three lines, each containing three characters. The *j*-th character of the *i*-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0". | [
"1 0 0\n0 0 0\n0 0 1\n",
"1 0 1\n8 8 8\n2 0 3\n"
] | [
"001\n010\n100\n",
"010\n011\n100\n"
] | none | 500 | [
{
"input": "1 0 0\n0 0 0\n0 0 1",
"output": "001\n010\n100"
},
{
"input": "1 0 1\n8 8 8\n2 0 3",
"output": "010\n011\n100"
},
{
"input": "13 85 77\n25 50 45\n65 79 9",
"output": "000\n010\n000"
},
{
"input": "96 95 5\n8 84 74\n67 31 61",
"output": "011\n011\n101"
},
{... | 1,679,590,620 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 30 | 0 | x=[]
for u in range(3):
a=[]
for j in range(3):
a.append(0)
x.append(a)
for s in range(3):
b=list(map(int,input().split()))
for i in range(3):
x[s][i]+=b[i]
if s-1>=0:
x[s-1][i]+=b[i]
if s+1<3:
x[s+1][i]+=b[i]
if i-1>=0:
x[s][i-1]+=b[i]
if i+1<3:
x[s][i-1]+=b[i]
for y in range(3):
for a in range(3):
if x[y][a]%2==0:
print('1',end="")
else:
print("0",end="")
print("")
| Title: Lights Out
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Lenny is playing a game on a 3<=×<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input Specification:
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The *j*-th number in the *i*-th row is the number of times the *j*-th light of the *i*-th row of the grid is pressed.
Output Specification:
Print three lines, each containing three characters. The *j*-th character of the *i*-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Demo Input:
['1 0 0\n0 0 0\n0 0 1\n', '1 0 1\n8 8 8\n2 0 3\n']
Demo Output:
['001\n010\n100\n', '010\n011\n100\n']
Note:
none | ```python
x=[]
for u in range(3):
a=[]
for j in range(3):
a.append(0)
x.append(a)
for s in range(3):
b=list(map(int,input().split()))
for i in range(3):
x[s][i]+=b[i]
if s-1>=0:
x[s-1][i]+=b[i]
if s+1<3:
x[s+1][i]+=b[i]
if i-1>=0:
x[s][i-1]+=b[i]
if i+1<3:
x[s][i-1]+=b[i]
for y in range(3):
for a in range(3):
if x[y][a]%2==0:
print('1',end="")
else:
print("0",end="")
print("")
``` | 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,684,335,530 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 46 | 0 | n, m, a = map(int, input().split())
num_plates = -n // -a * (-m // -a)
print(num_plates)
| 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())
num_plates = -n // -a * (-m // -a)
print(num_plates)
``` | 0 |
534 | A | Exam | PROGRAMMING | 1,100 | [
"constructive algorithms",
"implementation",
"math"
] | null | null | An exam for *n* students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (*i* and *i*<=+<=1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.
Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side. | A single line contains integer *n* (1<=≤<=*n*<=≤<=5000) — the number of students at an exam. | In the first line print integer *k* — the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other.
In the second line print *k* distinct integers *a*1,<=*a*2,<=...,<=*a**k* (1<=≤<=*a**i*<=≤<=*n*), where *a**i* is the number of the student on the *i*-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |*a**i*<=-<=*a**i*<=+<=1|<=≠<=1 for all *i* from 1 to *k*<=-<=1.
If there are several possible answers, output any of them. | [
"6",
"3\n"
] | [
"6\n1 5 3 6 2 4",
"2\n1 3"
] | none | 500 | [
{
"input": "6",
"output": "6\n5 3 1 6 4 2 "
},
{
"input": "3",
"output": "2\n1 3"
},
{
"input": "1",
"output": "1\n1 "
},
{
"input": "2",
"output": "1\n1"
},
{
"input": "4",
"output": "4\n3 1 4 2 "
},
{
"input": "5",
"output": "5\n5 3 1 4 2 "
},
... | 1,646,407,424 | 2,147,483,647 | Python 3 | OK | TESTS | 36 | 46 | 0 | n = int(input())
if(n==1 or n==2):
print("1\n1")
elif(n==3):
print("2\n1 3")
else:
A=[]
for i in range(2,n+1,2):
A.append(i)
for i in range(1,n+1,2):
A.append(i)
print(len(A))
for x in A:
print(x,end=" ") | Title: Exam
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
An exam for *n* students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (*i* and *i*<=+<=1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.
Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.
Input Specification:
A single line contains integer *n* (1<=≤<=*n*<=≤<=5000) — the number of students at an exam.
Output Specification:
In the first line print integer *k* — the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other.
In the second line print *k* distinct integers *a*1,<=*a*2,<=...,<=*a**k* (1<=≤<=*a**i*<=≤<=*n*), where *a**i* is the number of the student on the *i*-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |*a**i*<=-<=*a**i*<=+<=1|<=≠<=1 for all *i* from 1 to *k*<=-<=1.
If there are several possible answers, output any of them.
Demo Input:
['6', '3\n']
Demo Output:
['6\n1 5 3 6 2 4', '2\n1 3']
Note:
none | ```python
n = int(input())
if(n==1 or n==2):
print("1\n1")
elif(n==3):
print("2\n1 3")
else:
A=[]
for i in range(2,n+1,2):
A.append(i)
for i in range(1,n+1,2):
A.append(i)
print(len(A))
for x in A:
print(x,end=" ")
``` | 3 | |
535 | B | Tavas and SaDDas | PROGRAMMING | 1,100 | [
"bitmasks",
"brute force",
"combinatorics",
"implementation"
] | null | null | Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
The problem is:
You are given a lucky number *n*. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
If we sort all lucky numbers in increasing order, what's the 1-based index of *n*?
Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back. | The first and only line of input contains a lucky number *n* (1<=≤<=*n*<=≤<=109). | Print the index of *n* among all lucky numbers. | [
"4\n",
"7\n",
"77\n"
] | [
"1\n",
"2\n",
"6\n"
] | none | 1,000 | [
{
"input": "4",
"output": "1"
},
{
"input": "7",
"output": "2"
},
{
"input": "77",
"output": "6"
},
{
"input": "4",
"output": "1"
},
{
"input": "474744",
"output": "83"
},
{
"input": "777774",
"output": "125"
},
{
"input": "447",
"outpu... | 1,574,446,981 | 2,147,483,647 | Python 3 | OK | TESTS | 33 | 109 | 0 | myLucky = int(input())
aux = 1
position = 0
while(myLucky>0):
if(int(myLucky%10) == 4):
position += int(aux)
else:
position += int(2*aux)
myLucky = int(myLucky/10)
aux = int(aux*2)
print(position)
| Title: Tavas and SaDDas
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
The problem is:
You are given a lucky number *n*. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
If we sort all lucky numbers in increasing order, what's the 1-based index of *n*?
Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.
Input Specification:
The first and only line of input contains a lucky number *n* (1<=≤<=*n*<=≤<=109).
Output Specification:
Print the index of *n* among all lucky numbers.
Demo Input:
['4\n', '7\n', '77\n']
Demo Output:
['1\n', '2\n', '6\n']
Note:
none | ```python
myLucky = int(input())
aux = 1
position = 0
while(myLucky>0):
if(int(myLucky%10) == 4):
position += int(aux)
else:
position += int(2*aux)
myLucky = int(myLucky/10)
aux = int(aux*2)
print(position)
``` | 3 | |
65 | A | Harry Potter and Three Spells | PROGRAMMING | 1,800 | [
"implementation",
"math"
] | A. Harry Potter and Three Spells | 2 | 256 | A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert *a* grams of sand into *b* grams of lead, the second one allows you to convert *c* grams of lead into *d* grams of gold and third one allows you to convert *e* grams of gold into *f* grams of sand. When Harry told his friends about these spells, Ron Weasley was amazed. After all, if they succeed in turning sand into lead, lead into gold, and then turning part of the gold into sand again and so on, then it will be possible to start with a small amount of sand and get huge amounts of gold! Even an infinite amount of gold! Hermione Granger, by contrast, was skeptical about that idea. She argues that according to the law of conservation of matter getting an infinite amount of matter, even using magic, is impossible. On the contrary, the amount of matter may even decrease during transformation, being converted to magical energy. Though Hermione's theory seems convincing, Ron won't believe her. As far as Ron is concerned, Hermione made up her law of conservation of matter to stop Harry and Ron wasting their time with this nonsense, and to make them go and do homework instead. That's why Ron has already collected a certain amount of sand for the experiments. A quarrel between the friends seems unavoidable...
Help Harry to determine which one of his friends is right, and avoid the quarrel after all. To do this you have to figure out whether it is possible to get the amount of gold greater than any preassigned number from some finite amount of sand. | The first line contains 6 integers *a*, *b*, *c*, *d*, *e*, *f* (0<=≤<=*a*,<=*b*,<=*c*,<=*d*,<=*e*,<=*f*<=≤<=1000). | Print "Ron", if it is possible to get an infinitely large amount of gold having a certain finite amount of sand (and not having any gold and lead at all), i.e., Ron is right. Otherwise, print "Hermione". | [
"100 200 250 150 200 250\n",
"100 50 50 200 200 100\n",
"100 10 200 20 300 30\n",
"0 0 0 0 0 0\n",
"1 1 0 1 1 1\n",
"1 0 1 2 1 2\n",
"100 1 100 1 0 1\n"
] | [
"Ron\n",
"Hermione\n",
"Hermione\n",
"Hermione\n",
"Ron\n",
"Hermione\n",
"Ron\n"
] | Consider the first sample. Let's start with the 500 grams of sand. Apply the first spell 5 times and turn the sand into 1000 grams of lead. Then apply the second spell 4 times to get 600 grams of gold. Let’s take 400 grams from the resulting amount of gold turn them back into sand. We get 500 grams of sand and 200 grams of gold. If we apply the same operations to 500 grams of sand again, we can get extra 200 grams of gold every time. Thus, you can get 200, 400, 600 etc. grams of gold, i.e., starting with a finite amount of sand (500 grams), you can get the amount of gold which is greater than any preassigned number.
In the forth sample it is impossible to get sand, or lead, or gold, applying the spells.
In the fifth sample an infinitely large amount of gold can be obtained by using only the second spell, which allows you to receive 1 gram of gold out of nothing. Note that if such a second spell is available, then the first and the third one do not affect the answer at all.
The seventh sample is more interesting. We can also start with a zero amount of sand there. With the aid of the third spell you can get sand out of nothing. We get 10000 grams of sand in this manner. Let's get 100 grams of lead using the first spell 100 times. Then make 1 gram of gold from them. We managed to receive 1 gram of gold, starting with a zero amount of sand! Clearly, in this manner you can get an infinitely large amount of gold. | 500 | [
{
"input": "100 200 250 150 200 250",
"output": "Ron"
},
{
"input": "100 50 50 200 200 100",
"output": "Hermione"
},
{
"input": "100 10 200 20 300 30",
"output": "Hermione"
},
{
"input": "0 0 0 0 0 0",
"output": "Hermione"
},
{
"input": "1 1 0 1 1 1",
"output"... | 1,630,878,888 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 19 | 186 | 20,172,800 | a, b, c, d, e, f=[int(k) for k in input().split()]
if f!=0:
if e!=0:
if d!=0:
if c!=0:
if b!=0:
if a!=0:
if a*c*e<b*d*f:
print("Ron")
else:
print("Hermione")
else:
print("Ron")
else:
print("Hermione")
else:
print("Ron")
else:
print("Hermione")
else:
print("Ron")
else:
print("Hermione") | Title: Harry Potter and Three Spells
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert *a* grams of sand into *b* grams of lead, the second one allows you to convert *c* grams of lead into *d* grams of gold and third one allows you to convert *e* grams of gold into *f* grams of sand. When Harry told his friends about these spells, Ron Weasley was amazed. After all, if they succeed in turning sand into lead, lead into gold, and then turning part of the gold into sand again and so on, then it will be possible to start with a small amount of sand and get huge amounts of gold! Even an infinite amount of gold! Hermione Granger, by contrast, was skeptical about that idea. She argues that according to the law of conservation of matter getting an infinite amount of matter, even using magic, is impossible. On the contrary, the amount of matter may even decrease during transformation, being converted to magical energy. Though Hermione's theory seems convincing, Ron won't believe her. As far as Ron is concerned, Hermione made up her law of conservation of matter to stop Harry and Ron wasting their time with this nonsense, and to make them go and do homework instead. That's why Ron has already collected a certain amount of sand for the experiments. A quarrel between the friends seems unavoidable...
Help Harry to determine which one of his friends is right, and avoid the quarrel after all. To do this you have to figure out whether it is possible to get the amount of gold greater than any preassigned number from some finite amount of sand.
Input Specification:
The first line contains 6 integers *a*, *b*, *c*, *d*, *e*, *f* (0<=≤<=*a*,<=*b*,<=*c*,<=*d*,<=*e*,<=*f*<=≤<=1000).
Output Specification:
Print "Ron", if it is possible to get an infinitely large amount of gold having a certain finite amount of sand (and not having any gold and lead at all), i.e., Ron is right. Otherwise, print "Hermione".
Demo Input:
['100 200 250 150 200 250\n', '100 50 50 200 200 100\n', '100 10 200 20 300 30\n', '0 0 0 0 0 0\n', '1 1 0 1 1 1\n', '1 0 1 2 1 2\n', '100 1 100 1 0 1\n']
Demo Output:
['Ron\n', 'Hermione\n', 'Hermione\n', 'Hermione\n', 'Ron\n', 'Hermione\n', 'Ron\n']
Note:
Consider the first sample. Let's start with the 500 grams of sand. Apply the first spell 5 times and turn the sand into 1000 grams of lead. Then apply the second spell 4 times to get 600 grams of gold. Let’s take 400 grams from the resulting amount of gold turn them back into sand. We get 500 grams of sand and 200 grams of gold. If we apply the same operations to 500 grams of sand again, we can get extra 200 grams of gold every time. Thus, you can get 200, 400, 600 etc. grams of gold, i.e., starting with a finite amount of sand (500 grams), you can get the amount of gold which is greater than any preassigned number.
In the forth sample it is impossible to get sand, or lead, or gold, applying the spells.
In the fifth sample an infinitely large amount of gold can be obtained by using only the second spell, which allows you to receive 1 gram of gold out of nothing. Note that if such a second spell is available, then the first and the third one do not affect the answer at all.
The seventh sample is more interesting. We can also start with a zero amount of sand there. With the aid of the third spell you can get sand out of nothing. We get 10000 grams of sand in this manner. Let's get 100 grams of lead using the first spell 100 times. Then make 1 gram of gold from them. We managed to receive 1 gram of gold, starting with a zero amount of sand! Clearly, in this manner you can get an infinitely large amount of gold. | ```python
a, b, c, d, e, f=[int(k) for k in input().split()]
if f!=0:
if e!=0:
if d!=0:
if c!=0:
if b!=0:
if a!=0:
if a*c*e<b*d*f:
print("Ron")
else:
print("Hermione")
else:
print("Ron")
else:
print("Hermione")
else:
print("Ron")
else:
print("Hermione")
else:
print("Ron")
else:
print("Hermione")
``` | 0 |
353 | A | Domino | PROGRAMMING | 1,200 | [
"implementation",
"math"
] | null | null | Valera has got *n* domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true. | The first line contains integer *n* (1<=≤<=*n*<=≤<=100), denoting the number of dominoes Valera has. Next *n* lines contain two space-separated integers *x**i*,<=*y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=6). Number *x**i* is initially written on the upper half of the *i*-th domino, *y**i* is initially written on the lower half. | Print a single number — the minimum required number of seconds. If Valera can't do the task in any time, print <=-<=1. | [
"2\n4 2\n6 4\n",
"1\n2 3\n",
"3\n1 4\n2 3\n4 4\n"
] | [
"0\n",
"-1\n",
"1\n"
] | In the first test case the sum of the numbers on the upper halves equals 10 and the sum of the numbers on the lower halves equals 6. Both numbers are even, so Valera doesn't required to do anything.
In the second sample Valera has only one piece of domino. It is written 3 on the one of its halves, therefore one of the sums will always be odd.
In the third case Valera can rotate the first piece, and after that the sum on the upper halves will be equal to 10, and the sum on the lower halves will be equal to 8. | 500 | [
{
"input": "2\n4 2\n6 4",
"output": "0"
},
{
"input": "1\n2 3",
"output": "-1"
},
{
"input": "3\n1 4\n2 3\n4 4",
"output": "1"
},
{
"input": "5\n5 4\n5 4\n1 5\n5 5\n3 3",
"output": "1"
},
{
"input": "20\n1 3\n5 2\n5 2\n2 6\n2 4\n1 1\n1 3\n1 4\n2 6\n4 2\n5 6\n2 2\n... | 1,627,302,964 | 2,147,483,647 | Python 3 | OK | TESTS | 59 | 154 | 6,963,200 | def main():
n = int(input())
upper = []
lower = []
for i in range(n):
x, y = [int(x) for x in input().split()]
upper.append(x)
lower.append(y)
if sum(upper) % 2 == 0 and sum(lower) % 2 == 0:
print(0)
return 0
elif sum(upper) % 2 != 0 and sum(lower) % 2 != 0:
for i in range(n):
if (upper[i] % 2 == 0 and lower[i] % 2 != 0) or (upper[i] % 2 != 0 and lower[i] % 2 == 0):
print(1)
return 0
print(-1)
else:
print(-1)
if __name__ == "__main__":
main()
| Title: Domino
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Valera has got *n* domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=100), denoting the number of dominoes Valera has. Next *n* lines contain two space-separated integers *x**i*,<=*y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=6). Number *x**i* is initially written on the upper half of the *i*-th domino, *y**i* is initially written on the lower half.
Output Specification:
Print a single number — the minimum required number of seconds. If Valera can't do the task in any time, print <=-<=1.
Demo Input:
['2\n4 2\n6 4\n', '1\n2 3\n', '3\n1 4\n2 3\n4 4\n']
Demo Output:
['0\n', '-1\n', '1\n']
Note:
In the first test case the sum of the numbers on the upper halves equals 10 and the sum of the numbers on the lower halves equals 6. Both numbers are even, so Valera doesn't required to do anything.
In the second sample Valera has only one piece of domino. It is written 3 on the one of its halves, therefore one of the sums will always be odd.
In the third case Valera can rotate the first piece, and after that the sum on the upper halves will be equal to 10, and the sum on the lower halves will be equal to 8. | ```python
def main():
n = int(input())
upper = []
lower = []
for i in range(n):
x, y = [int(x) for x in input().split()]
upper.append(x)
lower.append(y)
if sum(upper) % 2 == 0 and sum(lower) % 2 == 0:
print(0)
return 0
elif sum(upper) % 2 != 0 and sum(lower) % 2 != 0:
for i in range(n):
if (upper[i] % 2 == 0 and lower[i] % 2 != 0) or (upper[i] % 2 != 0 and lower[i] % 2 == 0):
print(1)
return 0
print(-1)
else:
print(-1)
if __name__ == "__main__":
main()
``` | 3 | |
758 | A | Holiday Of Equality | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are *n* citizens, the welfare of each of them is estimated as the integer in *a**i* burles (burle is the currency in Berland).
You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them. | The first line contains the integer *n* (1<=≤<=*n*<=≤<=100) — the number of citizens in the kingdom.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* (0<=≤<=*a**i*<=≤<=106) — the welfare of the *i*-th citizen. | In the only line print the integer *S* — the minimum number of burles which are had to spend. | [
"5\n0 1 2 3 4\n",
"5\n1 1 0 1 1\n",
"3\n1 3 1\n",
"1\n12\n"
] | [
"10",
"1",
"4",
"0"
] | In the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.
In the second example it is enough to give one burle to the third citizen.
In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.
In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles. | 500 | [
{
"input": "5\n0 1 2 3 4",
"output": "10"
},
{
"input": "5\n1 1 0 1 1",
"output": "1"
},
{
"input": "3\n1 3 1",
"output": "4"
},
{
"input": "1\n12",
"output": "0"
},
{
"input": "3\n1 2 3",
"output": "3"
},
{
"input": "14\n52518 718438 358883 462189 853... | 1,674,121,544 | 2,147,483,647 | Python 3 | OK | TESTS | 41 | 46 | 0 | n=int(input())
s=list(map(int,input().split()))
m=max(s)
su=0
for i in range (0,len(s)):
su=su+m-s[i]
print(su) | Title: Holiday Of Equality
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are *n* citizens, the welfare of each of them is estimated as the integer in *a**i* burles (burle is the currency in Berland).
You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.
Input Specification:
The first line contains the integer *n* (1<=≤<=*n*<=≤<=100) — the number of citizens in the kingdom.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* (0<=≤<=*a**i*<=≤<=106) — the welfare of the *i*-th citizen.
Output Specification:
In the only line print the integer *S* — the minimum number of burles which are had to spend.
Demo Input:
['5\n0 1 2 3 4\n', '5\n1 1 0 1 1\n', '3\n1 3 1\n', '1\n12\n']
Demo Output:
['10', '1', '4', '0']
Note:
In the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.
In the second example it is enough to give one burle to the third citizen.
In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.
In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles. | ```python
n=int(input())
s=list(map(int,input().split()))
m=max(s)
su=0
for i in range (0,len(s)):
su=su+m-s[i]
print(su)
``` | 3 | |
877 | A | Alex and broken contest | PROGRAMMING | 1,100 | [
"implementation",
"strings"
] | null | null | One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems.
But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest by its name.
It is known, that problem is from this contest if and only if its name contains one of Alex's friends' name exactly once. His friends' names are "Danil", "Olya", "Slava", "Ann" and "Nikita".
Names are case sensitive. | The only line contains string from lowercase and uppercase letters and "_" symbols of length, not more than 100 — the name of the problem. | Print "YES", if problem is from this contest, and "NO" otherwise. | [
"Alex_and_broken_contest\n",
"NikitaAndString\n",
"Danil_and_Olya\n"
] | [
"NO",
"YES",
"NO"
] | none | 500 | [
{
"input": "Alex_and_broken_contest",
"output": "NO"
},
{
"input": "NikitaAndString",
"output": "YES"
},
{
"input": "Danil_and_Olya",
"output": "NO"
},
{
"input": "Slava____and_the_game",
"output": "YES"
},
{
"input": "Olya_and_energy_drinks",
"output": "YES"
... | 1,527,015,668 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 20 | 93 | 0 | line = input()
names_count = {"Danil": 0, "Olya": 0, "Slava": 0, "Ann": 0, "Nikita": 0}
for name in names_count.keys():
while name in line:
names_count[name] += 1
line = line.replace(name, "#")
count = 0
for name in names_count.keys():
count += names_count[name]
if count == 1:
print("YES")
else:
print("NO") | Title: Alex and broken contest
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems.
But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest by its name.
It is known, that problem is from this contest if and only if its name contains one of Alex's friends' name exactly once. His friends' names are "Danil", "Olya", "Slava", "Ann" and "Nikita".
Names are case sensitive.
Input Specification:
The only line contains string from lowercase and uppercase letters and "_" symbols of length, not more than 100 — the name of the problem.
Output Specification:
Print "YES", if problem is from this contest, and "NO" otherwise.
Demo Input:
['Alex_and_broken_contest\n', 'NikitaAndString\n', 'Danil_and_Olya\n']
Demo Output:
['NO', 'YES', 'NO']
Note:
none | ```python
line = input()
names_count = {"Danil": 0, "Olya": 0, "Slava": 0, "Ann": 0, "Nikita": 0}
for name in names_count.keys():
while name in line:
names_count[name] += 1
line = line.replace(name, "#")
count = 0
for name in names_count.keys():
count += names_count[name]
if count == 1:
print("YES")
else:
print("NO")
``` | 0 | |
749 | A | Bachgold Problem | PROGRAMMING | 800 | [
"greedy",
"implementation",
"math",
"number theory"
] | null | null | Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and *k*. | The only line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=100<=000). | The first line of the output contains a single integer *k* — maximum possible number of primes in representation.
The second line should contain *k* primes with their sum equal to *n*. You can print them in any order. If there are several optimal solution, print any of them. | [
"5\n",
"6\n"
] | [
"2\n2 3\n",
"3\n2 2 2\n"
] | none | 500 | [
{
"input": "5",
"output": "2\n2 3"
},
{
"input": "6",
"output": "3\n2 2 2"
},
{
"input": "2",
"output": "1\n2"
},
{
"input": "3",
"output": "1\n3"
},
{
"input": "99999",
"output": "49999\n2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ... | 1,682,673,198 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 30 | 0 | n=int(input())
print((n)//2)
l=[2]*n
if n%2==1:
l[-1]+=1
print(*l) | Title: Bachgold Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and *k*.
Input Specification:
The only line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=100<=000).
Output Specification:
The first line of the output contains a single integer *k* — maximum possible number of primes in representation.
The second line should contain *k* primes with their sum equal to *n*. You can print them in any order. If there are several optimal solution, print any of them.
Demo Input:
['5\n', '6\n']
Demo Output:
['2\n2 3\n', '3\n2 2 2\n']
Note:
none | ```python
n=int(input())
print((n)//2)
l=[2]*n
if n%2==1:
l[-1]+=1
print(*l)
``` | 0 | |
334 | B | Eight Point Sets | PROGRAMMING | 1,400 | [
"sortings"
] | null | null | Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three integers *x*1,<=*x*2,<=*x*3 and three more integers *y*1,<=*y*2,<=*y*3, such that *x*1<=<<=*x*2<=<<=*x*3, *y*1<=<<=*y*2<=<<=*y*3 and the eight point set consists of all points (*x**i*,<=*y**j*) (1<=≤<=*i*,<=*j*<=≤<=3), except for point (*x*2,<=*y*2).
You have a set of eight points. Find out if Gerald can use this set? | The input consists of eight lines, the *i*-th line contains two space-separated integers *x**i* and *y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=106). You do not have any other conditions for these points. | In a single line print word "respectable", if the given set of points corresponds to Gerald's decency rules, and "ugly" otherwise. | [
"0 0\n0 1\n0 2\n1 0\n1 2\n2 0\n2 1\n2 2\n",
"0 0\n1 0\n2 0\n3 0\n4 0\n5 0\n6 0\n7 0\n",
"1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n"
] | [
"respectable\n",
"ugly\n",
"ugly\n"
] | none | 1,000 | [
{
"input": "0 0\n0 1\n0 2\n1 0\n1 2\n2 0\n2 1\n2 2",
"output": "respectable"
},
{
"input": "0 0\n1 0\n2 0\n3 0\n4 0\n5 0\n6 0\n7 0",
"output": "ugly"
},
{
"input": "1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2",
"output": "ugly"
},
{
"input": "0 0\n0 0\n0 0\n0 0\n0 0\n0 0\n0 0\n0 0... | 1,550,541,396 | 2,147,483,647 | Python 3 | OK | TESTS | 45 | 218 | 0 | lines = []
for i in range(0, 8):
lines.append(list(map(int, input().split())))
lines = sorted(lines)
countA = [lines[0][0]]
countB = [lines[0][1]]
for i in range(1, len(lines)):
if lines[i][0] != lines[i-1][0]:
countA.append(lines[i][0])
if lines[i][1] not in countB:
countB.append(lines[i][1])
if len(countA) != 3 or len(countB) != 3:
print("ugly")
else:
index = 0
check = True
for i in countA:
for j in countB:
if i == countA[1] and j == countB[1]:
continue
if i != lines[index][0] or j != lines[index][1]:
check = False
break
index+=1
if check:
print("respectable")
else:
print("ugly")
| Title: Eight Point Sets
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three integers *x*1,<=*x*2,<=*x*3 and three more integers *y*1,<=*y*2,<=*y*3, such that *x*1<=<<=*x*2<=<<=*x*3, *y*1<=<<=*y*2<=<<=*y*3 and the eight point set consists of all points (*x**i*,<=*y**j*) (1<=≤<=*i*,<=*j*<=≤<=3), except for point (*x*2,<=*y*2).
You have a set of eight points. Find out if Gerald can use this set?
Input Specification:
The input consists of eight lines, the *i*-th line contains two space-separated integers *x**i* and *y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=106). You do not have any other conditions for these points.
Output Specification:
In a single line print word "respectable", if the given set of points corresponds to Gerald's decency rules, and "ugly" otherwise.
Demo Input:
['0 0\n0 1\n0 2\n1 0\n1 2\n2 0\n2 1\n2 2\n', '0 0\n1 0\n2 0\n3 0\n4 0\n5 0\n6 0\n7 0\n', '1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n']
Demo Output:
['respectable\n', 'ugly\n', 'ugly\n']
Note:
none | ```python
lines = []
for i in range(0, 8):
lines.append(list(map(int, input().split())))
lines = sorted(lines)
countA = [lines[0][0]]
countB = [lines[0][1]]
for i in range(1, len(lines)):
if lines[i][0] != lines[i-1][0]:
countA.append(lines[i][0])
if lines[i][1] not in countB:
countB.append(lines[i][1])
if len(countA) != 3 or len(countB) != 3:
print("ugly")
else:
index = 0
check = True
for i in countA:
for j in countB:
if i == countA[1] and j == countB[1]:
continue
if i != lines[index][0] or j != lines[index][1]:
check = False
break
index+=1
if check:
print("respectable")
else:
print("ugly")
``` | 3 | |
747 | A | Display Size | PROGRAMMING | 800 | [
"brute force",
"math"
] | null | null | A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly *n* pixels.
Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels *a* and the number of columns of pixels *b*, so that:
- there are exactly *n* pixels on the display; - the number of rows does not exceed the number of columns, it means *a*<=≤<=*b*; - the difference *b*<=-<=*a* is as small as possible. | The first line contains the positive integer *n* (1<=≤<=*n*<=≤<=106) — the number of pixels display should have. | Print two integers — the number of rows and columns on the display. | [
"8\n",
"64\n",
"5\n",
"999999\n"
] | [
"2 4\n",
"8 8\n",
"1 5\n",
"999 1001\n"
] | In the first example the minimum possible difference equals 2, so on the display should be 2 rows of 4 pixels.
In the second example the minimum possible difference equals 0, so on the display should be 8 rows of 8 pixels.
In the third example the minimum possible difference equals 4, so on the display should be 1 row of 5 pixels. | 500 | [
{
"input": "8",
"output": "2 4"
},
{
"input": "64",
"output": "8 8"
},
{
"input": "5",
"output": "1 5"
},
{
"input": "999999",
"output": "999 1001"
},
{
"input": "716539",
"output": "97 7387"
},
{
"input": "1",
"output": "1 1"
},
{
"input":... | 1,534,753,162 | 2,147,483,647 | Python 3 | OK | TESTS | 43 | 342 | 0 | import math
n=int(input())
x=str(math.sqrt(n))
if x.endswith('.0'):
print(x[:len(x)-2],x[:len(x)-2])
exit(0)
l=[]
for i in range(1,n+1):
if n%i==0:
l.append(i)
m,temp=[],[]
for i in range(len(l)):
for j in range(i+1,len(l)):
if l[i]*l[j]==n and l[i]<=l[j]:
m.append(l[j]-l[i])
temp.append([l[i],l[j]])
minimum,x,y=m[0],temp[0][0],temp[0][1]
for i in range(1,len(m)):
if minimum>m[i]:
minimum,x,y=m[i],temp[i][0],temp[i][1]
print(x,y) | Title: Display Size
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly *n* pixels.
Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels *a* and the number of columns of pixels *b*, so that:
- there are exactly *n* pixels on the display; - the number of rows does not exceed the number of columns, it means *a*<=≤<=*b*; - the difference *b*<=-<=*a* is as small as possible.
Input Specification:
The first line contains the positive integer *n* (1<=≤<=*n*<=≤<=106) — the number of pixels display should have.
Output Specification:
Print two integers — the number of rows and columns on the display.
Demo Input:
['8\n', '64\n', '5\n', '999999\n']
Demo Output:
['2 4\n', '8 8\n', '1 5\n', '999 1001\n']
Note:
In the first example the minimum possible difference equals 2, so on the display should be 2 rows of 4 pixels.
In the second example the minimum possible difference equals 0, so on the display should be 8 rows of 8 pixels.
In the third example the minimum possible difference equals 4, so on the display should be 1 row of 5 pixels. | ```python
import math
n=int(input())
x=str(math.sqrt(n))
if x.endswith('.0'):
print(x[:len(x)-2],x[:len(x)-2])
exit(0)
l=[]
for i in range(1,n+1):
if n%i==0:
l.append(i)
m,temp=[],[]
for i in range(len(l)):
for j in range(i+1,len(l)):
if l[i]*l[j]==n and l[i]<=l[j]:
m.append(l[j]-l[i])
temp.append([l[i],l[j]])
minimum,x,y=m[0],temp[0][0],temp[0][1]
for i in range(1,len(m)):
if minimum>m[i]:
minimum,x,y=m[i],temp[i][0],temp[i][1]
print(x,y)
``` | 3 | |
442 | A | Borya and Hanabi | PROGRAMMING | 1,700 | [
"bitmasks",
"brute force",
"implementation"
] | null | null | Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game.
Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding *n* cards. The game is somewhat complicated by the fact that everybody sees Borya's cards except for Borya himself. Borya knows which cards he has but he knows nothing about the order they lie in. Note that Borya can have multiple identical cards (and for each of the 25 types of cards he knows exactly how many cards of this type he has).
The aim of the other players is to achieve the state when Borya knows the color and number value of each of his cards. For that, other players can give him hints. The hints can be of two types: color hints and value hints.
A color hint goes like that: a player names some color and points at all the cards of this color.
Similarly goes the value hint. A player names some value and points at all the cards that contain the value.
Determine what minimum number of hints the other players should make for Borya to be certain about each card's color and value. | The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of Borya's cards. The next line contains the descriptions of *n* cards. The description of each card consists of exactly two characters. The first character shows the color (overall this position can contain five distinct letters — R, G, B, Y, W). The second character shows the card's value (a digit from 1 to 5). Borya doesn't know exact order of the cards they lie in. | Print a single integer — the minimum number of hints that the other players should make. | [
"2\nG3 G3\n",
"4\nG4 R4 R3 B3\n",
"5\nB1 Y1 W1 G1 R1\n"
] | [
"0\n",
"2\n",
"4\n"
] | In the first sample Borya already knows for each card that it is a green three.
In the second sample we can show all fours and all red cards.
In the third sample you need to make hints about any four colors. | 500 | [
{
"input": "2\nG3 G3",
"output": "0"
},
{
"input": "4\nG4 R4 R3 B3",
"output": "2"
},
{
"input": "5\nB1 Y1 W1 G1 R1",
"output": "4"
},
{
"input": "10\nY4 B1 R3 G5 R5 W3 W5 W2 R1 Y1",
"output": "6"
},
{
"input": "3\nG4 G3 B4",
"output": "2"
},
{
"input"... | 1,604,678,672 | 2,147,483,647 | Python 3 | OK | TESTS | 54 | 109 | 0 | input()
p={ (1<< 'RGBYW'.index(c)) + (1<<int(k)+4) for c, k in input().split()}
mn=20
res=90
for i in range(1024):
if len(p)==len(set(i&j for j in p)):
mn=min(mn,bin(i).count('1'))
print(mn) | Title: Borya and Hanabi
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game.
Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding *n* cards. The game is somewhat complicated by the fact that everybody sees Borya's cards except for Borya himself. Borya knows which cards he has but he knows nothing about the order they lie in. Note that Borya can have multiple identical cards (and for each of the 25 types of cards he knows exactly how many cards of this type he has).
The aim of the other players is to achieve the state when Borya knows the color and number value of each of his cards. For that, other players can give him hints. The hints can be of two types: color hints and value hints.
A color hint goes like that: a player names some color and points at all the cards of this color.
Similarly goes the value hint. A player names some value and points at all the cards that contain the value.
Determine what minimum number of hints the other players should make for Borya to be certain about each card's color and value.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of Borya's cards. The next line contains the descriptions of *n* cards. The description of each card consists of exactly two characters. The first character shows the color (overall this position can contain five distinct letters — R, G, B, Y, W). The second character shows the card's value (a digit from 1 to 5). Borya doesn't know exact order of the cards they lie in.
Output Specification:
Print a single integer — the minimum number of hints that the other players should make.
Demo Input:
['2\nG3 G3\n', '4\nG4 R4 R3 B3\n', '5\nB1 Y1 W1 G1 R1\n']
Demo Output:
['0\n', '2\n', '4\n']
Note:
In the first sample Borya already knows for each card that it is a green three.
In the second sample we can show all fours and all red cards.
In the third sample you need to make hints about any four colors. | ```python
input()
p={ (1<< 'RGBYW'.index(c)) + (1<<int(k)+4) for c, k in input().split()}
mn=20
res=90
for i in range(1024):
if len(p)==len(set(i&j for j in p)):
mn=min(mn,bin(i).count('1'))
print(mn)
``` | 3 | |
2 | B | The least round way | PROGRAMMING | 2,000 | [
"dp",
"math"
] | B. The least round way | 2 | 64 | There is a square matrix *n*<=×<=*n*, consisting of non-negative integer numbers. You should find such a way on it that
- starts in the upper left cell of the matrix; - each following cell is to the right or down from the current cell; - the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | The first line contains an integer number *n* (2<=≤<=*n*<=≤<=1000), *n* is the size of the matrix. Then follow *n* lines containing the matrix elements (non-negative integer numbers not exceeding 109). | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | [
"3\n1 2 3\n4 5 6\n7 8 9\n"
] | [
"0\nDDRR\n"
] | none | 0 | [
{
"input": "3\n1 2 3\n4 5 6\n7 8 9",
"output": "0\nDDRR"
},
{
"input": "2\n7 6\n3 8",
"output": "0\nDR"
},
{
"input": "3\n4 10 5\n10 9 4\n6 5 3",
"output": "1\nDRRD"
},
{
"input": "4\n1 1 9 9\n3 4 7 3\n7 9 1 7\n1 7 1 5",
"output": "0\nDDDRRR"
},
{
"input": "5\n8 3... | 1,542,494,378 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 2 | 140 | 0 | def func(num,mod):
ans = 0
while num % mod == 0:
num //= mod
ans += 1
return ans
n = int(input())
matrix = [list(map(int,input().split())) for i in range(n)]
for i in range(n):
for j in range(n):
matrix[i][j] = [func(matrix[i][j],2),func(matrix[i][j],5)]
m5 = [[0]*n for i in range(n)]
m6 = [[0]*n for i in range(n)]
m2 = [[0,0] for i in range(n)]
m3 = [[0,0] for i in range(n)]
m4 = [[0,0] for i in range(n)]
ans = 0
m2[0][0] = matrix[0][0][0]
m2[0][1] = matrix[0][0][1]
m4[0][0] = matrix[0][0][0]
m4[0][1] = matrix[0][0][1]
for i in range(1,n):
m2[i][0] = m2[i-1][0] + matrix[i][0][0]
m2[i][1] = m2[i-1][1] + matrix[i][1][1]
m3[i][0] = m2[i][0]
m3[i][1] = m2[i][1]
for i in range(1,n):
m4[i][0] = m4[i-1][0] + matrix[i][0][0]
m4[i][1] = m4[i-1][1] + matrix[i][0][1]
m5[i][0] = 1
m6[i][0] = 1
for i in range(1,n):
m2[0][0] = m4[i][0]
m2[0][1] = m4[i][1]
for j in range(1,n):
if m2[j][0] > m2[j-1][0]:
m2[j][0] = m2[j-1][0] + matrix[i][j][0]
m2[j][1] = m2[j-1][1] + matrix[i][j][1]
elif m2[j][0] == m2[j-1][0]:
if m2[j][1] > m2[j-1][1]:
m2[j][0] = m2[j-1][0] + matrix[i][j][0]
m2[j][1] = m2[j-1][1] + matrix[i][j][1]
else:
m2[j][0] = m2[j][0] + matrix[i][j][0]
m2[j][1] = m2[j][1] + matrix[i][j][1]
m5[i][j] = 1
else:
m2[j][0] = m2[j][0] + matrix[i][j][0]
m2[j][1] = m2[j][1] + matrix[i][j][1]
m5[i][j] = 1
if m3[j][1] > m3[j-1][1]:
m3[j][0] = m3[j-1][0] + matrix[i][j][0]
m3[j][1] = m3[j-1][1] + matrix[i][j][1]
elif m3[j][1] == m3[j-1][1]:
if m3[j][0] > m3[j-1][0]:
m3[j][0] = m3[j-1][0] + matrix[i][j][0]
m3[j][1] = m3[j-1][1] + matrix[i][j][1]
else:
m3[j][0] = m3[j][0] + matrix[i][j][0]
m3[j][1] = m3[j][1] + matrix[i][j][1]
m6[i][j] = 1
else:
m3[j][0] = m3[j][0] + matrix[i][j][0]
m3[j][1] = m3[j][1] + matrix[i][j][1]
m6[j][j] = 1
num1 = min(m2[n-1][0],m2[n-1][1])
num2 = min(m3[n-1][0],m3[n-1][1])
print(min(num1,num2))
num3 = n*2-2
ans = [""] * (num3)
if num1 <= num2:
i = n-1
j = n-1
while num3 > 0:
temp = m5[i][j]
num3 -= 1
ans[num3] = "D" * temp + "R" * (1-temp)
i = i - temp
j = j - 1 + temp
else:
i = n-1
j = n-1
while num3 > 0:
temp = m6[i][j]
num3 -= 1
ans[num3] = "D" * temp + "R" * (1-temp)
i = i - temp
j = j - 1 + temp
print("".join(ans))
| Title: The least round way
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
There is a square matrix *n*<=×<=*n*, consisting of non-negative integer numbers. You should find such a way on it that
- starts in the upper left cell of the matrix; - each following cell is to the right or down from the current cell; - the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
Input Specification:
The first line contains an integer number *n* (2<=≤<=*n*<=≤<=1000), *n* is the size of the matrix. Then follow *n* lines containing the matrix elements (non-negative integer numbers not exceeding 109).
Output Specification:
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
Demo Input:
['3\n1 2 3\n4 5 6\n7 8 9\n']
Demo Output:
['0\nDDRR\n']
Note:
none | ```python
def func(num,mod):
ans = 0
while num % mod == 0:
num //= mod
ans += 1
return ans
n = int(input())
matrix = [list(map(int,input().split())) for i in range(n)]
for i in range(n):
for j in range(n):
matrix[i][j] = [func(matrix[i][j],2),func(matrix[i][j],5)]
m5 = [[0]*n for i in range(n)]
m6 = [[0]*n for i in range(n)]
m2 = [[0,0] for i in range(n)]
m3 = [[0,0] for i in range(n)]
m4 = [[0,0] for i in range(n)]
ans = 0
m2[0][0] = matrix[0][0][0]
m2[0][1] = matrix[0][0][1]
m4[0][0] = matrix[0][0][0]
m4[0][1] = matrix[0][0][1]
for i in range(1,n):
m2[i][0] = m2[i-1][0] + matrix[i][0][0]
m2[i][1] = m2[i-1][1] + matrix[i][1][1]
m3[i][0] = m2[i][0]
m3[i][1] = m2[i][1]
for i in range(1,n):
m4[i][0] = m4[i-1][0] + matrix[i][0][0]
m4[i][1] = m4[i-1][1] + matrix[i][0][1]
m5[i][0] = 1
m6[i][0] = 1
for i in range(1,n):
m2[0][0] = m4[i][0]
m2[0][1] = m4[i][1]
for j in range(1,n):
if m2[j][0] > m2[j-1][0]:
m2[j][0] = m2[j-1][0] + matrix[i][j][0]
m2[j][1] = m2[j-1][1] + matrix[i][j][1]
elif m2[j][0] == m2[j-1][0]:
if m2[j][1] > m2[j-1][1]:
m2[j][0] = m2[j-1][0] + matrix[i][j][0]
m2[j][1] = m2[j-1][1] + matrix[i][j][1]
else:
m2[j][0] = m2[j][0] + matrix[i][j][0]
m2[j][1] = m2[j][1] + matrix[i][j][1]
m5[i][j] = 1
else:
m2[j][0] = m2[j][0] + matrix[i][j][0]
m2[j][1] = m2[j][1] + matrix[i][j][1]
m5[i][j] = 1
if m3[j][1] > m3[j-1][1]:
m3[j][0] = m3[j-1][0] + matrix[i][j][0]
m3[j][1] = m3[j-1][1] + matrix[i][j][1]
elif m3[j][1] == m3[j-1][1]:
if m3[j][0] > m3[j-1][0]:
m3[j][0] = m3[j-1][0] + matrix[i][j][0]
m3[j][1] = m3[j-1][1] + matrix[i][j][1]
else:
m3[j][0] = m3[j][0] + matrix[i][j][0]
m3[j][1] = m3[j][1] + matrix[i][j][1]
m6[i][j] = 1
else:
m3[j][0] = m3[j][0] + matrix[i][j][0]
m3[j][1] = m3[j][1] + matrix[i][j][1]
m6[j][j] = 1
num1 = min(m2[n-1][0],m2[n-1][1])
num2 = min(m3[n-1][0],m3[n-1][1])
print(min(num1,num2))
num3 = n*2-2
ans = [""] * (num3)
if num1 <= num2:
i = n-1
j = n-1
while num3 > 0:
temp = m5[i][j]
num3 -= 1
ans[num3] = "D" * temp + "R" * (1-temp)
i = i - temp
j = j - 1 + temp
else:
i = n-1
j = n-1
while num3 > 0:
temp = m6[i][j]
num3 -= 1
ans[num3] = "D" * temp + "R" * (1-temp)
i = i - temp
j = j - 1 + temp
print("".join(ans))
``` | 0 |
630 | C | Lucky Numbers | PROGRAMMING | 1,100 | [
"combinatorics",
"math"
] | null | null | The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than *n* digits. | The only line of input contains one integer *n* (1<=≤<=*n*<=≤<=55) — the maximum length of a number that a door-plate can hold. | Output one integer — the maximum number of offices, than can have unique lucky numbers not longer than *n* digits. | [
"2\n"
] | [
"6"
] | none | 0 | [
{
"input": "2",
"output": "6"
},
{
"input": "1",
"output": "2"
},
{
"input": "3",
"output": "14"
},
{
"input": "5",
"output": "62"
},
{
"input": "12",
"output": "8190"
},
{
"input": "34",
"output": "34359738366"
},
{
"input": "43",
"out... | 1,695,458,307 | 2,147,483,647 | Python 3 | OK | TESTS | 10 | 31 | 0 | n = int(input())
z=0
while n!=0:
z=z+2**n
n=n-1
print(z)
# Sat Sep 23 2023 11:38:26 GMT+0300 (Moscow Standard Time)
| Title: Lucky Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than *n* digits.
Input Specification:
The only line of input contains one integer *n* (1<=≤<=*n*<=≤<=55) — the maximum length of a number that a door-plate can hold.
Output Specification:
Output one integer — the maximum number of offices, than can have unique lucky numbers not longer than *n* digits.
Demo Input:
['2\n']
Demo Output:
['6']
Note:
none | ```python
n = int(input())
z=0
while n!=0:
z=z+2**n
n=n-1
print(z)
# Sat Sep 23 2023 11:38:26 GMT+0300 (Moscow Standard Time)
``` | 3 | |
977 | A | Wrong Subtraction | PROGRAMMING | 800 | [
"implementation"
] | null | null | Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
- if the last digit of the number is non-zero, she decreases the number by one; - if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit).
You are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions.
It is guaranteed that the result will be positive integer number. | The first line of the input contains two integer numbers $n$ and $k$ ($2 \le n \le 10^9$, $1 \le k \le 50$) — the number from which Tanya will subtract and the number of subtractions correspondingly. | Print one integer number — the result of the decreasing $n$ by one $k$ times.
It is guaranteed that the result will be positive integer number. | [
"512 4\n",
"1000000000 9\n"
] | [
"50\n",
"1\n"
] | The first example corresponds to the following sequence: $512 \rightarrow 511 \rightarrow 510 \rightarrow 51 \rightarrow 50$. | 0 | [
{
"input": "512 4",
"output": "50"
},
{
"input": "1000000000 9",
"output": "1"
},
{
"input": "131203 11",
"output": "12"
},
{
"input": "999999999 50",
"output": "9999"
},
{
"input": "999999999 49",
"output": "99990"
},
{
"input": "131203 9",
"outpu... | 1,697,045,389 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 11 | 46 | 0 | x,y=input().split()
a=int(x)
b=int(y)
for i in range(0,b):
if int(x[-1])>0:
a-=1
x=str(a)
elif int(x[-1])==0:
a=a//10
x=str(a)
print(a) | Title: Wrong Subtraction
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
- if the last digit of the number is non-zero, she decreases the number by one; - if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit).
You are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions.
It is guaranteed that the result will be positive integer number.
Input Specification:
The first line of the input contains two integer numbers $n$ and $k$ ($2 \le n \le 10^9$, $1 \le k \le 50$) — the number from which Tanya will subtract and the number of subtractions correspondingly.
Output Specification:
Print one integer number — the result of the decreasing $n$ by one $k$ times.
It is guaranteed that the result will be positive integer number.
Demo Input:
['512 4\n', '1000000000 9\n']
Demo Output:
['50\n', '1\n']
Note:
The first example corresponds to the following sequence: $512 \rightarrow 511 \rightarrow 510 \rightarrow 51 \rightarrow 50$. | ```python
x,y=input().split()
a=int(x)
b=int(y)
for i in range(0,b):
if int(x[-1])>0:
a-=1
x=str(a)
elif int(x[-1])==0:
a=a//10
x=str(a)
print(a)
``` | 3 | |
997 | A | Convert to Ones | PROGRAMMING | 1,500 | [
"brute force",
"greedy",
"implementation",
"math"
] | null | null | You've got a string $a_1, a_2, \dots, a_n$, consisting of zeros and ones.
Let's call a sequence of consecutive elements $a_i, a_{i<=+<=1}, \ldots,<=a_j$ ($1\leq<=i\leq<=j\leq<=n$) a substring of string $a$.
You can apply the following operations any number of times:
- Choose some substring of string $a$ (for example, you can choose entire string) and reverse it, paying $x$ coins for it (for example, «0101101» $\to$ «0111001»); - Choose some substring of string $a$ (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying $y$ coins for it (for example, «0101101» $\to$ «0110001»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones? | The first line of input contains integers $n$, $x$ and $y$ ($1<=\leq<=n<=\leq<=300\,000, 0 \leq x, y \leq 10^9$) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string $a$ of length $n$, consisting of zeros and ones. | Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print $0$, if you do not need to perform any operations. | [
"5 1 10\n01000\n",
"5 10 1\n01000\n",
"7 2 3\n1111111\n"
] | [
"11\n",
"2\n",
"0\n"
] | In the first sample, at first you need to reverse substring $[1 \dots 2]$, and then you need to invert substring $[2 \dots 5]$.
Then the string was changed as follows:
«01000» $\to$ «10000» $\to$ «11111».
The total cost of operations is $1 + 10 = 11$.
In the second sample, at first you need to invert substring $[1 \dots 1]$, and then you need to invert substring $[3 \dots 5]$.
Then the string was changed as follows:
«01000» $\to$ «11000» $\to$ «11111».
The overall cost is $1 + 1 = 2$.
In the third example, string already consists only of ones, so the answer is $0$. | 500 | [
{
"input": "5 1 10\n01000",
"output": "11"
},
{
"input": "5 10 1\n01000",
"output": "2"
},
{
"input": "7 2 3\n1111111",
"output": "0"
},
{
"input": "1 60754033 959739508\n0",
"output": "959739508"
},
{
"input": "1 431963980 493041212\n1",
"output": "0"
},
... | 1,660,651,189 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 115 | 77 | 2,969,600 | def rev():
ret=0
i=0
while i<n and s[i]=='1':i+=1
while i<n:
if s[i]=='1':
while i<n and s[i]=='1':i+=1
if i<n:ret+=x
else:i+=1
return ret+y
def change():
ret1,ret2=0,0
cnt=0
for i in s:
if i=='1':cnt+=1
ret1=(cnt*y)+(n*y)
i=0
while i<n:
if s[i]=='0':
while i<n and s[i]=='0':i+=1
ret2+=y
else:i+=1
return min(ret1,ret2)
n,x,y=[int(a) for a in input().split()]
s=input()
print(min(rev(),change())) | Title: Convert to Ones
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've got a string $a_1, a_2, \dots, a_n$, consisting of zeros and ones.
Let's call a sequence of consecutive elements $a_i, a_{i<=+<=1}, \ldots,<=a_j$ ($1\leq<=i\leq<=j\leq<=n$) a substring of string $a$.
You can apply the following operations any number of times:
- Choose some substring of string $a$ (for example, you can choose entire string) and reverse it, paying $x$ coins for it (for example, «0101101» $\to$ «0111001»); - Choose some substring of string $a$ (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying $y$ coins for it (for example, «0101101» $\to$ «0110001»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones?
Input Specification:
The first line of input contains integers $n$, $x$ and $y$ ($1<=\leq<=n<=\leq<=300\,000, 0 \leq x, y \leq 10^9$) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string $a$ of length $n$, consisting of zeros and ones.
Output Specification:
Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print $0$, if you do not need to perform any operations.
Demo Input:
['5 1 10\n01000\n', '5 10 1\n01000\n', '7 2 3\n1111111\n']
Demo Output:
['11\n', '2\n', '0\n']
Note:
In the first sample, at first you need to reverse substring $[1 \dots 2]$, and then you need to invert substring $[2 \dots 5]$.
Then the string was changed as follows:
«01000» $\to$ «10000» $\to$ «11111».
The total cost of operations is $1 + 10 = 11$.
In the second sample, at first you need to invert substring $[1 \dots 1]$, and then you need to invert substring $[3 \dots 5]$.
Then the string was changed as follows:
«01000» $\to$ «11000» $\to$ «11111».
The overall cost is $1 + 1 = 2$.
In the third example, string already consists only of ones, so the answer is $0$. | ```python
def rev():
ret=0
i=0
while i<n and s[i]=='1':i+=1
while i<n:
if s[i]=='1':
while i<n and s[i]=='1':i+=1
if i<n:ret+=x
else:i+=1
return ret+y
def change():
ret1,ret2=0,0
cnt=0
for i in s:
if i=='1':cnt+=1
ret1=(cnt*y)+(n*y)
i=0
while i<n:
if s[i]=='0':
while i<n and s[i]=='0':i+=1
ret2+=y
else:i+=1
return min(ret1,ret2)
n,x,y=[int(a) for a in input().split()]
s=input()
print(min(rev(),change()))
``` | 3 | |
544 | B | Sea and Islands | PROGRAMMING | 1,400 | [
"constructive algorithms",
"implementation"
] | null | null | A map of some object is a rectangular field consisting of *n* rows and *n* columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly *k* islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).
Find a way to cover some cells with sand so that exactly *k* islands appear on the *n*<=×<=*n* map, or determine that no such way exists. | The single line contains two positive integers *n*, *k* (1<=≤<=*n*<=≤<=100, 0<=≤<=*k*<=≤<=*n*2) — the size of the map and the number of islands you should form. | If the answer doesn't exist, print "NO" (without the quotes) in a single line.
Otherwise, print "YES" in the first line. In the next *n* lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal *n*.
If there are multiple answers, you may print any of them.
You should not maximize the sizes of islands. | [
"5 2\n",
"5 25\n"
] | [
"YES\nSSSSS\nLLLLL\nSSSSS\nLLLLL\nSSSSS\n",
"NO\n"
] | none | 1,000 | [
{
"input": "5 2",
"output": "YES\nSSSSS\nLLLLL\nSSSSS\nLLLLL\nSSSSS"
},
{
"input": "5 25",
"output": "NO"
},
{
"input": "82 6047",
"output": "NO"
},
{
"input": "6 5",
"output": "YES\nLSLSLS\nSLSLSS\nSSSSSS\nSSSSSS\nSSSSSS\nSSSSSS"
},
{
"input": "10 80",
"outpu... | 1,464,455,511 | 2,147,483,647 | Python 3 | OK | TESTS | 42 | 78 | 5,734,400 |
n,k=map(int,input().split())
lm=(n*n+1)//2
if lm<k:
print('NO')
else:
print('YES')
for i in range(n):
for j in range(n):
if k>0 and (i+j)%2==0:
print('L',end='')
k-=1
else:
print('S',end='')
print()
| Title: Sea and Islands
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A map of some object is a rectangular field consisting of *n* rows and *n* columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly *k* islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).
Find a way to cover some cells with sand so that exactly *k* islands appear on the *n*<=×<=*n* map, or determine that no such way exists.
Input Specification:
The single line contains two positive integers *n*, *k* (1<=≤<=*n*<=≤<=100, 0<=≤<=*k*<=≤<=*n*2) — the size of the map and the number of islands you should form.
Output Specification:
If the answer doesn't exist, print "NO" (without the quotes) in a single line.
Otherwise, print "YES" in the first line. In the next *n* lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal *n*.
If there are multiple answers, you may print any of them.
You should not maximize the sizes of islands.
Demo Input:
['5 2\n', '5 25\n']
Demo Output:
['YES\nSSSSS\nLLLLL\nSSSSS\nLLLLL\nSSSSS\n', 'NO\n']
Note:
none | ```python
n,k=map(int,input().split())
lm=(n*n+1)//2
if lm<k:
print('NO')
else:
print('YES')
for i in range(n):
for j in range(n):
if k>0 and (i+j)%2==0:
print('L',end='')
k-=1
else:
print('S',end='')
print()
``` | 3 | |
0 | none | none | none | 0 | [
"none"
] | null | null | Little Artem is given a graph, constructed as follows: start with some *k*-clique, then add new vertices one by one, connecting them to *k* already existing vertices that form a *k*-clique.
Artem wants to count the number of spanning trees in this graph modulo 109<=+<=7. | First line of the input contains two integers *n* and *k* (1<=≤<=*n*<=≤<=10<=000, 1<=≤<=*k*<=≤<=*min*(*n*,<=5)) — the total size of the graph and the size of the initial clique, respectively.
Next *n*<=-<=*k* lines describe *k*<=+<=1-th, *k*<=+<=2-th, ..., *i*-th, ..., *n*-th vertices by listing *k* distinct vertex indices 1<=≤<=*a**ij*<=<<=*i* it is connected to. It is guaranteed that those vertices form a k-clique. | Output a single integer — the number of spanning trees in the given graph modulo 109<=+<=7. | [
"3 2\n1 2\n",
"4 3\n1 2 3\n"
] | [
"3\n",
"16\n"
] | none | 0 | [] | 1,692,386,289 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 46 | 0 | print("_RANDOM_GUESS_1692386289.2897065")# 1692386289.2897222 | Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Artem is given a graph, constructed as follows: start with some *k*-clique, then add new vertices one by one, connecting them to *k* already existing vertices that form a *k*-clique.
Artem wants to count the number of spanning trees in this graph modulo 109<=+<=7.
Input Specification:
First line of the input contains two integers *n* and *k* (1<=≤<=*n*<=≤<=10<=000, 1<=≤<=*k*<=≤<=*min*(*n*,<=5)) — the total size of the graph and the size of the initial clique, respectively.
Next *n*<=-<=*k* lines describe *k*<=+<=1-th, *k*<=+<=2-th, ..., *i*-th, ..., *n*-th vertices by listing *k* distinct vertex indices 1<=≤<=*a**ij*<=<<=*i* it is connected to. It is guaranteed that those vertices form a k-clique.
Output Specification:
Output a single integer — the number of spanning trees in the given graph modulo 109<=+<=7.
Demo Input:
['3 2\n1 2\n', '4 3\n1 2 3\n']
Demo Output:
['3\n', '16\n']
Note:
none | ```python
print("_RANDOM_GUESS_1692386289.2897065")# 1692386289.2897222
``` | 0 | |
989 | A | A Blend of Springtime | PROGRAMMING | 900 | [
"implementation",
"strings"
] | null | null | "What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone."
"But these blends are at their best, aren't they?" Absorbed in the landscape, Kanno remains optimistic.
The landscape can be expressed as a row of consecutive cells, each of which either contains a flower of colour amber or buff or canary yellow, or is empty.
When a flower withers, it disappears from the cell that it originally belonged to, and it spreads petals of its colour in its two neighbouring cells (or outside the field if the cell is on the side of the landscape). In case petals fall outside the given cells, they simply become invisible.
You are to help Kanno determine whether it's possible that after some (possibly none or all) flowers shed their petals, at least one of the cells contains all three colours, considering both petals and flowers. Note that flowers can wither in arbitrary order. | The first and only line of input contains a non-empty string $s$ consisting of uppercase English letters 'A', 'B', 'C' and characters '.' (dots) only ($\lvert s \rvert \leq 100$) — denoting cells containing an amber flower, a buff one, a canary yellow one, and no flowers, respectively. | Output "Yes" if it's possible that all three colours appear in some cell, and "No" otherwise.
You can print each letter in any case (upper or lower). | [
".BAC.\n",
"AA..CB\n"
] | [
"Yes\n",
"No\n"
] | In the first example, the buff and canary yellow flowers can leave their petals in the central cell, blending all three colours in it.
In the second example, it's impossible to satisfy the requirement because there is no way that amber and buff meet in any cell. | 500 | [
{
"input": ".BAC.",
"output": "Yes"
},
{
"input": "AA..CB",
"output": "No"
},
{
"input": ".",
"output": "No"
},
{
"input": "ACB.AAAAAA",
"output": "Yes"
},
{
"input": "B.BC.BBBCA",
"output": "Yes"
},
{
"input": "BA..CAB..B",
"output": "Yes"
},
... | 1,550,571,318 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 4 | 124 | 0 | landscape=input()
pos=0
for i in range(len(landscape)-3):
temp=landscape[i:i+3]
if "A" in temp and "B" in temp and "C" in temp:
print("YES")
quit()
pos+=1
print("NO") | Title: A Blend of Springtime
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
"What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone."
"But these blends are at their best, aren't they?" Absorbed in the landscape, Kanno remains optimistic.
The landscape can be expressed as a row of consecutive cells, each of which either contains a flower of colour amber or buff or canary yellow, or is empty.
When a flower withers, it disappears from the cell that it originally belonged to, and it spreads petals of its colour in its two neighbouring cells (or outside the field if the cell is on the side of the landscape). In case petals fall outside the given cells, they simply become invisible.
You are to help Kanno determine whether it's possible that after some (possibly none or all) flowers shed their petals, at least one of the cells contains all three colours, considering both petals and flowers. Note that flowers can wither in arbitrary order.
Input Specification:
The first and only line of input contains a non-empty string $s$ consisting of uppercase English letters 'A', 'B', 'C' and characters '.' (dots) only ($\lvert s \rvert \leq 100$) — denoting cells containing an amber flower, a buff one, a canary yellow one, and no flowers, respectively.
Output Specification:
Output "Yes" if it's possible that all three colours appear in some cell, and "No" otherwise.
You can print each letter in any case (upper or lower).
Demo Input:
['.BAC.\n', 'AA..CB\n']
Demo Output:
['Yes\n', 'No\n']
Note:
In the first example, the buff and canary yellow flowers can leave their petals in the central cell, blending all three colours in it.
In the second example, it's impossible to satisfy the requirement because there is no way that amber and buff meet in any cell. | ```python
landscape=input()
pos=0
for i in range(len(landscape)-3):
temp=landscape[i:i+3]
if "A" in temp and "B" in temp and "C" in temp:
print("YES")
quit()
pos+=1
print("NO")
``` | 0 | |
515 | C | Drazil and Factorial | PROGRAMMING | 1,400 | [
"greedy",
"math",
"sortings"
] | null | null | Drazil is playing a math game with Varda.
Let's define for positive integer *x* as a product of factorials of its digits. For example, .
First, they choose a decimal number *a* consisting of *n* digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number *x* satisfying following two conditions:
1. *x* doesn't contain neither digit 0 nor digit 1.
2. = .
Help friends find such number. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=15) — the number of digits in *a*.
The second line contains *n* digits of *a*. There is at least one digit in *a* that is larger than 1. Number *a* may possibly contain leading zeroes. | Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation. | [
"4\n1234\n",
"3\n555\n"
] | [
"33222\n",
"555\n"
] | In the first case, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f5a4207f23215fddce977ab5ea9e9d2e7578fb52.png" style="max-width: 100.0%;max-height: 100.0%;"/> | 1,000 | [
{
"input": "4\n1234",
"output": "33222"
},
{
"input": "3\n555",
"output": "555"
},
{
"input": "15\n012345781234578",
"output": "7777553333222222222222"
},
{
"input": "1\n8",
"output": "7222"
},
{
"input": "10\n1413472614",
"output": "75333332222222"
},
{
... | 1,641,913,495 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 4 | 77 | 0 | n = int(input())
s = input()
t = ""
for c in s:
if c in ['2','3','5','7']:
t = t + c
elif c == '4':
t += '223'
elif c == '6':
t += '532'
elif c == '8':
t += '7222'
elif c == '9':
t += '7332'
t = sorted(t)
t = t[::-1]
s = ""
for i in t:
s += i
print(s) | Title: Drazil and Factorial
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Drazil is playing a math game with Varda.
Let's define for positive integer *x* as a product of factorials of its digits. For example, .
First, they choose a decimal number *a* consisting of *n* digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number *x* satisfying following two conditions:
1. *x* doesn't contain neither digit 0 nor digit 1.
2. = .
Help friends find such number.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=15) — the number of digits in *a*.
The second line contains *n* digits of *a*. There is at least one digit in *a* that is larger than 1. Number *a* may possibly contain leading zeroes.
Output Specification:
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Demo Input:
['4\n1234\n', '3\n555\n']
Demo Output:
['33222\n', '555\n']
Note:
In the first case, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f5a4207f23215fddce977ab5ea9e9d2e7578fb52.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
n = int(input())
s = input()
t = ""
for c in s:
if c in ['2','3','5','7']:
t = t + c
elif c == '4':
t += '223'
elif c == '6':
t += '532'
elif c == '8':
t += '7222'
elif c == '9':
t += '7332'
t = sorted(t)
t = t[::-1]
s = ""
for i in t:
s += i
print(s)
``` | 0 | |
1,007 | A | Reorder the Array | PROGRAMMING | 1,300 | [
"combinatorics",
"data structures",
"math",
"sortings",
"two pointers"
] | null | null | You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20>10$, $40>20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case.
Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal. | The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the length of the array.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the elements of the array. | Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array. | [
"7\n10 1 1 1 5 5 3\n",
"5\n1 1 1 1 1\n"
] | [
"4\n",
"0\n"
] | In the first sample, one of the best permutations is $[1, 5, 5, 3, 10, 1, 1]$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.
In the second sample, there is no way to increase any element with a permutation, so the answer is 0. | 500 | [
{
"input": "7\n10 1 1 1 5 5 3",
"output": "4"
},
{
"input": "5\n1 1 1 1 1",
"output": "0"
},
{
"input": "6\n300000000 200000000 300000000 200000000 1000000000 300000000",
"output": "3"
},
{
"input": "10\n1 2 3 4 5 6 7 8 9 10",
"output": "9"
},
{
"input": "1\n1",
... | 1,672,746,809 | 2,147,483,647 | Python 3 | OK | TESTS | 33 | 124 | 12,800,000 | n = int(input())
x_list = input().split()
a_list = [int(item) for item in x_list]
count = 0
dic = {}
for i in range(n):
if a_list[i] not in dic:
dic[a_list[i]]= 1
else:
dic[a_list[i]] += 1
print(n - max(dic.values())) | Title: Reorder the Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20>10$, $40>20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case.
Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.
Input Specification:
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the length of the array.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the elements of the array.
Output Specification:
Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.
Demo Input:
['7\n10 1 1 1 5 5 3\n', '5\n1 1 1 1 1\n']
Demo Output:
['4\n', '0\n']
Note:
In the first sample, one of the best permutations is $[1, 5, 5, 3, 10, 1, 1]$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.
In the second sample, there is no way to increase any element with a permutation, so the answer is 0. | ```python
n = int(input())
x_list = input().split()
a_list = [int(item) for item in x_list]
count = 0
dic = {}
for i in range(n):
if a_list[i] not in dic:
dic[a_list[i]]= 1
else:
dic[a_list[i]] += 1
print(n - max(dic.values()))
``` | 3 | |
723 | A | The New Year: Meeting Friends | PROGRAMMING | 800 | [
"implementation",
"math",
"sortings"
] | null | null | There are three friend living on the straight line *Ox* in Lineland. The first friend lives at the point *x*1, the second friend lives at the point *x*2, and the third friend lives at the point *x*3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?
It's guaranteed that the optimal answer is always integer. | The first line of the input contains three distinct integers *x*1, *x*2 and *x*3 (1<=≤<=*x*1,<=*x*2,<=*x*3<=≤<=100) — the coordinates of the houses of the first, the second and the third friends respectively. | Print one integer — the minimum total distance the friends need to travel in order to meet together. | [
"7 1 4\n",
"30 20 10\n"
] | [
"6\n",
"20\n"
] | In the first sample, friends should meet at the point 4. Thus, the first friend has to travel the distance of 3 (from the point 7 to the point 4), the second friend also has to travel the distance of 3 (from the point 1 to the point 4), while the third friend should not go anywhere because he lives at the point 4. | 500 | [
{
"input": "7 1 4",
"output": "6"
},
{
"input": "30 20 10",
"output": "20"
},
{
"input": "1 4 100",
"output": "99"
},
{
"input": "100 1 91",
"output": "99"
},
{
"input": "1 45 100",
"output": "99"
},
{
"input": "1 2 3",
"output": "2"
},
{
"... | 1,690,896,484 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 2 | 46 | 0 | from sys import stdin
def input(): return stdin.readline()[:-1]
x,y,z=map(int,input().split())
mp=(x+y+z)//3
print(abs(x-mp)+abs(y-mp)+abs(z-mp)) | Title: The New Year: Meeting Friends
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are three friend living on the straight line *Ox* in Lineland. The first friend lives at the point *x*1, the second friend lives at the point *x*2, and the third friend lives at the point *x*3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?
It's guaranteed that the optimal answer is always integer.
Input Specification:
The first line of the input contains three distinct integers *x*1, *x*2 and *x*3 (1<=≤<=*x*1,<=*x*2,<=*x*3<=≤<=100) — the coordinates of the houses of the first, the second and the third friends respectively.
Output Specification:
Print one integer — the minimum total distance the friends need to travel in order to meet together.
Demo Input:
['7 1 4\n', '30 20 10\n']
Demo Output:
['6\n', '20\n']
Note:
In the first sample, friends should meet at the point 4. Thus, the first friend has to travel the distance of 3 (from the point 7 to the point 4), the second friend also has to travel the distance of 3 (from the point 1 to the point 4), while the third friend should not go anywhere because he lives at the point 4. | ```python
from sys import stdin
def input(): return stdin.readline()[:-1]
x,y,z=map(int,input().split())
mp=(x+y+z)//3
print(abs(x-mp)+abs(y-mp)+abs(z-mp))
``` | 0 | |
455 | A | Boredom | PROGRAMMING | 1,500 | [
"dp"
] | null | null | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him. | The first line contains integer *n* (1<=≤<=*n*<=≤<=105) that shows how many numbers are in Alex's sequence.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=105). | Print a single integer — the maximum number of points that Alex can earn. | [
"2\n1 2\n",
"3\n1 2 3\n",
"9\n1 2 1 3 2 2 2 2 3\n"
] | [
"2\n",
"4\n",
"10\n"
] | Consider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | 500 | [
{
"input": "2\n1 2",
"output": "2"
},
{
"input": "3\n1 2 3",
"output": "4"
},
{
"input": "9\n1 2 1 3 2 2 2 2 3",
"output": "10"
},
{
"input": "5\n3 3 4 5 4",
"output": "11"
},
{
"input": "5\n5 3 5 3 4",
"output": "16"
},
{
"input": "5\n4 2 3 2 5",
... | 1,694,234,122 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 6 | 30 | 0 | n = int(input())
sequence = list(map(int, input().split()))
# Step 1: Create a dictionary to store frequency
frequency = {}
for num in sequence:
frequency[num] = frequency.get(num, 0) + 1
# Initialize variables
prev = 0
current = 0
# Step 3: Loop through unique elements in ascending order
unique_elements = sorted(frequency.keys())
for elem in unique_elements:
# Step 4: Calculate points for selecting the current element
points = (frequency[elem] * elem) + prev
# Step 5: Update current and prev variables
prev = current
current = max(current, points)
# Step 7: Print the maximum points
print(current)
| Title: Boredom
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) that shows how many numbers are in Alex's sequence.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=105).
Output Specification:
Print a single integer — the maximum number of points that Alex can earn.
Demo Input:
['2\n1 2\n', '3\n1 2 3\n', '9\n1 2 1 3 2 2 2 2 3\n']
Demo Output:
['2\n', '4\n', '10\n']
Note:
Consider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | ```python
n = int(input())
sequence = list(map(int, input().split()))
# Step 1: Create a dictionary to store frequency
frequency = {}
for num in sequence:
frequency[num] = frequency.get(num, 0) + 1
# Initialize variables
prev = 0
current = 0
# Step 3: Loop through unique elements in ascending order
unique_elements = sorted(frequency.keys())
for elem in unique_elements:
# Step 4: Calculate points for selecting the current element
points = (frequency[elem] * elem) + prev
# Step 5: Update current and prev variables
prev = current
current = max(current, points)
# Step 7: Print the maximum points
print(current)
``` | 0 | |
155 | A | I_love_\%username\% | PROGRAMMING | 800 | [
"brute force"
] | null | null | Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).
Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him. | The first line contains the single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of contests where the coder participated.
The next line contains *n* space-separated non-negative integer numbers — they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000. | Print the single number — the number of amazing performances the coder has had during his whole history of participating in the contests. | [
"5\n100 50 200 150 200\n",
"10\n4664 6496 5814 7010 5762 5736 6944 4850 3698 7242\n"
] | [
"2\n",
"4\n"
] | In the first sample the performances number 2 and 3 are amazing.
In the second sample the performances number 2, 4, 9 and 10 are amazing. | 500 | [
{
"input": "5\n100 50 200 150 200",
"output": "2"
},
{
"input": "10\n4664 6496 5814 7010 5762 5736 6944 4850 3698 7242",
"output": "4"
},
{
"input": "1\n6",
"output": "0"
},
{
"input": "2\n2 1",
"output": "1"
},
{
"input": "5\n100 36 53 7 81",
"output": "2"
... | 1,696,326,889 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 37 | 124 | 0 | number = int(input())
numbers = [int(el) for el in input().split(" ")]
min = numbers[0]
max = numbers[0]
count = 0
for i in range(1, len(numbers)):
if numbers[i] > max:
max = numbers[i]
count += 1
if numbers[i] < min:
min = numbers[i]
count += 1
print(count) | Title: I_love_\%username\%
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).
Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.
Input Specification:
The first line contains the single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of contests where the coder participated.
The next line contains *n* space-separated non-negative integer numbers — they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000.
Output Specification:
Print the single number — the number of amazing performances the coder has had during his whole history of participating in the contests.
Demo Input:
['5\n100 50 200 150 200\n', '10\n4664 6496 5814 7010 5762 5736 6944 4850 3698 7242\n']
Demo Output:
['2\n', '4\n']
Note:
In the first sample the performances number 2 and 3 are amazing.
In the second sample the performances number 2, 4, 9 and 10 are amazing. | ```python
number = int(input())
numbers = [int(el) for el in input().split(" ")]
min = numbers[0]
max = numbers[0]
count = 0
for i in range(1, len(numbers)):
if numbers[i] > max:
max = numbers[i]
count += 1
if numbers[i] < min:
min = numbers[i]
count += 1
print(count)
``` | 3 | |
86 | D | Powerful array | PROGRAMMING | 2,200 | [
"data structures",
"implementation",
"math",
"two pointers"
] | D. Powerful array | 5 | 256 | An array of positive integers *a*1,<=*a*2,<=...,<=*a**n* is given. Let us consider its arbitrary subarray *a**l*,<=*a**l*<=+<=1...,<=*a**r*, where 1<=≤<=*l*<=≤<=*r*<=≤<=*n*. For every positive integer *s* denote by *K**s* the number of occurrences of *s* into the subarray. We call the power of the subarray the sum of products *K**s*·*K**s*·*s* for every positive integer *s*. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite.
You should calculate the power of *t* given subarrays. | First line contains two integers *n* and *t* (1<=≤<=*n*,<=*t*<=≤<=200000) — the array length and the number of queries correspondingly.
Second line contains *n* positive integers *a**i* (1<=≤<=*a**i*<=≤<=106) — the elements of the array.
Next *t* lines contain two positive integers *l*, *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) each — the indices of the left and the right ends of the corresponding subarray. | Output *t* lines, the *i*-th line of the output should contain single positive integer — the power of the *i*-th query subarray.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d). | [
"3 2\n1 2 1\n1 2\n1 3\n",
"8 3\n1 1 2 2 1 3 1 1\n2 7\n1 6\n2 7\n"
] | [
"3\n6\n",
"20\n20\n20\n"
] | Consider the following array (see the second sample) and its [2, 7] subarray (elements of the subarray are colored): | 2,500 | [
{
"input": "3 2\n1 2 1\n1 2\n1 3",
"output": "3\n6"
},
{
"input": "8 3\n1 1 2 2 1 3 1 1\n2 7\n1 6\n2 7",
"output": "20\n20\n20"
},
{
"input": "20 8\n1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2\n4 15\n1 2\n2 20\n7 7\n13 18\n7 7\n3 19\n3 8",
"output": "108\n3\n281\n1\n27\n1\n209\n27"
},
... | 1,594,403,977 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 2 | 280 | 24,268,800 | # n=int(input())
# n,k=map(int,input().split())
# arr=list(map(int,input().split()))
#ls=list(map(int,input().split()))
#for i in range(m):
# for _ in range(int(input())):
from collections import Counter
#from fractions import Fraction
#n=int(input())
#arr=list(map(int,input().split()))
#ls = [list(map(int, input().split())) for i in range(n)]
from math import log2
#for _ in range(int(input())):
#n, m = map(int, input().split())
# for _ in range(int(input())):
from math import gcd
#n=int(input())
#def fxn(l_ptr,r_ptr,l,r,p):
l_ptr=0
r_ptr=0
p=0
n, m = map(int, input().split())
arr=list(map(int,input().split()))
q=[]
for i in range(m):
u,v=map(int, input().split())
q.append((u,v))
q.sort(key=lambda x : x[1] )
f=[0]*(10**6+1)
for i in range(m):
var=q[i]
l=var[0]
r=var[1]
while l_ptr<l-1:
f1=f[arr[l_ptr]]
f[arr[l_ptr]]-=1
p-=f1*f1*arr[l_ptr]
p+=f[arr[l_ptr]]*f[arr[l_ptr]]*arr[l_ptr]
l_ptr+=1
while l_ptr>=l: ###
f1 = f[arr[l_ptr]]
f[arr[l_ptr]]-=1
p-= f1 * f1 * arr[l_ptr]
p += f[arr[l_ptr]] * f[arr[l_ptr]] * arr[l_ptr]
l_ptr -= 1
while r_ptr<=r-1:
f1 = f[arr[r_ptr]]
f[arr[r_ptr]]+=1
p-= f1 * f1 * arr[r_ptr]
p += f[arr[r_ptr]] * f[arr[r_ptr]] * arr[r_ptr]
r_ptr +=1
while r_ptr>r:
r_ptr -= 1
f1 = f[arr[r_ptr]]
f[arr[r_ptr]] -= 1
p -= f1 * f1 * arr[l_ptr]
p += f[arr[r_ptr]] * f[arr[r_ptr]] * arr[r_ptr]
#t=fxn(l_ptr,r_ptr,var[0],var[1],p)
print(p)
| Title: Powerful array
Time Limit: 5 seconds
Memory Limit: 256 megabytes
Problem Description:
An array of positive integers *a*1,<=*a*2,<=...,<=*a**n* is given. Let us consider its arbitrary subarray *a**l*,<=*a**l*<=+<=1...,<=*a**r*, where 1<=≤<=*l*<=≤<=*r*<=≤<=*n*. For every positive integer *s* denote by *K**s* the number of occurrences of *s* into the subarray. We call the power of the subarray the sum of products *K**s*·*K**s*·*s* for every positive integer *s*. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite.
You should calculate the power of *t* given subarrays.
Input Specification:
First line contains two integers *n* and *t* (1<=≤<=*n*,<=*t*<=≤<=200000) — the array length and the number of queries correspondingly.
Second line contains *n* positive integers *a**i* (1<=≤<=*a**i*<=≤<=106) — the elements of the array.
Next *t* lines contain two positive integers *l*, *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) each — the indices of the left and the right ends of the corresponding subarray.
Output Specification:
Output *t* lines, the *i*-th line of the output should contain single positive integer — the power of the *i*-th query subarray.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d).
Demo Input:
['3 2\n1 2 1\n1 2\n1 3\n', '8 3\n1 1 2 2 1 3 1 1\n2 7\n1 6\n2 7\n']
Demo Output:
['3\n6\n', '20\n20\n20\n']
Note:
Consider the following array (see the second sample) and its [2, 7] subarray (elements of the subarray are colored): | ```python
# n=int(input())
# n,k=map(int,input().split())
# arr=list(map(int,input().split()))
#ls=list(map(int,input().split()))
#for i in range(m):
# for _ in range(int(input())):
from collections import Counter
#from fractions import Fraction
#n=int(input())
#arr=list(map(int,input().split()))
#ls = [list(map(int, input().split())) for i in range(n)]
from math import log2
#for _ in range(int(input())):
#n, m = map(int, input().split())
# for _ in range(int(input())):
from math import gcd
#n=int(input())
#def fxn(l_ptr,r_ptr,l,r,p):
l_ptr=0
r_ptr=0
p=0
n, m = map(int, input().split())
arr=list(map(int,input().split()))
q=[]
for i in range(m):
u,v=map(int, input().split())
q.append((u,v))
q.sort(key=lambda x : x[1] )
f=[0]*(10**6+1)
for i in range(m):
var=q[i]
l=var[0]
r=var[1]
while l_ptr<l-1:
f1=f[arr[l_ptr]]
f[arr[l_ptr]]-=1
p-=f1*f1*arr[l_ptr]
p+=f[arr[l_ptr]]*f[arr[l_ptr]]*arr[l_ptr]
l_ptr+=1
while l_ptr>=l: ###
f1 = f[arr[l_ptr]]
f[arr[l_ptr]]-=1
p-= f1 * f1 * arr[l_ptr]
p += f[arr[l_ptr]] * f[arr[l_ptr]] * arr[l_ptr]
l_ptr -= 1
while r_ptr<=r-1:
f1 = f[arr[r_ptr]]
f[arr[r_ptr]]+=1
p-= f1 * f1 * arr[r_ptr]
p += f[arr[r_ptr]] * f[arr[r_ptr]] * arr[r_ptr]
r_ptr +=1
while r_ptr>r:
r_ptr -= 1
f1 = f[arr[r_ptr]]
f[arr[r_ptr]] -= 1
p -= f1 * f1 * arr[l_ptr]
p += f[arr[r_ptr]] * f[arr[r_ptr]] * arr[r_ptr]
#t=fxn(l_ptr,r_ptr,var[0],var[1],p)
print(p)
``` | 0 |
610 | A | Pasha and Stick | PROGRAMMING | 1,000 | [
"combinatorics",
"math"
] | null | null | Pasha has a wooden stick of some positive integer length *n*. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be *n*.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square.
Your task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer *x*, such that the number of parts of length *x* in the first way differ from the number of parts of length *x* in the second way. | The first line of the input contains a positive integer *n* (1<=≤<=*n*<=≤<=2·109) — the length of Pasha's stick. | The output should contain a single integer — the number of ways to split Pasha's stick into four parts of positive integer length so that it's possible to make a rectangle by connecting the ends of these parts, but is impossible to form a square. | [
"6\n",
"20\n"
] | [
"1\n",
"4\n"
] | There is only one way to divide the stick in the first sample {1, 1, 2, 2}.
Four ways to divide the stick in the second sample are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}. Note that {5, 5, 5, 5} doesn't work. | 500 | [
{
"input": "6",
"output": "1"
},
{
"input": "20",
"output": "4"
},
{
"input": "1",
"output": "0"
},
{
"input": "2",
"output": "0"
},
{
"input": "3",
"output": "0"
},
{
"input": "4",
"output": "0"
},
{
"input": "2000000000",
"output": "4... | 1,695,487,749 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 76 | 62 | 0 | n = int(input())
if n % 2 == 1:
print(0)
else:
print(n//4 if n % 4 != 0 else n//4 - 1)
| Title: Pasha and Stick
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Pasha has a wooden stick of some positive integer length *n*. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be *n*.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square.
Your task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer *x*, such that the number of parts of length *x* in the first way differ from the number of parts of length *x* in the second way.
Input Specification:
The first line of the input contains a positive integer *n* (1<=≤<=*n*<=≤<=2·109) — the length of Pasha's stick.
Output Specification:
The output should contain a single integer — the number of ways to split Pasha's stick into four parts of positive integer length so that it's possible to make a rectangle by connecting the ends of these parts, but is impossible to form a square.
Demo Input:
['6\n', '20\n']
Demo Output:
['1\n', '4\n']
Note:
There is only one way to divide the stick in the first sample {1, 1, 2, 2}.
Four ways to divide the stick in the second sample are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}. Note that {5, 5, 5, 5} doesn't work. | ```python
n = int(input())
if n % 2 == 1:
print(0)
else:
print(n//4 if n % 4 != 0 else n//4 - 1)
``` | 3 | |
560 | B | Gerald is into Art | PROGRAMMING | 1,200 | [
"constructive algorithms",
"implementation"
] | null | null | Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an *a*1<=×<=*b*1 rectangle, the paintings have shape of a *a*2<=×<=*b*2 and *a*3<=×<=*b*3 rectangles.
Since the paintings are painted in the style of abstract art, it does not matter exactly how they will be rotated, but still, one side of both the board, and each of the paintings must be parallel to the floor. The paintings can touch each other and the edges of the board, but can not overlap or go beyond the edge of the board. Gerald asks whether it is possible to place the paintings on the board, or is the board he bought not large enough? | The first line contains two space-separated numbers *a*1 and *b*1 — the sides of the board. Next two lines contain numbers *a*2,<=*b*2,<=*a*3 and *b*3 — the sides of the paintings. All numbers *a**i*,<=*b**i* in the input are integers and fit into the range from 1 to 1000. | If the paintings can be placed on the wall, print "YES" (without the quotes), and if they cannot, print "NO" (without the quotes). | [
"3 2\n1 3\n2 1\n",
"5 5\n3 3\n3 3\n",
"4 2\n2 3\n1 2\n"
] | [
"YES\n",
"NO\n",
"YES\n"
] | That's how we can place the pictures in the first test:
<img class="tex-graphics" src="https://espresso.codeforces.com/b41bf40c649073c6d3dd62eb7ae7adfc4bd131bd.png" style="max-width: 100.0%;max-height: 100.0%;"/>
And that's how we can do it in the third one.
<img class="tex-graphics" src="https://espresso.codeforces.com/dafdf616eaa5ef10cd3c9ccdc7fba7ece392268c.png" style="max-width: 100.0%;max-height: 100.0%;"/> | 1,000 | [
{
"input": "3 2\n1 3\n2 1",
"output": "YES"
},
{
"input": "5 5\n3 3\n3 3",
"output": "NO"
},
{
"input": "4 2\n2 3\n1 2",
"output": "YES"
},
{
"input": "3 3\n1 1\n1 1",
"output": "YES"
},
{
"input": "1000 1000\n999 999\n1 1000",
"output": "YES"
},
{
"in... | 1,437,576,502 | 2,902 | Python 3 | OK | TESTS | 101 | 62 | 0 | def main():
a, b = list(map(int, input().split()))
obj = [None, None]
obj[0] = list(map(int, input().split()))
obj[1] = list(map(int, input().split()))
#portrait
def vlezet(a, b, i, j, sx, sy):
return (i + sx <= a) and (j + sy <= b)
if vlezet(a, b, 0, 0, *obj[0]):
x = obj[0][0]
y = obj[0][1]
if vlezet(a, b, x, 0, *obj[1]) or vlezet(a, b, x, 0, obj[1][1], obj[1][0]):
print('YES')
return 0
elif vlezet(a, b, 0, y, *obj[1]) or vlezet(a, b, 0, y, obj[1][1], obj[1][0]):
print('YES')
return 0
obj[0][1], obj[0][0] = obj[0][0], obj[0][1]
if vlezet(a, b, 0, 0, *obj[0]):
x = obj[0][0]
y = obj[0][1]
if vlezet(a, b, x, 0, *obj[1]) or vlezet(a, b, x, 0, obj[1][1], obj[1][0]):
print('YES')
return 0
elif vlezet(a, b, 0, y, *obj[1]) or vlezet(a, b, 0, y, obj[1][1], obj[1][0]):
print('YES')
return 0
print('NO')
return 0
main()
| Title: Gerald is into Art
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an *a*1<=×<=*b*1 rectangle, the paintings have shape of a *a*2<=×<=*b*2 and *a*3<=×<=*b*3 rectangles.
Since the paintings are painted in the style of abstract art, it does not matter exactly how they will be rotated, but still, one side of both the board, and each of the paintings must be parallel to the floor. The paintings can touch each other and the edges of the board, but can not overlap or go beyond the edge of the board. Gerald asks whether it is possible to place the paintings on the board, or is the board he bought not large enough?
Input Specification:
The first line contains two space-separated numbers *a*1 and *b*1 — the sides of the board. Next two lines contain numbers *a*2,<=*b*2,<=*a*3 and *b*3 — the sides of the paintings. All numbers *a**i*,<=*b**i* in the input are integers and fit into the range from 1 to 1000.
Output Specification:
If the paintings can be placed on the wall, print "YES" (without the quotes), and if they cannot, print "NO" (without the quotes).
Demo Input:
['3 2\n1 3\n2 1\n', '5 5\n3 3\n3 3\n', '4 2\n2 3\n1 2\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
That's how we can place the pictures in the first test:
<img class="tex-graphics" src="https://espresso.codeforces.com/b41bf40c649073c6d3dd62eb7ae7adfc4bd131bd.png" style="max-width: 100.0%;max-height: 100.0%;"/>
And that's how we can do it in the third one.
<img class="tex-graphics" src="https://espresso.codeforces.com/dafdf616eaa5ef10cd3c9ccdc7fba7ece392268c.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
def main():
a, b = list(map(int, input().split()))
obj = [None, None]
obj[0] = list(map(int, input().split()))
obj[1] = list(map(int, input().split()))
#portrait
def vlezet(a, b, i, j, sx, sy):
return (i + sx <= a) and (j + sy <= b)
if vlezet(a, b, 0, 0, *obj[0]):
x = obj[0][0]
y = obj[0][1]
if vlezet(a, b, x, 0, *obj[1]) or vlezet(a, b, x, 0, obj[1][1], obj[1][0]):
print('YES')
return 0
elif vlezet(a, b, 0, y, *obj[1]) or vlezet(a, b, 0, y, obj[1][1], obj[1][0]):
print('YES')
return 0
obj[0][1], obj[0][0] = obj[0][0], obj[0][1]
if vlezet(a, b, 0, 0, *obj[0]):
x = obj[0][0]
y = obj[0][1]
if vlezet(a, b, x, 0, *obj[1]) or vlezet(a, b, x, 0, obj[1][1], obj[1][0]):
print('YES')
return 0
elif vlezet(a, b, 0, y, *obj[1]) or vlezet(a, b, 0, y, obj[1][1], obj[1][0]):
print('YES')
return 0
print('NO')
return 0
main()
``` | 3 | |
894 | A | QAQ | PROGRAMMING | 800 | [
"brute force",
"dp"
] | null | null | "QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact. | The only line contains a string of length *n* (1<=≤<=*n*<=≤<=100). It's guaranteed that the string only contains uppercase English letters. | Print a single integer — the number of subsequences "QAQ" in the string. | [
"QAQAQYSYIOIWIN\n",
"QAQQQZZYNOIWIN\n"
] | [
"4\n",
"3\n"
] | In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | 500 | [
{
"input": "QAQAQYSYIOIWIN",
"output": "4"
},
{
"input": "QAQQQZZYNOIWIN",
"output": "3"
},
{
"input": "QA",
"output": "0"
},
{
"input": "IAQVAQZLQBQVQFTQQQADAQJA",
"output": "24"
},
{
"input": "QQAAQASGAYAAAAKAKAQIQEAQAIAAIAQQQQQ",
"output": "378"
},
{
... | 1,659,605,766 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 46 | 0 | data = input().split()
count = 0
print(data)
for i in range(len(data)):
if data[i] == "Q":
for j in range(i+1,len(data)):
if data[j] == "A":
for k in range(j+1,len(data)):
if data[k] == "Q":
count +=1
print(count) | Title: QAQ
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
Input Specification:
The only line contains a string of length *n* (1<=≤<=*n*<=≤<=100). It's guaranteed that the string only contains uppercase English letters.
Output Specification:
Print a single integer — the number of subsequences "QAQ" in the string.
Demo Input:
['QAQAQYSYIOIWIN\n', 'QAQQQZZYNOIWIN\n']
Demo Output:
['4\n', '3\n']
Note:
In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | ```python
data = input().split()
count = 0
print(data)
for i in range(len(data)):
if data[i] == "Q":
for j in range(i+1,len(data)):
if data[j] == "A":
for k in range(j+1,len(data)):
if data[k] == "Q":
count +=1
print(count)
``` | 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.