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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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,662,233,995 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 4 | 156 | 4,710,400 | from collections import deque,Counter
from math import *
import sys
import random
from bisect import *
from functools import reduce
from sys import stdin
import copy
def find(s,t):
p = 31
m = 10**9 + 9
p_pow = [0] * max(len(s),len(t))
p_pow[0] = 1
for i in range(1,len(p_pow)):
p_pow[i] = (p_pow[i-1] * p) % m
h = [0]*(len(t)+1)
for i in range(len(t)):
h[i+1] = (h[i] + (ord(t[i]) - 97)*p_pow[i])%m
h_s = 0
for i in range(len(s)):
h_s = (h_s + (ord(s[i]) - 97)*p_pow[i])%m
ans = 0
for i in range(len(t)-len(s)+1):
curr_h = (h[i+len(s)] - h[i])%m
if curr_h == (h_s * p_pow[i])%m:
ans+=1
return ans
t = input()
s = input()
print(find(s,t))
| 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
from collections import deque,Counter
from math import *
import sys
import random
from bisect import *
from functools import reduce
from sys import stdin
import copy
def find(s,t):
p = 31
m = 10**9 + 9
p_pow = [0] * max(len(s),len(t))
p_pow[0] = 1
for i in range(1,len(p_pow)):
p_pow[i] = (p_pow[i-1] * p) % m
h = [0]*(len(t)+1)
for i in range(len(t)):
h[i+1] = (h[i] + (ord(t[i]) - 97)*p_pow[i])%m
h_s = 0
for i in range(len(s)):
h_s = (h_s + (ord(s[i]) - 97)*p_pow[i])%m
ans = 0
for i in range(len(t)-len(s)+1):
curr_h = (h[i+len(s)] - h[i])%m
if curr_h == (h_s * p_pow[i])%m:
ans+=1
return ans
t = input()
s = input()
print(find(s,t))
``` | 0 | |
377 | A | Maze | PROGRAMMING | 1,600 | [
"dfs and similar"
] | null | null | Pavel loves grid mazes. A grid maze is an *n*<=×<=*m* rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly *k* empty cells into walls so that all the remaining cells still formed a connected area. Help him. | The first line contains three integers *n*, *m*, *k* (1<=≤<=*n*,<=*m*<=≤<=500, 0<=≤<=*k*<=<<=*s*), where *n* and *m* are the maze's height and width, correspondingly, *k* is the number of walls Pavel wants to add and letter *s* represents the number of empty cells in the original maze.
Each of the next *n* lines contains *m* characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall. | Print *n* lines containing *m* characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them. | [
"3 4 2\n#..#\n..#.\n#...\n",
"5 4 5\n#...\n#.#.\n.#..\n...#\n.#.#\n"
] | [
"#.X#\nX.#.\n#...\n",
"#XXX\n#X#.\nX#..\n...#\n.#.#\n"
] | none | 500 | [
{
"input": "5 4 5\n#...\n#.#.\n.#..\n...#\n.#.#",
"output": "#XXX\n#X#.\nX#..\n...#\n.#.#"
},
{
"input": "3 3 2\n#.#\n...\n#.#",
"output": "#X#\nX..\n#.#"
},
{
"input": "7 7 18\n#.....#\n..#.#..\n.#...#.\n...#...\n.#...#.\n..#.#..\n#.....#",
"output": "#XXXXX#\nXX#X#X.\nX#XXX#.\nXXX#... | 1,667,461,550 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 9 | 233 | 21,504,000 | from collections import defaultdict
grid = []
n,m,k = list(map(int, input().split()))
count = 0
def solve():
global n,m,k, count
for _ in range(n):
grid.append(list(input()))
total = 0
x,y = -1,-1
for i in range(n):
for j in range(m):
if grid[i][j] == '.':
grid[i][j] = 'X'
total += 1
x = i
y = j
stack = [(x,y)]
while stack:
if count == (total - k):
return
i,j = stack.pop()
count += 1
grid[i][j] = '.'
for dx,dy in [(0,1),(0,-1),(1,0),(-1,0)]:
n_i,n_j = i + dx , j + dy
if 0 <= n_i < n and 0 <= n_j < m and grid[n_i][n_j] == 'X':
stack.append((n_i, n_j))
solve()
for i in range(n):
print("".join(grid[i])) | Title: Maze
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Pavel loves grid mazes. A grid maze is an *n*<=×<=*m* rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly *k* empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input Specification:
The first line contains three integers *n*, *m*, *k* (1<=≤<=*n*,<=*m*<=≤<=500, 0<=≤<=*k*<=<<=*s*), where *n* and *m* are the maze's height and width, correspondingly, *k* is the number of walls Pavel wants to add and letter *s* represents the number of empty cells in the original maze.
Each of the next *n* lines contains *m* characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output Specification:
Print *n* lines containing *m* characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Demo Input:
['3 4 2\n#..#\n..#.\n#...\n', '5 4 5\n#...\n#.#.\n.#..\n...#\n.#.#\n']
Demo Output:
['#.X#\nX.#.\n#...\n', '#XXX\n#X#.\nX#..\n...#\n.#.#\n']
Note:
none | ```python
from collections import defaultdict
grid = []
n,m,k = list(map(int, input().split()))
count = 0
def solve():
global n,m,k, count
for _ in range(n):
grid.append(list(input()))
total = 0
x,y = -1,-1
for i in range(n):
for j in range(m):
if grid[i][j] == '.':
grid[i][j] = 'X'
total += 1
x = i
y = j
stack = [(x,y)]
while stack:
if count == (total - k):
return
i,j = stack.pop()
count += 1
grid[i][j] = '.'
for dx,dy in [(0,1),(0,-1),(1,0),(-1,0)]:
n_i,n_j = i + dx , j + dy
if 0 <= n_i < n and 0 <= n_j < m and grid[n_i][n_j] == 'X':
stack.append((n_i, n_j))
solve()
for i in range(n):
print("".join(grid[i]))
``` | 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,615,248,249 | 2,147,483,647 | Python 3 | OK | TESTS | 102 | 109 | 2,764,800 | from operator import xor
from typing import Callable, List, TypeVar, cast
F = TypeVar("F", bound=Callable[[], None])
def my_decorator(func: F) -> F:
def wrapper():
for _ in range(int(input("Times: "))):
func()
return cast(F, wrapper)
def main() -> None:
VALUES: List[str] = [input() for _ in range(2)]
print(f"{xor(*(int(value,2)for value in VALUES)):b}".zfill(len(VALUES[0])))
if __name__ == "__main__":
main()
| 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
from operator import xor
from typing import Callable, List, TypeVar, cast
F = TypeVar("F", bound=Callable[[], None])
def my_decorator(func: F) -> F:
def wrapper():
for _ in range(int(input("Times: "))):
func()
return cast(F, wrapper)
def main() -> None:
VALUES: List[str] = [input() for _ in range(2)]
print(f"{xor(*(int(value,2)for value in VALUES)):b}".zfill(len(VALUES[0])))
if __name__ == "__main__":
main()
``` | 3.9676 |
548 | A | Mike and Fax | PROGRAMMING | 1,100 | [
"brute force",
"implementation",
"strings"
] | null | null | While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string *s*.
He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly *k* messages in his own bag, each was a palindrome string and all those strings had the same length.
He asked you to help him and tell him if he has worn his own back-bag. Check if the given string *s* is a concatenation of *k* palindromes of the same length. | The first line of input contains string *s* containing lowercase English letters (1<=≤<=|*s*|<=≤<=1000).
The second line contains integer *k* (1<=≤<=*k*<=≤<=1000). | Print "YES"(without quotes) if he has worn his own back-bag or "NO"(without quotes) otherwise. | [
"saba\n2\n",
"saddastavvat\n2\n"
] | [
"NO\n",
"YES\n"
] | Palindrome is a string reading the same forward and backward.
In the second sample, the faxes in his back-bag can be "saddas" and "tavvat". | 500 | [
{
"input": "saba\n2",
"output": "NO"
},
{
"input": "saddastavvat\n2",
"output": "YES"
},
{
"input": "aaaaaaaaaa\n3",
"output": "NO"
},
{
"input": "aaaaaa\n3",
"output": "YES"
},
{
"input": "abaacca\n2",
"output": "NO"
},
{
"input": "a\n1",
"output"... | 1,657,257,121 | 2,147,483,647 | Python 3 | OK | TESTS | 56 | 46 | 0 | string = input()
partskitnekarnehai = int(input())
if len(string)%partskitnekarnehai!=0:
print('NO')
exit()
nayalength = len(string) // partskitnekarnehai
# o is length of part
for j in range(partskitnekarnehai):
seedha_part = string[ j*nayalength : (j + 1)*nayalength]
# print(seedha_part)
ulta_part=reversed(seedha_part)
# print("".join(ulta_part))
if seedha_part != "".join(ulta_part):
print("NO")
exit()
print("YES")
'''
https://codeforces.com/problemset/problem/548/A
1. Aaj exit() seekha, kaafi useful, i always thought agar aise kuch
karna hai to i'll have to define a function, fir use return to get
out of the code.
4. Abe yaar mai bhi kya gadha hu, like agar NO hai answer,
to exit karna chahiye, i exited on YES wala case
3. Are bhai yaaar wo sabse upar wala block mai bhool hi gaya tha,
gahdam ek aur wrong submission
2. Also line 7 me agar -1 kia to it only check first part of string
''' | Title: Mike and Fax
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string *s*.
He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly *k* messages in his own bag, each was a palindrome string and all those strings had the same length.
He asked you to help him and tell him if he has worn his own back-bag. Check if the given string *s* is a concatenation of *k* palindromes of the same length.
Input Specification:
The first line of input contains string *s* containing lowercase English letters (1<=≤<=|*s*|<=≤<=1000).
The second line contains integer *k* (1<=≤<=*k*<=≤<=1000).
Output Specification:
Print "YES"(without quotes) if he has worn his own back-bag or "NO"(without quotes) otherwise.
Demo Input:
['saba\n2\n', 'saddastavvat\n2\n']
Demo Output:
['NO\n', 'YES\n']
Note:
Palindrome is a string reading the same forward and backward.
In the second sample, the faxes in his back-bag can be "saddas" and "tavvat". | ```python
string = input()
partskitnekarnehai = int(input())
if len(string)%partskitnekarnehai!=0:
print('NO')
exit()
nayalength = len(string) // partskitnekarnehai
# o is length of part
for j in range(partskitnekarnehai):
seedha_part = string[ j*nayalength : (j + 1)*nayalength]
# print(seedha_part)
ulta_part=reversed(seedha_part)
# print("".join(ulta_part))
if seedha_part != "".join(ulta_part):
print("NO")
exit()
print("YES")
'''
https://codeforces.com/problemset/problem/548/A
1. Aaj exit() seekha, kaafi useful, i always thought agar aise kuch
karna hai to i'll have to define a function, fir use return to get
out of the code.
4. Abe yaar mai bhi kya gadha hu, like agar NO hai answer,
to exit karna chahiye, i exited on YES wala case
3. Are bhai yaaar wo sabse upar wala block mai bhool hi gaya tha,
gahdam ek aur wrong submission
2. Also line 7 me agar -1 kia to it only check first part of string
'''
``` | 3 | |
411 | A | Password Check | PROGRAMMING | 800 | [
"*special",
"implementation"
] | null | null | You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic check.
Web-developers of the company Q assume that a password is complex enough, if it meets all of the following conditions:
- the password length is at least 5 characters; - the password contains at least one large English letter; - the password contains at least one small English letter; - the password contains at least one digit.
You are given a password. Please implement the automatic check of its complexity for company Q. | The first line contains a non-empty sequence of characters (at most 100 characters). Each character is either a large English letter, or a small English letter, or a digit, or one of characters: "!", "?", ".", ",", "_". | If the password is complex enough, print message "Correct" (without the quotes), otherwise print message "Too weak" (without the quotes). | [
"abacaba\n",
"X12345\n",
"CONTEST_is_STARTED!!11\n"
] | [
"Too weak\n",
"Too weak\n",
"Correct\n"
] | none | 0 | [
{
"input": "abacaba",
"output": "Too weak"
},
{
"input": "X12345",
"output": "Too weak"
},
{
"input": "CONTEST_is_STARTED!!11",
"output": "Correct"
},
{
"input": "1zA__",
"output": "Correct"
},
{
"input": "1zA_",
"output": "Too weak"
},
{
"input": "zA_... | 1,618,994,030 | 2,147,483,647 | Python 3 | OK | TESTS | 81 | 93 | 819,200 | import string
def selection_sort(l):
for i in range(len(l)):
min_val = l[i]
min_val_index = i
for j in range(i, len(l)):
if l[j] < min_val:
min_val = l[j]
min_val_index = j
l[i], l[min_val_index] = l[min_val_index], l[i]
return l
def merge_sort(l):
def merge(l1, l2):
output_list = []
i, j = 0, 0
while i < len(l1) and j < len(l2):
if l1[i] < l2[j]:
output_list.append(l1[i])
i += 1
else:
output_list.append(l2[j])
j += 1
if i == len(l1):
output_list += l2[j:]
else:
output_list += l1[i:]
return output_list
def sort(li):
if len(li) < 2:
return li
mid = len(li) // 2
left = sort(li[:mid])
right = sort(li[mid:])
return merge(left, right)
return sort(l)
def main_function():
is_len_greater_than_5 = False
does_contain_digit = False
does_contain_upper = False
does_contain_lower = False
password = input()
if len(password) >= 5:
is_len_greater_than_5 = True
for i in password:
if i.isdigit():
does_contain_digit = True
elif i.isupper():
does_contain_upper = True
elif i.islower():
does_contain_lower = True
if is_len_greater_than_5 and does_contain_lower and does_contain_upper and does_contain_digit:
return "Correct"
return "Too weak"
print(main_function()) | Title: Password Check
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic check.
Web-developers of the company Q assume that a password is complex enough, if it meets all of the following conditions:
- the password length is at least 5 characters; - the password contains at least one large English letter; - the password contains at least one small English letter; - the password contains at least one digit.
You are given a password. Please implement the automatic check of its complexity for company Q.
Input Specification:
The first line contains a non-empty sequence of characters (at most 100 characters). Each character is either a large English letter, or a small English letter, or a digit, or one of characters: "!", "?", ".", ",", "_".
Output Specification:
If the password is complex enough, print message "Correct" (without the quotes), otherwise print message "Too weak" (without the quotes).
Demo Input:
['abacaba\n', 'X12345\n', 'CONTEST_is_STARTED!!11\n']
Demo Output:
['Too weak\n', 'Too weak\n', 'Correct\n']
Note:
none | ```python
import string
def selection_sort(l):
for i in range(len(l)):
min_val = l[i]
min_val_index = i
for j in range(i, len(l)):
if l[j] < min_val:
min_val = l[j]
min_val_index = j
l[i], l[min_val_index] = l[min_val_index], l[i]
return l
def merge_sort(l):
def merge(l1, l2):
output_list = []
i, j = 0, 0
while i < len(l1) and j < len(l2):
if l1[i] < l2[j]:
output_list.append(l1[i])
i += 1
else:
output_list.append(l2[j])
j += 1
if i == len(l1):
output_list += l2[j:]
else:
output_list += l1[i:]
return output_list
def sort(li):
if len(li) < 2:
return li
mid = len(li) // 2
left = sort(li[:mid])
right = sort(li[mid:])
return merge(left, right)
return sort(l)
def main_function():
is_len_greater_than_5 = False
does_contain_digit = False
does_contain_upper = False
does_contain_lower = False
password = input()
if len(password) >= 5:
is_len_greater_than_5 = True
for i in password:
if i.isdigit():
does_contain_digit = True
elif i.isupper():
does_contain_upper = True
elif i.islower():
does_contain_lower = True
if is_len_greater_than_5 and does_contain_lower and does_contain_upper and does_contain_digit:
return "Correct"
return "Too weak"
print(main_function())
``` | 3 | |
755 | C | PolandBall and Forest | PROGRAMMING | 1,300 | [
"dfs and similar",
"dsu",
"graphs",
"interactive",
"trees"
] | null | null | PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with *k* vertices and *k*<=-<=1 edges, where *k* is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to *n*. For each Ball *i* we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest? | The first line contains single integer *n* (1<=≤<=*n*<=≤<=104) — the number of Balls living in the forest.
The second line contains a sequence *p*1,<=*p*2,<=...,<=*p**n* of length *n*, where (1<=≤<=*p**i*<=≤<=*n*) holds and *p**i* denotes the most distant from Ball *i* relative living on the same tree. If there are several most distant relatives living on the same tree, *p**i* is the id of one with the smallest id.
It's guaranteed that the sequence *p* corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence *p* will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer *n* (1<=≤<=*n*<=≤<=104) — the number of Balls and the integer *m* (0<=≤<=*m*<=<<=*n*) — the total number of edges in the forest. Then *m* lines should follow. The *i*-th of them should contain two integers *a**i* and *b**i* and represent an edge between vertices in which relatives *a**i* and *b**i* live. For example, the first sample is written as follows: | You should output the number of trees in the forest where PolandBall lives. | [
"5\n2 1 5 3 3",
"1\n1\n"
] | [
"2",
"1"
] | In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree. | 1,500 | [
{
"input": "5 3\n1 2\n3 4\n4 5",
"output": "2"
},
{
"input": "1 0",
"output": "1"
},
{
"input": "5 1\n4 5",
"output": "4"
},
{
"input": "10 3\n2 8\n5 9\n6 10",
"output": "7"
},
{
"input": "18 2\n9 17\n1 18",
"output": "16"
},
{
"input": "1 0",
"out... | 1,629,203,300 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 13 | 77 | 8,089,600 |
# Problem: C. PolandBall and Forest
# Contest: Codeforces - 8VC Venture Cup 2017 - Elimination Round
# URL: https://codeforces.com/contest/755/problem/C
# Memory Limit: 256 MB
# Time Limit: 1000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)
from sys import stdin
def get_ints(): return list(map(int, stdin.readline().strip().split()))
class DSU:
def __init__(self, n):
# Constructor to create and
# initialize sets of n items
self.rank = [1] * n
self.parent = [i for i in range(n)]
# Finds set of given item x
def find(self, x):
# Finds the representative of the set
# that x is an element of
if (self.parent[x] != x):
# if x is not the parent of itself
# Then x is not the representative of
# its set,
self.parent[x] = self.find(self.parent[x])
# so we recursively call Find on its parent
# and move i's node directly under the
# representative of this set
return self.parent[x]
# Do union of two sets represented
# by x and y.
def Union(self, x, y):
# Find current sets of x and y
xset = self.find(x)
yset = self.find(y)
# If they are already in same set
if xset == yset:
return
# Put smaller ranked item under
# bigger ranked item if ranks are
# different
if self.rank[xset] < self.rank[yset]:
self.parent[xset] = yset
elif self.rank[xset] > self.rank[yset]:
self.parent[yset] = xset
# If ranks are same, then move y under
# x (doesn't matter which one goes where)
# and increment rank of x's tree
else:
self.parent[yset] = xset
self.rank[xset] = self.rank[xset] + 1
n = int(input())
dsu = DSU(n)
ar = get_ints()
for i in range(n):
dsu.Union(i,ar[i]-1)
print(len(set(dsu.parent))) | Title: PolandBall and Forest
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with *k* vertices and *k*<=-<=1 edges, where *k* is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to *n*. For each Ball *i* we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input Specification:
The first line contains single integer *n* (1<=≤<=*n*<=≤<=104) — the number of Balls living in the forest.
The second line contains a sequence *p*1,<=*p*2,<=...,<=*p**n* of length *n*, where (1<=≤<=*p**i*<=≤<=*n*) holds and *p**i* denotes the most distant from Ball *i* relative living on the same tree. If there are several most distant relatives living on the same tree, *p**i* is the id of one with the smallest id.
It's guaranteed that the sequence *p* corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence *p* will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer *n* (1<=≤<=*n*<=≤<=104) — the number of Balls and the integer *m* (0<=≤<=*m*<=<<=*n*) — the total number of edges in the forest. Then *m* lines should follow. The *i*-th of them should contain two integers *a**i* and *b**i* and represent an edge between vertices in which relatives *a**i* and *b**i* live. For example, the first sample is written as follows:
Output Specification:
You should output the number of trees in the forest where PolandBall lives.
Demo Input:
['5\n2 1 5 3 3', '1\n1\n']
Demo Output:
['2', '1']
Note:
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree. | ```python
# Problem: C. PolandBall and Forest
# Contest: Codeforces - 8VC Venture Cup 2017 - Elimination Round
# URL: https://codeforces.com/contest/755/problem/C
# Memory Limit: 256 MB
# Time Limit: 1000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)
from sys import stdin
def get_ints(): return list(map(int, stdin.readline().strip().split()))
class DSU:
def __init__(self, n):
# Constructor to create and
# initialize sets of n items
self.rank = [1] * n
self.parent = [i for i in range(n)]
# Finds set of given item x
def find(self, x):
# Finds the representative of the set
# that x is an element of
if (self.parent[x] != x):
# if x is not the parent of itself
# Then x is not the representative of
# its set,
self.parent[x] = self.find(self.parent[x])
# so we recursively call Find on its parent
# and move i's node directly under the
# representative of this set
return self.parent[x]
# Do union of two sets represented
# by x and y.
def Union(self, x, y):
# Find current sets of x and y
xset = self.find(x)
yset = self.find(y)
# If they are already in same set
if xset == yset:
return
# Put smaller ranked item under
# bigger ranked item if ranks are
# different
if self.rank[xset] < self.rank[yset]:
self.parent[xset] = yset
elif self.rank[xset] > self.rank[yset]:
self.parent[yset] = xset
# If ranks are same, then move y under
# x (doesn't matter which one goes where)
# and increment rank of x's tree
else:
self.parent[yset] = xset
self.rank[xset] = self.rank[xset] + 1
n = int(input())
dsu = DSU(n)
ar = get_ints()
for i in range(n):
dsu.Union(i,ar[i]-1)
print(len(set(dsu.parent)))
``` | 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,603,101,859 | 2,147,483,647 | Python 3 | OK | TESTS | 36 | 218 | 0 | m = max(list(map(int,input().split())))
if m==1: print('1/1')
elif m==2: print('5/6')
elif m==3: print('2/3')
elif m==4: print('1/2')
elif m==5: print('1/3')
else: print('1/6') | Title: Die Roll
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.
But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.
Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.
It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
Input Specification:
The only line of the input file contains two natural numbers Y and W — the results of Yakko's and Wakko's die rolls.
Output Specification:
Output the required probability in the form of irreducible fraction in format «A/B», where A — the numerator, and B — the denominator. If the required probability equals to zero, output «0/1». If the required probability equals to 1, output «1/1».
Demo Input:
['4 2\n']
Demo Output:
['1/2\n']
Note:
Dot will go to Transylvania, if she is lucky to roll 4, 5 or 6 points. | ```python
m = max(list(map(int,input().split())))
if m==1: print('1/1')
elif m==2: print('5/6')
elif m==3: print('2/3')
elif m==4: print('1/2')
elif m==5: print('1/3')
else: print('1/6')
``` | 3.891 |
227 | B | Effective Approach | PROGRAMMING | 1,100 | [
"implementation"
] | null | null | Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.
According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.
Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to *n*) and ending with the *n*-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the *n*-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.
To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to *n*, and generated *m* queries of the form: find element with value *b**i* in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.
But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute. | The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements in the array. The second line contains *n* distinct space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — the elements of array.
The third line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of queries. The last line contains *m* space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=*n*) — the search queries. Note that the queries can repeat. | Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. | [
"2\n1 2\n1\n1\n",
"2\n2 1\n1\n1\n",
"3\n3 1 2\n3\n1 2 3\n"
] | [
"1 2\n",
"2 1\n",
"6 6\n"
] | In the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).
In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element). | 1,000 | [
{
"input": "2\n1 2\n1\n1",
"output": "1 2"
},
{
"input": "2\n2 1\n1\n1",
"output": "2 1"
},
{
"input": "3\n3 1 2\n3\n1 2 3",
"output": "6 6"
},
{
"input": "9\n2 9 3 1 6 4 7 8 5\n9\n5 1 5 2 8 4 4 4 5",
"output": "58 32"
},
{
"input": "10\n3 10 9 2 7 6 5 8 4 1\n1\n4... | 1,696,536,861 | 2,147,483,647 | PyPy 3-64 | TIME_LIMIT_EXCEEDED | TESTS | 6 | 2,000 | 17,408,000 | from sys import stdin, stdout
def input():
return stdin.readline().strip()
def print(string):
return stdout.write(str(string) + "\n")
def main():
n, v, p = int(input()), 0, 0
a = [int(x) for x in input().split()]
m = int(input())
b = [int(x) for x in input().split()]
for i in range(m):
bi = a.index(b[i])
v += bi + 1
p += n - bi
print(f"{v} {p}")
if __name__ == "__main__":
main()
| Title: Effective Approach
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.
According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.
Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to *n*) and ending with the *n*-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the *n*-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.
To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to *n*, and generated *m* queries of the form: find element with value *b**i* in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.
But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements in the array. The second line contains *n* distinct space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — the elements of array.
The third line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of queries. The last line contains *m* space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=*n*) — the search queries. Note that the queries can repeat.
Output Specification:
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Demo Input:
['2\n1 2\n1\n1\n', '2\n2 1\n1\n1\n', '3\n3 1 2\n3\n1 2 3\n']
Demo Output:
['1 2\n', '2 1\n', '6 6\n']
Note:
In the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).
In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element). | ```python
from sys import stdin, stdout
def input():
return stdin.readline().strip()
def print(string):
return stdout.write(str(string) + "\n")
def main():
n, v, p = int(input()), 0, 0
a = [int(x) for x in input().split()]
m = int(input())
b = [int(x) for x in input().split()]
for i in range(m):
bi = a.index(b[i])
v += bi + 1
p += n - bi
print(f"{v} {p}")
if __name__ == "__main__":
main()
``` | 0 | |
225 | B | Well-known Numbers | PROGRAMMING | 1,600 | [
"binary search",
"greedy",
"number theory"
] | null | null | Numbers *k*-bonacci (*k* is integer, *k*<=><=1) are a generalization of Fibonacci numbers and are determined as follows:
- *F*(*k*,<=*n*)<==<=0, for integer *n*, 1<=≤<=*n*<=<<=*k*; - *F*(*k*,<=*k*)<==<=1; - *F*(*k*,<=*n*)<==<=*F*(*k*,<=*n*<=-<=1)<=+<=*F*(*k*,<=*n*<=-<=2)<=+<=...<=+<=*F*(*k*,<=*n*<=-<=*k*), for integer *n*, *n*<=><=*k*.
Note that we determine the *k*-bonacci numbers, *F*(*k*,<=*n*), only for integer values of *n* and *k*.
You've got a number *s*, represent it as a sum of several (at least two) distinct *k*-bonacci numbers. | The first line contains two integers *s* and *k* (1<=≤<=*s*,<=*k*<=≤<=109; *k*<=><=1). | In the first line print an integer *m* (*m*<=≥<=2) that shows how many numbers are in the found representation. In the second line print *m* distinct integers *a*1,<=*a*2,<=...,<=*a**m*. Each printed integer should be a *k*-bonacci number. The sum of printed integers must equal *s*.
It is guaranteed that the answer exists. If there are several possible answers, print any of them. | [
"5 2\n",
"21 5\n"
] | [
"3\n0 2 3\n",
"3\n4 1 16\n"
] | none | 1,000 | [
{
"input": "5 2",
"output": "3\n0 2 3"
},
{
"input": "21 5",
"output": "3\n4 1 16"
},
{
"input": "1 1000",
"output": "2\n1 0 "
},
{
"input": "1000000000 1000000000",
"output": "14\n536870912 268435456 134217728 33554432 16777216 8388608 1048576 524288 131072 32768 16384 2... | 1,642,937,340 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 60 | 0 | s = input().split()
(m,k) = (int(i) for i in s)
a = [0 for i in range(k-1)]
a.append(1)
i = 0
#print(a[-1],m)
while(a[-1] <= m):
a.append(sum(a[i:i+k]))
i += 1
res = []
res.append(a[-2])
m -= a[-2]
while(m>0):
if(m in a):
res.append(m)
m = 0
else:
res.append(1)
m -= 1
print(len(res))
res = res[::-1]
for i in range(len(res)):
print(res[i], end = ' ')
| Title: Well-known Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Numbers *k*-bonacci (*k* is integer, *k*<=><=1) are a generalization of Fibonacci numbers and are determined as follows:
- *F*(*k*,<=*n*)<==<=0, for integer *n*, 1<=≤<=*n*<=<<=*k*; - *F*(*k*,<=*k*)<==<=1; - *F*(*k*,<=*n*)<==<=*F*(*k*,<=*n*<=-<=1)<=+<=*F*(*k*,<=*n*<=-<=2)<=+<=...<=+<=*F*(*k*,<=*n*<=-<=*k*), for integer *n*, *n*<=><=*k*.
Note that we determine the *k*-bonacci numbers, *F*(*k*,<=*n*), only for integer values of *n* and *k*.
You've got a number *s*, represent it as a sum of several (at least two) distinct *k*-bonacci numbers.
Input Specification:
The first line contains two integers *s* and *k* (1<=≤<=*s*,<=*k*<=≤<=109; *k*<=><=1).
Output Specification:
In the first line print an integer *m* (*m*<=≥<=2) that shows how many numbers are in the found representation. In the second line print *m* distinct integers *a*1,<=*a*2,<=...,<=*a**m*. Each printed integer should be a *k*-bonacci number. The sum of printed integers must equal *s*.
It is guaranteed that the answer exists. If there are several possible answers, print any of them.
Demo Input:
['5 2\n', '21 5\n']
Demo Output:
['3\n0 2 3\n', '3\n4 1 16\n']
Note:
none | ```python
s = input().split()
(m,k) = (int(i) for i in s)
a = [0 for i in range(k-1)]
a.append(1)
i = 0
#print(a[-1],m)
while(a[-1] <= m):
a.append(sum(a[i:i+k]))
i += 1
res = []
res.append(a[-2])
m -= a[-2]
while(m>0):
if(m in a):
res.append(m)
m = 0
else:
res.append(1)
m -= 1
print(len(res))
res = res[::-1]
for i in range(len(res)):
print(res[i], end = ' ')
``` | 0 | |
688 | B | Lovely Palindromes | PROGRAMMING | 1,000 | [
"constructive algorithms",
"math"
] | null | null | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.
Now Pari asks you to write a program that gets a huge integer *n* from the input and tells what is the *n*-th even-length positive palindrome number? | The only line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=10100<=000). | Print the *n*-th even-length palindrome number. | [
"1\n",
"10\n"
] | [
"11\n",
"1001\n"
] | The first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | 1,000 | [
{
"input": "1",
"output": "11"
},
{
"input": "10",
"output": "1001"
},
{
"input": "11",
"output": "1111"
},
{
"input": "12",
"output": "1221"
},
{
"input": "100",
"output": "100001"
},
{
"input": "1321",
"output": "13211231"
},
{
"input": "... | 1,672,745,218 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 30 | 0 | n=input()
print(n+n[-1:])
| Title: Lovely Palindromes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.
Now Pari asks you to write a program that gets a huge integer *n* from the input and tells what is the *n*-th even-length positive palindrome number?
Input Specification:
The only line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=10100<=000).
Output Specification:
Print the *n*-th even-length palindrome number.
Demo Input:
['1\n', '10\n']
Demo Output:
['11\n', '1001\n']
Note:
The first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | ```python
n=input()
print(n+n[-1:])
``` | 0 | |
701 | A | Cards | PROGRAMMING | 800 | [
"greedy",
"implementation"
] | null | null | There are *n* cards (*n* is even) in the deck. Each card has a positive integer written on it. *n*<=/<=2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible. | The first line of the input contains integer *n* (2<=≤<=*n*<=≤<=100) — the number of cards in the deck. It is guaranteed that *n* is even.
The second line contains the sequence of *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100), where *a**i* is equal to the number written on the *i*-th card. | Print *n*<=/<=2 pairs of integers, the *i*-th pair denote the cards that should be given to the *i*-th player. Each card should be given to exactly one player. Cards are numbered in the order they appear in the input.
It is guaranteed that solution exists. If there are several correct answers, you are allowed to print any of them. | [
"6\n1 5 7 4 4 3\n",
"4\n10 10 10 10\n"
] | [
"1 3\n6 2\n4 5\n",
"1 2\n3 4\n"
] | In the first sample, cards are distributed in such a way that each player has the sum of numbers written on his cards equal to 8.
In the second sample, all values *a*<sub class="lower-index">*i*</sub> are equal. Thus, any distribution is acceptable. | 500 | [
{
"input": "6\n1 5 7 4 4 3",
"output": "1 3\n6 2\n4 5"
},
{
"input": "4\n10 10 10 10",
"output": "1 4\n2 3"
},
{
"input": "100\n2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ... | 1,570,361,214 | 2,147,483,647 | Python 3 | OK | TESTS | 35 | 109 | 0 | n=int(input())
l=list(map(int,input().split()))
a=[]
for q in range(n):
a.append([l[q],q])
a.sort()
for q in range(n//2):
print(a[q][1]+1,a[n-q-1][1]+1) | Title: Cards
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* cards (*n* is even) in the deck. Each card has a positive integer written on it. *n*<=/<=2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.
Input Specification:
The first line of the input contains integer *n* (2<=≤<=*n*<=≤<=100) — the number of cards in the deck. It is guaranteed that *n* is even.
The second line contains the sequence of *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100), where *a**i* is equal to the number written on the *i*-th card.
Output Specification:
Print *n*<=/<=2 pairs of integers, the *i*-th pair denote the cards that should be given to the *i*-th player. Each card should be given to exactly one player. Cards are numbered in the order they appear in the input.
It is guaranteed that solution exists. If there are several correct answers, you are allowed to print any of them.
Demo Input:
['6\n1 5 7 4 4 3\n', '4\n10 10 10 10\n']
Demo Output:
['1 3\n6 2\n4 5\n', '1 2\n3 4\n']
Note:
In the first sample, cards are distributed in such a way that each player has the sum of numbers written on his cards equal to 8.
In the second sample, all values *a*<sub class="lower-index">*i*</sub> are equal. Thus, any distribution is acceptable. | ```python
n=int(input())
l=list(map(int,input().split()))
a=[]
for q in range(n):
a.append([l[q],q])
a.sort()
for q in range(n//2):
print(a[q][1]+1,a[n-q-1][1]+1)
``` | 3 | |
937 | A | Olympiad | PROGRAMMING | 800 | [
"implementation",
"sortings"
] | null | null | The recent All-Berland Olympiad in Informatics featured *n* participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
- At least one participant should get a diploma. - None of those with score equal to zero should get awarded. - When someone is awarded, all participants with score not less than his score should also be awarded.
Determine the number of ways to choose a subset of participants that will receive the diplomas. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of participants.
The next line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=600) — participants' scores.
It's guaranteed that at least one participant has non-zero score. | Print a single integer — the desired number of ways. | [
"4\n1 3 3 2\n",
"3\n1 1 1\n",
"4\n42 0 0 42\n"
] | [
"3\n",
"1\n",
"1\n"
] | There are three ways to choose a subset in sample case one.
1. Only participants with 3 points will get diplomas. 1. Participants with 2 or 3 points will get diplomas. 1. Everyone will get a diploma!
The only option in sample case two is to award everyone.
Note that in sample case three participants with zero scores cannot get anything. | 500 | [
{
"input": "4\n1 3 3 2",
"output": "3"
},
{
"input": "3\n1 1 1",
"output": "1"
},
{
"input": "4\n42 0 0 42",
"output": "1"
},
{
"input": "10\n1 0 1 0 1 0 0 0 0 1",
"output": "1"
},
{
"input": "10\n572 471 540 163 50 30 561 510 43 200",
"output": "10"
},
{
... | 1,671,085,105 | 2,147,483,647 | Python 3 | OK | TESTS | 21 | 46 | 0 | n=int(input())
a=list(map(int,input().split()))
sa=set(a)
arr=list(sa)
count=0
for i in sa:
if i!=0:
count+=1
print(count)
| Title: Olympiad
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The recent All-Berland Olympiad in Informatics featured *n* participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
- At least one participant should get a diploma. - None of those with score equal to zero should get awarded. - When someone is awarded, all participants with score not less than his score should also be awarded.
Determine the number of ways to choose a subset of participants that will receive the diplomas.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of participants.
The next line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=600) — participants' scores.
It's guaranteed that at least one participant has non-zero score.
Output Specification:
Print a single integer — the desired number of ways.
Demo Input:
['4\n1 3 3 2\n', '3\n1 1 1\n', '4\n42 0 0 42\n']
Demo Output:
['3\n', '1\n', '1\n']
Note:
There are three ways to choose a subset in sample case one.
1. Only participants with 3 points will get diplomas. 1. Participants with 2 or 3 points will get diplomas. 1. Everyone will get a diploma!
The only option in sample case two is to award everyone.
Note that in sample case three participants with zero scores cannot get anything. | ```python
n=int(input())
a=list(map(int,input().split()))
sa=set(a)
arr=list(sa)
count=0
for i in sa:
if i!=0:
count+=1
print(count)
``` | 3 | |
990 | B | Micro-World | PROGRAMMING | 1,200 | [
"greedy",
"sortings"
] | null | null | You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.
You know that you have $n$ bacteria in the Petri dish and size of the $i$-th bacteria is $a_i$. Also you know intergalactic positive integer constant $K$.
The $i$-th bacteria can swallow the $j$-th bacteria if and only if $a_i > a_j$ and $a_i \le a_j + K$. The $j$-th bacteria disappear, but the $i$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $i$ can swallow any bacteria $j$ if $a_i > a_j$ and $a_i \le a_j + K$. The swallow operations go one after another.
For example, the sequence of bacteria sizes $a=[101, 53, 42, 102, 101, 55, 54]$ and $K=1$. The one of possible sequences of swallows is: $[101, 53, 42, 102, \underline{101}, 55, 54]$ $\to$ $[101, \underline{53}, 42, 102, 55, 54]$ $\to$ $[\underline{101}, 42, 102, 55, 54]$ $\to$ $[42, 102, 55, \underline{54}]$ $\to$ $[42, 102, 55]$. In total there are $3$ bacteria remained in the Petri dish.
Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope. | The first line contains two space separated positive integers $n$ and $K$ ($1 \le n \le 2 \cdot 10^5$, $1 \le K \le 10^6$) — number of bacteria and intergalactic constant $K$.
The second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^6$) — sizes of bacteria you have. | Print the only integer — minimal possible number of bacteria can remain. | [
"7 1\n101 53 42 102 101 55 54\n",
"6 5\n20 15 10 15 20 25\n",
"7 1000000\n1 1 1 1 1 1 1\n"
] | [
"3\n",
"1\n",
"7\n"
] | The first example is clarified in the problem statement.
In the second example an optimal possible sequence of swallows is: $[20, 15, 10, 15, \underline{20}, 25]$ $\to$ $[20, 15, 10, \underline{15}, 25]$ $\to$ $[20, 15, \underline{10}, 25]$ $\to$ $[20, \underline{15}, 25]$ $\to$ $[\underline{20}, 25]$ $\to$ $[25]$.
In the third example no bacteria can swallow any other bacteria. | 0 | [
{
"input": "7 1\n101 53 42 102 101 55 54",
"output": "3"
},
{
"input": "6 5\n20 15 10 15 20 25",
"output": "1"
},
{
"input": "7 1000000\n1 1 1 1 1 1 1",
"output": "7"
},
{
"input": "1 1\n1",
"output": "1"
},
{
"input": "1 4\n8",
"output": "1"
},
{
"inp... | 1,553,015,310 | 2,147,483,647 | Python 3 | OK | TESTS | 36 | 358 | 14,643,200 | n, K = map(int, input().split())
a = sorted(list(map(int, input().split())))
num = 0
for i in a:
while a[num] < i:
if i <= K+a[num]:
n-=1
num += 1
print(n)
| Title: Micro-World
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.
You know that you have $n$ bacteria in the Petri dish and size of the $i$-th bacteria is $a_i$. Also you know intergalactic positive integer constant $K$.
The $i$-th bacteria can swallow the $j$-th bacteria if and only if $a_i > a_j$ and $a_i \le a_j + K$. The $j$-th bacteria disappear, but the $i$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $i$ can swallow any bacteria $j$ if $a_i > a_j$ and $a_i \le a_j + K$. The swallow operations go one after another.
For example, the sequence of bacteria sizes $a=[101, 53, 42, 102, 101, 55, 54]$ and $K=1$. The one of possible sequences of swallows is: $[101, 53, 42, 102, \underline{101}, 55, 54]$ $\to$ $[101, \underline{53}, 42, 102, 55, 54]$ $\to$ $[\underline{101}, 42, 102, 55, 54]$ $\to$ $[42, 102, 55, \underline{54}]$ $\to$ $[42, 102, 55]$. In total there are $3$ bacteria remained in the Petri dish.
Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.
Input Specification:
The first line contains two space separated positive integers $n$ and $K$ ($1 \le n \le 2 \cdot 10^5$, $1 \le K \le 10^6$) — number of bacteria and intergalactic constant $K$.
The second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^6$) — sizes of bacteria you have.
Output Specification:
Print the only integer — minimal possible number of bacteria can remain.
Demo Input:
['7 1\n101 53 42 102 101 55 54\n', '6 5\n20 15 10 15 20 25\n', '7 1000000\n1 1 1 1 1 1 1\n']
Demo Output:
['3\n', '1\n', '7\n']
Note:
The first example is clarified in the problem statement.
In the second example an optimal possible sequence of swallows is: $[20, 15, 10, 15, \underline{20}, 25]$ $\to$ $[20, 15, 10, \underline{15}, 25]$ $\to$ $[20, 15, \underline{10}, 25]$ $\to$ $[20, \underline{15}, 25]$ $\to$ $[\underline{20}, 25]$ $\to$ $[25]$.
In the third example no bacteria can swallow any other bacteria. | ```python
n, K = map(int, input().split())
a = sorted(list(map(int, input().split())))
num = 0
for i in a:
while a[num] < i:
if i <= K+a[num]:
n-=1
num += 1
print(n)
``` | 3 | |
71 | A | Way Too Long Words | PROGRAMMING | 800 | [
"strings"
] | A. Way Too Long Words | 1 | 256 | Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). Each of the following *n* lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters. | Print *n* lines. The *i*-th line should contain the result of replacing of the *i*-th word from the input data. | [
"4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis\n"
] | [
"word\nl10n\ni18n\np43s\n"
] | none | 500 | [
{
"input": "4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis",
"output": "word\nl10n\ni18n\np43s"
},
{
"input": "5\nabcdefgh\nabcdefghi\nabcdefghij\nabcdefghijk\nabcdefghijklm",
"output": "abcdefgh\nabcdefghi\nabcdefghij\na9k\na11m"
},
{
"input":... | 1,688,908,307 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 30 | 0 | t=int(input())
for i in range(t):
w=input("")
l=len(w)
s=w[1:l-1]
print("word")if l<=10 else print(w[0]+str(len(s))+w[l-1])
| Title: Way Too Long Words
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). Each of the following *n* lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output Specification:
Print *n* lines. The *i*-th line should contain the result of replacing of the *i*-th word from the input data.
Demo Input:
['4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis\n']
Demo Output:
['word\nl10n\ni18n\np43s\n']
Note:
none | ```python
t=int(input())
for i in range(t):
w=input("")
l=len(w)
s=w[1:l-1]
print("word")if l<=10 else print(w[0]+str(len(s))+w[l-1])
``` | 0 |
954 | A | Diagonal Walking | PROGRAMMING | 800 | [
"implementation"
] | null | null | Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.
Your problem is to print the minimum possible length of the sequence of moves after the replacements. | The first line of the input contains one integer *n* (1<=≤<=*n*<=≤<=100) — the length of the sequence. The second line contains the sequence consisting of *n* characters U and R. | Print the minimum possible length of the sequence of moves after all replacements are done. | [
"5\nRUURU\n",
"17\nUUURRRRRUUURURUUU\n"
] | [
"3\n",
"13\n"
] | In the first test the shortened sequence of moves may be DUD (its length is 3).
In the second test the shortened sequence of moves can be UUDRRRDUDDUUU (its length is 13). | 0 | [
{
"input": "5\nRUURU",
"output": "3"
},
{
"input": "17\nUUURRRRRUUURURUUU",
"output": "13"
},
{
"input": "100\nUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU",
"output": "100"
},
{
"input": "100\nRRURRUUUURURRRURRRRURRRRRR... | 1,637,228,111 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 31 | 0 | n = input()
s= len(n)
j =n.count('RU' and 'UR')
print((s-(j*2))+j-1) | Title: Diagonal Walking
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.
Your problem is to print the minimum possible length of the sequence of moves after the replacements.
Input Specification:
The first line of the input contains one integer *n* (1<=≤<=*n*<=≤<=100) — the length of the sequence. The second line contains the sequence consisting of *n* characters U and R.
Output Specification:
Print the minimum possible length of the sequence of moves after all replacements are done.
Demo Input:
['5\nRUURU\n', '17\nUUURRRRRUUURURUUU\n']
Demo Output:
['3\n', '13\n']
Note:
In the first test the shortened sequence of moves may be DUD (its length is 3).
In the second test the shortened sequence of moves can be UUDRRRDUDDUUU (its length is 13). | ```python
n = input()
s= len(n)
j =n.count('RU' and 'UR')
print((s-(j*2))+j-1)
``` | 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,697,790,922 | 2,147,483,647 | Python 3 | OK | TESTS | 31 | 92 | 0 | teams=int(input())
matches=[]
for i in range(teams):
z=list(map(int,input().split(' ')))
matches.append(z)
out=0
for i in matches:
for m in matches:
if i[0]==m[1]:
out+=1
print(out)
| 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
teams=int(input())
matches=[]
for i in range(teams):
z=list(map(int,input().split(' ')))
matches.append(z)
out=0
for i in matches:
for m in matches:
if i[0]==m[1]:
out+=1
print(out)
``` | 3 | |
415 | A | Mashmokh and Lights | PROGRAMMING | 900 | [
"implementation"
] | null | null | Mashmokh works in a factory. At the end of each day he must turn off all of the lights.
The lights on the factory are indexed from 1 to *n*. There are *n* buttons in Mashmokh's room indexed from 1 to *n* as well. If Mashmokh pushes button with index *i*, then each light with index not less than *i* that is still turned on turns off.
Mashmokh is not very clever. So instead of pushing the first button he pushes some of the buttons randomly each night. He pushed *m* distinct buttons *b*1,<=*b*2,<=...,<=*b**m* (the buttons were pushed consecutively in the given order) this night. Now he wants to know for each light the index of the button that turned this light off. Please note that the index of button *b**i* is actually *b**i*, not *i*.
Please, help Mashmokh, print these indices. | The first line of the input contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100), the number of the factory lights and the pushed buttons respectively. The next line contains *m* distinct space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=*n*).
It is guaranteed that all lights will be turned off after pushing all buttons. | Output *n* space-separated integers where the *i*-th number is index of the button that turns the *i*-th light off. | [
"5 4\n4 3 1 2\n",
"5 5\n5 4 3 2 1\n"
] | [
"1 1 3 4 4 \n",
"1 2 3 4 5 \n"
] | In the first sample, after pressing button number 4, lights 4 and 5 are turned off and lights 1, 2 and 3 are still on. Then after pressing button number 3, light number 3 is turned off as well. Pressing button number 1 turns off lights number 1 and 2 as well so pressing button number 2 in the end has no effect. Thus button number 4 turned lights 4 and 5 off, button number 3 turned light 3 off and button number 1 turned light 1 and 2 off. | 500 | [
{
"input": "5 4\n4 3 1 2",
"output": "1 1 3 4 4 "
},
{
"input": "5 5\n5 4 3 2 1",
"output": "1 2 3 4 5 "
},
{
"input": "16 11\n8 5 12 10 14 2 6 3 15 9 1",
"output": "1 2 2 2 5 5 5 8 8 8 8 8 8 8 8 8 "
},
{
"input": "79 22\n76 32 48 28 33 44 58 59 1 51 77 13 15 64 49 72 74 21 6... | 1,556,639,925 | 2,147,483,647 | Python 3 | OK | TESTS | 31 | 109 | 0 | def main():
[n, m] = [int(_) for _ in input().split()]
buttons = [int(_) for _ in input().split()]
# index = 0
# while index < len(buttons) - 1:
# button = buttons[index]
# buttons = buttons[:(index + 1)] + [buttons[i] for i in range(index + 1, len(buttons)) if buttons[i] < button]
# index += 1
lights = [0] * (n + 1)
for button in buttons:
i = button
while i <= n and lights[i] == 0:
lights[i] = button
i += 1
result = ' '.join([str(lights[i]) for i in range(1, n + 1)])
print(result)
if __name__ == '__main__':
main()
| Title: Mashmokh and Lights
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mashmokh works in a factory. At the end of each day he must turn off all of the lights.
The lights on the factory are indexed from 1 to *n*. There are *n* buttons in Mashmokh's room indexed from 1 to *n* as well. If Mashmokh pushes button with index *i*, then each light with index not less than *i* that is still turned on turns off.
Mashmokh is not very clever. So instead of pushing the first button he pushes some of the buttons randomly each night. He pushed *m* distinct buttons *b*1,<=*b*2,<=...,<=*b**m* (the buttons were pushed consecutively in the given order) this night. Now he wants to know for each light the index of the button that turned this light off. Please note that the index of button *b**i* is actually *b**i*, not *i*.
Please, help Mashmokh, print these indices.
Input Specification:
The first line of the input contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100), the number of the factory lights and the pushed buttons respectively. The next line contains *m* distinct space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=*n*).
It is guaranteed that all lights will be turned off after pushing all buttons.
Output Specification:
Output *n* space-separated integers where the *i*-th number is index of the button that turns the *i*-th light off.
Demo Input:
['5 4\n4 3 1 2\n', '5 5\n5 4 3 2 1\n']
Demo Output:
['1 1 3 4 4 \n', '1 2 3 4 5 \n']
Note:
In the first sample, after pressing button number 4, lights 4 and 5 are turned off and lights 1, 2 and 3 are still on. Then after pressing button number 3, light number 3 is turned off as well. Pressing button number 1 turns off lights number 1 and 2 as well so pressing button number 2 in the end has no effect. Thus button number 4 turned lights 4 and 5 off, button number 3 turned light 3 off and button number 1 turned light 1 and 2 off. | ```python
def main():
[n, m] = [int(_) for _ in input().split()]
buttons = [int(_) for _ in input().split()]
# index = 0
# while index < len(buttons) - 1:
# button = buttons[index]
# buttons = buttons[:(index + 1)] + [buttons[i] for i in range(index + 1, len(buttons)) if buttons[i] < button]
# index += 1
lights = [0] * (n + 1)
for button in buttons:
i = button
while i <= n and lights[i] == 0:
lights[i] = button
i += 1
result = ' '.join([str(lights[i]) for i in range(1, n + 1)])
print(result)
if __name__ == '__main__':
main()
``` | 3 | |
897 | A | Scarborough Fair | PROGRAMMING | 800 | [
"implementation"
] | null | null | Parsley, sage, rosemary and thyme.
Remember me to one who lives there.
He once was the true love of mine.
Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.
Willem asks his friend, Grick for directions, Grick helped them, and gave them a task.
Although the girl wants to help, Willem insists on doing it by himself.
Grick gave Willem a string of length *n*.
Willem needs to do *m* operations, each operation has four parameters *l*,<=*r*,<=*c*1,<=*c*2, which means that all symbols *c*1 in range [*l*,<=*r*] (from *l*-th to *r*-th, including *l* and *r*) are changed into *c*2. String is 1-indexed.
Grick wants to know the final string after all the *m* operations. | The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100).
The second line contains a string *s* of length *n*, consisting of lowercase English letters.
Each of the next *m* lines contains four parameters *l*,<=*r*,<=*c*1,<=*c*2 (1<=≤<=*l*<=≤<=*r*<=≤<=*n*, *c*1,<=*c*2 are lowercase English letters), separated by space. | Output string *s* after performing *m* operations described above. | [
"3 1\nioi\n1 1 i n\n",
"5 3\nwxhak\n3 3 h x\n1 5 x a\n1 3 w g\n"
] | [
"noi",
"gaaak"
] | For the second example:
After the first operation, the string is wxxak.
After the second operation, the string is waaak.
After the third operation, the string is gaaak. | 500 | [
{
"input": "3 1\nioi\n1 1 i n",
"output": "noi"
},
{
"input": "5 3\nwxhak\n3 3 h x\n1 5 x a\n1 3 w g",
"output": "gaaak"
},
{
"input": "9 51\nbhfbdcgff\n2 3 b b\n2 8 e f\n3 8 g f\n5 7 d a\n1 5 e b\n3 4 g b\n6 7 c d\n3 6 e g\n3 6 e h\n5 6 a e\n7 9 a c\n4 9 a h\n3 7 c b\n6 9 b g\n1 7 h b\n... | 1,619,169,874 | 2,147,483,647 | PyPy 3 | OK | TESTS | 47 | 108 | 2,560,000 | n, m = map(int, input().rstrip().split())
s=list(input())
for i in range(m):
l, r, c1,c2 = map(str,input().rstrip().split())
for j in range(int(l)-1,int(r)):
if s[j]==c1:
s[j]=c2
print("".join(s)) | Title: Scarborough Fair
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Parsley, sage, rosemary and thyme.
Remember me to one who lives there.
He once was the true love of mine.
Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.
Willem asks his friend, Grick for directions, Grick helped them, and gave them a task.
Although the girl wants to help, Willem insists on doing it by himself.
Grick gave Willem a string of length *n*.
Willem needs to do *m* operations, each operation has four parameters *l*,<=*r*,<=*c*1,<=*c*2, which means that all symbols *c*1 in range [*l*,<=*r*] (from *l*-th to *r*-th, including *l* and *r*) are changed into *c*2. String is 1-indexed.
Grick wants to know the final string after all the *m* operations.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100).
The second line contains a string *s* of length *n*, consisting of lowercase English letters.
Each of the next *m* lines contains four parameters *l*,<=*r*,<=*c*1,<=*c*2 (1<=≤<=*l*<=≤<=*r*<=≤<=*n*, *c*1,<=*c*2 are lowercase English letters), separated by space.
Output Specification:
Output string *s* after performing *m* operations described above.
Demo Input:
['3 1\nioi\n1 1 i n\n', '5 3\nwxhak\n3 3 h x\n1 5 x a\n1 3 w g\n']
Demo Output:
['noi', 'gaaak']
Note:
For the second example:
After the first operation, the string is wxxak.
After the second operation, the string is waaak.
After the third operation, the string is gaaak. | ```python
n, m = map(int, input().rstrip().split())
s=list(input())
for i in range(m):
l, r, c1,c2 = map(str,input().rstrip().split())
for j in range(int(l)-1,int(r)):
if s[j]==c1:
s[j]=c2
print("".join(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,681,107,614 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 9 | 92 | 716,800 | #!/bin/python3
import math
import os
import random
import re
import sys
n = int(input())
visited = [0]*2001
checks = []
for i in range(1, n+1):
t = int(input())
checks.append([t, i])
checks.sort()
for x in range(0, len(checks)):
i = checks[x][1]
t = checks[x][0]
if t == -1:
visited[i] = 1
else:
visited[i] = visited[t]+1
print(max(visited))
| 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
#!/bin/python3
import math
import os
import random
import re
import sys
n = int(input())
visited = [0]*2001
checks = []
for i in range(1, n+1):
t = int(input())
checks.append([t, i])
checks.sort()
for x in range(0, len(checks)):
i = checks[x][1]
t = checks[x][0]
if t == -1:
visited[i] = 1
else:
visited[i] = visited[t]+1
print(max(visited))
``` | 0 | |
934 | A | A Compatible Pair | PROGRAMMING | 1,400 | [
"brute force",
"games"
] | null | null | Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.
Little Tommy has *n* lanterns and Big Banban has *m* lanterns. Tommy's lanterns have brightness *a*1,<=*a*2,<=...,<=*a**n*, and Banban's have brightness *b*1,<=*b*2,<=...,<=*b**m* respectively.
Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.
Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible.
You are asked to find the brightness of the chosen pair if both of them choose optimally. | The first line contains two space-separated integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=50).
The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n*.
The third line contains *m* space-separated integers *b*1,<=*b*2,<=...,<=*b**m*.
All the integers range from <=-<=109 to 109. | Print a single integer — the brightness of the chosen pair. | [
"2 2\n20 18\n2 14\n",
"5 3\n-1 0 1 2 3\n-1 0 1\n"
] | [
"252\n",
"2\n"
] | In the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself.
In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself. | 500 | [
{
"input": "2 2\n20 18\n2 14",
"output": "252"
},
{
"input": "5 3\n-1 0 1 2 3\n-1 0 1",
"output": "2"
},
{
"input": "10 2\n1 6 2 10 2 3 2 10 6 4\n5 7",
"output": "70"
},
{
"input": "50 50\n1 6 2 10 2 3 2 10 6 4 5 0 3 1 7 3 2 4 4 2 1 5 0 6 10 1 8 0 10 9 0 4 10 5 5 7 4 9 9 5 5 ... | 1,529,575,877 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 9 | 77 | 0 | n1,n2=map(int,input().split())
l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
l1.sort()
l2.sort(reverse=True)
print(l1[-2]*l2[0]) | Title: A Compatible Pair
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.
Little Tommy has *n* lanterns and Big Banban has *m* lanterns. Tommy's lanterns have brightness *a*1,<=*a*2,<=...,<=*a**n*, and Banban's have brightness *b*1,<=*b*2,<=...,<=*b**m* respectively.
Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.
Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible.
You are asked to find the brightness of the chosen pair if both of them choose optimally.
Input Specification:
The first line contains two space-separated integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=50).
The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n*.
The third line contains *m* space-separated integers *b*1,<=*b*2,<=...,<=*b**m*.
All the integers range from <=-<=109 to 109.
Output Specification:
Print a single integer — the brightness of the chosen pair.
Demo Input:
['2 2\n20 18\n2 14\n', '5 3\n-1 0 1 2 3\n-1 0 1\n']
Demo Output:
['252\n', '2\n']
Note:
In the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself.
In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself. | ```python
n1,n2=map(int,input().split())
l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
l1.sort()
l2.sort(reverse=True)
print(l1[-2]*l2[0])
``` | 0 | |
698 | A | Vacations | PROGRAMMING | 1,400 | [
"dp"
] | null | null | Vasya has *n* days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this *n* days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the *i*-th day there are four options:
1. on this day the gym is closed and the contest is not carried out; 1. on this day the gym is closed and the contest is carried out; 1. on this day the gym is open and the contest is not carried out; 1. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. | The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100) — the number of days of Vasya's vacations.
The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=3) separated by space, where:
- *a**i* equals 0, if on the *i*-th day of vacations the gym is closed and the contest is not carried out; - *a**i* equals 1, if on the *i*-th day of vacations the gym is closed, but the contest is carried out; - *a**i* equals 2, if on the *i*-th day of vacations the gym is open and the contest is not carried out; - *a**i* equals 3, if on the *i*-th day of vacations the gym is open and the contest is carried out. | Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
- to do sport on any two consecutive days, - to write the contest on any two consecutive days. | [
"4\n1 3 2 0\n",
"7\n1 3 3 2 1 2 3\n",
"2\n2 2\n"
] | [
"2\n",
"0\n",
"1\n"
] | In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. | 500 | [
{
"input": "4\n1 3 2 0",
"output": "2"
},
{
"input": "7\n1 3 3 2 1 2 3",
"output": "0"
},
{
"input": "2\n2 2",
"output": "1"
},
{
"input": "1\n0",
"output": "1"
},
{
"input": "10\n0 0 1 1 0 0 0 0 1 0",
"output": "8"
},
{
"input": "100\n3 2 3 3 3 2 3 1 ... | 1,666,420,095 | 2,147,483,647 | Python 3 | OK | TESTS | 88 | 62 | 716,800 | from calendar import calendar
def List():
return list(map(int,input().split()))
def Lst():
return list(input())
def Int():
return int(input())
def two():
return map(int,input().split())
numOfVactions = Int()
calendar = List()
outPut = 0
prevState = 0
for currState in calendar:
if currState == 3:
prevState = currState - prevState
elif currState == 0 or currState == prevState:
outPut +=1
prevState = 0
else:
prevState = currState
print(outPut)
| Title: Vacations
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has *n* days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this *n* days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the *i*-th day there are four options:
1. on this day the gym is closed and the contest is not carried out; 1. on this day the gym is closed and the contest is carried out; 1. on this day the gym is open and the contest is not carried out; 1. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input Specification:
The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100) — the number of days of Vasya's vacations.
The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=3) separated by space, where:
- *a**i* equals 0, if on the *i*-th day of vacations the gym is closed and the contest is not carried out; - *a**i* equals 1, if on the *i*-th day of vacations the gym is closed, but the contest is carried out; - *a**i* equals 2, if on the *i*-th day of vacations the gym is open and the contest is not carried out; - *a**i* equals 3, if on the *i*-th day of vacations the gym is open and the contest is carried out.
Output Specification:
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
- to do sport on any two consecutive days, - to write the contest on any two consecutive days.
Demo Input:
['4\n1 3 2 0\n', '7\n1 3 3 2 1 2 3\n', '2\n2 2\n']
Demo Output:
['2\n', '0\n', '1\n']
Note:
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. | ```python
from calendar import calendar
def List():
return list(map(int,input().split()))
def Lst():
return list(input())
def Int():
return int(input())
def two():
return map(int,input().split())
numOfVactions = Int()
calendar = List()
outPut = 0
prevState = 0
for currState in calendar:
if currState == 3:
prevState = currState - prevState
elif currState == 0 or currState == prevState:
outPut +=1
prevState = 0
else:
prevState = currState
print(outPut)
``` | 3 | |
265 | A | Colorful Stones (Simplified Edition) | PROGRAMMING | 800 | [
"implementation"
] | null | null | There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string *s*. The *i*-th (1-based) character of *s* represents the color of the *i*-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively.
Initially Squirrel Liss is standing on the first stone. You perform instructions one or more times.
Each instruction is one of the three types: "RED", "GREEN", or "BLUE". After an instruction *c*, if Liss is standing on a stone whose colors is *c*, Liss will move one stone forward, else she will not move.
You are given a string *t*. The number of instructions is equal to the length of *t*, and the *i*-th character of *t* represents the *i*-th instruction.
Calculate the final position of Liss (the number of the stone she is going to stand on in the end) after performing all the instructions, and print its 1-based position. It is guaranteed that Liss don't move out of the sequence. | The input contains two lines. The first line contains the string *s* (1<=≤<=|*s*|<=≤<=50). The second line contains the string *t* (1<=≤<=|*t*|<=≤<=50). The characters of each string will be one of "R", "G", or "B". It is guaranteed that Liss don't move out of the sequence. | Print the final 1-based position of Liss in a single line. | [
"RGB\nRRR\n",
"RRRBGBRBBB\nBBBRR\n",
"BRRBGBRGRBGRGRRGGBGBGBRGBRGRGGGRBRRRBRBBBGRRRGGBBB\nBBRBGGRGRGBBBRBGRBRBBBBRBRRRBGBBGBBRRBBGGRBRRBRGRB\n"
] | [
"2\n",
"3\n",
"15\n"
] | none | 500 | [
{
"input": "RGB\nRRR",
"output": "2"
},
{
"input": "RRRBGBRBBB\nBBBRR",
"output": "3"
},
{
"input": "BRRBGBRGRBGRGRRGGBGBGBRGBRGRGGGRBRRRBRBBBGRRRGGBBB\nBBRBGGRGRGBBBRBGRBRBBBBRBRRRBGBBGBBRRBBGGRBRRBRGRB",
"output": "15"
},
{
"input": "G\nRRBBRBRRBR",
"output": "1"
},
... | 1,647,890,424 | 2,147,483,647 | Python 3 | OK | TESTS | 19 | 186 | 6,041,600 | #A. Colorful Stones
from tkinter import S
s = input()
t = input()
i = 0
j = 0
counter = 1
while j < len(t):
if s[i] != t[j]:
j += 1
elif s[i] == t[j]:
i += 1
j += 1
counter += 1
print(counter) | Title: Colorful Stones (Simplified Edition)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string *s*. The *i*-th (1-based) character of *s* represents the color of the *i*-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively.
Initially Squirrel Liss is standing on the first stone. You perform instructions one or more times.
Each instruction is one of the three types: "RED", "GREEN", or "BLUE". After an instruction *c*, if Liss is standing on a stone whose colors is *c*, Liss will move one stone forward, else she will not move.
You are given a string *t*. The number of instructions is equal to the length of *t*, and the *i*-th character of *t* represents the *i*-th instruction.
Calculate the final position of Liss (the number of the stone she is going to stand on in the end) after performing all the instructions, and print its 1-based position. It is guaranteed that Liss don't move out of the sequence.
Input Specification:
The input contains two lines. The first line contains the string *s* (1<=≤<=|*s*|<=≤<=50). The second line contains the string *t* (1<=≤<=|*t*|<=≤<=50). The characters of each string will be one of "R", "G", or "B". It is guaranteed that Liss don't move out of the sequence.
Output Specification:
Print the final 1-based position of Liss in a single line.
Demo Input:
['RGB\nRRR\n', 'RRRBGBRBBB\nBBBRR\n', 'BRRBGBRGRBGRGRRGGBGBGBRGBRGRGGGRBRRRBRBBBGRRRGGBBB\nBBRBGGRGRGBBBRBGRBRBBBBRBRRRBGBBGBBRRBBGGRBRRBRGRB\n']
Demo Output:
['2\n', '3\n', '15\n']
Note:
none | ```python
#A. Colorful Stones
from tkinter import S
s = input()
t = input()
i = 0
j = 0
counter = 1
while j < len(t):
if s[i] != t[j]:
j += 1
elif s[i] == t[j]:
i += 1
j += 1
counter += 1
print(counter)
``` | 3 | |
9 | A | Die Roll | PROGRAMMING | 800 | [
"math",
"probabilities"
] | A. Die Roll | 1 | 64 | Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.
But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.
Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.
It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win. | The only line of the input file contains two natural numbers Y and W — the results of Yakko's and Wakko's die rolls. | Output the required probability in the form of irreducible fraction in format «A/B», where A — the numerator, and B — the denominator. If the required probability equals to zero, output «0/1». If the required probability equals to 1, output «1/1». | [
"4 2\n"
] | [
"1/2\n"
] | Dot will go to Transylvania, if she is lucky to roll 4, 5 or 6 points. | 0 | [
{
"input": "4 2",
"output": "1/2"
},
{
"input": "1 1",
"output": "1/1"
},
{
"input": "1 2",
"output": "5/6"
},
{
"input": "1 3",
"output": "2/3"
},
{
"input": "1 4",
"output": "1/2"
},
{
"input": "1 5",
"output": "1/3"
},
{
"input": "1 6",
... | 1,604,048,357 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 2 | 248 | 0 | import math
y,w=map(int,input().split())
g=math.gcd(y,w)
print(str(w//g)+"/"+str(y//g)) | 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
import math
y,w=map(int,input().split())
g=math.gcd(y,w)
print(str(w//g)+"/"+str(y//g))
``` | 0 |
886 | B | Vlad and Cafes | PROGRAMMING | 1,000 | [] | null | null | Vlad likes to eat in cafes very much. During his life, he has visited cafes *n* times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe. | In first line there is one integer *n* (1<=≤<=*n*<=≤<=2·105) — number of cafes indices written by Vlad.
In second line, *n* numbers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=2·105) are written — indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted. | Print one integer — index of the cafe that Vlad hasn't visited for as long as possible. | [
"5\n1 3 2 1 2\n",
"6\n2 1 2 2 4 1\n"
] | [
"3\n",
"2\n"
] | In first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer.
In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes. | 1,000 | [
{
"input": "5\n1 3 2 1 2",
"output": "3"
},
{
"input": "6\n2 1 2 2 4 1",
"output": "2"
},
{
"input": "1\n0",
"output": "0"
},
{
"input": "1\n200000",
"output": "200000"
},
{
"input": "2\n2018 2017",
"output": "2018"
},
{
"input": "5\n100 1000 1000 1000... | 1,510,509,514 | 6,814 | Python 3 | RUNTIME_ERROR | PRETESTS | 0 | 46 | 0 | from itertools import groupby
k=0
l=0
l1=0
a=[]
s=0
n=int(input())
for i in range(n):
k=int(input())
a.append(k)
new = [el for el, _ in groupby(a)]
a.reverse()
for i in range(len(new)):
l=a.index(new[i-1])
if l>l1: l1=l; s=new[i-1]
print(s)
| Title: Vlad and Cafes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vlad likes to eat in cafes very much. During his life, he has visited cafes *n* times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.
Input Specification:
In first line there is one integer *n* (1<=≤<=*n*<=≤<=2·105) — number of cafes indices written by Vlad.
In second line, *n* numbers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=2·105) are written — indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted.
Output Specification:
Print one integer — index of the cafe that Vlad hasn't visited for as long as possible.
Demo Input:
['5\n1 3 2 1 2\n', '6\n2 1 2 2 4 1\n']
Demo Output:
['3\n', '2\n']
Note:
In first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer.
In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes. | ```python
from itertools import groupby
k=0
l=0
l1=0
a=[]
s=0
n=int(input())
for i in range(n):
k=int(input())
a.append(k)
new = [el for el, _ in groupby(a)]
a.reverse()
for i in range(len(new)):
l=a.index(new[i-1])
if l>l1: l1=l; s=new[i-1]
print(s)
``` | -1 | |
616 | C | The Labyrinth | PROGRAMMING | 1,600 | [
"dfs and similar"
] | null | null | You are given a rectangular field of *n*<=×<=*m* cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.
Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.
For each impassable cell (*x*,<=*y*) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (*x*,<=*y*). You should do it for each impassable cell independently.
The answer should be printed as a matrix with *n* rows and *m* columns. The *j*-th symbol of the *i*-th row should be "." if the cell is empty at the start. Otherwise the *j*-th symbol of the *i*-th row should contain the only digit —- the answer modulo 10. The matrix should be printed without any spaces.
To make your output faster it is recommended to build the output as an array of *n* strings having length *m* and print it as a sequence of lines. It will be much faster than writing character-by-character.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. | The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and columns in the field.
Each of the next *n* lines contains *m* symbols: "." for empty cells, "*" for impassable cells. | Print the answer as a matrix as described above. See the examples to precise the format of the output. | [
"3 3\n*.*\n.*.\n*.*\n",
"4 5\n**..*\n..***\n.*.*.\n*.*.*\n"
] | [
"3.3\n.5.\n3.3\n",
"46..3\n..732\n.6.4.\n5.4.3\n"
] | In first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner). | 0 | [
{
"input": "3 3\n*.*\n.*.\n*.*",
"output": "3.3\n.5.\n3.3"
},
{
"input": "4 5\n**..*\n..***\n.*.*.\n*.*.*",
"output": "46..3\n..732\n.6.4.\n5.4.3"
},
{
"input": "1 1\n*",
"output": "1"
},
{
"input": "1 1\n.",
"output": "."
},
{
"input": "1 10\n**********",
"ou... | 1,594,530,330 | 2,147,483,647 | PyPy 3 | OK | TESTS | 19 | 810 | 70,348,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())
# for i in range(m):
# for i in range(int(input())):
# n,k= map(int, input().split())
# arr=list(map(int,input().split()))
# n=sys.stdin.readline()
# n=int(n)
# n,k= map(int, input().split())
# arr=list(map(int,input().split()))
# n=int(inaput())
#for _ in range(int(input())):
#arr=list(map(int,input().split()))
from collections import deque
dx=[-1,0,0,1]
dy=[0,-1,1,0]
def bfs(x,y):
global total
total+=1
q=deque([(x,y)])
v[x][y]=True
h[x][y]=comp
#q.append()
while q:
x,y=q.pop()
for i in range(4):
nx=x+dx[i]
ny=y+dy[i]
#print("nx,y",nx, ny)
if (nx>=0 and nx<n) and (ny>=0 and ny<m) and (v[nx][ny]==False) and (g[nx][ny]=="."):
q.appendleft((nx,ny))
total+=1
v[nx][ny]=True
h[nx][ny]=comp
#global g,h,r,comp,total
n, m = map(int, input().split())
h=[[-1 for i in range(m)] for j in range(n)]
g=[]
v=[[False for i in range(m)]for j in range(n)]
for i in range(n):
g.append(list(input()))
component=[]
for i in range(n):
for j in range(m):
if v[i][j]==False and g[i][j]==".":############
comp=len(component)
#global total
total=0
bfs(i,j)
component.append(total)
#print(component)
for x in range(n):
for y in range(m):
if g[x][y] == "*":
ans = 0
s = set()
for k in range(4):
nx = x + dx[k]
ny = y + dy[k]
if nx >= 0 and nx < n and ny >= 0 and ny < m and g[nx][ny] == ".":
s.add(h[nx][ny])
for itm in s:
ans += component[itm]
ans += 1
ans %= 10
g[x][y] = str(ans)
for i in range(n):
print("".join(g[i]))
| Title: The Labyrinth
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a rectangular field of *n*<=×<=*m* cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.
Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.
For each impassable cell (*x*,<=*y*) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (*x*,<=*y*). You should do it for each impassable cell independently.
The answer should be printed as a matrix with *n* rows and *m* columns. The *j*-th symbol of the *i*-th row should be "." if the cell is empty at the start. Otherwise the *j*-th symbol of the *i*-th row should contain the only digit —- the answer modulo 10. The matrix should be printed without any spaces.
To make your output faster it is recommended to build the output as an array of *n* strings having length *m* and print it as a sequence of lines. It will be much faster than writing character-by-character.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
Input Specification:
The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and columns in the field.
Each of the next *n* lines contains *m* symbols: "." for empty cells, "*" for impassable cells.
Output Specification:
Print the answer as a matrix as described above. See the examples to precise the format of the output.
Demo Input:
['3 3\n*.*\n.*.\n*.*\n', '4 5\n**..*\n..***\n.*.*.\n*.*.*\n']
Demo Output:
['3.3\n.5.\n3.3\n', '46..3\n..732\n.6.4.\n5.4.3\n']
Note:
In first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner). | ```python
# 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())
# for i in range(m):
# for i in range(int(input())):
# n,k= map(int, input().split())
# arr=list(map(int,input().split()))
# n=sys.stdin.readline()
# n=int(n)
# n,k= map(int, input().split())
# arr=list(map(int,input().split()))
# n=int(inaput())
#for _ in range(int(input())):
#arr=list(map(int,input().split()))
from collections import deque
dx=[-1,0,0,1]
dy=[0,-1,1,0]
def bfs(x,y):
global total
total+=1
q=deque([(x,y)])
v[x][y]=True
h[x][y]=comp
#q.append()
while q:
x,y=q.pop()
for i in range(4):
nx=x+dx[i]
ny=y+dy[i]
#print("nx,y",nx, ny)
if (nx>=0 and nx<n) and (ny>=0 and ny<m) and (v[nx][ny]==False) and (g[nx][ny]=="."):
q.appendleft((nx,ny))
total+=1
v[nx][ny]=True
h[nx][ny]=comp
#global g,h,r,comp,total
n, m = map(int, input().split())
h=[[-1 for i in range(m)] for j in range(n)]
g=[]
v=[[False for i in range(m)]for j in range(n)]
for i in range(n):
g.append(list(input()))
component=[]
for i in range(n):
for j in range(m):
if v[i][j]==False and g[i][j]==".":############
comp=len(component)
#global total
total=0
bfs(i,j)
component.append(total)
#print(component)
for x in range(n):
for y in range(m):
if g[x][y] == "*":
ans = 0
s = set()
for k in range(4):
nx = x + dx[k]
ny = y + dy[k]
if nx >= 0 and nx < n and ny >= 0 and ny < m and g[nx][ny] == ".":
s.add(h[nx][ny])
for itm in s:
ans += component[itm]
ans += 1
ans %= 10
g[x][y] = str(ans)
for i in range(n):
print("".join(g[i]))
``` | 3 | |
553 | B | Kyoya and Permutation | PROGRAMMING | 1,900 | [
"binary search",
"combinatorics",
"constructive algorithms",
"greedy",
"implementation",
"math"
] | null | null | Let's define the permutation of length *n* as an array *p*<==<=[*p*1,<=*p*2,<=...,<=*p**n*] consisting of *n* distinct integers from range from 1 to *n*. We say that this permutation maps value 1 into the value *p*1, value 2 into the value *p*2 and so on.
Kyota Ootori has just learned about cyclic representation of a permutation. A cycle is a sequence of numbers such that each element of this sequence is being mapped into the next element of this sequence (and the last element of the cycle is being mapped into the first element of the cycle). The cyclic representation is a representation of *p* as a collection of cycles forming *p*. For example, permutation *p*<==<=[4,<=1,<=6,<=2,<=5,<=3] has a cyclic representation that looks like (142)(36)(5) because 1 is replaced by 4, 4 is replaced by 2, 2 is replaced by 1, 3 and 6 are swapped, and 5 remains in place.
Permutation may have several cyclic representations, so Kyoya defines the standard cyclic representation of a permutation as follows. First, reorder the elements within each cycle so the largest element is first. Then, reorder all of the cycles so they are sorted by their first element. For our example above, the standard cyclic representation of [4,<=1,<=6,<=2,<=5,<=3] is (421)(5)(63).
Now, Kyoya notices that if we drop the parenthesis in the standard cyclic representation, we get another permutation! For instance, [4,<=1,<=6,<=2,<=5,<=3] will become [4,<=2,<=1,<=5,<=6,<=3].
Kyoya notices that some permutations don't change after applying operation described above at all. He wrote all permutations of length *n* that do not change in a list in lexicographic order. Unfortunately, his friend Tamaki Suoh lost this list. Kyoya wishes to reproduce the list and he needs your help. Given the integers *n* and *k*, print the permutation that was *k*-th on Kyoya's list. | The first line will contain two integers *n*, *k* (1<=≤<=*n*<=≤<=50, 1<=≤<=*k*<=≤<=*min*{1018,<=*l*} where *l* is the length of the Kyoya's list). | Print *n* space-separated integers, representing the permutation that is the answer for the question. | [
"4 3\n",
"10 1\n"
] | [
"1 3 2 4\n",
"1 2 3 4 5 6 7 8 9 10\n"
] | The standard cycle representation is (1)(32)(4), which after removing parenthesis gives us the original permutation. The first permutation on the list would be [1, 2, 3, 4], while the second permutation would be [1, 2, 4, 3]. | 500 | [
{
"input": "4 3",
"output": "1 3 2 4"
},
{
"input": "10 1",
"output": "1 2 3 4 5 6 7 8 9 10"
},
{
"input": "1 1",
"output": "1"
},
{
"input": "50 1",
"output": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 ... | 1,435,166,677 | 3,277 | Python 3 | OK | TESTS | 65 | 62 | 0 | #!/usr/bin/python3
arr = [1] * 51
for i in range(2, 51):
arr[i] = arr[i - 1] + arr[i - 2]
ans = []
def generate(i, n, to):
if i == n:
assert to == 1
print(" ".join(map(str, ans)))
return
if i + 1 == n:
ans.append(n)
generate(i + 1, n, to)
return
if arr[n - i - 1] < to:
ans.append(i + 2)
ans.append(i + 1)
generate(i + 2, n, to - arr[n - i - 1])
else:
ans.append(i + 1)
generate(i + 1, n, to)
n, k = map(int, input().split())
generate(0, n, k)
| Title: Kyoya and Permutation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's define the permutation of length *n* as an array *p*<==<=[*p*1,<=*p*2,<=...,<=*p**n*] consisting of *n* distinct integers from range from 1 to *n*. We say that this permutation maps value 1 into the value *p*1, value 2 into the value *p*2 and so on.
Kyota Ootori has just learned about cyclic representation of a permutation. A cycle is a sequence of numbers such that each element of this sequence is being mapped into the next element of this sequence (and the last element of the cycle is being mapped into the first element of the cycle). The cyclic representation is a representation of *p* as a collection of cycles forming *p*. For example, permutation *p*<==<=[4,<=1,<=6,<=2,<=5,<=3] has a cyclic representation that looks like (142)(36)(5) because 1 is replaced by 4, 4 is replaced by 2, 2 is replaced by 1, 3 and 6 are swapped, and 5 remains in place.
Permutation may have several cyclic representations, so Kyoya defines the standard cyclic representation of a permutation as follows. First, reorder the elements within each cycle so the largest element is first. Then, reorder all of the cycles so they are sorted by their first element. For our example above, the standard cyclic representation of [4,<=1,<=6,<=2,<=5,<=3] is (421)(5)(63).
Now, Kyoya notices that if we drop the parenthesis in the standard cyclic representation, we get another permutation! For instance, [4,<=1,<=6,<=2,<=5,<=3] will become [4,<=2,<=1,<=5,<=6,<=3].
Kyoya notices that some permutations don't change after applying operation described above at all. He wrote all permutations of length *n* that do not change in a list in lexicographic order. Unfortunately, his friend Tamaki Suoh lost this list. Kyoya wishes to reproduce the list and he needs your help. Given the integers *n* and *k*, print the permutation that was *k*-th on Kyoya's list.
Input Specification:
The first line will contain two integers *n*, *k* (1<=≤<=*n*<=≤<=50, 1<=≤<=*k*<=≤<=*min*{1018,<=*l*} where *l* is the length of the Kyoya's list).
Output Specification:
Print *n* space-separated integers, representing the permutation that is the answer for the question.
Demo Input:
['4 3\n', '10 1\n']
Demo Output:
['1 3 2 4\n', '1 2 3 4 5 6 7 8 9 10\n']
Note:
The standard cycle representation is (1)(32)(4), which after removing parenthesis gives us the original permutation. The first permutation on the list would be [1, 2, 3, 4], while the second permutation would be [1, 2, 4, 3]. | ```python
#!/usr/bin/python3
arr = [1] * 51
for i in range(2, 51):
arr[i] = arr[i - 1] + arr[i - 2]
ans = []
def generate(i, n, to):
if i == n:
assert to == 1
print(" ".join(map(str, ans)))
return
if i + 1 == n:
ans.append(n)
generate(i + 1, n, to)
return
if arr[n - i - 1] < to:
ans.append(i + 2)
ans.append(i + 1)
generate(i + 2, n, to - arr[n - i - 1])
else:
ans.append(i + 1)
generate(i + 1, n, to)
n, k = map(int, input().split())
generate(0, n, k)
``` | 3 | |
69 | A | Young Physicist | PROGRAMMING | 1,000 | [
"implementation",
"math"
] | A. Young Physicist | 2 | 256 | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. | The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100), then follow *n* lines containing three integers each: the *x**i* coordinate, the *y**i* coordinate and the *z**i* coordinate of the force vector, applied to the body (<=-<=100<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=100). | Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. | [
"3\n4 1 7\n-2 4 -1\n1 -5 -3\n",
"3\n3 -1 7\n-5 2 -4\n2 -1 -3\n"
] | [
"NO",
"YES"
] | none | 500 | [
{
"input": "3\n4 1 7\n-2 4 -1\n1 -5 -3",
"output": "NO"
},
{
"input": "3\n3 -1 7\n-5 2 -4\n2 -1 -3",
"output": "YES"
},
{
"input": "10\n21 32 -46\n43 -35 21\n42 2 -50\n22 40 20\n-27 -9 38\n-4 1 1\n-40 6 -31\n-13 -2 34\n-21 34 -12\n-32 -29 41",
"output": "NO"
},
{
"input": "10... | 1,588,614,256 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 2 | 156 | 307,200 | ipnum=int(input())
mylist=[]
ans=[]
count=0
for i in range(ipnum):
listip=[int(n) for n in input().split()]
mylist.append(listip)
#print(mylist)
for i in range(len(mylist)):
summ=0
for j in range(len(mylist[0])):
summ=summ + mylist[j][i]
ans.append(summ)
#print(ans)
for item in ans:
if item==0:
count=count+1
if count==len(ans):
print("YES")
else:
print("NO")
| Title: Young Physicist
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
Input Specification:
The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100), then follow *n* lines containing three integers each: the *x**i* coordinate, the *y**i* coordinate and the *z**i* coordinate of the force vector, applied to the body (<=-<=100<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=100).
Output Specification:
Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.
Demo Input:
['3\n4 1 7\n-2 4 -1\n1 -5 -3\n', '3\n3 -1 7\n-5 2 -4\n2 -1 -3\n']
Demo Output:
['NO', 'YES']
Note:
none | ```python
ipnum=int(input())
mylist=[]
ans=[]
count=0
for i in range(ipnum):
listip=[int(n) for n in input().split()]
mylist.append(listip)
#print(mylist)
for i in range(len(mylist)):
summ=0
for j in range(len(mylist[0])):
summ=summ + mylist[j][i]
ans.append(summ)
#print(ans)
for item in ans:
if item==0:
count=count+1
if count==len(ans):
print("YES")
else:
print("NO")
``` | -1 |
954 | D | Fight Against Traffic | PROGRAMMING | 1,600 | [
"dfs and similar",
"graphs",
"shortest paths"
] | null | null | Little town Nsk consists of *n* junctions connected by *m* bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction *s* to work located near junction *t*. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between *s* and *t* won't decrease. | The firt line of the input contains integers *n*, *m*, *s* and *t* (2<=≤<=*n*<=≤<=1000, 1<=≤<=*m*<=≤<=1000, 1<=≤<=*s*,<=*t*<=≤<=*n*, *s*<=≠<=*t*) — the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The *i*-th of the following *m* lines contains two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*), meaning that this road connects junctions *u**i* and *v**i* directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions. | Print one integer — the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions *s* and *t*. | [
"5 4 1 5\n1 2\n2 3\n3 4\n4 5\n",
"5 4 3 5\n1 2\n2 3\n3 4\n4 5\n",
"5 6 1 5\n1 2\n1 3\n1 4\n4 5\n3 5\n2 5\n"
] | [
"0\n",
"5\n",
"3\n"
] | none | 0 | [
{
"input": "5 4 1 5\n1 2\n2 3\n3 4\n4 5",
"output": "0"
},
{
"input": "5 4 3 5\n1 2\n2 3\n3 4\n4 5",
"output": "5"
},
{
"input": "5 6 1 5\n1 2\n1 3\n1 4\n4 5\n3 5\n2 5",
"output": "3"
},
{
"input": "2 1 2 1\n1 2",
"output": "0"
},
{
"input": "3 2 2 3\n1 2\n2 3",
... | 1,671,700,141 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 8 | 109 | 4,608,000 | from collections import defaultdict
from heapq import heappop, heappush
n, m, s, t = list(map(int, input().split()))
graph = defaultdict(set)
for _ in range(m):
u, v = list(map(int, input().split()))
graph[u - 1].add((v - 1, 1))
graph[v - 1].add((u - 1, 1))
total_edges = [((n*(n-1))//2) - m]
queue = [(s - 1, 0)]
distance = [float('inf')]*n
distance[s - 1] = 0
while queue:
size = len(queue)
for _ in range(size):
node, distance_so_far = heappop(queue)
for nei, weight in graph[node]:
if distance_so_far + weight < distance[nei]:
distance[nei] = distance_so_far + weight
heappush(queue, (nei, distance[nei]))
min_distance = distance[t - 1]
# print(distance)
total_min_paths = [0]
def dfs(cur_node = s - 1, parent = -1, depth = 0):
# print(cur_node)
if cur_node == t - 1:
# print(depth)
if depth == min_distance:
total_min_paths[0] += 1
return
for nei, weight in graph[cur_node]:
if nei != parent:
dfs(nei, cur_node, depth + 1)
dfs()
nodes = min_distance + 1
max_possible = ((nodes*(nodes-1))//2) - min_distance
deductable = (total_min_paths[0]*max_possible) - ((total_min_paths[0]) - 1)
total_edges[0] -= deductable
print(total_edges[0])
| Title: Fight Against Traffic
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little town Nsk consists of *n* junctions connected by *m* bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction *s* to work located near junction *t*. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between *s* and *t* won't decrease.
Input Specification:
The firt line of the input contains integers *n*, *m*, *s* and *t* (2<=≤<=*n*<=≤<=1000, 1<=≤<=*m*<=≤<=1000, 1<=≤<=*s*,<=*t*<=≤<=*n*, *s*<=≠<=*t*) — the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The *i*-th of the following *m* lines contains two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*), meaning that this road connects junctions *u**i* and *v**i* directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output Specification:
Print one integer — the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions *s* and *t*.
Demo Input:
['5 4 1 5\n1 2\n2 3\n3 4\n4 5\n', '5 4 3 5\n1 2\n2 3\n3 4\n4 5\n', '5 6 1 5\n1 2\n1 3\n1 4\n4 5\n3 5\n2 5\n']
Demo Output:
['0\n', '5\n', '3\n']
Note:
none | ```python
from collections import defaultdict
from heapq import heappop, heappush
n, m, s, t = list(map(int, input().split()))
graph = defaultdict(set)
for _ in range(m):
u, v = list(map(int, input().split()))
graph[u - 1].add((v - 1, 1))
graph[v - 1].add((u - 1, 1))
total_edges = [((n*(n-1))//2) - m]
queue = [(s - 1, 0)]
distance = [float('inf')]*n
distance[s - 1] = 0
while queue:
size = len(queue)
for _ in range(size):
node, distance_so_far = heappop(queue)
for nei, weight in graph[node]:
if distance_so_far + weight < distance[nei]:
distance[nei] = distance_so_far + weight
heappush(queue, (nei, distance[nei]))
min_distance = distance[t - 1]
# print(distance)
total_min_paths = [0]
def dfs(cur_node = s - 1, parent = -1, depth = 0):
# print(cur_node)
if cur_node == t - 1:
# print(depth)
if depth == min_distance:
total_min_paths[0] += 1
return
for nei, weight in graph[cur_node]:
if nei != parent:
dfs(nei, cur_node, depth + 1)
dfs()
nodes = min_distance + 1
max_possible = ((nodes*(nodes-1))//2) - min_distance
deductable = (total_min_paths[0]*max_possible) - ((total_min_paths[0]) - 1)
total_edges[0] -= deductable
print(total_edges[0])
``` | 0 | |
427 | A | Police Recruits | PROGRAMMING | 800 | [
"implementation"
] | null | null | The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.
Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated. | The first line of input will contain an integer *n* (1<=≤<=*n*<=≤<=105), the number of events. The next line will contain *n* space-separated integers.
If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time. | Print a single integer, the number of crimes which will go untreated. | [
"3\n-1 -1 1\n",
"8\n1 -1 1 -1 -1 1 1 1\n",
"11\n-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1\n"
] | [
"2\n",
"1\n",
"8\n"
] | Lets consider the second example:
1. Firstly one person is hired. 1. Then crime appears, the last hired person will investigate this crime. 1. One more person is hired. 1. One more crime appears, the last hired person will investigate this crime. 1. Crime appears. There is no free policeman at the time, so this crime will go untreated. 1. One more person is hired. 1. One more person is hired. 1. One more person is hired.
The answer is one, as one crime (on step 5) will go untreated. | 500 | [
{
"input": "3\n-1 -1 1",
"output": "2"
},
{
"input": "8\n1 -1 1 -1 -1 1 1 1",
"output": "1"
},
{
"input": "11\n-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1",
"output": "8"
},
{
"input": "7\n-1 -1 1 1 -1 -1 1",
"output": "2"
},
{
"input": "21\n-1 -1 -1 -1 -1 3 2 -1 6 -1 -1 2 1 ... | 1,676,643,475 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 5 | 46 | 0 | n = int(input())
s = [int(i) for i in input().split()]
kol = 0
n=len(s)-1
p=0
while True:
if(s[n]==-1):
break
n-=1
while True:
if(s[p]>0):
break
p+=1
out = s[p]
i=p
l=len(s)
while i<n:
try:
s[p]+=s[p+1]
s.pop(p+1)
i+=1
except:
out = abs(sum([i for i in s if i<0]))
break
out = abs(sum([i for i in s if i<0]))
print(out)
| Title: Police Recruits
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.
Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.
Input Specification:
The first line of input will contain an integer *n* (1<=≤<=*n*<=≤<=105), the number of events. The next line will contain *n* space-separated integers.
If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.
Output Specification:
Print a single integer, the number of crimes which will go untreated.
Demo Input:
['3\n-1 -1 1\n', '8\n1 -1 1 -1 -1 1 1 1\n', '11\n-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1\n']
Demo Output:
['2\n', '1\n', '8\n']
Note:
Lets consider the second example:
1. Firstly one person is hired. 1. Then crime appears, the last hired person will investigate this crime. 1. One more person is hired. 1. One more crime appears, the last hired person will investigate this crime. 1. Crime appears. There is no free policeman at the time, so this crime will go untreated. 1. One more person is hired. 1. One more person is hired. 1. One more person is hired.
The answer is one, as one crime (on step 5) will go untreated. | ```python
n = int(input())
s = [int(i) for i in input().split()]
kol = 0
n=len(s)-1
p=0
while True:
if(s[n]==-1):
break
n-=1
while True:
if(s[p]>0):
break
p+=1
out = s[p]
i=p
l=len(s)
while i<n:
try:
s[p]+=s[p+1]
s.pop(p+1)
i+=1
except:
out = abs(sum([i for i in s if i<0]))
break
out = abs(sum([i for i in s if i<0]))
print(out)
``` | 0 | |
361 | A | Levko and Table | PROGRAMMING | 800 | [
"constructive algorithms",
"implementation"
] | null | null | Levko loves tables that consist of *n* rows and *n* columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals *k*.
Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them. | The single line contains two integers, *n* and *k* (1<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=1000). | Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value.
If there are multiple suitable tables, you are allowed to print any of them. | [
"2 4\n",
"4 7\n"
] | [
"1 3\n3 1\n",
"2 1 0 4\n4 0 2 1\n1 3 3 0\n0 3 2 2\n"
] | In the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.
In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements. | 500 | [
{
"input": "2 4",
"output": "4 0 \n0 4 "
},
{
"input": "4 7",
"output": "7 0 0 0 \n0 7 0 0 \n0 0 7 0 \n0 0 0 7 "
},
{
"input": "1 8",
"output": "8 "
},
{
"input": "9 3",
"output": "3 0 0 0 0 0 0 0 0 \n0 3 0 0 0 0 0 0 0 \n0 0 3 0 0 0 0 0 0 \n0 0 0 3 0 0 0 0 0 \n0 0 0 0 3 0... | 1,614,523,427 | 2,147,483,647 | Python 3 | OK | TESTS | 22 | 77 | 307,200 | n, k = map(int, input().split());
a = list(range(n));
for i in range (0, n):
a[i] = list(range(n));
for j in range (0, n):
if j == i:
a[i][j] = k;
else: a[i][j] = 0;
print(*a[i], sep=" ") | Title: Levko and Table
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Levko loves tables that consist of *n* rows and *n* columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals *k*.
Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
Input Specification:
The single line contains two integers, *n* and *k* (1<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=1000).
Output Specification:
Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value.
If there are multiple suitable tables, you are allowed to print any of them.
Demo Input:
['2 4\n', '4 7\n']
Demo Output:
['1 3\n3 1\n', '2 1 0 4\n4 0 2 1\n1 3 3 0\n0 3 2 2\n']
Note:
In the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.
In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements. | ```python
n, k = map(int, input().split());
a = list(range(n));
for i in range (0, n):
a[i] = list(range(n));
for j in range (0, n):
if j == i:
a[i][j] = k;
else: a[i][j] = 0;
print(*a[i], sep=" ")
``` | 3 | |
678 | A | Johny Likes Numbers | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | Johny likes numbers *n* and *k* very much. Now Johny wants to find the smallest integer *x* greater than *n*, so it is divisible by the number *k*. | The only line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=109). | Print the smallest integer *x*<=><=*n*, so it is divisible by the number *k*. | [
"5 3\n",
"25 13\n",
"26 13\n"
] | [
"6\n",
"26\n",
"39\n"
] | none | 0 | [
{
"input": "5 3",
"output": "6"
},
{
"input": "25 13",
"output": "26"
},
{
"input": "26 13",
"output": "39"
},
{
"input": "1 1",
"output": "2"
},
{
"input": "8 8",
"output": "16"
},
{
"input": "14 15",
"output": "15"
},
{
"input": "197 894"... | 1,594,989,439 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 109 | 6,656,000 | n,k=map(int,input().split())
for i in range(1,k):
if(k*i>n):
print(k*i)
break | Title: Johny Likes Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Johny likes numbers *n* and *k* very much. Now Johny wants to find the smallest integer *x* greater than *n*, so it is divisible by the number *k*.
Input Specification:
The only line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=109).
Output Specification:
Print the smallest integer *x*<=><=*n*, so it is divisible by the number *k*.
Demo Input:
['5 3\n', '25 13\n', '26 13\n']
Demo Output:
['6\n', '26\n', '39\n']
Note:
none | ```python
n,k=map(int,input().split())
for i in range(1,k):
if(k*i>n):
print(k*i)
break
``` | 0 | |
582 | A | GCD Table | PROGRAMMING | 1,700 | [
"constructive algorithms",
"greedy",
"number theory"
] | null | null | The GCD table *G* of size *n*<=×<=*n* for an array of positive integers *a* of length *n* is defined by formula
Let us remind you that the greatest common divisor (GCD) of two positive integers *x* and *y* is the greatest integer that is divisor of both *x* and *y*, it is denoted as . For example, for array *a*<==<={4,<=3,<=6,<=2} of length 4 the GCD table will look as follows:
Given all the numbers of the GCD table *G*, restore array *a*. | The first line contains number *n* (1<=≤<=*n*<=≤<=500) — the length of array *a*. The second line contains *n*2 space-separated numbers — the elements of the GCD table of *G* for array *a*.
All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array *a*. | In the single line print *n* positive integers — the elements of array *a*. If there are multiple possible solutions, you are allowed to print any of them. | [
"4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2\n",
"1\n42\n",
"2\n1 1 1 1\n"
] | [
"4 3 6 2",
"42 ",
"1 1 "
] | none | 750 | [
{
"input": "4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2",
"output": "2 3 4 6 "
},
{
"input": "1\n42",
"output": "42 "
},
{
"input": "2\n1 1 1 1",
"output": "1 1 "
},
{
"input": "2\n54748096 1 641009859 1",
"output": "54748096 641009859 "
},
{
"input": "3\n1 7 923264237 374... | 1,592,034,328 | 2,147,483,647 | PyPy 3 | OK | TESTS | 54 | 451 | 21,811,200 | import math as ma
import sys
input=sys.stdin.readline
def fu(b):
for i in b:
if b[i]!=0:
return i
return -1
def gcd(a,b):
if a%b==0:
return b
else:
return gcd(b,a%b)
n=int(input())
a=list(map(int,input().split()))
a.sort(reverse=True)
b={}
for i in range(n*n):
if a[i] in b.keys():
b[a[i]]+=1
else:
b[a[i]]=1
c=[]
for i in b:
c.append(i)
b[i]-=1
break
while 1>0:
if len(c)<n:
a=fu(b)
if a==-1:
break
else:
b[a]-=1
for i in range(len(c)):
b[gcd(a,c[i])]-=2
c.append(a)
else:
break
print(*c) | Title: GCD Table
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The GCD table *G* of size *n*<=×<=*n* for an array of positive integers *a* of length *n* is defined by formula
Let us remind you that the greatest common divisor (GCD) of two positive integers *x* and *y* is the greatest integer that is divisor of both *x* and *y*, it is denoted as . For example, for array *a*<==<={4,<=3,<=6,<=2} of length 4 the GCD table will look as follows:
Given all the numbers of the GCD table *G*, restore array *a*.
Input Specification:
The first line contains number *n* (1<=≤<=*n*<=≤<=500) — the length of array *a*. The second line contains *n*2 space-separated numbers — the elements of the GCD table of *G* for array *a*.
All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array *a*.
Output Specification:
In the single line print *n* positive integers — the elements of array *a*. If there are multiple possible solutions, you are allowed to print any of them.
Demo Input:
['4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2\n', '1\n42\n', '2\n1 1 1 1\n']
Demo Output:
['4 3 6 2', '42 ', '1 1 ']
Note:
none | ```python
import math as ma
import sys
input=sys.stdin.readline
def fu(b):
for i in b:
if b[i]!=0:
return i
return -1
def gcd(a,b):
if a%b==0:
return b
else:
return gcd(b,a%b)
n=int(input())
a=list(map(int,input().split()))
a.sort(reverse=True)
b={}
for i in range(n*n):
if a[i] in b.keys():
b[a[i]]+=1
else:
b[a[i]]=1
c=[]
for i in b:
c.append(i)
b[i]-=1
break
while 1>0:
if len(c)<n:
a=fu(b)
if a==-1:
break
else:
b[a]-=1
for i in range(len(c)):
b[gcd(a,c[i])]-=2
c.append(a)
else:
break
print(*c)
``` | 3 | |
960 | B | Minimize the error | PROGRAMMING | 1,500 | [
"data structures",
"greedy",
"sortings"
] | null | null | You are given two arrays *A* and *B*, each of size *n*. The error, *E*, between these two arrays is defined . You have to perform exactly *k*1 operations on array *A* and exactly *k*2 operations on array *B*. In one operation, you have to choose one element of the array and increase or decrease it by 1.
Output the minimum possible value of error after *k*1 operations on array *A* and *k*2 operations on array *B* have been performed. | The first line contains three space-separated integers *n* (1<=≤<=*n*<=≤<=103), *k*1 and *k*2 (0<=≤<=*k*1<=+<=*k*2<=≤<=103, *k*1 and *k*2 are non-negative) — size of arrays and number of operations to perform on *A* and *B* respectively.
Second line contains *n* space separated integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=106<=≤<=*a**i*<=≤<=106) — array *A*.
Third line contains *n* space separated integers *b*1,<=*b*2,<=...,<=*b**n* (<=-<=106<=≤<=*b**i*<=≤<=106)— array *B*. | Output a single integer — the minimum possible value of after doing exactly *k*1 operations on array *A* and exactly *k*2 operations on array *B*. | [
"2 0 0\n1 2\n2 3\n",
"2 1 0\n1 2\n2 2\n",
"2 5 7\n3 4\n14 4\n"
] | [
"2",
"0",
"1"
] | In the first sample case, we cannot perform any operations on *A* or *B*. Therefore the minimum possible error *E* = (1 - 2)<sup class="upper-index">2</sup> + (2 - 3)<sup class="upper-index">2</sup> = 2.
In the second sample case, we are required to perform exactly one operation on *A*. In order to minimize error, we increment the first element of *A* by 1. Now, *A* = [2, 2]. The error is now *E* = (2 - 2)<sup class="upper-index">2</sup> + (2 - 2)<sup class="upper-index">2</sup> = 0. This is the minimum possible error obtainable.
In the third sample case, we can increase the first element of *A* to 8, using the all of the 5 moves available to us. Also, the first element of *B* can be reduced to 8 using the 6 of the 7 available moves. Now *A* = [8, 4] and *B* = [8, 4]. The error is now *E* = (8 - 8)<sup class="upper-index">2</sup> + (4 - 4)<sup class="upper-index">2</sup> = 0, but we are still left with 1 move for array *B*. Increasing the second element of *B* to 5 using the left move, we get *B* = [8, 5] and *E* = (8 - 8)<sup class="upper-index">2</sup> + (4 - 5)<sup class="upper-index">2</sup> = 1. | 1,000 | [
{
"input": "2 0 0\n1 2\n2 3",
"output": "2"
},
{
"input": "2 1 0\n1 2\n2 2",
"output": "0"
},
{
"input": "2 5 7\n3 4\n14 4",
"output": "1"
},
{
"input": "2 0 1\n1 2\n2 2",
"output": "0"
},
{
"input": "2 1 1\n0 0\n1 1",
"output": "0"
},
{
"input": "5 5 ... | 1,523,118,753 | 1,653 | Python 3 | RUNTIME_ERROR | PRETESTS | 7 | 93 | 7,168,000 | from collections import Counter
n, k1, k2 = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
k = k1 + k2
d = [abs(a[i] - b[i]) for i in range(n)]
C = Counter(d)
if sum(d) > k:
while k > 0:
m = max(C.keys())
t = min(k, C[m])
k -= t
C[m] -= t
if C[m] == 0:
del C[m]
m = max(C.keys())
C[m] += t
else:
break
ans = sum([k ** 2 * v for k, v in C.items()])
print(ans)
else:
print((k - sum(d)) % 2)
| Title: Minimize the error
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two arrays *A* and *B*, each of size *n*. The error, *E*, between these two arrays is defined . You have to perform exactly *k*1 operations on array *A* and exactly *k*2 operations on array *B*. In one operation, you have to choose one element of the array and increase or decrease it by 1.
Output the minimum possible value of error after *k*1 operations on array *A* and *k*2 operations on array *B* have been performed.
Input Specification:
The first line contains three space-separated integers *n* (1<=≤<=*n*<=≤<=103), *k*1 and *k*2 (0<=≤<=*k*1<=+<=*k*2<=≤<=103, *k*1 and *k*2 are non-negative) — size of arrays and number of operations to perform on *A* and *B* respectively.
Second line contains *n* space separated integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=106<=≤<=*a**i*<=≤<=106) — array *A*.
Third line contains *n* space separated integers *b*1,<=*b*2,<=...,<=*b**n* (<=-<=106<=≤<=*b**i*<=≤<=106)— array *B*.
Output Specification:
Output a single integer — the minimum possible value of after doing exactly *k*1 operations on array *A* and exactly *k*2 operations on array *B*.
Demo Input:
['2 0 0\n1 2\n2 3\n', '2 1 0\n1 2\n2 2\n', '2 5 7\n3 4\n14 4\n']
Demo Output:
['2', '0', '1']
Note:
In the first sample case, we cannot perform any operations on *A* or *B*. Therefore the minimum possible error *E* = (1 - 2)<sup class="upper-index">2</sup> + (2 - 3)<sup class="upper-index">2</sup> = 2.
In the second sample case, we are required to perform exactly one operation on *A*. In order to minimize error, we increment the first element of *A* by 1. Now, *A* = [2, 2]. The error is now *E* = (2 - 2)<sup class="upper-index">2</sup> + (2 - 2)<sup class="upper-index">2</sup> = 0. This is the minimum possible error obtainable.
In the third sample case, we can increase the first element of *A* to 8, using the all of the 5 moves available to us. Also, the first element of *B* can be reduced to 8 using the 6 of the 7 available moves. Now *A* = [8, 4] and *B* = [8, 4]. The error is now *E* = (8 - 8)<sup class="upper-index">2</sup> + (4 - 4)<sup class="upper-index">2</sup> = 0, but we are still left with 1 move for array *B*. Increasing the second element of *B* to 5 using the left move, we get *B* = [8, 5] and *E* = (8 - 8)<sup class="upper-index">2</sup> + (4 - 5)<sup class="upper-index">2</sup> = 1. | ```python
from collections import Counter
n, k1, k2 = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
k = k1 + k2
d = [abs(a[i] - b[i]) for i in range(n)]
C = Counter(d)
if sum(d) > k:
while k > 0:
m = max(C.keys())
t = min(k, C[m])
k -= t
C[m] -= t
if C[m] == 0:
del C[m]
m = max(C.keys())
C[m] += t
else:
break
ans = sum([k ** 2 * v for k, v in C.items()])
print(ans)
else:
print((k - sum(d)) % 2)
``` | -1 | |
102 | B | Sum of Digits | PROGRAMMING | 1,000 | [
"implementation"
] | B. Sum of Digits | 2 | 265 | Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit? | The first line contains the only integer *n* (0<=≤<=*n*<=≤<=10100000). It is guaranteed that *n* doesn't contain any leading zeroes. | Print the number of times a number can be replaced by the sum of its digits until it only contains one digit. | [
"0\n",
"10\n",
"991\n"
] | [
"0\n",
"1\n",
"3\n"
] | In the first sample the number already is one-digit — Herald can't cast a spell.
The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.
The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit. | 1,000 | [
{
"input": "0",
"output": "0"
},
{
"input": "10",
"output": "1"
},
{
"input": "991",
"output": "3"
},
{
"input": "99",
"output": "2"
},
{
"input": "100",
"output": "1"
},
{
"input": "123456789",
"output": "2"
},
{
"input": "32",
"output... | 1,647,802,245 | 2,147,483,647 | Python 3 | OK | TESTS | 51 | 124 | 0 | s=input()
c=0
while(len(s)>1):
sum=0
for i in s:
sum+=int(i)
s=str(sum)
c+=1
print(c) | Title: Sum of Digits
Time Limit: 2 seconds
Memory Limit: 265 megabytes
Problem Description:
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit?
Input Specification:
The first line contains the only integer *n* (0<=≤<=*n*<=≤<=10100000). It is guaranteed that *n* doesn't contain any leading zeroes.
Output Specification:
Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.
Demo Input:
['0\n', '10\n', '991\n']
Demo Output:
['0\n', '1\n', '3\n']
Note:
In the first sample the number already is one-digit — Herald can't cast a spell.
The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.
The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit. | ```python
s=input()
c=0
while(len(s)>1):
sum=0
for i in s:
sum+=int(i)
s=str(sum)
c+=1
print(c)
``` | 3.969 |
58 | A | Chat room | PROGRAMMING | 1,000 | [
"greedy",
"strings"
] | A. Chat room | 1 | 256 | Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*. | The first and only line contains the word *s*, which Vasya typed. This word consisits of small Latin letters, its length is no less that 1 and no more than 100 letters. | If Vasya managed to say hello, print "YES", otherwise print "NO". | [
"ahhellllloou\n",
"hlelo\n"
] | [
"YES\n",
"NO\n"
] | none | 500 | [
{
"input": "ahhellllloou",
"output": "YES"
},
{
"input": "hlelo",
"output": "NO"
},
{
"input": "helhcludoo",
"output": "YES"
},
{
"input": "hehwelloho",
"output": "YES"
},
{
"input": "pnnepelqomhhheollvlo",
"output": "YES"
},
{
"input": "tymbzjyqhymeda... | 1,687,879,406 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 30 | 0 | s = str(input())
x = 0
if len(s) > 5 :
if "h" in s :
x += 1
if "e" in s :
x+= 1
if "l" in s :
x += 1
if "o" in s :
x += 1
if x >= 5 or "hello" in s:
print("YES")
else :
print("NO") | Title: Chat room
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
Input Specification:
The first and only line contains the word *s*, which Vasya typed. This word consisits of small Latin letters, its length is no less that 1 and no more than 100 letters.
Output Specification:
If Vasya managed to say hello, print "YES", otherwise print "NO".
Demo Input:
['ahhellllloou\n', 'hlelo\n']
Demo Output:
['YES\n', 'NO\n']
Note:
none | ```python
s = str(input())
x = 0
if len(s) > 5 :
if "h" in s :
x += 1
if "e" in s :
x+= 1
if "l" in s :
x += 1
if "o" in s :
x += 1
if x >= 5 or "hello" in s:
print("YES")
else :
print("NO")
``` | 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,553,772,872 | 2,147,483,647 | Python 3 | OK | TESTS | 102 | 124 | 0 | m = input()
oo = []
mm = list(m)
n = input()
nn = list(n)
for i in range(0,len(m)):
oo.append(int(mm[i]) + int(nn[i]))
for i in range(0,len(oo)):
oo[i] = str(oo[i])
str1 = ''.join(oo)
finfin = str1.replace('2','0')
print(finfin) | 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
m = input()
oo = []
mm = list(m)
n = input()
nn = list(n)
for i in range(0,len(m)):
oo.append(int(mm[i]) + int(nn[i]))
for i in range(0,len(oo)):
oo[i] = str(oo[i])
str1 = ''.join(oo)
finfin = str1.replace('2','0')
print(finfin)
``` | 3.969 |
248 | A | Cupboards | PROGRAMMING | 800 | [
"implementation"
] | null | null | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on *n* wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.
And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.
Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds *t*, in which he is able to bring all the cupboard doors in the required position.
Your task is to write a program that will determine the required number of seconds *t*. | The first input line contains a single integer *n* — the number of cupboards in the kitchen (2<=≤<=*n*<=≤<=104). Then follow *n* lines, each containing two integers *l**i* and *r**i* (0<=≤<=*l**i*,<=*r**i*<=≤<=1). Number *l**i* equals one, if the left door of the *i*-th cupboard is opened, otherwise number *l**i* equals zero. Similarly, number *r**i* equals one, if the right door of the *i*-th cupboard is opened, otherwise number *r**i* equals zero.
The numbers in the lines are separated by single spaces. | In the only output line print a single integer *t* — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | [
"5\n0 1\n1 0\n0 1\n1 1\n0 1\n"
] | [
"3\n"
] | none | 500 | [
{
"input": "5\n0 1\n1 0\n0 1\n1 1\n0 1",
"output": "3"
},
{
"input": "2\n0 0\n0 0",
"output": "0"
},
{
"input": "3\n0 1\n1 1\n1 1",
"output": "1"
},
{
"input": "8\n0 1\n1 0\n0 1\n1 1\n0 1\n1 0\n0 1\n1 0",
"output": "7"
},
{
"input": "8\n1 0\n1 0\n1 0\n0 1\n0 1\n1 ... | 1,634,793,345 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 92 | 4,505,600 | n = int(input())
l = []
for i in range(n):
a = list(map(int, input().split()))
l.append(a)
#1 == open, 0 == closed
clo = clc = cro = crc = 0
for i in l:
if i[0] == 1: clo+=1
else: clc+=1
if i[1] == 1: cro+=1
else: crc +=1
ld = rd = 0
if clo > cro or clc < crc:
ld = 1
rd = 0
else:
ld = 0
rd = 1
if ld == 1: #if left doors have to be open
print(clc+cro)
else:
print(clo+crc)
| Title: Cupboards
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on *n* wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.
And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.
Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds *t*, in which he is able to bring all the cupboard doors in the required position.
Your task is to write a program that will determine the required number of seconds *t*.
Input Specification:
The first input line contains a single integer *n* — the number of cupboards in the kitchen (2<=≤<=*n*<=≤<=104). Then follow *n* lines, each containing two integers *l**i* and *r**i* (0<=≤<=*l**i*,<=*r**i*<=≤<=1). Number *l**i* equals one, if the left door of the *i*-th cupboard is opened, otherwise number *l**i* equals zero. Similarly, number *r**i* equals one, if the right door of the *i*-th cupboard is opened, otherwise number *r**i* equals zero.
The numbers in the lines are separated by single spaces.
Output Specification:
In the only output line print a single integer *t* — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.
Demo Input:
['5\n0 1\n1 0\n0 1\n1 1\n0 1\n']
Demo Output:
['3\n']
Note:
none | ```python
n = int(input())
l = []
for i in range(n):
a = list(map(int, input().split()))
l.append(a)
#1 == open, 0 == closed
clo = clc = cro = crc = 0
for i in l:
if i[0] == 1: clo+=1
else: clc+=1
if i[1] == 1: cro+=1
else: crc +=1
ld = rd = 0
if clo > cro or clc < crc:
ld = 1
rd = 0
else:
ld = 0
rd = 1
if ld == 1: #if left doors have to be open
print(clc+cro)
else:
print(clo+crc)
``` | 0 | |
764 | A | Taymyr is calling you | PROGRAMMING | 800 | [
"brute force",
"implementation",
"math"
] | null | null | Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.
Ilia-alpinist calls every *n* minutes, i.e. in minutes *n*, 2*n*, 3*n* and so on. Artists come to the comrade every *m* minutes, i.e. in minutes *m*, 2*m*, 3*m* and so on. The day is *z* minutes long, i.e. the day consists of minutes 1,<=2,<=...,<=*z*. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute. | The only string contains three integers — *n*, *m* and *z* (1<=≤<=*n*,<=*m*,<=*z*<=≤<=104). | Print single integer — the minimum number of artists that should be killed so that there are no artists in the room when Ilia calls. | [
"1 1 10\n",
"1 2 5\n",
"2 3 9\n"
] | [
"10\n",
"2\n",
"1\n"
] | Taymyr is a place in the north of Russia.
In the first test the artists come each minute, as well as the calls, so we need to kill all of them.
In the second test we need to kill artists which come on the second and the fourth minutes.
In the third test — only the artist which comes on the sixth minute. | 500 | [
{
"input": "1 1 10",
"output": "10"
},
{
"input": "1 2 5",
"output": "2"
},
{
"input": "2 3 9",
"output": "1"
},
{
"input": "4 8 9",
"output": "1"
},
{
"input": "7 9 2",
"output": "0"
},
{
"input": "10000 10000 10000",
"output": "1"
},
{
"i... | 1,486,136,023 | 2,147,483,647 | Python 3 | OK | TESTS | 32 | 61 | 5,939,200 | n, m, z = (int(i) for i in input().split())
calls = set(i for i in range(0, z + 1, n))
art = set(i for i in range(0, z + 1, m))
print(len(calls & art) - 1) | Title: Taymyr is calling you
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.
Ilia-alpinist calls every *n* minutes, i.e. in minutes *n*, 2*n*, 3*n* and so on. Artists come to the comrade every *m* minutes, i.e. in minutes *m*, 2*m*, 3*m* and so on. The day is *z* minutes long, i.e. the day consists of minutes 1,<=2,<=...,<=*z*. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute.
Input Specification:
The only string contains three integers — *n*, *m* and *z* (1<=≤<=*n*,<=*m*,<=*z*<=≤<=104).
Output Specification:
Print single integer — the minimum number of artists that should be killed so that there are no artists in the room when Ilia calls.
Demo Input:
['1 1 10\n', '1 2 5\n', '2 3 9\n']
Demo Output:
['10\n', '2\n', '1\n']
Note:
Taymyr is a place in the north of Russia.
In the first test the artists come each minute, as well as the calls, so we need to kill all of them.
In the second test we need to kill artists which come on the second and the fourth minutes.
In the third test — only the artist which comes on the sixth minute. | ```python
n, m, z = (int(i) for i in input().split())
calls = set(i for i in range(0, z + 1, n))
art = set(i for i in range(0, z + 1, m))
print(len(calls & art) - 1)
``` | 3 | |
78 | A | Haiku | PROGRAMMING | 800 | [
"implementation",
"strings"
] | A. Haiku | 2 | 256 | Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.
To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".
Three phases from a certain poem are given. Determine whether it is haiku or not. | The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The *i*-th line contains the *i*-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification. | Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes). | [
"on codeforces \nbeta round is running\n a rustling of keys \n",
"how many gallons\nof edo s rain did you drink\n cuckoo\n"
] | [
"YES",
"NO"
] | none | 500 | [
{
"input": "on codeforces \nbeta round is running\n a rustling of keys ",
"output": "YES"
},
{
"input": "how many gallons\nof edo s rain did you drink\n cuckoo",
"output": "NO"
},
{
"input": " hatsu shigure\n saru mo komino wo\nhoshige nari",
... | 1,572,794,228 | 2,147,483,647 | Python 3 | OK | TESTS | 40 | 218 | 0 | a=input()
b=input()
c=input()
p=['a','e','i','o','u']
d=0
e=0
f=0
for i in a:
if i in p:
d=d+1
for j in b:
if j in p:
e=e+1
for k in c:
if k in p:
f=f+1
if d==5 and e==7 and f==5:
print('YES')
else:
print('NO') | Title: Haiku
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.
To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".
Three phases from a certain poem are given. Determine whether it is haiku or not.
Input Specification:
The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The *i*-th line contains the *i*-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.
Output Specification:
Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).
Demo Input:
['on codeforces \nbeta round is running\n a rustling of keys \n', 'how many gallons\nof edo s rain did you drink\n cuckoo\n']
Demo Output:
['YES', 'NO']
Note:
none | ```python
a=input()
b=input()
c=input()
p=['a','e','i','o','u']
d=0
e=0
f=0
for i in a:
if i in p:
d=d+1
for j in b:
if j in p:
e=e+1
for k in c:
if k in p:
f=f+1
if d==5 and e==7 and f==5:
print('YES')
else:
print('NO')
``` | 3.9455 |
965 | A | Paper Airplanes | PROGRAMMING | 800 | [
"math"
] | null | null | To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes.
A group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people. Each person should have enough sheets to make $n$ airplanes. How many packs should they buy? | The only line contains four integers $k$, $n$, $s$, $p$ ($1 \le k, n, s, p \le 10^4$) — the number of people, the number of airplanes each should make, the number of airplanes that can be made using one sheet and the number of sheets in one pack, respectively. | Print a single integer — the minimum number of packs they should buy. | [
"5 3 2 3\n",
"5 3 100 1\n"
] | [
"4\n",
"5\n"
] | In the first sample they have to buy $4$ packs of paper: there will be $12$ sheets in total, and giving $2$ sheets to each person is enough to suit everyone's needs.
In the second sample they have to buy a pack for each person as they can't share sheets. | 500 | [
{
"input": "5 3 2 3",
"output": "4"
},
{
"input": "5 3 100 1",
"output": "5"
},
{
"input": "10000 10000 1 1",
"output": "100000000"
},
{
"input": "1 1 10000 10000",
"output": "1"
},
{
"input": "300 300 21 23",
"output": "196"
},
{
"input": "300 2 37 51... | 1,552,765,663 | 2,147,483,647 | Python 3 | OK | TESTS | 18 | 109 | 0 | import math
k,n,s,p=map(int,input().split())
print(math.ceil(k*math.ceil(n/s)/p))
| Title: Paper Airplanes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes.
A group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people. Each person should have enough sheets to make $n$ airplanes. How many packs should they buy?
Input Specification:
The only line contains four integers $k$, $n$, $s$, $p$ ($1 \le k, n, s, p \le 10^4$) — the number of people, the number of airplanes each should make, the number of airplanes that can be made using one sheet and the number of sheets in one pack, respectively.
Output Specification:
Print a single integer — the minimum number of packs they should buy.
Demo Input:
['5 3 2 3\n', '5 3 100 1\n']
Demo Output:
['4\n', '5\n']
Note:
In the first sample they have to buy $4$ packs of paper: there will be $12$ sheets in total, and giving $2$ sheets to each person is enough to suit everyone's needs.
In the second sample they have to buy a pack for each person as they can't share sheets. | ```python
import math
k,n,s,p=map(int,input().split())
print(math.ceil(k*math.ceil(n/s)/p))
``` | 3 | |
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,586,000,560 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 77 | 307,200 | n=input("please enter number1")
m=input("please enter number2")
list_a=[]
list_b=[]
list_c=[]
for ch1 in n:
list_a.append(ch1)
for ch2 in m:
list_b.append(ch2)
for i in range(len(n)):
for j in range(len(m)):
if i==j :
if list_a.pop()==list_b.pop():
list_c.append(0)
else:
list_c.append(1)
list_c.reverse()
for k in list_c:
print(k,end='') | 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
n=input("please enter number1")
m=input("please enter number2")
list_a=[]
list_b=[]
list_c=[]
for ch1 in n:
list_a.append(ch1)
for ch2 in m:
list_b.append(ch2)
for i in range(len(n)):
for j in range(len(m)):
if i==j :
if list_a.pop()==list_b.pop():
list_c.append(0)
else:
list_c.append(1)
list_c.reverse()
for k in list_c:
print(k,end='')
``` | 0 |
96 | A | Football | PROGRAMMING | 900 | [
"implementation",
"strings"
] | A. Football | 2 | 256 | Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not. | The first input line contains a non-empty string consisting of characters "0" and "1", which represents players. The length of the string does not exceed 100 characters. There's at least one player from each team present on the field. | Print "YES" if the situation is dangerous. Otherwise, print "NO". | [
"001001\n",
"1000000001\n"
] | [
"NO\n",
"YES\n"
] | none | 500 | [
{
"input": "001001",
"output": "NO"
},
{
"input": "1000000001",
"output": "YES"
},
{
"input": "00100110111111101",
"output": "YES"
},
{
"input": "11110111111111111",
"output": "YES"
},
{
"input": "01",
"output": "NO"
},
{
"input": "10100101",
"outp... | 1,696,332,928 | 2,147,483,647 | Python 3 | OK | TESTS | 44 | 92 | 0 | line = input()
ans = "NO"
for i in range(len(line) - 6):
if line[i: i + 7].count('0') == 7 or line[i: i + 7].count('1') == 7:
ans = "YES"
break
print(ans)
| Title: Football
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.
Input Specification:
The first input line contains a non-empty string consisting of characters "0" and "1", which represents players. The length of the string does not exceed 100 characters. There's at least one player from each team present on the field.
Output Specification:
Print "YES" if the situation is dangerous. Otherwise, print "NO".
Demo Input:
['001001\n', '1000000001\n']
Demo Output:
['NO\n', 'YES\n']
Note:
none | ```python
line = input()
ans = "NO"
for i in range(len(line) - 6):
if line[i: i + 7].count('0') == 7 or line[i: i + 7].count('1') == 7:
ans = "YES"
break
print(ans)
``` | 3.977 |
609 | B | The Best Gift | PROGRAMMING | 1,100 | [
"constructive algorithms",
"implementation"
] | null | null | Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are *n* books on sale from one of *m* genres.
In the bookshop, Jack decides to buy two books of different genres.
Based on the genre of books on sale in the shop, find the number of options available to Jack for choosing two books of different genres for Emily. Options are considered different if they differ in at least one book.
The books are given by indices of their genres. The genres are numbered from 1 to *m*. | The first line contains two positive integers *n* and *m* (2<=≤<=*n*<=≤<=2·105,<=2<=≤<=*m*<=≤<=10) — the number of books in the bookstore and the number of genres.
The second line contains a sequence *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* (1<=≤<=*a**i*<=≤<=*m*) equals the genre of the *i*-th book.
It is guaranteed that for each genre there is at least one book of that genre. | Print the only integer — the number of ways in which Jack can choose books.
It is guaranteed that the answer doesn't exceed the value 2·109. | [
"4 3\n2 1 3 1\n",
"7 4\n4 2 3 1 2 4 3\n"
] | [
"5\n",
"18\n"
] | The answer to the first test sample equals 5 as Sasha can choose:
1. the first and second books, 1. the first and third books, 1. the first and fourth books, 1. the second and third books, 1. the third and fourth books. | 0 | [
{
"input": "4 3\n2 1 3 1",
"output": "5"
},
{
"input": "7 4\n4 2 3 1 2 4 3",
"output": "18"
},
{
"input": "2 2\n1 2",
"output": "1"
},
{
"input": "3 2\n1 2 2",
"output": "2"
},
{
"input": "10 10\n1 2 3 4 5 6 7 8 9 10",
"output": "45"
},
{
"input": "9 2... | 1,647,091,117 | 2,147,483,647 | PyPy 3-64 | TIME_LIMIT_EXCEEDED | TESTS | 18 | 2,000 | 11,264,000 | asd = input()
num = input().split()
count = 0
for j in range(len(num)):
for i in num[j+1:]:
if num[j] != i:
count += 1
print(count) | Title: The Best Gift
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are *n* books on sale from one of *m* genres.
In the bookshop, Jack decides to buy two books of different genres.
Based on the genre of books on sale in the shop, find the number of options available to Jack for choosing two books of different genres for Emily. Options are considered different if they differ in at least one book.
The books are given by indices of their genres. The genres are numbered from 1 to *m*.
Input Specification:
The first line contains two positive integers *n* and *m* (2<=≤<=*n*<=≤<=2·105,<=2<=≤<=*m*<=≤<=10) — the number of books in the bookstore and the number of genres.
The second line contains a sequence *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* (1<=≤<=*a**i*<=≤<=*m*) equals the genre of the *i*-th book.
It is guaranteed that for each genre there is at least one book of that genre.
Output Specification:
Print the only integer — the number of ways in which Jack can choose books.
It is guaranteed that the answer doesn't exceed the value 2·109.
Demo Input:
['4 3\n2 1 3 1\n', '7 4\n4 2 3 1 2 4 3\n']
Demo Output:
['5\n', '18\n']
Note:
The answer to the first test sample equals 5 as Sasha can choose:
1. the first and second books, 1. the first and third books, 1. the first and fourth books, 1. the second and third books, 1. the third and fourth books. | ```python
asd = input()
num = input().split()
count = 0
for j in range(len(num)):
for i in num[j+1:]:
if num[j] != i:
count += 1
print(count)
``` | 0 | |
560 | A | Currency System in Geraldion | PROGRAMMING | 1,000 | [
"implementation",
"sortings"
] | null | null | A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum? | The first line contains number *n* (1<=≤<=*n*<=≤<=1000) — the number of values of the banknotes that used in Geraldion.
The second line contains *n* distinct space-separated numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=106) — the values of the banknotes. | Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print <=-<=1. | [
"5\n1 2 3 4 5\n"
] | [
"-1\n"
] | none | 500 | [
{
"input": "5\n1 2 3 4 5",
"output": "-1"
},
{
"input": "1\n2",
"output": "1"
},
{
"input": "10\n371054 506438 397130 1 766759 208409 769264 549213 641270 771837",
"output": "-1"
},
{
"input": "10\n635370 154890 909382 220996 276501 716105 538714 140162 171960 271264",
"o... | 1,450,812,026 | 2,147,483,647 | Python 3 | OK | TESTS | 16 | 46 | 0 | n = int(input())
num = map(int, input().rstrip().split())
if 1 in num:
print(-1)
else:
print(1) | Title: Currency System in Geraldion
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
Input Specification:
The first line contains number *n* (1<=≤<=*n*<=≤<=1000) — the number of values of the banknotes that used in Geraldion.
The second line contains *n* distinct space-separated numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=106) — the values of the banknotes.
Output Specification:
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print <=-<=1.
Demo Input:
['5\n1 2 3 4 5\n']
Demo Output:
['-1\n']
Note:
none | ```python
n = int(input())
num = map(int, input().rstrip().split())
if 1 in num:
print(-1)
else:
print(1)
``` | 3 | |
703 | C | Chris and Road | PROGRAMMING | 2,100 | [
"geometry",
"implementation"
] | null | null | And while Mishka is enjoying her trip...
Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend.
Once walking with his friend, John gave Chris the following problem:
At the infinite horizontal road of width *w*, bounded by lines *y*<==<=0 and *y*<==<=*w*, there is a bus moving, presented as a convex polygon of *n* vertices. The bus moves continuously with a constant speed of *v* in a straight *Ox* line in direction of decreasing *x* coordinates, thus in time only *x* coordinates of its points are changing. Formally, after time *t* each of *x* coordinates of its points will be decreased by *vt*.
There is a pedestrian in the point (0,<=0), who can move only by a vertical pedestrian crossing, presented as a segment connecting points (0,<=0) and (0,<=*w*) with any speed not exceeding *u*. Thus the pedestrian can move only in a straight line *Oy* in any direction with any speed not exceeding *u* and not leaving the road borders. The pedestrian can instantly change his speed, thus, for example, he can stop instantly.
Please look at the sample note picture for better understanding.
We consider the pedestrian is hit by the bus, if at any moment the point he is located in lies strictly inside the bus polygon (this means that if the point lies on the polygon vertex or on its edge, the pedestrian is not hit by the bus).
You are given the bus position at the moment 0. Please help Chris determine minimum amount of time the pedestrian needs to cross the road and reach the point (0,<=*w*) and not to be hit by the bus. | The first line of the input contains four integers *n*, *w*, *v*, *u* (3<=≤<=*n*<=≤<=10<=000, 1<=≤<=*w*<=≤<=109, 1<=≤<=*v*,<=<=*u*<=≤<=1000) — the number of the bus polygon vertices, road width, bus speed and pedestrian speed respectively.
The next *n* lines describes polygon vertices in counter-clockwise order. *i*-th of them contains pair of integers *x**i* and *y**i* (<=-<=109<=≤<=*x**i*<=≤<=109, 0<=≤<=*y**i*<=≤<=*w*) — coordinates of *i*-th polygon point. It is guaranteed that the polygon is non-degenerate. | Print the single real *t* — the time the pedestrian needs to croos the road and not to be hit by the bus. The answer is considered correct if its relative or absolute error doesn't exceed 10<=-<=6. | [
"5 5 1 2\n1 2\n3 1\n4 3\n3 4\n1 4\n"
] | [
"5.0000000000"
] | Following image describes initial position in the first sample case:
<img class="tex-graphics" src="https://espresso.codeforces.com/6d0966ee3194a0c11a228fa83f19a00157de89f7.png" style="max-width: 100.0%;max-height: 100.0%;"/> | 1,750 | [
{
"input": "5 5 1 2\n1 2\n3 1\n4 3\n3 4\n1 4",
"output": "5.0000000000"
},
{
"input": "3 3 5 2\n3 1\n4 0\n5 1",
"output": "1.5000000000"
},
{
"input": "3 3 2 4\n0 1\n2 1\n1 2",
"output": "1.5000000000"
},
{
"input": "3 3 1 1\n0 0\n1 1\n0 2",
"output": "3.0000000000"
},
... | 1,689,168,344 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 30 | 0 | print("_RANDOM_GUESS_1689168344.601377")# 1689168344.601391 | Title: Chris and Road
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
And while Mishka is enjoying her trip...
Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend.
Once walking with his friend, John gave Chris the following problem:
At the infinite horizontal road of width *w*, bounded by lines *y*<==<=0 and *y*<==<=*w*, there is a bus moving, presented as a convex polygon of *n* vertices. The bus moves continuously with a constant speed of *v* in a straight *Ox* line in direction of decreasing *x* coordinates, thus in time only *x* coordinates of its points are changing. Formally, after time *t* each of *x* coordinates of its points will be decreased by *vt*.
There is a pedestrian in the point (0,<=0), who can move only by a vertical pedestrian crossing, presented as a segment connecting points (0,<=0) and (0,<=*w*) with any speed not exceeding *u*. Thus the pedestrian can move only in a straight line *Oy* in any direction with any speed not exceeding *u* and not leaving the road borders. The pedestrian can instantly change his speed, thus, for example, he can stop instantly.
Please look at the sample note picture for better understanding.
We consider the pedestrian is hit by the bus, if at any moment the point he is located in lies strictly inside the bus polygon (this means that if the point lies on the polygon vertex or on its edge, the pedestrian is not hit by the bus).
You are given the bus position at the moment 0. Please help Chris determine minimum amount of time the pedestrian needs to cross the road and reach the point (0,<=*w*) and not to be hit by the bus.
Input Specification:
The first line of the input contains four integers *n*, *w*, *v*, *u* (3<=≤<=*n*<=≤<=10<=000, 1<=≤<=*w*<=≤<=109, 1<=≤<=*v*,<=<=*u*<=≤<=1000) — the number of the bus polygon vertices, road width, bus speed and pedestrian speed respectively.
The next *n* lines describes polygon vertices in counter-clockwise order. *i*-th of them contains pair of integers *x**i* and *y**i* (<=-<=109<=≤<=*x**i*<=≤<=109, 0<=≤<=*y**i*<=≤<=*w*) — coordinates of *i*-th polygon point. It is guaranteed that the polygon is non-degenerate.
Output Specification:
Print the single real *t* — the time the pedestrian needs to croos the road and not to be hit by the bus. The answer is considered correct if its relative or absolute error doesn't exceed 10<=-<=6.
Demo Input:
['5 5 1 2\n1 2\n3 1\n4 3\n3 4\n1 4\n']
Demo Output:
['5.0000000000']
Note:
Following image describes initial position in the first sample case:
<img class="tex-graphics" src="https://espresso.codeforces.com/6d0966ee3194a0c11a228fa83f19a00157de89f7.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
print("_RANDOM_GUESS_1689168344.601377")# 1689168344.601391
``` | 0 | |
462 | A | Appleman and Easy Task | PROGRAMMING | 1,000 | [
"brute force",
"implementation"
] | null | null | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a *n*<=×<=*n* checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). Then *n* lines follow containing the description of the checkerboard. Each of them contains *n* characters (either 'x' or 'o') without spaces. | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | [
"3\nxxo\nxox\noxx\n",
"4\nxxxo\nxoxo\noxox\nxxxx\n"
] | [
"YES\n",
"NO\n"
] | none | 500 | [
{
"input": "3\nxxo\nxox\noxx",
"output": "YES"
},
{
"input": "4\nxxxo\nxoxo\noxox\nxxxx",
"output": "NO"
},
{
"input": "1\no",
"output": "YES"
},
{
"input": "2\nox\nxo",
"output": "YES"
},
{
"input": "2\nxx\nxo",
"output": "NO"
},
{
"input": "3\nooo\no... | 1,648,535,153 | 2,147,483,647 | Python 3 | OK | TESTS | 32 | 46 | 0 | num = int(input())
li = []
for x in range(num):
l = input()
for i in l:
if i == "x":
li.append(0)
else:
li.append(1)
li = [0 for x in range(num)] + li + [0 for x in range(num)]
lis = []
for x in range(num,len(li)-num):
if x%num==0:
lis.append(li[x+1]+ li[x-num]+ li[x+num])
elif (x+1)%num==0:
lis.append(li[x-1]+ li[x-num]+ li[x+num])
else:
lis.append(li[x-1]+ li[x+1]+ li[x-num]+ li[x+num])
yes = True
for i in lis:
if i%2 == 0:
yes = True
else:
yes = False
break
if yes: print("YES")
else: print("NO") | Title: Appleman and Easy Task
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a *n*<=×<=*n* checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). Then *n* lines follow containing the description of the checkerboard. Each of them contains *n* characters (either 'x' or 'o') without spaces.
Output Specification:
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
Demo Input:
['3\nxxo\nxox\noxx\n', '4\nxxxo\nxoxo\noxox\nxxxx\n']
Demo Output:
['YES\n', 'NO\n']
Note:
none | ```python
num = int(input())
li = []
for x in range(num):
l = input()
for i in l:
if i == "x":
li.append(0)
else:
li.append(1)
li = [0 for x in range(num)] + li + [0 for x in range(num)]
lis = []
for x in range(num,len(li)-num):
if x%num==0:
lis.append(li[x+1]+ li[x-num]+ li[x+num])
elif (x+1)%num==0:
lis.append(li[x-1]+ li[x-num]+ li[x+num])
else:
lis.append(li[x-1]+ li[x+1]+ li[x-num]+ li[x+num])
yes = True
for i in lis:
if i%2 == 0:
yes = True
else:
yes = False
break
if yes: print("YES")
else: print("NO")
``` | 3 | |
71 | A | Way Too Long Words | PROGRAMMING | 800 | [
"strings"
] | A. Way Too Long Words | 1 | 256 | Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes. | The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). Each of the following *n* lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters. | Print *n* lines. The *i*-th line should contain the result of replacing of the *i*-th word from the input data. | [
"4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis\n"
] | [
"word\nl10n\ni18n\np43s\n"
] | none | 500 | [
{
"input": "4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis",
"output": "word\nl10n\ni18n\np43s"
},
{
"input": "5\nabcdefgh\nabcdefghi\nabcdefghij\nabcdefghijk\nabcdefghijklm",
"output": "abcdefgh\nabcdefghi\nabcdefghij\na9k\na11m"
},
{
"input":... | 1,694,806,020 | 2,147,483,647 | Python 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | s = input()
start = 1
end = len(s) - 1
counts = 0
res = s
if len(s) <= 1:
break
for i in range(start, end):
if len(s) >= 10:
counts+=1
re = str(counts)
res = (f"{s[0]}{counts}{s[end]}")
print(res) | Title: Way Too Long Words
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). Each of the following *n* lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output Specification:
Print *n* lines. The *i*-th line should contain the result of replacing of the *i*-th word from the input data.
Demo Input:
['4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis\n']
Demo Output:
['word\nl10n\ni18n\np43s\n']
Note:
none | ```python
s = input()
start = 1
end = len(s) - 1
counts = 0
res = s
if len(s) <= 1:
break
for i in range(start, end):
if len(s) >= 10:
counts+=1
re = str(counts)
res = (f"{s[0]}{counts}{s[end]}")
print(res)
``` | -1 |
622 | C | Not Equal on a Segment | PROGRAMMING | 1,700 | [
"data structures",
"implementation"
] | null | null | You are given array *a* with *n* integers and *m* queries. The *i*-th query is given with three integers *l**i*,<=*r**i*,<=*x**i*.
For the *i*-th query find any position *p**i* (*l**i*<=≤<=*p**i*<=≤<=*r**i*) so that *a**p**i*<=≠<=*x**i*. | The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=2·105) — the number of elements in *a* and the number of queries.
The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=106) — the elements of the array *a*.
Each of the next *m* lines contains three integers *l**i*,<=*r**i*,<=*x**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*,<=1<=≤<=*x**i*<=≤<=106) — the parameters of the *i*-th query. | Print *m* lines. On the *i*-th line print integer *p**i* — the position of any number not equal to *x**i* in segment [*l**i*,<=*r**i*] or the value <=-<=1 if there is no such number. | [
"6 4\n1 2 1 1 3 5\n1 4 1\n2 6 2\n3 4 1\n3 4 2\n"
] | [
"2\n6\n-1\n4\n"
] | none | 0 | [
{
"input": "6 4\n1 2 1 1 3 5\n1 4 1\n2 6 2\n3 4 1\n3 4 2",
"output": "2\n6\n-1\n4"
},
{
"input": "1 1\n1\n1 1 1",
"output": "-1"
},
{
"input": "1 1\n2\n1 1 2",
"output": "-1"
},
{
"input": "1 1\n569888\n1 1 967368",
"output": "1"
},
{
"input": "10 10\n1 1 1 1 1 1 ... | 1,463,127,229 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 10 | 1,000 | 5,120,000 | class number:
def __init__(self,n,num):
self.n = n
self.num = num
def upquicksort(sta,l,r):
if l >= r:
return
i = l
j = r
temp = sta[i]
while i != j:
while j > i and sta[j].n > temp.n:
j -= 1
if j > i:
sta[i] = sta[j]
i += 1
while j > i and sta[i].n < temp.n:
i += 1
if j > i:
sta[j] = sta[i]
j -= 1
sta[i] = temp
upquicksort(sta,l,i-1)
upquicksort(sta,i+1,r)
return
n,m = map(int,input().split())
a1 = list(map(int,input().split()))
a = []
for i in range(len(a1)):
a.append(number(a1[i],i+1))
for i in range(m):
b = list(map(int,input().split()))
c = a[b[0]-1:b[1]]
upquicksort(c,0,len(c)-1)
if c[0].n != b[2]:
print (c[0].num)
elif c[-1].n != b[2]:
print (c[-1].num)
else:
print (-1)
| Title: Not Equal on a Segment
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given array *a* with *n* integers and *m* queries. The *i*-th query is given with three integers *l**i*,<=*r**i*,<=*x**i*.
For the *i*-th query find any position *p**i* (*l**i*<=≤<=*p**i*<=≤<=*r**i*) so that *a**p**i*<=≠<=*x**i*.
Input Specification:
The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=2·105) — the number of elements in *a* and the number of queries.
The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=106) — the elements of the array *a*.
Each of the next *m* lines contains three integers *l**i*,<=*r**i*,<=*x**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*,<=1<=≤<=*x**i*<=≤<=106) — the parameters of the *i*-th query.
Output Specification:
Print *m* lines. On the *i*-th line print integer *p**i* — the position of any number not equal to *x**i* in segment [*l**i*,<=*r**i*] or the value <=-<=1 if there is no such number.
Demo Input:
['6 4\n1 2 1 1 3 5\n1 4 1\n2 6 2\n3 4 1\n3 4 2\n']
Demo Output:
['2\n6\n-1\n4\n']
Note:
none | ```python
class number:
def __init__(self,n,num):
self.n = n
self.num = num
def upquicksort(sta,l,r):
if l >= r:
return
i = l
j = r
temp = sta[i]
while i != j:
while j > i and sta[j].n > temp.n:
j -= 1
if j > i:
sta[i] = sta[j]
i += 1
while j > i and sta[i].n < temp.n:
i += 1
if j > i:
sta[j] = sta[i]
j -= 1
sta[i] = temp
upquicksort(sta,l,i-1)
upquicksort(sta,i+1,r)
return
n,m = map(int,input().split())
a1 = list(map(int,input().split()))
a = []
for i in range(len(a1)):
a.append(number(a1[i],i+1))
for i in range(m):
b = list(map(int,input().split()))
c = a[b[0]-1:b[1]]
upquicksort(c,0,len(c)-1)
if c[0].n != b[2]:
print (c[0].num)
elif c[-1].n != b[2]:
print (c[-1].num)
else:
print (-1)
``` | 0 | |
855 | B | Marvolo Gaunt's Ring | PROGRAMMING | 1,500 | [
"brute force",
"data structures",
"dp"
] | null | null | Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly *x* drops of the potion he made.
Value of *x* is calculated as maximum of *p*·*a**i*<=+<=*q*·*a**j*<=+<=*r*·*a**k* for given *p*,<=*q*,<=*r* and array *a*1,<=*a*2,<=... *a**n* such that 1<=≤<=*i*<=≤<=*j*<=≤<=*k*<=≤<=*n*. Help Snape find the value of *x*. Do note that the value of *x* may be negative. | First line of input contains 4 integers *n*,<=*p*,<=*q*,<=*r* (<=-<=109<=≤<=*p*,<=*q*,<=*r*<=≤<=109,<=1<=≤<=*n*<=≤<=105).
Next line of input contains *n* space separated integers *a*1,<=*a*2,<=... *a**n* (<=-<=109<=≤<=*a**i*<=≤<=109). | Output a single integer the maximum value of *p*·*a**i*<=+<=*q*·*a**j*<=+<=*r*·*a**k* that can be obtained provided 1<=≤<=*i*<=≤<=*j*<=≤<=*k*<=≤<=*n*. | [
"5 1 2 3\n1 2 3 4 5\n",
"5 1 2 -3\n-1 -2 -3 -4 -5\n"
] | [
"30\n",
"12\n"
] | In the first sample case, we can take *i* = *j* = *k* = 5, thus making the answer as 1·5 + 2·5 + 3·5 = 30.
In second sample case, selecting *i* = *j* = 1 and *k* = 5 gives the answer 12. | 1,000 | [
{
"input": "5 1 2 3\n1 2 3 4 5",
"output": "30"
},
{
"input": "5 1 2 -3\n-1 -2 -3 -4 -5",
"output": "12"
},
{
"input": "5 886327859 82309257 -68295239\n-731225382 354766539 -48222231 -474691998 360965777",
"output": "376059240645059046"
},
{
"input": "4 -96405765 -495906217 6... | 1,691,231,512 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 82 | 108 | 17,920,000 | n,p,q,r=map(int,input().split())
arr=list(map(int,input().strip().split()))
pi,qj,rk= [],[],[]
for i in range(n):
x=arr[i]
pi.append(x*p)
qj.append(x*q)
rk.append(x*r)
for i in range(1,n):
pi[i]=max(pi[i-1],pi[i])
rk[n-i-1]=max(rk[n-i],rk[n-i-1])
s=pi[0]+qj[0]+rk[0]
for i in range(1,n):s=max(s,pi[i]+qj[i]+rk[i])
print(s) | Title: Marvolo Gaunt's Ring
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly *x* drops of the potion he made.
Value of *x* is calculated as maximum of *p*·*a**i*<=+<=*q*·*a**j*<=+<=*r*·*a**k* for given *p*,<=*q*,<=*r* and array *a*1,<=*a*2,<=... *a**n* such that 1<=≤<=*i*<=≤<=*j*<=≤<=*k*<=≤<=*n*. Help Snape find the value of *x*. Do note that the value of *x* may be negative.
Input Specification:
First line of input contains 4 integers *n*,<=*p*,<=*q*,<=*r* (<=-<=109<=≤<=*p*,<=*q*,<=*r*<=≤<=109,<=1<=≤<=*n*<=≤<=105).
Next line of input contains *n* space separated integers *a*1,<=*a*2,<=... *a**n* (<=-<=109<=≤<=*a**i*<=≤<=109).
Output Specification:
Output a single integer the maximum value of *p*·*a**i*<=+<=*q*·*a**j*<=+<=*r*·*a**k* that can be obtained provided 1<=≤<=*i*<=≤<=*j*<=≤<=*k*<=≤<=*n*.
Demo Input:
['5 1 2 3\n1 2 3 4 5\n', '5 1 2 -3\n-1 -2 -3 -4 -5\n']
Demo Output:
['30\n', '12\n']
Note:
In the first sample case, we can take *i* = *j* = *k* = 5, thus making the answer as 1·5 + 2·5 + 3·5 = 30.
In second sample case, selecting *i* = *j* = 1 and *k* = 5 gives the answer 12. | ```python
n,p,q,r=map(int,input().split())
arr=list(map(int,input().strip().split()))
pi,qj,rk= [],[],[]
for i in range(n):
x=arr[i]
pi.append(x*p)
qj.append(x*q)
rk.append(x*r)
for i in range(1,n):
pi[i]=max(pi[i-1],pi[i])
rk[n-i-1]=max(rk[n-i],rk[n-i-1])
s=pi[0]+qj[0]+rk[0]
for i in range(1,n):s=max(s,pi[i]+qj[i]+rk[i])
print(s)
``` | 3 | |
186 | A | Comparing Strings | PROGRAMMING | 1,100 | [
"implementation",
"strings"
] | null | null | Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.
Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not. | The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters.
The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters.
The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length. | Print "YES", if the dwarves belong to the same race. Otherwise, print "NO". | [
"ab\nba\n",
"aa\nab\n"
] | [
"YES\n",
"NO\n"
] | - First example: you can simply swap two letters in string "ab". So we get "ba". - Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b". | 500 | [
{
"input": "ab\nba",
"output": "YES"
},
{
"input": "aa\nab",
"output": "NO"
},
{
"input": "a\nza",
"output": "NO"
},
{
"input": "vvea\nvvae",
"output": "YES"
},
{
"input": "rtfabanpc\natfabrnpc",
"output": "YES"
},
{
"input": "mt\ntm",
"output": "Y... | 1,615,054,742 | 2,147,483,647 | Python 3 | OK | TESTS | 53 | 154 | 716,800 | a = input()
b = input()
d = 0
f = []
if not len(a) == len(b):
print('NO')
else:
for i in range(len(a)):
if not a[i] == b[i]:
d += 1
if d == 3:
break
f.append([a[i], b[i]])
if d == 2:
print('YES' if f[0][0] == f[1][1] and f[0][1] == f[1][0] else 'NO')
else:
print('NO')
| Title: Comparing Strings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.
Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.
Input Specification:
The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters.
The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters.
The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length.
Output Specification:
Print "YES", if the dwarves belong to the same race. Otherwise, print "NO".
Demo Input:
['ab\nba\n', 'aa\nab\n']
Demo Output:
['YES\n', 'NO\n']
Note:
- First example: you can simply swap two letters in string "ab". So we get "ba". - Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b". | ```python
a = input()
b = input()
d = 0
f = []
if not len(a) == len(b):
print('NO')
else:
for i in range(len(a)):
if not a[i] == b[i]:
d += 1
if d == 3:
break
f.append([a[i], b[i]])
if d == 2:
print('YES' if f[0][0] == f[1][1] and f[0][1] == f[1][0] else 'NO')
else:
print('NO')
``` | 3 | |
982 | B | Bus of Characters | PROGRAMMING | 1,300 | [
"data structures",
"greedy",
"implementation"
] | null | null | In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct.
Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers:
- an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; - an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it.
You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take. | The first line contains a single integer $n$ ($1 \le n \le 200\,000$) — the number of rows in the bus.
The second line contains the sequence of integers $w_1, w_2, \dots, w_n$ ($1 \le w_i \le 10^{9}$), where $w_i$ is the width of each of the seats in the $i$-th row. It is guaranteed that all $w_i$ are distinct.
The third line contains a string of length $2n$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $j$-th character is '0', then the passenger that enters the bus on the $j$-th stop is an introvert. If the $j$-th character is '1', the the passenger that enters the bus on the $j$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $n$), and for each extrovert there always is a suitable row. | Print $2n$ integers — the rows the passengers will take. The order of passengers should be the same as in input. | [
"2\n3 1\n0011\n",
"6\n10 8 9 11 13 5\n010010011101\n"
] | [
"2 1 1 2 \n",
"6 6 2 3 3 1 4 4 1 2 5 5 \n"
] | In the first example the first passenger (introvert) chooses the row $2$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $1$, because it is the only empty row now. The third passenger (extrovert) chooses the row $1$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $2$, because it is the only row with an empty place. | 1,000 | [
{
"input": "2\n3 1\n0011",
"output": "2 1 1 2 "
},
{
"input": "6\n10 8 9 11 13 5\n010010011101",
"output": "6 6 2 3 3 1 4 4 1 2 5 5 "
},
{
"input": "1\n1\n01",
"output": "1 1 "
},
{
"input": "1\n1000000\n01",
"output": "1 1 "
},
{
"input": "2\n1 1000000\n0011",
... | 1,598,898,097 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 5 | 140 | 0 | try:
n = int(input())
ans = []
ansst = ""
seats = list(map(int,input().split()))
que = input()
quelen = len(que)
mis = min(seats)
ind = seats.index(mis)
ans.append(ind+1)
ansst+=str(ind+1)
ansst+=" "
seats[ind]=23563652
for k in range(1,quelen):
if(que[k]=='0'):
mis = min(seats)
ind = seats.index(mis)
ans.append(ind+1)
ansst+=str(ind+1)
ansst+=" "
seats[ind]=23563652
else:
for u in range(len(ans)-1,-1,-1):
if(ans.count(ans[u])!=2):
ans.append(ans[u])
ansst+=str(ans[u])
ansst+=" "
break
print(ansst)
except:
pass
| Title: Bus of Characters
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct.
Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers:
- an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; - an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it.
You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.
Input Specification:
The first line contains a single integer $n$ ($1 \le n \le 200\,000$) — the number of rows in the bus.
The second line contains the sequence of integers $w_1, w_2, \dots, w_n$ ($1 \le w_i \le 10^{9}$), where $w_i$ is the width of each of the seats in the $i$-th row. It is guaranteed that all $w_i$ are distinct.
The third line contains a string of length $2n$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $j$-th character is '0', then the passenger that enters the bus on the $j$-th stop is an introvert. If the $j$-th character is '1', the the passenger that enters the bus on the $j$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $n$), and for each extrovert there always is a suitable row.
Output Specification:
Print $2n$ integers — the rows the passengers will take. The order of passengers should be the same as in input.
Demo Input:
['2\n3 1\n0011\n', '6\n10 8 9 11 13 5\n010010011101\n']
Demo Output:
['2 1 1 2 \n', '6 6 2 3 3 1 4 4 1 2 5 5 \n']
Note:
In the first example the first passenger (introvert) chooses the row $2$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $1$, because it is the only empty row now. The third passenger (extrovert) chooses the row $1$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $2$, because it is the only row with an empty place. | ```python
try:
n = int(input())
ans = []
ansst = ""
seats = list(map(int,input().split()))
que = input()
quelen = len(que)
mis = min(seats)
ind = seats.index(mis)
ans.append(ind+1)
ansst+=str(ind+1)
ansst+=" "
seats[ind]=23563652
for k in range(1,quelen):
if(que[k]=='0'):
mis = min(seats)
ind = seats.index(mis)
ans.append(ind+1)
ansst+=str(ind+1)
ansst+=" "
seats[ind]=23563652
else:
for u in range(len(ans)-1,-1,-1):
if(ans.count(ans[u])!=2):
ans.append(ans[u])
ansst+=str(ans[u])
ansst+=" "
break
print(ansst)
except:
pass
``` | 0 | |
358 | B | Dima and Text Messages | PROGRAMMING | 1,500 | [
"brute force",
"strings"
] | null | null | Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.
Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3*word*1<3*word*2<3 ... *word**n*<3.
Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.
Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above. | The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of words in Dima's message. Next *n* lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105.
The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less. | In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise. | [
"3\ni\nlove\nyou\n<3i<3love<23you<3\n",
"7\ni\nam\nnot\nmain\nin\nthe\nfamily\n<3i<>3am<3the<3<main<3in<3the<3><3family<3\n"
] | [
"yes\n",
"no\n"
] | Please note that Dima got a good old kick in the pants for the second sample from the statement. | 1,000 | [
{
"input": "3\ni\nlove\nyou\n<3i<3love<23you<3",
"output": "yes"
},
{
"input": "7\ni\nam\nnot\nmain\nin\nthe\nfamily\n<3i<>3am<3the<3<main<3in<3the<3><3family<3",
"output": "no"
},
{
"input": "3\ni\nlove\nyou\n<3i<3lo<3ve<3y<<<<<<<ou3<3",
"output": "yes"
},
{
"input": "4\na\n... | 1,653,941,980 | 2,147,483,647 | PyPy 3 | OK | TESTS | 30 | 702 | 10,035,200 | s = []
for i in range(int(input())):
s.append(input())
s = "<3" + '<3'.join(s) + "<3"
cur = 0
t = input()
for i in t:
if i == s[cur]: cur += 1
if cur == len(s): break
print('yes' if cur == len(s) else 'no') | Title: Dima and Text Messages
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.
Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3*word*1<3*word*2<3 ... *word**n*<3.
Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.
Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of words in Dima's message. Next *n* lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105.
The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.
Output Specification:
In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.
Demo Input:
['3\ni\nlove\nyou\n<3i<3love<23you<3\n', '7\ni\nam\nnot\nmain\nin\nthe\nfamily\n<3i<>3am<3the<3<main<3in<3the<3><3family<3\n']
Demo Output:
['yes\n', 'no\n']
Note:
Please note that Dima got a good old kick in the pants for the second sample from the statement. | ```python
s = []
for i in range(int(input())):
s.append(input())
s = "<3" + '<3'.join(s) + "<3"
cur = 0
t = input()
for i in t:
if i == s[cur]: cur += 1
if cur == len(s): break
print('yes' if cur == len(s) else 'no')
``` | 3 | |
250 | A | Paper Work | PROGRAMMING | 1,000 | [
"greedy"
] | null | null | Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as *n* days. Right now his task is to make a series of reports about the company's performance for the last *n* days. We know that the main information in a day report is value *a**i*, the company's profit on the *i*-th day. If *a**i* is negative, then the company suffered losses on the *i*-th day.
Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the *n* days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.
It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (*a**i*<=<<=0), he loses his temper and his wrath is terrible.
Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.
Write a program that, given sequence *a**i*, will print the minimum number of folders. | The first line contains integer *n* (1<=≤<=*n*<=≤<=100), *n* is the number of days. The second line contains a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (|*a**i*|<=≤<=100), where *a**i* means the company profit on the *i*-th day. It is possible that the company has no days with the negative *a**i*. | Print an integer *k* — the required minimum number of folders. In the second line print a sequence of integers *b*1, *b*2, ..., *b**k*, where *b**j* is the number of day reports in the *j*-th folder.
If there are multiple ways to sort the reports into *k* days, print any of them. | [
"11\n1 2 3 -4 -5 -6 5 -5 -6 -7 6\n",
"5\n0 -1 100 -1 0\n"
] | [
"3\n5 3 3 ",
"1\n5 "
] | Here goes a way to sort the reports from the first sample into three folders:
In the second sample you can put all five reports in one folder. | 500 | [
{
"input": "11\n1 2 3 -4 -5 -6 5 -5 -6 -7 6",
"output": "3\n5 3 3 "
},
{
"input": "5\n0 -1 100 -1 0",
"output": "1\n5 "
},
{
"input": "1\n0",
"output": "1\n1 "
},
{
"input": "1\n-1",
"output": "1\n1 "
},
{
"input": "2\n0 0",
"output": "1\n2 "
},
{
"inp... | 1,667,083,853 | 2,147,483,647 | Python 3 | OK | TESTS | 69 | 92 | 0 | days = int(input())
sequence = input().split()
folder = 1
bad_rep = 0
rep = 0
ans = ""
for profit in sequence:
rep += 1
if int(profit) < 0:
bad_rep += 1
if bad_rep == 3:
folder += 1
ans = ans + str(rep - 1) + " "
bad_rep = 1
rep = 1
ans += str(rep)
print(folder)
print(ans)
| Title: Paper Work
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as *n* days. Right now his task is to make a series of reports about the company's performance for the last *n* days. We know that the main information in a day report is value *a**i*, the company's profit on the *i*-th day. If *a**i* is negative, then the company suffered losses on the *i*-th day.
Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the *n* days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.
It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (*a**i*<=<<=0), he loses his temper and his wrath is terrible.
Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.
Write a program that, given sequence *a**i*, will print the minimum number of folders.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=100), *n* is the number of days. The second line contains a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (|*a**i*|<=≤<=100), where *a**i* means the company profit on the *i*-th day. It is possible that the company has no days with the negative *a**i*.
Output Specification:
Print an integer *k* — the required minimum number of folders. In the second line print a sequence of integers *b*1, *b*2, ..., *b**k*, where *b**j* is the number of day reports in the *j*-th folder.
If there are multiple ways to sort the reports into *k* days, print any of them.
Demo Input:
['11\n1 2 3 -4 -5 -6 5 -5 -6 -7 6\n', '5\n0 -1 100 -1 0\n']
Demo Output:
['3\n5 3 3 ', '1\n5 ']
Note:
Here goes a way to sort the reports from the first sample into three folders:
In the second sample you can put all five reports in one folder. | ```python
days = int(input())
sequence = input().split()
folder = 1
bad_rep = 0
rep = 0
ans = ""
for profit in sequence:
rep += 1
if int(profit) < 0:
bad_rep += 1
if bad_rep == 3:
folder += 1
ans = ans + str(rep - 1) + " "
bad_rep = 1
rep = 1
ans += str(rep)
print(folder)
print(ans)
``` | 3 | |
938 | B | Run For Your Prize | PROGRAMMING | 1,100 | [
"brute force",
"greedy"
] | null | null | You and your friend are participating in a TV show "Run For Your Prize".
At the start of the show *n* prizes are located on a straight line. *i*-th prize is located at position *a**i*. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.
You know that it takes exactly 1 second to move from position *x* to position *x*<=+<=1 or *x*<=-<=1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.
Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.
What is the minimum number of seconds it will take to pick up all the prizes? | The first line contains one integer *n* (1<=≤<=*n*<=≤<=105) — the number of prizes.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (2<=≤<=*a**i*<=≤<=106<=-<=1) — the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order. | Print one integer — the minimum number of seconds it will take to collect all prizes. | [
"3\n2 3 9\n",
"2\n2 999995\n"
] | [
"8\n",
"5\n"
] | In the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.
In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5. | 0 | [
{
"input": "3\n2 3 9",
"output": "8"
},
{
"input": "2\n2 999995",
"output": "5"
},
{
"input": "1\n20",
"output": "19"
},
{
"input": "6\n2 3 500000 999997 999998 999999",
"output": "499999"
},
{
"input": "1\n999999",
"output": "1"
},
{
"input": "1\n5100... | 1,639,988,402 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 78 | 7,372,800 | n = int(input())
if n!=0:
str = list(map(int,input().split()))
sum = 0
A = []
B = []
for i in str:
if i <= 500000:
A.append(i)
if i > 500000:
B.append(i)
A.sort()
A.reverse()
B.sort()
if len(A)!=0 and len(B)!=0:
print(A[0]-1+999999-B[0])
if len(A)!=0 and len(B)==0:
print(A[0]-1)
if len(A)==0 and len(b)!=0:
print(999999-B[0])
| Title: Run For Your Prize
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You and your friend are participating in a TV show "Run For Your Prize".
At the start of the show *n* prizes are located on a straight line. *i*-th prize is located at position *a**i*. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.
You know that it takes exactly 1 second to move from position *x* to position *x*<=+<=1 or *x*<=-<=1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.
Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.
What is the minimum number of seconds it will take to pick up all the prizes?
Input Specification:
The first line contains one integer *n* (1<=≤<=*n*<=≤<=105) — the number of prizes.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (2<=≤<=*a**i*<=≤<=106<=-<=1) — the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.
Output Specification:
Print one integer — the minimum number of seconds it will take to collect all prizes.
Demo Input:
['3\n2 3 9\n', '2\n2 999995\n']
Demo Output:
['8\n', '5\n']
Note:
In the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.
In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5. | ```python
n = int(input())
if n!=0:
str = list(map(int,input().split()))
sum = 0
A = []
B = []
for i in str:
if i <= 500000:
A.append(i)
if i > 500000:
B.append(i)
A.sort()
A.reverse()
B.sort()
if len(A)!=0 and len(B)!=0:
print(A[0]-1+999999-B[0])
if len(A)!=0 and len(B)==0:
print(A[0]-1)
if len(A)==0 and len(b)!=0:
print(999999-B[0])
``` | 0 | |
404 | D | Minesweeper 1D | PROGRAMMING | 1,900 | [
"dp",
"implementation"
] | null | null | Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is *n* squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.
For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.
Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of *n* cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end. | The first line contains sequence of characters without spaces *s*1*s*2... *s**n* (1<=≤<=*n*<=≤<=106), containing only characters "*", "?" and digits "0", "1" or "2". If character *s**i* equals "*", then the *i*-th cell of the field contains a bomb. If character *s**i* equals "?", then Valera hasn't yet decided what to put in the *i*-th cell. Character *s**i*, that is equal to a digit, represents the digit written in the *i*-th square. | Print a single integer — the number of ways Valera can fill the empty cells and get a correct field.
As the answer can be rather large, print it modulo 1000000007 (109<=+<=7). | [
"?01???\n",
"?\n",
"**12\n",
"1\n"
] | [
"4\n",
"2\n",
"0\n",
"0\n"
] | In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10. | 2,000 | [
{
"input": "?01???",
"output": "4"
},
{
"input": "?",
"output": "2"
},
{
"input": "**12",
"output": "0"
},
{
"input": "1",
"output": "0"
},
{
"input": "?01*??****",
"output": "4"
},
{
"input": "0",
"output": "1"
},
{
"input": "2",
"outp... | 1,675,861,476 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 7 | 889 | 3,072,000 | # LUOGU_RID: 101728300
s=input()
mod=1000000007
a,b,c=1,1,0
for ch in s:
if ch=='0':a,b,c=a,0,0
elif ch=='1':a,b,c=c,a,0
elif ch=='2':a,b,c=0,c,0
elif ch=='*':a,b,c=0,0,b+c
else:a,b,c=a+c,a+c,b+c
a%=mod
b%=mod
c%=mod
print(a+c) | Title: Minesweeper 1D
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is *n* squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.
For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.
Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of *n* cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.
Input Specification:
The first line contains sequence of characters without spaces *s*1*s*2... *s**n* (1<=≤<=*n*<=≤<=106), containing only characters "*", "?" and digits "0", "1" or "2". If character *s**i* equals "*", then the *i*-th cell of the field contains a bomb. If character *s**i* equals "?", then Valera hasn't yet decided what to put in the *i*-th cell. Character *s**i*, that is equal to a digit, represents the digit written in the *i*-th square.
Output Specification:
Print a single integer — the number of ways Valera can fill the empty cells and get a correct field.
As the answer can be rather large, print it modulo 1000000007 (109<=+<=7).
Demo Input:
['?01???\n', '?\n', '**12\n', '1\n']
Demo Output:
['4\n', '2\n', '0\n', '0\n']
Note:
In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10. | ```python
# LUOGU_RID: 101728300
s=input()
mod=1000000007
a,b,c=1,1,0
for ch in s:
if ch=='0':a,b,c=a,0,0
elif ch=='1':a,b,c=c,a,0
elif ch=='2':a,b,c=0,c,0
elif ch=='*':a,b,c=0,0,b+c
else:a,b,c=a+c,a+c,b+c
a%=mod
b%=mod
c%=mod
print(a+c)
``` | 0 | |
907 | A | Masha and Bears | PROGRAMMING | 1,300 | [
"brute force",
"implementation"
] | null | null | A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car.
Masha came to test these cars. She could climb into all cars, but she liked only the smallest car.
It's known that a character with size *a* can climb into some car with size *b* if and only if *a*<=≤<=*b*, he or she likes it if and only if he can climb into this car and 2*a*<=≥<=*b*.
You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars. | You are given four integers *V*1, *V*2, *V*3, *V**m*(1<=≤<=*V**i*<=≤<=100) — sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that *V*1<=><=*V*2<=><=*V*3. | Output three integers — sizes of father bear's car, mother bear's car and son bear's car, respectively.
If there are multiple possible solutions, print any.
If there is no solution, print "-1" (without quotes). | [
"50 30 10 10\n",
"100 50 10 21\n"
] | [
"50\n30\n10\n",
"-1\n"
] | In first test case all conditions for cars' sizes are satisfied.
In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20. | 500 | [
{
"input": "50 30 10 10",
"output": "50\n30\n10"
},
{
"input": "100 50 10 21",
"output": "-1"
},
{
"input": "100 50 19 10",
"output": "100\n50\n19"
},
{
"input": "99 50 25 49",
"output": "100\n99\n49"
},
{
"input": "3 2 1 1",
"output": "4\n3\n1"
},
{
"... | 1,573,786,748 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 109 | 0 | bearSizesInput = input()
bearSizesSplit = bearSizesInput.split()
v1 = int(bearSizesSplit[0])
v2 = int(bearSizesSplit[1])
v3 = int(bearSizesSplit[2])
vm = int(bearSizesSplit[3])
bearSizes = [v1, v2, v3]
selectedSizes = []
for bearSize in bearSizes:
maxHeight = bearSize * 2
if maxHeight >= vm and vm <= bearSize:
selectedSizes.append(bearSize)
else:
selectedSizes.clear()
break
if len(selectedSizes) == 0:
print("-1")
else:
for selectedSize in selectedSizes:
print(selectedSize) | Title: Masha and Bears
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car.
Masha came to test these cars. She could climb into all cars, but she liked only the smallest car.
It's known that a character with size *a* can climb into some car with size *b* if and only if *a*<=≤<=*b*, he or she likes it if and only if he can climb into this car and 2*a*<=≥<=*b*.
You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.
Input Specification:
You are given four integers *V*1, *V*2, *V*3, *V**m*(1<=≤<=*V**i*<=≤<=100) — sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that *V*1<=><=*V*2<=><=*V*3.
Output Specification:
Output three integers — sizes of father bear's car, mother bear's car and son bear's car, respectively.
If there are multiple possible solutions, print any.
If there is no solution, print "-1" (without quotes).
Demo Input:
['50 30 10 10\n', '100 50 10 21\n']
Demo Output:
['50\n30\n10\n', '-1\n']
Note:
In first test case all conditions for cars' sizes are satisfied.
In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20. | ```python
bearSizesInput = input()
bearSizesSplit = bearSizesInput.split()
v1 = int(bearSizesSplit[0])
v2 = int(bearSizesSplit[1])
v3 = int(bearSizesSplit[2])
vm = int(bearSizesSplit[3])
bearSizes = [v1, v2, v3]
selectedSizes = []
for bearSize in bearSizes:
maxHeight = bearSize * 2
if maxHeight >= vm and vm <= bearSize:
selectedSizes.append(bearSize)
else:
selectedSizes.clear()
break
if len(selectedSizes) == 0:
print("-1")
else:
for selectedSize in selectedSizes:
print(selectedSize)
``` | 0 | |
378 | A | Playing with Dice | PROGRAMMING | 800 | [
"brute force"
] | null | null | Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins? | The single line contains two integers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=6) — the numbers written on the paper by the first and second player, correspondingly. | Print three integers: the number of ways to throw the dice at which the first player wins, the game ends with a draw or the second player wins, correspondingly. | [
"2 5\n",
"2 4\n"
] | [
"3 0 3\n",
"2 1 3\n"
] | The dice is a standard cube-shaped six-sided object with each side containing a number from 1 to 6, and where all numbers on all sides are distinct.
You can assume that number *a* is closer to number *x* than number *b*, if |*a* - *x*| < |*b* - *x*|. | 500 | [
{
"input": "2 5",
"output": "3 0 3"
},
{
"input": "2 4",
"output": "2 1 3"
},
{
"input": "5 3",
"output": "2 1 3"
},
{
"input": "1 6",
"output": "3 0 3"
},
{
"input": "5 1",
"output": "3 1 2"
},
{
"input": "6 3",
"output": "2 0 4"
},
{
"inp... | 1,594,458,300 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 2 | 77 | 6,656,000 | a, b= list(map(int, input().split()))
player1= 0
t= 0
player2= 0
for i in range(1,7):
if abs(a- i) < abs(b-i):
player1+=1
elif abs(a-i)> abs(b-i):
player2+=1
elif a-i == -1 and b-i == 1:
t+=1
print(player1 , t , player2)
| Title: Playing with Dice
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
Input Specification:
The single line contains two integers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=6) — the numbers written on the paper by the first and second player, correspondingly.
Output Specification:
Print three integers: the number of ways to throw the dice at which the first player wins, the game ends with a draw or the second player wins, correspondingly.
Demo Input:
['2 5\n', '2 4\n']
Demo Output:
['3 0 3\n', '2 1 3\n']
Note:
The dice is a standard cube-shaped six-sided object with each side containing a number from 1 to 6, and where all numbers on all sides are distinct.
You can assume that number *a* is closer to number *x* than number *b*, if |*a* - *x*| < |*b* - *x*|. | ```python
a, b= list(map(int, input().split()))
player1= 0
t= 0
player2= 0
for i in range(1,7):
if abs(a- i) < abs(b-i):
player1+=1
elif abs(a-i)> abs(b-i):
player2+=1
elif a-i == -1 and b-i == 1:
t+=1
print(player1 , t , player2)
``` | 0 | |
394 | A | Counting Sticks | PROGRAMMING | 0 | [
"brute force",
"implementation"
] | null | null | When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add and subtract? — That's right, using counting sticks! An here's our new task:
An expression of counting sticks is an expression of type:
Sign + consists of two crossed sticks: one vertical and one horizontal. Sign = consists of two horizontal sticks. The expression is arithmetically correct if *A*<=+<=*B*<==<=*C*.
We've got an expression that looks like *A*<=+<=*B*<==<=*C* given by counting sticks. Our task is to shift at most one stick (or we can shift nothing) so that the expression became arithmetically correct. Note that we cannot remove the sticks from the expression, also we cannot shift the sticks from the signs + and =.
We really aren't fabulous at arithmetics. Can you help us? | The single line contains the initial expression. It is guaranteed that the expression looks like *A*<=+<=*B*<==<=*C*, where 1<=≤<=*A*,<=*B*,<=*C*<=≤<=100. | If there isn't a way to shift the stick so the expression becomes correct, print on a single line "Impossible" (without the quotes). If there is a way, print the resulting expression. Follow the format of the output from the test samples. Don't print extra space characters.
If there are multiple correct answers, print any of them. For clarifications, you are recommended to see the test samples. | [
"||+|=|||||\n",
"|||||+||=||\n",
"|+|=||||||\n",
"||||+||=||||||\n"
] | [
"|||+|=||||\n",
"Impossible\n",
"Impossible\n",
"||||+||=||||||\n"
] | In the first sample we can shift stick from the third group of sticks to the first one.
In the second sample we cannot shift vertical stick from + sign to the second group of sticks. So we cannot make a - sign.
There is no answer in the third sample because we cannot remove sticks from the expression.
In the forth sample the initial expression is already arithmetically correct and that is why we don't have to shift sticks. | 500 | [
{
"input": "||+|=|||||",
"output": "|||+|=||||"
},
{
"input": "|||||+||=||",
"output": "Impossible"
},
{
"input": "|+|=||||||",
"output": "Impossible"
},
{
"input": "||||+||=||||||",
"output": "||||+||=||||||"
},
{
"input": "||||||||||||+|||||||||||=||||||||||||||... | 1,524,645,638 | 2,147,483,647 | Python 3 | OK | TESTS | 49 | 93 | 7,372,800 | n = input()
lth = len(n)
a = n.find('+')
b = n.find('=') - a - 1
c = len(n) - n.find('=') - 1
if a + b == c:
print(n)
elif a + b == c - 2:
print('|',n[:lth-1],sep="")
elif a + b == c + 2:
if a >= 2:
print(n[1:],'|',sep="")
else:
print(n[:a+1],n[a+2:],'|',sep="")
else:
print('Impossible')
| Title: Counting Sticks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add and subtract? — That's right, using counting sticks! An here's our new task:
An expression of counting sticks is an expression of type:
Sign + consists of two crossed sticks: one vertical and one horizontal. Sign = consists of two horizontal sticks. The expression is arithmetically correct if *A*<=+<=*B*<==<=*C*.
We've got an expression that looks like *A*<=+<=*B*<==<=*C* given by counting sticks. Our task is to shift at most one stick (or we can shift nothing) so that the expression became arithmetically correct. Note that we cannot remove the sticks from the expression, also we cannot shift the sticks from the signs + and =.
We really aren't fabulous at arithmetics. Can you help us?
Input Specification:
The single line contains the initial expression. It is guaranteed that the expression looks like *A*<=+<=*B*<==<=*C*, where 1<=≤<=*A*,<=*B*,<=*C*<=≤<=100.
Output Specification:
If there isn't a way to shift the stick so the expression becomes correct, print on a single line "Impossible" (without the quotes). If there is a way, print the resulting expression. Follow the format of the output from the test samples. Don't print extra space characters.
If there are multiple correct answers, print any of them. For clarifications, you are recommended to see the test samples.
Demo Input:
['||+|=|||||\n', '|||||+||=||\n', '|+|=||||||\n', '||||+||=||||||\n']
Demo Output:
['|||+|=||||\n', 'Impossible\n', 'Impossible\n', '||||+||=||||||\n']
Note:
In the first sample we can shift stick from the third group of sticks to the first one.
In the second sample we cannot shift vertical stick from + sign to the second group of sticks. So we cannot make a - sign.
There is no answer in the third sample because we cannot remove sticks from the expression.
In the forth sample the initial expression is already arithmetically correct and that is why we don't have to shift sticks. | ```python
n = input()
lth = len(n)
a = n.find('+')
b = n.find('=') - a - 1
c = len(n) - n.find('=') - 1
if a + b == c:
print(n)
elif a + b == c - 2:
print('|',n[:lth-1],sep="")
elif a + b == c + 2:
if a >= 2:
print(n[1:],'|',sep="")
else:
print(n[:a+1],n[a+2:],'|',sep="")
else:
print('Impossible')
``` | 3 | |
898 | A | Rounding | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | Vasya has a non-negative integer *n*. He wants to round it to nearest integer, which ends up with 0. If *n* already ends up with 0, Vasya considers it already rounded.
For example, if *n*<==<=4722 answer is 4720. If *n*<==<=5 Vasya can round it to 0 or to 10. Both ways are correct.
For given *n* find out to which integer will Vasya round it. | The first line contains single integer *n* (0<=≤<=*n*<=≤<=109) — number that Vasya has. | Print result of rounding *n*. Pay attention that in some cases answer isn't unique. In that case print any correct answer. | [
"5\n",
"113\n",
"1000000000\n",
"5432359\n"
] | [
"0\n",
"110\n",
"1000000000\n",
"5432360\n"
] | In the first example *n* = 5. Nearest integers, that ends up with zero are 0 and 10. Any of these answers is correct, so you can print 0 or 10. | 500 | [
{
"input": "5",
"output": "0"
},
{
"input": "113",
"output": "110"
},
{
"input": "1000000000",
"output": "1000000000"
},
{
"input": "5432359",
"output": "5432360"
},
{
"input": "999999994",
"output": "999999990"
},
{
"input": "10",
"output": "10"
... | 1,608,412,479 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 78 | 0 | import math
n=int(input())
if(n<10):
print(n)
elif(n%10==0):
print(n)
else:
m=math.floor(n/10)*10
print(m)
| Title: Rounding
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has a non-negative integer *n*. He wants to round it to nearest integer, which ends up with 0. If *n* already ends up with 0, Vasya considers it already rounded.
For example, if *n*<==<=4722 answer is 4720. If *n*<==<=5 Vasya can round it to 0 or to 10. Both ways are correct.
For given *n* find out to which integer will Vasya round it.
Input Specification:
The first line contains single integer *n* (0<=≤<=*n*<=≤<=109) — number that Vasya has.
Output Specification:
Print result of rounding *n*. Pay attention that in some cases answer isn't unique. In that case print any correct answer.
Demo Input:
['5\n', '113\n', '1000000000\n', '5432359\n']
Demo Output:
['0\n', '110\n', '1000000000\n', '5432360\n']
Note:
In the first example *n* = 5. Nearest integers, that ends up with zero are 0 and 10. Any of these answers is correct, so you can print 0 or 10. | ```python
import math
n=int(input())
if(n<10):
print(n)
elif(n%10==0):
print(n)
else:
m=math.floor(n/10)*10
print(m)
``` | 0 | |
912 | A | Tricky Alchemy | PROGRAMMING | 800 | [
"implementation"
] | null | null | During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.
Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, green — one yellow and one blue, and for a blue ball, three blue crystals are enough.
Right now there are *A* yellow and *B* blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls. | The first line features two integers *A* and *B* (0<=≤<=*A*,<=*B*<=≤<=109), denoting the number of yellow and blue crystals respectively at Grisha's disposal.
The next line contains three integers *x*, *y* and *z* (0<=≤<=*x*,<=*y*,<=*z*<=≤<=109) — the respective amounts of yellow, green and blue balls to be obtained. | Print a single integer — the minimum number of crystals that Grisha should acquire in addition. | [
"4 3\n2 1 1\n",
"3 9\n1 1 3\n",
"12345678 87654321\n43043751 1000000000 53798715\n"
] | [
"2\n",
"1\n",
"2147483648\n"
] | In the first sample case, Grisha needs five yellow and four blue crystals to create two yellow balls, one green ball, and one blue ball. To do that, Grisha needs to obtain two additional crystals: one yellow and one blue. | 500 | [
{
"input": "4 3\n2 1 1",
"output": "2"
},
{
"input": "3 9\n1 1 3",
"output": "1"
},
{
"input": "12345678 87654321\n43043751 1000000000 53798715",
"output": "2147483648"
},
{
"input": "12 12\n3 5 2",
"output": "0"
},
{
"input": "770 1390\n170 442 311",
"output"... | 1,681,511,351 | 2,147,483,647 | Python 3 | OK | TESTS | 38 | 77 | 0 | a, b = map(int, input().split())
x, y, z = map(int, input().split())
need_yellow = x * 2 + y
need_blue = y + z * 3
yellow_diff = max(0, need_yellow - a)
blue_diff = max(0, need_blue - b)
total_diff = yellow_diff + blue_diff
print(total_diff)
| Title: Tricky Alchemy
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.
Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, green — one yellow and one blue, and for a blue ball, three blue crystals are enough.
Right now there are *A* yellow and *B* blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls.
Input Specification:
The first line features two integers *A* and *B* (0<=≤<=*A*,<=*B*<=≤<=109), denoting the number of yellow and blue crystals respectively at Grisha's disposal.
The next line contains three integers *x*, *y* and *z* (0<=≤<=*x*,<=*y*,<=*z*<=≤<=109) — the respective amounts of yellow, green and blue balls to be obtained.
Output Specification:
Print a single integer — the minimum number of crystals that Grisha should acquire in addition.
Demo Input:
['4 3\n2 1 1\n', '3 9\n1 1 3\n', '12345678 87654321\n43043751 1000000000 53798715\n']
Demo Output:
['2\n', '1\n', '2147483648\n']
Note:
In the first sample case, Grisha needs five yellow and four blue crystals to create two yellow balls, one green ball, and one blue ball. To do that, Grisha needs to obtain two additional crystals: one yellow and one blue. | ```python
a, b = map(int, input().split())
x, y, z = map(int, input().split())
need_yellow = x * 2 + y
need_blue = y + z * 3
yellow_diff = max(0, need_yellow - a)
blue_diff = max(0, need_blue - b)
total_diff = yellow_diff + blue_diff
print(total_diff)
``` | 3 | |
302 | A | Eugeny and Array | PROGRAMMING | 800 | [
"implementation"
] | null | null | Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries:
- Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of array *a* can be rearranged so as the sum *a**l**i*<=+<=*a**l**i*<=+<=1<=+<=...<=+<=*a**r**i*<==<=0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries. | The first line contains integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (*a**i*<==<=-1,<=1). Next *m* lines contain Eugene's queries. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). | Print *m* integers — the responses to Eugene's queries in the order they occur in the input. | [
"2 3\n1 -1\n1 1\n1 2\n2 2\n",
"5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5\n"
] | [
"0\n1\n0\n",
"0\n1\n0\n1\n0\n"
] | none | 500 | [
{
"input": "2 3\n1 -1\n1 1\n1 2\n2 2",
"output": "0\n1\n0"
},
{
"input": "5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5",
"output": "0\n1\n0\n1\n0"
},
{
"input": "3 3\n1 1 1\n2 2\n1 1\n1 1",
"output": "0\n0\n0"
},
{
"input": "4 4\n-1 -1 -1 -1\n1 3\n1 2\n1 2\n1 1",
"output": "... | 1,669,364,815 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 10 | 1,000 | 1,024,000 | ''' Евгений и массив '''
s = input()
s = s.split()
n = int(s[0])
m = int(s[1])
a = input()
a_1 = a.count('-1')
a1 = a.count('1') - a_1
for i in range(m):
b = input()
b = b.split()
l = int(b[0])
r = int(b[1])
if (r-l) % 2 == 0:
print( 0)
continue
k = (r-l+1) // 2
if k > a1 or k > a_1:
print( 0)
else:
print( 1) | Title: Eugeny and Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries:
- Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of array *a* can be rearranged so as the sum *a**l**i*<=+<=*a**l**i*<=+<=1<=+<=...<=+<=*a**r**i*<==<=0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input Specification:
The first line contains integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (*a**i*<==<=-1,<=1). Next *m* lines contain Eugene's queries. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*).
Output Specification:
Print *m* integers — the responses to Eugene's queries in the order they occur in the input.
Demo Input:
['2 3\n1 -1\n1 1\n1 2\n2 2\n', '5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5\n']
Demo Output:
['0\n1\n0\n', '0\n1\n0\n1\n0\n']
Note:
none | ```python
''' Евгений и массив '''
s = input()
s = s.split()
n = int(s[0])
m = int(s[1])
a = input()
a_1 = a.count('-1')
a1 = a.count('1') - a_1
for i in range(m):
b = input()
b = b.split()
l = int(b[0])
r = int(b[1])
if (r-l) % 2 == 0:
print( 0)
continue
k = (r-l+1) // 2
if k > a1 or k > a_1:
print( 0)
else:
print( 1)
``` | 0 | |
926 | E | Merge Equal Elements | PROGRAMMING | 1,900 | [
"constructive algorithms",
"data structures"
] | null | null | You are given a sequence of positive integers *a*1,<=*a*2,<=...,<=*a**n*.
While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to *x*, delete both and insert a single integer *x*<=+<=1 on their place. This way the number of elements in the sequence is decreased by 1 on each step.
You stop performing the operation when there is no pair of equal consecutive elements.
For example, if the initial sequence is [5,<=2,<=1,<=1,<=2,<=2], then after the first operation you get [5,<=2,<=2,<=2,<=2], after the second — [5,<=3,<=2,<=2], after the third — [5,<=3,<=3], and finally after the fourth you get [5,<=4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.
Determine the final sequence after you stop performing the operation. | The first line contains a single integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of elements in the sequence.
The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109). | In the first line print a single integer *k* — the number of elements in the sequence after you stop performing the operation.
In the second line print *k* integers — the sequence after you stop performing the operation. | [
"6\n5 2 1 1 2 2\n",
"4\n1000000000 1000000000 1000000000 1000000000\n",
"7\n4 10 22 11 12 5 6\n"
] | [
"2\n5 4 ",
"1\n1000000002 ",
"7\n4 10 22 11 12 5 6 "
] | The first example is described in the statements.
In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002].
In the third example there are no two equal consecutive elements initially, so the sequence does not change. | 0 | [
{
"input": "6\n5 2 1 1 2 2",
"output": "2\n5 4 "
},
{
"input": "4\n1000000000 1000000000 1000000000 1000000000",
"output": "1\n1000000002 "
},
{
"input": "7\n4 10 22 11 12 5 6",
"output": "7\n4 10 22 11 12 5 6 "
},
{
"input": "2\n1 1",
"output": "1\n2 "
},
{
"inpu... | 1,552,407,552 | 2,147,483,647 | PyPy 3 | COMPILATION_ERROR | TESTS | 0 | 0 | 0 | n = int(input())
a = list(map(int, input().split()))
p = 1
def f(n, a):
for _ in range(n):
od = True
x = len(a)
for g in range(max(p - 1, 0),len(a) - 1):
if a[g] == a[g + 1]:
od = False
p = g
s = int(a[g])
del a[g]
a[g] =str(s + 1)
break
if od:
print(x)
print(' '.join(list(map(str, a))))
break
f(n, a) | Title: Merge Equal Elements
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a sequence of positive integers *a*1,<=*a*2,<=...,<=*a**n*.
While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to *x*, delete both and insert a single integer *x*<=+<=1 on their place. This way the number of elements in the sequence is decreased by 1 on each step.
You stop performing the operation when there is no pair of equal consecutive elements.
For example, if the initial sequence is [5,<=2,<=1,<=1,<=2,<=2], then after the first operation you get [5,<=2,<=2,<=2,<=2], after the second — [5,<=3,<=2,<=2], after the third — [5,<=3,<=3], and finally after the fourth you get [5,<=4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.
Determine the final sequence after you stop performing the operation.
Input Specification:
The first line contains a single integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of elements in the sequence.
The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109).
Output Specification:
In the first line print a single integer *k* — the number of elements in the sequence after you stop performing the operation.
In the second line print *k* integers — the sequence after you stop performing the operation.
Demo Input:
['6\n5 2 1 1 2 2\n', '4\n1000000000 1000000000 1000000000 1000000000\n', '7\n4 10 22 11 12 5 6\n']
Demo Output:
['2\n5 4 ', '1\n1000000002 ', '7\n4 10 22 11 12 5 6 ']
Note:
The first example is described in the statements.
In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002].
In the third example there are no two equal consecutive elements initially, so the sequence does not change. | ```python
n = int(input())
a = list(map(int, input().split()))
p = 1
def f(n, a):
for _ in range(n):
od = True
x = len(a)
for g in range(max(p - 1, 0),len(a) - 1):
if a[g] == a[g + 1]:
od = False
p = g
s = int(a[g])
del a[g]
a[g] =str(s + 1)
break
if od:
print(x)
print(' '.join(list(map(str, a))))
break
f(n, a)
``` | -1 | |
0 | none | none | none | 0 | [
"none"
] | null | null | In the year of $30XX$ participants of some world programming championship live in a single large hotel. The hotel has $n$ floors. Each floor has $m$ sections with a single corridor connecting all of them. The sections are enumerated from $1$ to $m$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $n$ and width $m$. We can denote sections with pairs of integers $(i, j)$, where $i$ is the floor, and $j$ is the section number on the floor.
The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $(1, x)$, $(2, x)$, $\ldots$, $(n, x)$ for some $x$ between $1$ and $m$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $v$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.
You are to process $q$ queries. Each query is a question "what is the minimum time needed to go from a room in section $(x_1, y_1)$ to a room in section $(x_2, y_2)$?" | The first line contains five integers $n, m, c_l, c_e, v$ ($2 \leq n, m \leq 10^8$, $0 \leq c_l, c_e \leq 10^5$, $1 \leq c_l + c_e \leq m - 1$, $1 \leq v \leq n - 1$) — the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively.
The second line contains $c_l$ integers $l_1, \ldots, l_{c_l}$ in increasing order ($1 \leq l_i \leq m$), denoting the positions of the stairs. If $c_l = 0$, the second line is empty.
The third line contains $c_e$ integers $e_1, \ldots, e_{c_e}$ in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers $l_i$ and $e_i$ are distinct.
The fourth line contains a single integer $q$ ($1 \leq q \leq 10^5$) — the number of queries.
The next $q$ lines describe queries. Each of these lines contains four integers $x_1, y_1, x_2, y_2$ ($1 \leq x_1, x_2 \leq n$, $1 \leq y_1, y_2 \leq m$) — the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. $y_1$ and $y_2$ are not among $l_i$ and $e_i$. | Print $q$ integers, one per line — the answers for the queries. | [
"5 6 1 1 3\n2\n5\n3\n1 1 5 6\n1 3 5 4\n3 3 5 3\n"
] | [
"7\n5\n4\n"
] | In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.
In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. | 0 | [
{
"input": "5 6 1 1 3\n2\n5\n3\n1 1 5 6\n1 3 5 4\n3 3 5 3",
"output": "7\n5\n4"
},
{
"input": "2 2 0 1 1\n\n1\n1\n1 2 2 2",
"output": "3"
},
{
"input": "4 4 1 0 1\n4\n\n5\n1 1 2 2\n1 3 2 2\n3 3 4 3\n3 2 2 2\n1 2 2 3",
"output": "6\n4\n3\n5\n4"
},
{
"input": "10 10 1 8 4\n10\n... | 1,525,015,337 | 7,637 | Python 3 | TIME_LIMIT_EXCEEDED | PRETESTS | 6 | 2,000 | 14,233,600 | import bisect
N,M,L,E,V = map(int,input().split())
sts = list(map(int,input().split()))
els = list(map(int,input().split()))
def solve(x1,y1,x2,y2):
if x1 == x2:
return abs(y1-y2)
ans = N+M+9999
if y1 > y2: y1,y2 = y2,y1
if sts:
i = bisect.bisect(sts,y1)
if i == L:
st = sts[-1]
t = abs(st - y1) + abs(st - y2) + abs(x1 - x2)
ans = min(ans, t)
else:
st = sts[i]
t = abs(st - y1) + abs(st - y2) + abs(x1 - x2)
ans = min(ans, t)
if i < L-1:
st = sts[i+1]
t = abs(st - y1) + abs(st - y2) + abs(x1 - x2)
ans = min(ans, t)
if els:
i = bisect.bisect(els,y1)
if i == E:
el = els[-1]
t = abs(el - y1) + abs(el - y2) + (abs(x1-x2)-1)//V + 1
ans = min(ans, t)
else:
el = els[i]
t = abs(el - y1) + abs(el - y2) + (abs(x1-x2)-1)//V + 1
ans = min(ans, t)
if i < E-1:
el = els[i+1]
t = abs(el - y1) + abs(el - y2) + (abs(x1-x2)-1)//V + 1
ans = min(ans, t)
return ans
Q = int(input())
for i in range(Q):
print(solve(*tuple(map(int,input().split()))))
| Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the year of $30XX$ participants of some world programming championship live in a single large hotel. The hotel has $n$ floors. Each floor has $m$ sections with a single corridor connecting all of them. The sections are enumerated from $1$ to $m$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $n$ and width $m$. We can denote sections with pairs of integers $(i, j)$, where $i$ is the floor, and $j$ is the section number on the floor.
The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $(1, x)$, $(2, x)$, $\ldots$, $(n, x)$ for some $x$ between $1$ and $m$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $v$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.
You are to process $q$ queries. Each query is a question "what is the minimum time needed to go from a room in section $(x_1, y_1)$ to a room in section $(x_2, y_2)$?"
Input Specification:
The first line contains five integers $n, m, c_l, c_e, v$ ($2 \leq n, m \leq 10^8$, $0 \leq c_l, c_e \leq 10^5$, $1 \leq c_l + c_e \leq m - 1$, $1 \leq v \leq n - 1$) — the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively.
The second line contains $c_l$ integers $l_1, \ldots, l_{c_l}$ in increasing order ($1 \leq l_i \leq m$), denoting the positions of the stairs. If $c_l = 0$, the second line is empty.
The third line contains $c_e$ integers $e_1, \ldots, e_{c_e}$ in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers $l_i$ and $e_i$ are distinct.
The fourth line contains a single integer $q$ ($1 \leq q \leq 10^5$) — the number of queries.
The next $q$ lines describe queries. Each of these lines contains four integers $x_1, y_1, x_2, y_2$ ($1 \leq x_1, x_2 \leq n$, $1 \leq y_1, y_2 \leq m$) — the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. $y_1$ and $y_2$ are not among $l_i$ and $e_i$.
Output Specification:
Print $q$ integers, one per line — the answers for the queries.
Demo Input:
['5 6 1 1 3\n2\n5\n3\n1 1 5 6\n1 3 5 4\n3 3 5 3\n']
Demo Output:
['7\n5\n4\n']
Note:
In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.
In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. | ```python
import bisect
N,M,L,E,V = map(int,input().split())
sts = list(map(int,input().split()))
els = list(map(int,input().split()))
def solve(x1,y1,x2,y2):
if x1 == x2:
return abs(y1-y2)
ans = N+M+9999
if y1 > y2: y1,y2 = y2,y1
if sts:
i = bisect.bisect(sts,y1)
if i == L:
st = sts[-1]
t = abs(st - y1) + abs(st - y2) + abs(x1 - x2)
ans = min(ans, t)
else:
st = sts[i]
t = abs(st - y1) + abs(st - y2) + abs(x1 - x2)
ans = min(ans, t)
if i < L-1:
st = sts[i+1]
t = abs(st - y1) + abs(st - y2) + abs(x1 - x2)
ans = min(ans, t)
if els:
i = bisect.bisect(els,y1)
if i == E:
el = els[-1]
t = abs(el - y1) + abs(el - y2) + (abs(x1-x2)-1)//V + 1
ans = min(ans, t)
else:
el = els[i]
t = abs(el - y1) + abs(el - y2) + (abs(x1-x2)-1)//V + 1
ans = min(ans, t)
if i < E-1:
el = els[i+1]
t = abs(el - y1) + abs(el - y2) + (abs(x1-x2)-1)//V + 1
ans = min(ans, t)
return ans
Q = int(input())
for i in range(Q):
print(solve(*tuple(map(int,input().split()))))
``` | 0 | |
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,567,098,846 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 124 | 0 | a, b = map(int, input().split())
print(1)
while(1 == 0): print("questão bullshit")
| 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
a, b = map(int, input().split())
print(1)
while(1 == 0): print("questão bullshit")
``` | 0 | |
255 | A | Greg's Workout | PROGRAMMING | 800 | [
"implementation"
] | null | null | Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was *n* integers *a*1,<=*a*2,<=...,<=*a**n*. These numbers mean that Greg needs to do exactly *n* exercises today. Besides, Greg should repeat the *i*-th in order exercise *a**i* times.
Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the *n*-th exercise.
Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training. | The first line contains integer *n* (1<=≤<=*n*<=≤<=20). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=25) — the number of times Greg repeats the exercises. | Print word "chest" (without the quotes), if the chest gets the most exercise, "biceps" (without the quotes), if the biceps gets the most exercise and print "back" (without the quotes) if the back gets the most exercise.
It is guaranteed that the input is such that the answer to the problem is unambiguous. | [
"2\n2 8\n",
"3\n5 1 10\n",
"7\n3 3 2 7 9 6 8\n"
] | [
"biceps\n",
"back\n",
"chest\n"
] | In the first sample Greg does 2 chest, 8 biceps and zero back exercises, so the biceps gets the most exercises.
In the second sample Greg does 5 chest, 1 biceps and 10 back exercises, so the back gets the most exercises.
In the third sample Greg does 18 chest, 12 biceps and 8 back exercises, so the chest gets the most exercise. | 500 | [
{
"input": "2\n2 8",
"output": "biceps"
},
{
"input": "3\n5 1 10",
"output": "back"
},
{
"input": "7\n3 3 2 7 9 6 8",
"output": "chest"
},
{
"input": "4\n5 6 6 2",
"output": "chest"
},
{
"input": "5\n8 2 2 6 3",
"output": "chest"
},
{
"input": "6\n8 7 ... | 1,591,763,613 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 186 | 204,800 | t = int(input())
l = list(map(int, input().split()))
chest = 0
bicep = 0
back = 0
for i in range(1, len(l)+1):
if(i%3==1):
chest+=l[i-1]
elif(i%3==2):
bicep+=l[i-1]
else:
back+=l[i-1]
m = max(chest, bicep, back)
if(m==back):
print("back")
elif(m==chest):
print("chest")
else:
print("bicep")
| Title: Greg's Workout
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was *n* integers *a*1,<=*a*2,<=...,<=*a**n*. These numbers mean that Greg needs to do exactly *n* exercises today. Besides, Greg should repeat the *i*-th in order exercise *a**i* times.
Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the *n*-th exercise.
Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=20). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=25) — the number of times Greg repeats the exercises.
Output Specification:
Print word "chest" (without the quotes), if the chest gets the most exercise, "biceps" (without the quotes), if the biceps gets the most exercise and print "back" (without the quotes) if the back gets the most exercise.
It is guaranteed that the input is such that the answer to the problem is unambiguous.
Demo Input:
['2\n2 8\n', '3\n5 1 10\n', '7\n3 3 2 7 9 6 8\n']
Demo Output:
['biceps\n', 'back\n', 'chest\n']
Note:
In the first sample Greg does 2 chest, 8 biceps and zero back exercises, so the biceps gets the most exercises.
In the second sample Greg does 5 chest, 1 biceps and 10 back exercises, so the back gets the most exercises.
In the third sample Greg does 18 chest, 12 biceps and 8 back exercises, so the chest gets the most exercise. | ```python
t = int(input())
l = list(map(int, input().split()))
chest = 0
bicep = 0
back = 0
for i in range(1, len(l)+1):
if(i%3==1):
chest+=l[i-1]
elif(i%3==2):
bicep+=l[i-1]
else:
back+=l[i-1]
m = max(chest, bicep, back)
if(m==back):
print("back")
elif(m==chest):
print("chest")
else:
print("bicep")
``` | 0 | |
242 | E | XOR on Segment | PROGRAMMING | 2,000 | [
"bitmasks",
"data structures"
] | null | null | You've got an array *a*, consisting of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. You are allowed to perform two operations on this array:
1. Calculate the sum of current array elements on the segment [*l*,<=*r*], that is, count value *a**l*<=+<=*a**l*<=+<=1<=+<=...<=+<=*a**r*. 1. Apply the xor operation with a given number *x* to each array element on the segment [*l*,<=*r*], that is, execute . This operation changes exactly *r*<=-<=*l*<=+<=1 array elements.
Expression means applying bitwise xor operation to numbers *x* and *y*. The given operation exists in all modern programming languages, for example in language C++ and Java it is marked as "^", in Pascal — as "xor".
You've got a list of *m* operations of the indicated type. Your task is to perform all given operations, for each sum query you should print the result you get. | The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the size of the array. The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=106) — the original array.
The third line contains integer *m* (1<=≤<=*m*<=≤<=5·104) — the number of operations with the array. The *i*-th of the following *m* lines first contains an integer *t**i* (1<=≤<=*t**i*<=≤<=2) — the type of the *i*-th query. If *t**i*<==<=1, then this is the query of the sum, if *t**i*<==<=2, then this is the query to change array elements. If the *i*-th operation is of type 1, then next follow two integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). If the *i*-th operation is of type 2, then next follow three integers *l**i*,<=*r**i*,<=*x**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*,<=1<=≤<=*x**i*<=≤<=106). The numbers on the lines are separated by single spaces. | For each query of type 1 print in a single line the sum of numbers on the given segment. Print the answers to the queries in the order in which the queries go in the input.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams, or the %I64d specifier. | [
"5\n4 10 3 13 7\n8\n1 2 4\n2 1 3 3\n1 2 4\n1 3 3\n2 2 5 5\n1 1 5\n2 1 2 10\n1 2 3\n",
"6\n4 7 4 0 7 3\n5\n2 2 3 8\n1 1 5\n2 3 5 1\n2 4 5 6\n1 2 3\n"
] | [
"26\n22\n0\n34\n11\n",
"38\n28\n"
] | none | 2,500 | [] | 1,692,410,972 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 15 | 4,000 | 6,860,800 | n = int(input())
a = list(map(int, input().split()))
m = int(input())
for _ in range(m):
op = list(map(int, input().split()))
if op[0] == 1:
print(sum(a[op[1]-1:op[2]]))
else:
for i in range(op[1]-1, op[2]):
a[i] ^= op[3]
| Title: XOR on Segment
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've got an array *a*, consisting of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. You are allowed to perform two operations on this array:
1. Calculate the sum of current array elements on the segment [*l*,<=*r*], that is, count value *a**l*<=+<=*a**l*<=+<=1<=+<=...<=+<=*a**r*. 1. Apply the xor operation with a given number *x* to each array element on the segment [*l*,<=*r*], that is, execute . This operation changes exactly *r*<=-<=*l*<=+<=1 array elements.
Expression means applying bitwise xor operation to numbers *x* and *y*. The given operation exists in all modern programming languages, for example in language C++ and Java it is marked as "^", in Pascal — as "xor".
You've got a list of *m* operations of the indicated type. Your task is to perform all given operations, for each sum query you should print the result you get.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the size of the array. The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=106) — the original array.
The third line contains integer *m* (1<=≤<=*m*<=≤<=5·104) — the number of operations with the array. The *i*-th of the following *m* lines first contains an integer *t**i* (1<=≤<=*t**i*<=≤<=2) — the type of the *i*-th query. If *t**i*<==<=1, then this is the query of the sum, if *t**i*<==<=2, then this is the query to change array elements. If the *i*-th operation is of type 1, then next follow two integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). If the *i*-th operation is of type 2, then next follow three integers *l**i*,<=*r**i*,<=*x**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*,<=1<=≤<=*x**i*<=≤<=106). The numbers on the lines are separated by single spaces.
Output Specification:
For each query of type 1 print in a single line the sum of numbers on the given segment. Print the answers to the queries in the order in which the queries go in the input.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams, or the %I64d specifier.
Demo Input:
['5\n4 10 3 13 7\n8\n1 2 4\n2 1 3 3\n1 2 4\n1 3 3\n2 2 5 5\n1 1 5\n2 1 2 10\n1 2 3\n', '6\n4 7 4 0 7 3\n5\n2 2 3 8\n1 1 5\n2 3 5 1\n2 4 5 6\n1 2 3\n']
Demo Output:
['26\n22\n0\n34\n11\n', '38\n28\n']
Note:
none | ```python
n = int(input())
a = list(map(int, input().split()))
m = int(input())
for _ in range(m):
op = list(map(int, input().split()))
if op[0] == 1:
print(sum(a[op[1]-1:op[2]]))
else:
for i in range(op[1]-1, op[2]):
a[i] ^= op[3]
``` | 0 | |
302 | A | Eugeny and Array | PROGRAMMING | 800 | [
"implementation"
] | null | null | Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries:
- Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of array *a* can be rearranged so as the sum *a**l**i*<=+<=*a**l**i*<=+<=1<=+<=...<=+<=*a**r**i*<==<=0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries. | The first line contains integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (*a**i*<==<=-1,<=1). Next *m* lines contain Eugene's queries. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). | Print *m* integers — the responses to Eugene's queries in the order they occur in the input. | [
"2 3\n1 -1\n1 1\n1 2\n2 2\n",
"5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5\n"
] | [
"0\n1\n0\n",
"0\n1\n0\n1\n0\n"
] | none | 500 | [
{
"input": "2 3\n1 -1\n1 1\n1 2\n2 2",
"output": "0\n1\n0"
},
{
"input": "5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5",
"output": "0\n1\n0\n1\n0"
},
{
"input": "3 3\n1 1 1\n2 2\n1 1\n1 1",
"output": "0\n0\n0"
},
{
"input": "4 4\n-1 -1 -1 -1\n1 3\n1 2\n1 2\n1 1",
"output": "... | 1,618,677,904 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 46 | 0 | n, m = list(map(int,input().split()))
array = input().split()
while(m):
lower_idx, upper_idx = list(map(int,input().split()))
flag = (upper_idx-lower_idx)%2
seg_len = (upper_idx-lower_idx)
if(not flag):
print(0)
m -=1
continue
else:
pos_ones = array.count(1)
neg_ones = array.count(-1)
if(pos_ones >= seg_len//2 and neg_ones>=seg_len//2):
print(1)
else:
print(0)
m -=1
| Title: Eugeny and Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries:
- Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of array *a* can be rearranged so as the sum *a**l**i*<=+<=*a**l**i*<=+<=1<=+<=...<=+<=*a**r**i*<==<=0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input Specification:
The first line contains integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (*a**i*<==<=-1,<=1). Next *m* lines contain Eugene's queries. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*).
Output Specification:
Print *m* integers — the responses to Eugene's queries in the order they occur in the input.
Demo Input:
['2 3\n1 -1\n1 1\n1 2\n2 2\n', '5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5\n']
Demo Output:
['0\n1\n0\n', '0\n1\n0\n1\n0\n']
Note:
none | ```python
n, m = list(map(int,input().split()))
array = input().split()
while(m):
lower_idx, upper_idx = list(map(int,input().split()))
flag = (upper_idx-lower_idx)%2
seg_len = (upper_idx-lower_idx)
if(not flag):
print(0)
m -=1
continue
else:
pos_ones = array.count(1)
neg_ones = array.count(-1)
if(pos_ones >= seg_len//2 and neg_ones>=seg_len//2):
print(1)
else:
print(0)
m -=1
``` | 0 | |
914 | A | Perfect Squares | PROGRAMMING | 900 | [
"brute force",
"implementation",
"math"
] | null | null | Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square.
A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of elements in the array.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=106<=≤<=*a**i*<=≤<=106) — the elements of the array.
It is guaranteed that at least one element of the array is not a perfect square. | Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists. | [
"2\n4 2\n",
"8\n1 2 4 8 16 32 64 576\n"
] | [
"2\n",
"32\n"
] | In the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2. | 500 | [
{
"input": "2\n4 2",
"output": "2"
},
{
"input": "8\n1 2 4 8 16 32 64 576",
"output": "32"
},
{
"input": "3\n-1 -4 -9",
"output": "-1"
},
{
"input": "5\n918375 169764 598796 76602 538757",
"output": "918375"
},
{
"input": "5\n804610 765625 2916 381050 93025",
... | 1,592,748,386 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 14 | 108 | 204,800 | from math import sqrt as s
n=int(input())
a=sorted(list(map(int,input().split())),reverse=True)
for i in range(n):
# print(int(s(a[i]))*int(s(a[i])))
if a[i]>0:
if (int(s(a[i]))*int(s(a[i]))==a[i]):
pass
else:
print(a[i])
break
else:
print(a[i])
break | Title: Perfect Squares
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square.
A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of elements in the array.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=106<=≤<=*a**i*<=≤<=106) — the elements of the array.
It is guaranteed that at least one element of the array is not a perfect square.
Output Specification:
Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists.
Demo Input:
['2\n4 2\n', '8\n1 2 4 8 16 32 64 576\n']
Demo Output:
['2\n', '32\n']
Note:
In the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2. | ```python
from math import sqrt as s
n=int(input())
a=sorted(list(map(int,input().split())),reverse=True)
for i in range(n):
# print(int(s(a[i]))*int(s(a[i])))
if a[i]>0:
if (int(s(a[i]))*int(s(a[i]))==a[i]):
pass
else:
print(a[i])
break
else:
print(a[i])
break
``` | 0 | |
151 | A | Soft Drinking | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt.
To make a toast, each friend needs *nl* milliliters of the drink, a slice of lime and *np* grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make? | The first and only line contains positive integers *n*, *k*, *l*, *c*, *d*, *p*, *nl*, *np*, not exceeding 1000 and no less than 1. The numbers are separated by exactly one space. | Print a single integer — the number of toasts each friend can make. | [
"3 4 5 10 8 100 3 1\n",
"5 100 10 1 19 90 4 3\n",
"10 1000 1000 25 23 1 50 1\n"
] | [
"2\n",
"3\n",
"0\n"
] | A comment to the first sample:
Overall the friends have 4 * 5 = 20 milliliters of the drink, it is enough to make 20 / 3 = 6 toasts. The limes are enough for 10 * 8 = 80 toasts and the salt is enough for 100 / 1 = 100 toasts. However, there are 3 friends in the group, so the answer is *min*(6, 80, 100) / 3 = 2. | 500 | [
{
"input": "3 4 5 10 8 100 3 1",
"output": "2"
},
{
"input": "5 100 10 1 19 90 4 3",
"output": "3"
},
{
"input": "10 1000 1000 25 23 1 50 1",
"output": "0"
},
{
"input": "1 7 4 5 5 8 3 2",
"output": "4"
},
{
"input": "2 3 3 5 5 10 1 3",
"output": "1"
},
{
... | 1,698,140,851 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 0 | 60 | 0 | n,k,l,c,d,p,nl,np=map(int,input().split())
a=k*l
t=a/nl
l=c*d
s=p/np
print(min(t,l,s)//n) | Title: Soft Drinking
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt.
To make a toast, each friend needs *nl* milliliters of the drink, a slice of lime and *np* grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?
Input Specification:
The first and only line contains positive integers *n*, *k*, *l*, *c*, *d*, *p*, *nl*, *np*, not exceeding 1000 and no less than 1. The numbers are separated by exactly one space.
Output Specification:
Print a single integer — the number of toasts each friend can make.
Demo Input:
['3 4 5 10 8 100 3 1\n', '5 100 10 1 19 90 4 3\n', '10 1000 1000 25 23 1 50 1\n']
Demo Output:
['2\n', '3\n', '0\n']
Note:
A comment to the first sample:
Overall the friends have 4 * 5 = 20 milliliters of the drink, it is enough to make 20 / 3 = 6 toasts. The limes are enough for 10 * 8 = 80 toasts and the salt is enough for 100 / 1 = 100 toasts. However, there are 3 friends in the group, so the answer is *min*(6, 80, 100) / 3 = 2. | ```python
n,k,l,c,d,p,nl,np=map(int,input().split())
a=k*l
t=a/nl
l=c*d
s=p/np
print(min(t,l,s)//n)
``` | 0 | |
227 | B | Effective Approach | PROGRAMMING | 1,100 | [
"implementation"
] | null | null | Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.
According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.
Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to *n*) and ending with the *n*-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the *n*-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.
To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to *n*, and generated *m* queries of the form: find element with value *b**i* in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.
But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute. | The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements in the array. The second line contains *n* distinct space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — the elements of array.
The third line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of queries. The last line contains *m* space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=*n*) — the search queries. Note that the queries can repeat. | Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. | [
"2\n1 2\n1\n1\n",
"2\n2 1\n1\n1\n",
"3\n3 1 2\n3\n1 2 3\n"
] | [
"1 2\n",
"2 1\n",
"6 6\n"
] | In the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).
In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element). | 1,000 | [
{
"input": "2\n1 2\n1\n1",
"output": "1 2"
},
{
"input": "2\n2 1\n1\n1",
"output": "2 1"
},
{
"input": "3\n3 1 2\n3\n1 2 3",
"output": "6 6"
},
{
"input": "9\n2 9 3 1 6 4 7 8 5\n9\n5 1 5 2 8 4 4 4 5",
"output": "58 32"
},
{
"input": "10\n3 10 9 2 7 6 5 8 4 1\n1\n4... | 1,620,098,112 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 5 | 2,000 | 7,475,200 | N = int(input())
arr = list(map(int,input().split()))
M = int(input())
search = list(map(int,input().split()))
vasya = 1
petya = 1
res1 = 0
res2 = 0
for i in search:
for j in arr:
if i == j:
break
else:
vasya+=1
res1 += vasya
vasya = 1
## reverse search
for i in search:
for j in arr[::-1]:
if i == j:
break
else:
petya+=1
res2 += petya
petya = 1
print(res1,res2) | Title: Effective Approach
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.
According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.
Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to *n*) and ending with the *n*-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the *n*-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.
To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to *n*, and generated *m* queries of the form: find element with value *b**i* in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.
But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements in the array. The second line contains *n* distinct space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — the elements of array.
The third line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of queries. The last line contains *m* space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=*n*) — the search queries. Note that the queries can repeat.
Output Specification:
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Demo Input:
['2\n1 2\n1\n1\n', '2\n2 1\n1\n1\n', '3\n3 1 2\n3\n1 2 3\n']
Demo Output:
['1 2\n', '2 1\n', '6 6\n']
Note:
In the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).
In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element). | ```python
N = int(input())
arr = list(map(int,input().split()))
M = int(input())
search = list(map(int,input().split()))
vasya = 1
petya = 1
res1 = 0
res2 = 0
for i in search:
for j in arr:
if i == j:
break
else:
vasya+=1
res1 += vasya
vasya = 1
## reverse search
for i in search:
for j in arr[::-1]:
if i == j:
break
else:
petya+=1
res2 += petya
petya = 1
print(res1,res2)
``` | 0 | |
965 | C | Greedy Arkady | PROGRAMMING | 2,000 | [
"math"
] | null | null | $k$ people want to split $n$ candies between them. Each candy should be given to exactly one of them or be thrown away.
The people are numbered from $1$ to $k$, and Arkady is the first of them. To split the candies, Arkady will choose an integer $x$ and then give the first $x$ candies to himself, the next $x$ candies to the second person, the next $x$ candies to the third person and so on in a cycle. The leftover (the remainder that is not divisible by $x$) will be thrown away.
Arkady can't choose $x$ greater than $M$ as it is considered greedy. Also, he can't choose such a small $x$ that some person will receive candies more than $D$ times, as it is considered a slow splitting.
Please find what is the maximum number of candies Arkady can receive by choosing some valid $x$. | The only line contains four integers $n$, $k$, $M$ and $D$ ($2 \le n \le 10^{18}$, $2 \le k \le n$, $1 \le M \le n$, $1 \le D \le \min{(n, 1000)}$, $M \cdot D \cdot k \ge n$) — the number of candies, the number of people, the maximum number of candies given to a person at once, the maximum number of times a person can receive candies. | Print a single integer — the maximum possible number of candies Arkady can give to himself.
Note that it is always possible to choose some valid $x$. | [
"20 4 5 2\n",
"30 9 4 1\n"
] | [
"8\n",
"4\n"
] | In the first example Arkady should choose $x = 4$. He will give $4$ candies to himself, $4$ candies to the second person, $4$ candies to the third person, then $4$ candies to the fourth person and then again $4$ candies to himself. No person is given candies more than $2$ times, and Arkady receives $8$ candies in total.
Note that if Arkady chooses $x = 5$, he will receive only $5$ candies, and if he chooses $x = 3$, he will receive only $3 + 3 = 6$ candies as well as the second person, the third and the fourth persons will receive $3$ candies, and $2$ candies will be thrown away. He can't choose $x = 1$ nor $x = 2$ because in these cases he will receive candies more than $2$ times.
In the second example Arkady has to choose $x = 4$, because any smaller value leads to him receiving candies more than $1$ time. | 1,500 | [
{
"input": "20 4 5 2",
"output": "8"
},
{
"input": "30 9 4 1",
"output": "4"
},
{
"input": "2 2 1 1",
"output": "1"
},
{
"input": "42 20 5 29",
"output": "5"
},
{
"input": "1000000000000000000 135 1000000000000000 1000",
"output": "8325624421831635"
},
{
... | 1,525,286,181 | 2,147,483,647 | Python 3 | OK | TESTS | 25 | 109 | 7,065,600 | n, k, m, d = map(int, input().split())
ans = int(0)
for i in range(1, d + 1):
l, r, mid = 1, m + 1, 0
while l + 1 < r:
mid = (l + r) // 2
if (n - mid) // (k * mid) < i - 1:
r = mid
else:
l = mid
if (n - l) // (k * l) < i - 1:
break
ans = max(ans, l * i)
print(ans)
| Title: Greedy Arkady
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
$k$ people want to split $n$ candies between them. Each candy should be given to exactly one of them or be thrown away.
The people are numbered from $1$ to $k$, and Arkady is the first of them. To split the candies, Arkady will choose an integer $x$ and then give the first $x$ candies to himself, the next $x$ candies to the second person, the next $x$ candies to the third person and so on in a cycle. The leftover (the remainder that is not divisible by $x$) will be thrown away.
Arkady can't choose $x$ greater than $M$ as it is considered greedy. Also, he can't choose such a small $x$ that some person will receive candies more than $D$ times, as it is considered a slow splitting.
Please find what is the maximum number of candies Arkady can receive by choosing some valid $x$.
Input Specification:
The only line contains four integers $n$, $k$, $M$ and $D$ ($2 \le n \le 10^{18}$, $2 \le k \le n$, $1 \le M \le n$, $1 \le D \le \min{(n, 1000)}$, $M \cdot D \cdot k \ge n$) — the number of candies, the number of people, the maximum number of candies given to a person at once, the maximum number of times a person can receive candies.
Output Specification:
Print a single integer — the maximum possible number of candies Arkady can give to himself.
Note that it is always possible to choose some valid $x$.
Demo Input:
['20 4 5 2\n', '30 9 4 1\n']
Demo Output:
['8\n', '4\n']
Note:
In the first example Arkady should choose $x = 4$. He will give $4$ candies to himself, $4$ candies to the second person, $4$ candies to the third person, then $4$ candies to the fourth person and then again $4$ candies to himself. No person is given candies more than $2$ times, and Arkady receives $8$ candies in total.
Note that if Arkady chooses $x = 5$, he will receive only $5$ candies, and if he chooses $x = 3$, he will receive only $3 + 3 = 6$ candies as well as the second person, the third and the fourth persons will receive $3$ candies, and $2$ candies will be thrown away. He can't choose $x = 1$ nor $x = 2$ because in these cases he will receive candies more than $2$ times.
In the second example Arkady has to choose $x = 4$, because any smaller value leads to him receiving candies more than $1$ time. | ```python
n, k, m, d = map(int, input().split())
ans = int(0)
for i in range(1, d + 1):
l, r, mid = 1, m + 1, 0
while l + 1 < r:
mid = (l + r) // 2
if (n - mid) // (k * mid) < i - 1:
r = mid
else:
l = mid
if (n - l) // (k * l) < i - 1:
break
ans = max(ans, l * i)
print(ans)
``` | 3 | |
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,418,116,417 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 92 | 0 | def main():
n = int(input())
l = [0, 0, 0, 0]
for _ in range(n):
x, y = map(int, input().split())
l[(x & 1) * 2 + (y & 1)] ^= 1
print((0, 0, -1, -1, -1, -1, 1, 0)[l[1] * 4 + l[2] * 2 + l[3]])
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())
l = [0, 0, 0, 0]
for _ in range(n):
x, y = map(int, input().split())
l[(x & 1) * 2 + (y & 1)] ^= 1
print((0, 0, -1, -1, -1, -1, 1, 0)[l[1] * 4 + l[2] * 2 + l[3]])
if __name__ == '__main__':
main()
``` | 0 | |
753 | A | Santa Claus and Candies | PROGRAMMING | 1,000 | [
"dp",
"greedy",
"math"
] | null | null | Santa Claus has *n* candies, he dreams to give them as gifts to children.
What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all *n* candies he has. | The only line contains positive integer number *n* (1<=≤<=*n*<=≤<=1000) — number of candies Santa Claus has. | Print to the first line integer number *k* — maximal number of kids which can get candies.
Print to the second line *k* distinct integer numbers: number of candies for each of *k* kid. The sum of *k* printed numbers should be exactly *n*.
If there are many solutions, print any of them. | [
"5\n",
"9\n",
"2\n"
] | [
"2\n2 3\n",
"3\n3 5 1\n",
"1\n2 \n"
] | none | 500 | [
{
"input": "5",
"output": "2\n1 4 "
},
{
"input": "9",
"output": "3\n1 2 6 "
},
{
"input": "2",
"output": "1\n2 "
},
{
"input": "1",
"output": "1\n1 "
},
{
"input": "3",
"output": "2\n1 2 "
},
{
"input": "1000",
"output": "44\n1 2 3 4 5 6 7 8 9 10 ... | 1,592,543,288 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 3 | 109 | 0 | n=int(input())
i=1
l=[]
while n>0:
n-=i
l.append(i)
i+=1
l[0]+=n+i-1
print(len(l)-1)
for i in range(len(l)-1):
print(l[i],end=' ') | Title: Santa Claus and Candies
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Santa Claus has *n* candies, he dreams to give them as gifts to children.
What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all *n* candies he has.
Input Specification:
The only line contains positive integer number *n* (1<=≤<=*n*<=≤<=1000) — number of candies Santa Claus has.
Output Specification:
Print to the first line integer number *k* — maximal number of kids which can get candies.
Print to the second line *k* distinct integer numbers: number of candies for each of *k* kid. The sum of *k* printed numbers should be exactly *n*.
If there are many solutions, print any of them.
Demo Input:
['5\n', '9\n', '2\n']
Demo Output:
['2\n2 3\n', '3\n3 5 1\n', '1\n2 \n']
Note:
none | ```python
n=int(input())
i=1
l=[]
while n>0:
n-=i
l.append(i)
i+=1
l[0]+=n+i-1
print(len(l)-1)
for i in range(len(l)-1):
print(l[i],end=' ')
``` | 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,602,569,375 | 2,147,483,647 | Python 3 | OK | TESTS | 102 | 108 | 0 | num1=input()
num2=input()
list=[]
for i in range(len(num1)):
if num1[i]==num2[i]:
list.append(0)
else:
list.append(1)
for e in list:
print(e,end="") | 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
num1=input()
num2=input()
list=[]
for i in range(len(num1)):
if num1[i]==num2[i]:
list.append(0)
else:
list.append(1)
for e in list:
print(e,end="")
``` | 3.973 |
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,631,361,611 | 2,147,483,647 | Python 3 | OK | TESTS | 46 | 124 | 6,963,200 | n = int(input())
num = int(input())
lis = [i for i in str(num)]
lis1 = lis[:int(n/2)]
lis2 = lis[int(n/2):]
lis11 = [int(x) for x in lis1]
lis22 = [int(x) for x in lis2]
if( lis.count('7') + lis.count('4')) == n and sum(lis11) == sum(lis22):
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
n = int(input())
num = int(input())
lis = [i for i in str(num)]
lis1 = lis[:int(n/2)]
lis2 = lis[int(n/2):]
lis11 = [int(x) for x in lis1]
lis22 = [int(x) for x in lis2]
if( lis.count('7') + lis.count('4')) == n and sum(lis11) == sum(lis22):
print('YES')
else:
print('NO')
``` | 3 | |
450 | B | Jzzhu and Sequences | PROGRAMMING | 1,300 | [
"implementation",
"math"
] | null | null | Jzzhu has invented a kind of sequences, they meet the following property:
You are given *x* and *y*, please calculate *f**n* modulo 1000000007 (109<=+<=7). | The first line contains two integers *x* and *y* (|*x*|,<=|*y*|<=≤<=109). The second line contains a single integer *n* (1<=≤<=*n*<=≤<=2·109). | Output a single integer representing *f**n* modulo 1000000007 (109<=+<=7). | [
"2 3\n3\n",
"0 -1\n2\n"
] | [
"1\n",
"1000000006\n"
] | In the first sample, *f*<sub class="lower-index">2</sub> = *f*<sub class="lower-index">1</sub> + *f*<sub class="lower-index">3</sub>, 3 = 2 + *f*<sub class="lower-index">3</sub>, *f*<sub class="lower-index">3</sub> = 1.
In the second sample, *f*<sub class="lower-index">2</sub> = - 1; - 1 modulo (10<sup class="upper-index">9</sup> + 7) equals (10<sup class="upper-index">9</sup> + 6). | 1,000 | [
{
"input": "2 3\n3",
"output": "1"
},
{
"input": "0 -1\n2",
"output": "1000000006"
},
{
"input": "-9 -11\n12345",
"output": "1000000005"
},
{
"input": "0 0\n1000000000",
"output": "0"
},
{
"input": "-1000000000 1000000000\n2000000000",
"output": "1000000000"
... | 1,666,971,757 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 5 | 31 | 0 | x, y = tuple(map(int, input().split()))
n = int(input())
MOD = 1000000007
if n%3 == 1 :
if n%2==0:
print(-(x%MOD))
else:
print(x%MOD)
elif n%3==2:
if n%2==0:
print(y%MOD)
else:
print(-(y%MOD))
elif n%3==0:
if n%2==0:
print((x-y)%MOD)
else:
print((y-x)%MOD) | Title: Jzzhu and Sequences
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Jzzhu has invented a kind of sequences, they meet the following property:
You are given *x* and *y*, please calculate *f**n* modulo 1000000007 (109<=+<=7).
Input Specification:
The first line contains two integers *x* and *y* (|*x*|,<=|*y*|<=≤<=109). The second line contains a single integer *n* (1<=≤<=*n*<=≤<=2·109).
Output Specification:
Output a single integer representing *f**n* modulo 1000000007 (109<=+<=7).
Demo Input:
['2 3\n3\n', '0 -1\n2\n']
Demo Output:
['1\n', '1000000006\n']
Note:
In the first sample, *f*<sub class="lower-index">2</sub> = *f*<sub class="lower-index">1</sub> + *f*<sub class="lower-index">3</sub>, 3 = 2 + *f*<sub class="lower-index">3</sub>, *f*<sub class="lower-index">3</sub> = 1.
In the second sample, *f*<sub class="lower-index">2</sub> = - 1; - 1 modulo (10<sup class="upper-index">9</sup> + 7) equals (10<sup class="upper-index">9</sup> + 6). | ```python
x, y = tuple(map(int, input().split()))
n = int(input())
MOD = 1000000007
if n%3 == 1 :
if n%2==0:
print(-(x%MOD))
else:
print(x%MOD)
elif n%3==2:
if n%2==0:
print(y%MOD)
else:
print(-(y%MOD))
elif n%3==0:
if n%2==0:
print((x-y)%MOD)
else:
print((y-x)%MOD)
``` | 0 | |
474 | A | Keyboard | PROGRAMMING | 900 | [
"implementation"
] | null | null | Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That means that now he presses not a button he wants, but one neighboring button (left or right, as specified in input).
We have a sequence of characters he has typed and we want to find the original message. | First line of the input contains one letter describing direction of shifting ('L' or 'R' respectively for left or right).
Second line contains a sequence of characters written by Mole. The size of this sequence will be no more than 100. Sequence contains only symbols that appear on Mole's keyboard. It doesn't contain spaces as there is no space on Mole's keyboard.
It is guaranteed that even though Mole hands are moved, he is still pressing buttons on keyboard and not hitting outside it. | Print a line that contains the original message. | [
"R\ns;;upimrrfod;pbr\n"
] | [
"allyouneedislove\n"
] | none | 500 | [
{
"input": "R\ns;;upimrrfod;pbr",
"output": "allyouneedislove"
},
{
"input": "R\nwertyuiop;lkjhgfdsxcvbnm,.",
"output": "qwertyuiolkjhgfdsazxcvbnm,"
},
{
"input": "L\nzxcvbnm,kjhgfdsaqwertyuio",
"output": "xcvbnm,.lkjhgfdswertyuiop"
},
{
"input": "R\nbubbuduppudup",
"outp... | 1,690,219,769 | 2,147,483,647 | Python 3 | RUNTIME_ERROR | TESTS | 2 | 46 | 0 | v="qwertyuiop";v11="asdfghjkl;";v111="zxcvbnm,./"
v1=input();v2=input();v3=''
for i in v2:
for j in v,v11,v111:
if i in j:
if v1=="R":
w=j.find(i)
v3+=j[abs(w-1)]
else:
v3+=s[abs(w+1)]
print(v3) | Title: Keyboard
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That means that now he presses not a button he wants, but one neighboring button (left or right, as specified in input).
We have a sequence of characters he has typed and we want to find the original message.
Input Specification:
First line of the input contains one letter describing direction of shifting ('L' or 'R' respectively for left or right).
Second line contains a sequence of characters written by Mole. The size of this sequence will be no more than 100. Sequence contains only symbols that appear on Mole's keyboard. It doesn't contain spaces as there is no space on Mole's keyboard.
It is guaranteed that even though Mole hands are moved, he is still pressing buttons on keyboard and not hitting outside it.
Output Specification:
Print a line that contains the original message.
Demo Input:
['R\ns;;upimrrfod;pbr\n']
Demo Output:
['allyouneedislove\n']
Note:
none | ```python
v="qwertyuiop";v11="asdfghjkl;";v111="zxcvbnm,./"
v1=input();v2=input();v3=''
for i in v2:
for j in v,v11,v111:
if i in j:
if v1=="R":
w=j.find(i)
v3+=j[abs(w-1)]
else:
v3+=s[abs(w+1)]
print(v3)
``` | -1 | |
6 | C | Alice, Bob and Chocolate | PROGRAMMING | 1,200 | [
"greedy",
"two pointers"
] | C. Alice, Bob and Chocolate | 2 | 64 | Alice and Bob like games. And now they are ready to start a new game. They have placed *n* chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.
How many bars each of the players will consume? | The first line contains one integer *n* (1<=≤<=*n*<=≤<=105) — the amount of bars on the table. The second line contains a sequence *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=1000), where *t**i* is the time (in seconds) needed to consume the *i*-th bar (in the order from left to right). | Print two numbers *a* and *b*, where *a* is the amount of bars consumed by Alice, and *b* is the amount of bars consumed by Bob. | [
"5\n2 9 8 2 7\n"
] | [
"2 3\n"
] | none | 0 | [
{
"input": "5\n2 9 8 2 7",
"output": "2 3"
},
{
"input": "1\n1",
"output": "1 0"
},
{
"input": "2\n1 1",
"output": "1 1"
},
{
"input": "3\n1 1 1",
"output": "2 1"
},
{
"input": "4\n1 1 1 1",
"output": "2 2"
},
{
"input": "1\n6",
"output": "1 0"
}... | 1,682,004,027 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 40 | 248 | 14,131,200 | import sys
from math import *
from collections import *
from heapq import *
from bisect import *
input = sys.stdin.readline
n = int(input())
arr = list(map(int, input().split()))
i = 0
j = n - 1
a, al = 0, 0
b, bo = 0, 0
while i <= j:
if al <= bo:
al += arr[i]
a += 1
i += 1
else:
bo += arr[j]
b += 1
j -= 1
print(a, b)
| Title: Alice, Bob and Chocolate
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Alice and Bob like games. And now they are ready to start a new game. They have placed *n* chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.
How many bars each of the players will consume?
Input Specification:
The first line contains one integer *n* (1<=≤<=*n*<=≤<=105) — the amount of bars on the table. The second line contains a sequence *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=1000), where *t**i* is the time (in seconds) needed to consume the *i*-th bar (in the order from left to right).
Output Specification:
Print two numbers *a* and *b*, where *a* is the amount of bars consumed by Alice, and *b* is the amount of bars consumed by Bob.
Demo Input:
['5\n2 9 8 2 7\n']
Demo Output:
['2 3\n']
Note:
none | ```python
import sys
from math import *
from collections import *
from heapq import *
from bisect import *
input = sys.stdin.readline
n = int(input())
arr = list(map(int, input().split()))
i = 0
j = n - 1
a, al = 0, 0
b, bo = 0, 0
while i <= j:
if al <= bo:
al += arr[i]
a += 1
i += 1
else:
bo += arr[j]
b += 1
j -= 1
print(a, b)
``` | 3.832714 |
899 | A | Splitting in Teams | PROGRAMMING | 800 | [
"constructive algorithms",
"greedy",
"math"
] | null | null | There were *n* groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.
The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. | The first line contains single integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of groups.
The second line contains a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=2), where *a**i* is the number of people in group *i*. | Print the maximum number of teams of three people the coach can form. | [
"4\n1 1 2 1\n",
"2\n2 2\n",
"7\n2 2 2 1 1 1 1\n",
"3\n1 1 1\n"
] | [
"1\n",
"0\n",
"3\n",
"1\n"
] | In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.
In the second example he can't make a single team.
In the third example the coach can form three teams. For example, he can do this in the following way:
- The first group (of two people) and the seventh group (of one person), - The second group (of two people) and the sixth group (of one person), - The third group (of two people) and the fourth group (of one person). | 500 | [
{
"input": "4\n1 1 2 1",
"output": "1"
},
{
"input": "2\n2 2",
"output": "0"
},
{
"input": "7\n2 2 2 1 1 1 1",
"output": "3"
},
{
"input": "3\n1 1 1",
"output": "1"
},
{
"input": "3\n2 2 2",
"output": "0"
},
{
"input": "3\n1 2 1",
"output": "1"
}... | 1,630,646,978 | 458 | PyPy 3 | WRONG_ANSWER | TESTS | 1 | 77 | 20,172,800 | n = int(input())
l = list(map(int,input().split()))
t = l.count(2)
o = l.count(1)
ans = 0
if t <= o:
ans += t
o -= t
ans += (o//3)
else:
print(o)
print(ans) | Title: Splitting in Teams
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There were *n* groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.
The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.
Input Specification:
The first line contains single integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of groups.
The second line contains a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=2), where *a**i* is the number of people in group *i*.
Output Specification:
Print the maximum number of teams of three people the coach can form.
Demo Input:
['4\n1 1 2 1\n', '2\n2 2\n', '7\n2 2 2 1 1 1 1\n', '3\n1 1 1\n']
Demo Output:
['1\n', '0\n', '3\n', '1\n']
Note:
In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.
In the second example he can't make a single team.
In the third example the coach can form three teams. For example, he can do this in the following way:
- The first group (of two people) and the seventh group (of one person), - The second group (of two people) and the sixth group (of one person), - The third group (of two people) and the fourth group (of one person). | ```python
n = int(input())
l = list(map(int,input().split()))
t = l.count(2)
o = l.count(1)
ans = 0
if t <= o:
ans += t
o -= t
ans += (o//3)
else:
print(o)
print(ans)
``` | 0 | |
501 | B | Misha and Changing Handles | PROGRAMMING | 1,100 | [
"data structures",
"dsu",
"strings"
] | null | null | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | The first line contains integer *q* (1<=≤<=*q*<=≤<=1000), the number of handle change requests.
Next *q* lines contain the descriptions of the requests, one per line.
Each query consists of two non-empty strings *old* and *new*, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings *old* and *new* are distinct. The lengths of the strings do not exceed 20.
The requests are given chronologically. In other words, by the moment of a query there is a single person with handle *old*, and handle *new* is not used and has not been used by anyone. | In the first line output the integer *n* — the number of users that changed their handles at least once.
In the next *n* lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, *old* and *new*, separated by a space, meaning that before the user had handle *old*, and after all the requests are completed, his handle is *new*. You may output lines in any order.
Each user who changes the handle must occur exactly once in this description. | [
"5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov\n"
] | [
"3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123\n"
] | none | 500 | [
{
"input": "5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov",
"output": "3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"
},
{
"input": "1\nMisha Vasya",
"output": "1\nMisha Vasya"
},
{
"input": "10\na b\nb c\nc d\nd... | 1,599,593,132 | 2,147,483,647 | Python 3 | OK | TESTS | 49 | 109 | 307,200 | n=int(input())
a=[]
for i in range(n):
b=input().split()
if b[0] in a:
ind=a.index(b[0])
a.insert(ind,b[1])
a.pop(ind+1)
else:
a.append(b[0])
a.append(b[1])
print(len(a)//2)
for i in range(len(a)//2):
print(*a[:2])
a=a[2:]
| Title: Misha and Changing Handles
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
Input Specification:
The first line contains integer *q* (1<=≤<=*q*<=≤<=1000), the number of handle change requests.
Next *q* lines contain the descriptions of the requests, one per line.
Each query consists of two non-empty strings *old* and *new*, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings *old* and *new* are distinct. The lengths of the strings do not exceed 20.
The requests are given chronologically. In other words, by the moment of a query there is a single person with handle *old*, and handle *new* is not used and has not been used by anyone.
Output Specification:
In the first line output the integer *n* — the number of users that changed their handles at least once.
In the next *n* lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, *old* and *new*, separated by a space, meaning that before the user had handle *old*, and after all the requests are completed, his handle is *new*. You may output lines in any order.
Each user who changes the handle must occur exactly once in this description.
Demo Input:
['5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov\n']
Demo Output:
['3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123\n']
Note:
none | ```python
n=int(input())
a=[]
for i in range(n):
b=input().split()
if b[0] in a:
ind=a.index(b[0])
a.insert(ind,b[1])
a.pop(ind+1)
else:
a.append(b[0])
a.append(b[1])
print(len(a)//2)
for i in range(len(a)//2):
print(*a[:2])
a=a[2:]
``` | 3 | |
656 | D | Rosetta Problem | PROGRAMMING | 2,100 | [
"*special"
] | null | null | The input contains a single integer *a* (0<=≤<=*a*<=≤<=1<=000<=000). | Output a single integer. | [
"129\n"
] | [
"1\n"
] | none | 0 | [
{
"input": "129",
"output": "1"
},
{
"input": "0",
"output": "0"
},
{
"input": "4",
"output": "0"
},
{
"input": "6",
"output": "0"
},
{
"input": "16",
"output": "0"
},
{
"input": "299593",
"output": "7"
},
{
"input": "398929",
"output":... | 1,679,112,009 | 2,147,483,647 | PyPy 3-64 | OK | TESTS | 25 | 61 | 0 | n = int(input())
c = 0
while n:
c += n%8 == 1
n//=8
print(c) | Title: Rosetta Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Input Specification:
The input contains a single integer *a* (0<=≤<=*a*<=≤<=1<=000<=000).
Output Specification:
Output a single integer.
Demo Input:
['129\n']
Demo Output:
['1\n']
Note:
none | ```python
n = int(input())
c = 0
while n:
c += n%8 == 1
n//=8
print(c)
``` | 3 | ||
59 | A | Word | PROGRAMMING | 800 | [
"implementation",
"strings"
] | A. Word | 2 | 256 | Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word. | The first line contains a word *s* — it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100. | Print the corrected word *s*. If the given word *s* has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one. | [
"HoUse\n",
"ViP\n",
"maTRIx\n"
] | [
"house\n",
"VIP\n",
"matrix\n"
] | none | 500 | [
{
"input": "HoUse",
"output": "house"
},
{
"input": "ViP",
"output": "VIP"
},
{
"input": "maTRIx",
"output": "matrix"
},
{
"input": "BNHWpnpawg",
"output": "bnhwpnpawg"
},
{
"input": "VTYGP",
"output": "VTYGP"
},
{
"input": "CHNenu",
"output": "chn... | 1,595,847,899 | 2,147,483,647 | PyPy 3 | OK | TESTS | 30 | 436 | 22,220,800 | import string
word = input()
count_lower = 0
count_upper = 0
for i in word:
if "a" <= i <= "z":
count_lower +=1
else:
count_upper +=1
if count_lower >= count_upper:
print(word.lower())
else:
print(word.upper()) | Title: Word
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
Input Specification:
The first line contains a word *s* — it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100.
Output Specification:
Print the corrected word *s*. If the given word *s* has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one.
Demo Input:
['HoUse\n', 'ViP\n', 'maTRIx\n']
Demo Output:
['house\n', 'VIP\n', 'matrix\n']
Note:
none | ```python
import string
word = input()
count_lower = 0
count_upper = 0
for i in word:
if "a" <= i <= "z":
count_lower +=1
else:
count_upper +=1
if count_lower >= count_upper:
print(word.lower())
else:
print(word.upper())
``` | 3.849611 |
509 | B | Painting Pebbles | PROGRAMMING | 1,300 | [
"constructive algorithms",
"greedy",
"implementation"
] | null | null | There are *n* piles of pebbles on the table, the *i*-th pile contains *a**i* pebbles. Your task is to paint each pebble using one of the *k* given colors so that for each color *c* and any two piles *i* and *j* the difference between the number of pebbles of color *c* in pile *i* and number of pebbles of color *c* in pile *j* is at most one.
In other words, let's say that *b**i*,<=*c* is the number of pebbles of color *c* in the *i*-th pile. Then for any 1<=≤<=*c*<=≤<=*k*, 1<=≤<=*i*,<=*j*<=≤<=*n* the following condition must be satisfied |*b**i*,<=*c*<=-<=*b**j*,<=*c*|<=≤<=1. It isn't necessary to use all *k* colors: if color *c* hasn't been used in pile *i*, then *b**i*,<=*c* is considered to be zero. | The first line of the input contains positive integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=100), separated by a space — the number of piles and the number of colors respectively.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100) denoting number of pebbles in each of the piles. | If there is no way to paint the pebbles satisfying the given condition, output "NO" (without quotes) .
Otherwise in the first line output "YES" (without quotes). Then *n* lines should follow, the *i*-th of them should contain *a**i* space-separated integers. *j*-th (1<=≤<=*j*<=≤<=*a**i*) of these integers should be equal to the color of the *j*-th pebble in the *i*-th pile. If there are several possible answers, you may output any of them. | [
"4 4\n1 2 3 4\n",
"5 2\n3 2 4 1 3\n",
"5 4\n3 2 4 3 5\n"
] | [
"YES\n1\n1 4\n1 2 4\n1 2 3 4\n",
"NO\n",
"YES\n1 2 3\n1 3\n1 2 3 4\n1 3 4\n1 1 2 3 4\n"
] | none | 0 | [
{
"input": "4 4\n1 2 3 4",
"output": "YES\n1 \n1 1 \n1 1 2 \n1 1 2 3 "
},
{
"input": "5 2\n3 2 4 1 3",
"output": "NO"
},
{
"input": "5 4\n3 2 4 3 5",
"output": "YES\n1 1 1 \n1 1 \n1 1 1 2 \n1 1 1 \n1 1 1 2 3 "
},
{
"input": "4 3\n5 6 7 8",
"output": "YES\n1 1 1 1 1 \n1 1 ... | 1,596,118,938 | 2,147,483,647 | PyPy 3 | OK | TESTS | 24 | 171 | 23,040,000 | keeper=input()
n, m=keeper.split(' ')
keeper2=input()
tp=keeper2.split(' ')
map_object=map(int, tp)
arr=list(map_object)
if (max(arr))-(min(arr)) > int(m): print("NO")
else:
print("YES")
for x in arr:
for y in range(0,int(x)): print(int(y)%int(m)+1, end=" ")
print() | Title: Painting Pebbles
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* piles of pebbles on the table, the *i*-th pile contains *a**i* pebbles. Your task is to paint each pebble using one of the *k* given colors so that for each color *c* and any two piles *i* and *j* the difference between the number of pebbles of color *c* in pile *i* and number of pebbles of color *c* in pile *j* is at most one.
In other words, let's say that *b**i*,<=*c* is the number of pebbles of color *c* in the *i*-th pile. Then for any 1<=≤<=*c*<=≤<=*k*, 1<=≤<=*i*,<=*j*<=≤<=*n* the following condition must be satisfied |*b**i*,<=*c*<=-<=*b**j*,<=*c*|<=≤<=1. It isn't necessary to use all *k* colors: if color *c* hasn't been used in pile *i*, then *b**i*,<=*c* is considered to be zero.
Input Specification:
The first line of the input contains positive integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=100), separated by a space — the number of piles and the number of colors respectively.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100) denoting number of pebbles in each of the piles.
Output Specification:
If there is no way to paint the pebbles satisfying the given condition, output "NO" (without quotes) .
Otherwise in the first line output "YES" (without quotes). Then *n* lines should follow, the *i*-th of them should contain *a**i* space-separated integers. *j*-th (1<=≤<=*j*<=≤<=*a**i*) of these integers should be equal to the color of the *j*-th pebble in the *i*-th pile. If there are several possible answers, you may output any of them.
Demo Input:
['4 4\n1 2 3 4\n', '5 2\n3 2 4 1 3\n', '5 4\n3 2 4 3 5\n']
Demo Output:
['YES\n1\n1 4\n1 2 4\n1 2 3 4\n', 'NO\n', 'YES\n1 2 3\n1 3\n1 2 3 4\n1 3 4\n1 1 2 3 4\n']
Note:
none | ```python
keeper=input()
n, m=keeper.split(' ')
keeper2=input()
tp=keeper2.split(' ')
map_object=map(int, tp)
arr=list(map_object)
if (max(arr))-(min(arr)) > int(m): print("NO")
else:
print("YES")
for x in arr:
for y in range(0,int(x)): print(int(y)%int(m)+1, end=" ")
print()
``` | 3 | |
39 | J | Spelling Check | PROGRAMMING | 1,500 | [
"hashing",
"implementation",
"strings"
] | J. Spelling Check | 2 | 256 | Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete? | The input data contains two strings, consisting of lower-case Latin letters. The length of each string is from 1 to 106 symbols inclusive, the first string contains exactly 1 symbol more than the second one. | In the first line output the number of positions of the symbols in the first string, after the deleting of which the first string becomes identical to the second one. In the second line output space-separated positions of these symbols in increasing order. The positions are numbered starting from 1. If it is impossible to make the first string identical to the second string by deleting one symbol, output one number 0. | [
"abdrakadabra\nabrakadabra\n",
"aa\na\n",
"competition\ncodeforces\n"
] | [
"1\n3\n",
"2\n1 2\n",
"0\n"
] | none | 0 | [
{
"input": "abdrakadabra\nabrakadabra",
"output": "1\n3 "
},
{
"input": "aa\na",
"output": "2\n1 2 "
},
{
"input": "competition\ncodeforces",
"output": "0"
},
{
"input": "ab\na",
"output": "1\n2 "
},
{
"input": "bb\nb",
"output": "2\n1 2 "
},
{
"input"... | 1,697,025,857 | 2,147,483,647 | PyPy 3-64 | WRONG_ANSWER | TESTS | 3 | 92 | 0 | s = input()
t = input()
l = 0
r = 0
let = []
flag = 0
while l < len(s) and r < len(t):
if s[l] != t[r]:
let.append((s[l],l+1))
flag = 1
l += 1
else:
l += 1
r += 1
if flag:
if len(let) == 1:
print(1)
print(let[0][1])
else:
print(0)
else:
new = []
f = 0
while l < len(s):
new.append(l+1)
l += 1
l = len(s)-1
r = len(t)-1
while l >= 0 and r >= 0:
if s[l] != t[r]:
new.append(l+1)
f = 1
l -= 1
else:
l -= 1
r -= 1
if not f:
while l >= 0:
new.append(l+1)
l -= 1
if len(new) <= 2:
print(2)
new.sort()
print(*new)
| Title: Spelling Check
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete?
Input Specification:
The input data contains two strings, consisting of lower-case Latin letters. The length of each string is from 1 to 106 symbols inclusive, the first string contains exactly 1 symbol more than the second one.
Output Specification:
In the first line output the number of positions of the symbols in the first string, after the deleting of which the first string becomes identical to the second one. In the second line output space-separated positions of these symbols in increasing order. The positions are numbered starting from 1. If it is impossible to make the first string identical to the second string by deleting one symbol, output one number 0.
Demo Input:
['abdrakadabra\nabrakadabra\n', 'aa\na\n', 'competition\ncodeforces\n']
Demo Output:
['1\n3\n', '2\n1 2\n', '0\n']
Note:
none | ```python
s = input()
t = input()
l = 0
r = 0
let = []
flag = 0
while l < len(s) and r < len(t):
if s[l] != t[r]:
let.append((s[l],l+1))
flag = 1
l += 1
else:
l += 1
r += 1
if flag:
if len(let) == 1:
print(1)
print(let[0][1])
else:
print(0)
else:
new = []
f = 0
while l < len(s):
new.append(l+1)
l += 1
l = len(s)-1
r = len(t)-1
while l >= 0 and r >= 0:
if s[l] != t[r]:
new.append(l+1)
f = 1
l -= 1
else:
l -= 1
r -= 1
if not f:
while l >= 0:
new.append(l+1)
l -= 1
if len(new) <= 2:
print(2)
new.sort()
print(*new)
``` | 0 |
980 | A | Links and Pearls | PROGRAMMING | 900 | [
"implementation",
"math"
] | null | null | A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one.
You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you like, but you can't throw away any parts.
Can you make the number of links between every two adjacent pearls equal? Two pearls are considered to be adjacent if there is no other pearl between them.
Note that the final necklace should remain as one circular part of the same length as the initial necklace. | The only line of input contains a string $s$ ($3 \leq |s| \leq 100$), representing the necklace, where a dash '-' represents a link and the lowercase English letter 'o' represents a pearl. | Print "YES" if the links and pearls can be rejoined such that the number of links between adjacent pearls is equal. Otherwise print "NO".
You can print each letter in any case (upper or lower). | [
"-o-o--",
"-o---\n",
"-o---o-\n",
"ooo\n"
] | [
"YES",
"YES",
"NO",
"YES\n"
] | none | 500 | [
{
"input": "-o-o--",
"output": "YES"
},
{
"input": "-o---",
"output": "YES"
},
{
"input": "-o---o-",
"output": "NO"
},
{
"input": "ooo",
"output": "YES"
},
{
"input": "---",
"output": "YES"
},
{
"input": "--o-o-----o----o--oo-o-----ooo-oo---o--",
"... | 1,526,353,272 | 2,147,483,647 | PyPy 3 | RUNTIME_ERROR | TESTS | 4 | 155 | 22,425,600 | s = input()
a = s.count('o')
b = s.count('-')
x = b / a
if x - int(x) > 0:
print("NO")
else:
print("YES")
| Title: Links and Pearls
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one.
You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you like, but you can't throw away any parts.
Can you make the number of links between every two adjacent pearls equal? Two pearls are considered to be adjacent if there is no other pearl between them.
Note that the final necklace should remain as one circular part of the same length as the initial necklace.
Input Specification:
The only line of input contains a string $s$ ($3 \leq |s| \leq 100$), representing the necklace, where a dash '-' represents a link and the lowercase English letter 'o' represents a pearl.
Output Specification:
Print "YES" if the links and pearls can be rejoined such that the number of links between adjacent pearls is equal. Otherwise print "NO".
You can print each letter in any case (upper or lower).
Demo Input:
['-o-o--', '-o---\n', '-o---o-\n', 'ooo\n']
Demo Output:
['YES', 'YES', 'NO', 'YES\n']
Note:
none | ```python
s = input()
a = s.count('o')
b = s.count('-')
x = b / a
if x - int(x) > 0:
print("NO")
else:
print("YES")
``` | -1 | |
803 | A | Maximal Binary Matrix | PROGRAMMING | 1,400 | [
"constructive algorithms"
] | null | null | You are given matrix with *n* rows and *n* columns filled with zeroes. You should put *k* ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal.
One matrix is lexicographically greater than the other if the first different number in the first different row from the top in the first matrix is greater than the corresponding number in the second one.
If there exists no such matrix then output -1. | The first line consists of two numbers *n* and *k* (1<=≤<=*n*<=≤<=100, 0<=≤<=*k*<=≤<=106). | If the answer exists then output resulting matrix. Otherwise output -1. | [
"2 1\n",
"3 2\n",
"2 5\n"
] | [
"1 0 \n0 0 \n",
"1 0 0 \n0 1 0 \n0 0 0 \n",
"-1\n"
] | none | 0 | [
{
"input": "2 1",
"output": "1 0 \n0 0 "
},
{
"input": "3 2",
"output": "1 0 0 \n0 1 0 \n0 0 0 "
},
{
"input": "2 5",
"output": "-1"
},
{
"input": "1 0",
"output": "0 "
},
{
"input": "1 1",
"output": "1 "
},
{
"input": "20 398",
"output": "1 1 1 1 ... | 1,698,130,485 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 1 | 31 | 0 | n, k = map(int, input().split())
matrix = [[0]*n for _ in range(n)]
if k > n*n :
print(-1)
else:
for i in range(n):
for j in range(i,n):
if k <= 0:
break
elif k == 1:
matrix[max(i,j-1)][max(i,j-1)] =1
k -= 1
else:
if i == j:
matrix[i][j] = 1
k -= 1
else:
matrix[i][j] = 1
matrix[j][i] = 1
k -= 2
for i in range(n):
print(' '.join(map(str,matrix[i]))) | Title: Maximal Binary Matrix
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given matrix with *n* rows and *n* columns filled with zeroes. You should put *k* ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal.
One matrix is lexicographically greater than the other if the first different number in the first different row from the top in the first matrix is greater than the corresponding number in the second one.
If there exists no such matrix then output -1.
Input Specification:
The first line consists of two numbers *n* and *k* (1<=≤<=*n*<=≤<=100, 0<=≤<=*k*<=≤<=106).
Output Specification:
If the answer exists then output resulting matrix. Otherwise output -1.
Demo Input:
['2 1\n', '3 2\n', '2 5\n']
Demo Output:
['1 0 \n0 0 \n', '1 0 0 \n0 1 0 \n0 0 0 \n', '-1\n']
Note:
none | ```python
n, k = map(int, input().split())
matrix = [[0]*n for _ in range(n)]
if k > n*n :
print(-1)
else:
for i in range(n):
for j in range(i,n):
if k <= 0:
break
elif k == 1:
matrix[max(i,j-1)][max(i,j-1)] =1
k -= 1
else:
if i == j:
matrix[i][j] = 1
k -= 1
else:
matrix[i][j] = 1
matrix[j][i] = 1
k -= 2
for i in range(n):
print(' '.join(map(str,matrix[i])))
``` | 0 | |
285 | A | Slightly Decreasing Permutations | PROGRAMMING | 1,100 | [
"greedy",
"implementation"
] | null | null | Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*.
The decreasing coefficient of permutation *p*1,<=*p*2,<=...,<=*p**n* is the number of such *i* (1<=≤<=*i*<=<<=*n*), that *p**i*<=><=*p**i*<=+<=1.
You have numbers *n* and *k*. Your task is to print the permutation of length *n* with decreasing coefficient *k*. | The single line contains two space-separated integers: *n*,<=*k* (1<=≤<=*n*<=≤<=105,<=0<=≤<=*k*<=<<=*n*) — the permutation length and the decreasing coefficient. | In a single line print *n* space-separated integers: *p*1,<=*p*2,<=...,<=*p**n* — the permutation of length *n* with decreasing coefficient *k*.
If there are several permutations that meet this condition, print any of them. It is guaranteed that the permutation with the sought parameters exists. | [
"5 2\n",
"3 0\n",
"3 2\n"
] | [
"1 5 2 4 3\n",
"1 2 3\n",
"3 2 1\n"
] | none | 500 | [
{
"input": "5 2",
"output": "1 5 2 4 3"
},
{
"input": "3 0",
"output": "1 2 3"
},
{
"input": "3 2",
"output": "3 2 1"
},
{
"input": "1 0",
"output": "1"
},
{
"input": "2 0",
"output": "1 2"
},
{
"input": "2 1",
"output": "2 1"
},
{
"input":... | 1,696,322,227 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 0 | 30 | 0 | n, k = map(int, input().split())
perm = list(range(1, n + 1))
# Reverse the first k elements
for i in range(k):
perm[i] = n - i
print(" ".join(map(str, perm))) | Title: Slightly Decreasing Permutations
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*.
The decreasing coefficient of permutation *p*1,<=*p*2,<=...,<=*p**n* is the number of such *i* (1<=≤<=*i*<=<<=*n*), that *p**i*<=><=*p**i*<=+<=1.
You have numbers *n* and *k*. Your task is to print the permutation of length *n* with decreasing coefficient *k*.
Input Specification:
The single line contains two space-separated integers: *n*,<=*k* (1<=≤<=*n*<=≤<=105,<=0<=≤<=*k*<=<<=*n*) — the permutation length and the decreasing coefficient.
Output Specification:
In a single line print *n* space-separated integers: *p*1,<=*p*2,<=...,<=*p**n* — the permutation of length *n* with decreasing coefficient *k*.
If there are several permutations that meet this condition, print any of them. It is guaranteed that the permutation with the sought parameters exists.
Demo Input:
['5 2\n', '3 0\n', '3 2\n']
Demo Output:
['1 5 2 4 3\n', '1 2 3\n', '3 2 1\n']
Note:
none | ```python
n, k = map(int, input().split())
perm = list(range(1, n + 1))
# Reverse the first k elements
for i in range(k):
perm[i] = n - i
print(" ".join(map(str, perm)))
``` | 0 | |
177 | E1 | Space Voyage | PROGRAMMING | 1,700 | [
"binary search"
] | null | null | The Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit *n* planets. For planet *i* *a**i* is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and *b**i* is the number of citizens on the planet.
The Smart Beaver is going to bring some presents from ABBYY to the planets he will be visiting. The presents are packed in suitcases, *x* presents in each. The Beaver will take to the ship exactly *a*1<=+<=...<=+<=*a**n* suitcases.
As the Beaver lands on the *i*-th planet, he takes *a**i* suitcases and goes out. On the first day on the planet the Beaver takes a walk and gets to know the citizens. On the second and all subsequent days the Beaver gives presents to the citizens — each of the *b**i* citizens gets one present per day. The Beaver leaves the planet in the evening of the day when the number of presents left is strictly less than the number of citizens (i.e. as soon as he won't be able to give away the proper number of presents the next day). He leaves the remaining presents at the hotel.
The Beaver is going to spend exactly *c* days traveling. The time spent on flights between the planets is considered to be zero. In how many ways can one choose the positive integer *x* so that the planned voyage will take exactly *c* days? | The first input line contains space-separated integers *n* and *c* — the number of planets that the Beaver is going to visit and the number of days he is going to spend traveling, correspondingly.
The next *n* lines contain pairs of space-separated integers *a**i*,<=*b**i* (1<=≤<=*i*<=≤<=*n*) — the number of suitcases he can bring to the *i*-th planet and the number of citizens of the *i*-th planet, correspondingly.
The input limitations for getting 30 points are:
- 1<=≤<=*n*<=≤<=100 - 1<=≤<=*a**i*<=≤<=100 - 1<=≤<=*b**i*<=≤<=100 - 1<=≤<=*c*<=≤<=100
The input limitations for getting 100 points are:
- 1<=≤<=*n*<=≤<=104 - 0<=≤<=*a**i*<=≤<=109 - 1<=≤<=*b**i*<=≤<=109 - 1<=≤<=*c*<=≤<=109
Due to possible overflow, it is recommended to use the 64-bit arithmetic. In some solutions even the 64-bit arithmetic can overflow. So be careful in calculations! | Print a single number *k* — the number of ways to choose *x* so as to travel for exactly *c* days. If there are infinitely many possible values of *x*, print -1.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. | [
"2 5\n1 5\n2 4\n"
] | [
"1\n"
] | In the first example there is only one suitable value *x* = 5. Then the Beaver takes 1 suitcase with 5 presents to the first planet. Here he spends 2 days: he hangs around on the first day, and he gives away five presents on the second day. He takes 2 suitcases with 10 presents to the second planet. Here he spends 3 days — he gives away 4 presents on the second and the third days and leaves the remaining 2 presents at the hotel. In total, the Beaver spends 5 days traveling.
For *x* = 4 or less the Beaver won't have enough presents for the second day on the first planet, so the voyage will end too soon. For *x* = 6 and more the Beaver will spend at least one more day on the second planet, and the voyage will take too long. | 30 | [
{
"input": "2 5\n1 5\n2 4",
"output": "1"
},
{
"input": "1 97\n1 91",
"output": "91"
},
{
"input": "2 79\n1 91\n1 77",
"output": "42"
},
{
"input": "3 100\n8 46\n8 56\n77 98",
"output": "1"
},
{
"input": "71 100\n1 92\n1 94\n1 97\n1 95\n1 100\n1 100\n1 98\n1 99\n1... | 1,599,069,571 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS1 | 4 | 186 | 307,200 | def binary_search(arr, x):
arr.sort()
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = low + (high-low)//2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
def ternary_search(l, r, key, ar):
if (r >= l):
mid1 = l + (r - l) // 3
mid2 = r - (r - l) // 3
if (ar[mid1] == key):
return mid1
if (ar[mid2] == key):
return mid2
if (key < ar[mid1]):
return ternary_search(l, mid1 - 1, key, ar)
elif (key > ar[mid2]):
return ternary_search(mid2 + 1, r, key, ar)
else:
return ternary_search(mid1 + 1,
mid2 - 1, key, ar)
return -1
def cheaker(x):
cnt= 0
for i in range(n):
cnt+= ((a[i]*x)//b[i] +1)
return cnt
def binary_search_answer(low,high):
while((high - low )> 0):
mid = (high+low)//2
if cheaker(mid)<c:
low= mid+1
else:
high = mid
if cheaker(low)==c :
return low
else:
return -1
def binary_search_answer2(low,high):
while((high - low )> 0):
mid = (high+low+1)//2
if cheaker(mid)<=c:
low= mid
else:
high = mid-1
if cheaker(low )==c:
return low
else:
return -1
if __name__ == "__main__":
n,c= map(int,input().split())
a=[0 for i in range(n)]
b= [0 for i in range(n)]
flag=True
for j in range(n):
a[j],b[j]= map(int,input().split())
if a[j]!=0:
flag=False
z = 10**9
if flag and n==c :
print(0)
elif n== c:
print(min(b)-1)
elif flag :
print(-1)
elif n<c:
an1=binary_search_answer(1,10**18)
an2= binary_search_answer2(1,10**18)
if an1 ==-1 or an2 == -1:
print(0)
else:
print(an2-an1 +1)
else:
print(0) | Title: Space Voyage
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit *n* planets. For planet *i* *a**i* is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and *b**i* is the number of citizens on the planet.
The Smart Beaver is going to bring some presents from ABBYY to the planets he will be visiting. The presents are packed in suitcases, *x* presents in each. The Beaver will take to the ship exactly *a*1<=+<=...<=+<=*a**n* suitcases.
As the Beaver lands on the *i*-th planet, he takes *a**i* suitcases and goes out. On the first day on the planet the Beaver takes a walk and gets to know the citizens. On the second and all subsequent days the Beaver gives presents to the citizens — each of the *b**i* citizens gets one present per day. The Beaver leaves the planet in the evening of the day when the number of presents left is strictly less than the number of citizens (i.e. as soon as he won't be able to give away the proper number of presents the next day). He leaves the remaining presents at the hotel.
The Beaver is going to spend exactly *c* days traveling. The time spent on flights between the planets is considered to be zero. In how many ways can one choose the positive integer *x* so that the planned voyage will take exactly *c* days?
Input Specification:
The first input line contains space-separated integers *n* and *c* — the number of planets that the Beaver is going to visit and the number of days he is going to spend traveling, correspondingly.
The next *n* lines contain pairs of space-separated integers *a**i*,<=*b**i* (1<=≤<=*i*<=≤<=*n*) — the number of suitcases he can bring to the *i*-th planet and the number of citizens of the *i*-th planet, correspondingly.
The input limitations for getting 30 points are:
- 1<=≤<=*n*<=≤<=100 - 1<=≤<=*a**i*<=≤<=100 - 1<=≤<=*b**i*<=≤<=100 - 1<=≤<=*c*<=≤<=100
The input limitations for getting 100 points are:
- 1<=≤<=*n*<=≤<=104 - 0<=≤<=*a**i*<=≤<=109 - 1<=≤<=*b**i*<=≤<=109 - 1<=≤<=*c*<=≤<=109
Due to possible overflow, it is recommended to use the 64-bit arithmetic. In some solutions even the 64-bit arithmetic can overflow. So be careful in calculations!
Output Specification:
Print a single number *k* — the number of ways to choose *x* so as to travel for exactly *c* days. If there are infinitely many possible values of *x*, print -1.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Demo Input:
['2 5\n1 5\n2 4\n']
Demo Output:
['1\n']
Note:
In the first example there is only one suitable value *x* = 5. Then the Beaver takes 1 suitcase with 5 presents to the first planet. Here he spends 2 days: he hangs around on the first day, and he gives away five presents on the second day. He takes 2 suitcases with 10 presents to the second planet. Here he spends 3 days — he gives away 4 presents on the second and the third days and leaves the remaining 2 presents at the hotel. In total, the Beaver spends 5 days traveling.
For *x* = 4 or less the Beaver won't have enough presents for the second day on the first planet, so the voyage will end too soon. For *x* = 6 and more the Beaver will spend at least one more day on the second planet, and the voyage will take too long. | ```python
def binary_search(arr, x):
arr.sort()
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = low + (high-low)//2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
def ternary_search(l, r, key, ar):
if (r >= l):
mid1 = l + (r - l) // 3
mid2 = r - (r - l) // 3
if (ar[mid1] == key):
return mid1
if (ar[mid2] == key):
return mid2
if (key < ar[mid1]):
return ternary_search(l, mid1 - 1, key, ar)
elif (key > ar[mid2]):
return ternary_search(mid2 + 1, r, key, ar)
else:
return ternary_search(mid1 + 1,
mid2 - 1, key, ar)
return -1
def cheaker(x):
cnt= 0
for i in range(n):
cnt+= ((a[i]*x)//b[i] +1)
return cnt
def binary_search_answer(low,high):
while((high - low )> 0):
mid = (high+low)//2
if cheaker(mid)<c:
low= mid+1
else:
high = mid
if cheaker(low)==c :
return low
else:
return -1
def binary_search_answer2(low,high):
while((high - low )> 0):
mid = (high+low+1)//2
if cheaker(mid)<=c:
low= mid
else:
high = mid-1
if cheaker(low )==c:
return low
else:
return -1
if __name__ == "__main__":
n,c= map(int,input().split())
a=[0 for i in range(n)]
b= [0 for i in range(n)]
flag=True
for j in range(n):
a[j],b[j]= map(int,input().split())
if a[j]!=0:
flag=False
z = 10**9
if flag and n==c :
print(0)
elif n== c:
print(min(b)-1)
elif flag :
print(-1)
elif n<c:
an1=binary_search_answer(1,10**18)
an2= binary_search_answer2(1,10**18)
if an1 ==-1 or an2 == -1:
print(0)
else:
print(an2-an1 +1)
else:
print(0)
``` | 0 | |
293 | A | Weird Game | PROGRAMMING | 1,500 | [
"games",
"greedy"
] | null | null | Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·*n* binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·*n*, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as *s*<==<=*s*1*s*2... *s*2*n*. Similarly, let's represent Andrey's word as *t*<==<=*t*1*t*2... *t*2*n*. Then, if Yaroslav choose number *k* during his move, then he is going to write out character *s**k* on the piece of paper. Similarly, if Andrey choose number *r* during his move, then he is going to write out character *t**r* on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings *s* and *t*. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well. | The first line contains integer *n* (1<=≤<=*n*<=≤<=106). The second line contains string *s* — Yaroslav's word. The third line contains string *t* — Andrey's word.
It is guaranteed that both words consist of 2·*n* characters "0" and "1". | Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes. | [
"2\n0111\n0001\n",
"3\n110110\n001001\n",
"3\n111000\n000111\n",
"4\n01010110\n00101101\n",
"4\n01100000\n10010011\n"
] | [
"First\n",
"First\n",
"Draw\n",
"First\n",
"Second\n"
] | none | 500 | [
{
"input": "2\n0111\n0001",
"output": "First"
},
{
"input": "3\n110110\n001001",
"output": "First"
},
{
"input": "3\n111000\n000111",
"output": "Draw"
},
{
"input": "4\n01010110\n00101101",
"output": "First"
},
{
"input": "4\n01100000\n10010011",
"output": "Se... | 1,516,822,818 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 5 | 122 | 5,632,000 | n = input()
s = input()
t = input()
fir = 0
sec = 0
same = 0
for (l, r) in zip(s, t):
if l == '1':
fir += 1
if r == 1:
same += 1
elif r == '1':
sec += 1
if fir > sec or same % 2 != 0:
print("First")
elif sec > fir + 1:
print("Second")
else:
print("Draw") | Title: Weird Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·*n* binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·*n*, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as *s*<==<=*s*1*s*2... *s*2*n*. Similarly, let's represent Andrey's word as *t*<==<=*t*1*t*2... *t*2*n*. Then, if Yaroslav choose number *k* during his move, then he is going to write out character *s**k* on the piece of paper. Similarly, if Andrey choose number *r* during his move, then he is going to write out character *t**r* on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings *s* and *t*. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=106). The second line contains string *s* — Yaroslav's word. The third line contains string *t* — Andrey's word.
It is guaranteed that both words consist of 2·*n* characters "0" and "1".
Output Specification:
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Demo Input:
['2\n0111\n0001\n', '3\n110110\n001001\n', '3\n111000\n000111\n', '4\n01010110\n00101101\n', '4\n01100000\n10010011\n']
Demo Output:
['First\n', 'First\n', 'Draw\n', 'First\n', 'Second\n']
Note:
none | ```python
n = input()
s = input()
t = input()
fir = 0
sec = 0
same = 0
for (l, r) in zip(s, t):
if l == '1':
fir += 1
if r == 1:
same += 1
elif r == '1':
sec += 1
if fir > sec or same % 2 != 0:
print("First")
elif sec > fir + 1:
print("Second")
else:
print("Draw")
``` | 0 | |
151 | A | Soft Drinking | PROGRAMMING | 800 | [
"implementation",
"math"
] | null | null | This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt.
To make a toast, each friend needs *nl* milliliters of the drink, a slice of lime and *np* grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make? | The first and only line contains positive integers *n*, *k*, *l*, *c*, *d*, *p*, *nl*, *np*, not exceeding 1000 and no less than 1. The numbers are separated by exactly one space. | Print a single integer — the number of toasts each friend can make. | [
"3 4 5 10 8 100 3 1\n",
"5 100 10 1 19 90 4 3\n",
"10 1000 1000 25 23 1 50 1\n"
] | [
"2\n",
"3\n",
"0\n"
] | A comment to the first sample:
Overall the friends have 4 * 5 = 20 milliliters of the drink, it is enough to make 20 / 3 = 6 toasts. The limes are enough for 10 * 8 = 80 toasts and the salt is enough for 100 / 1 = 100 toasts. However, there are 3 friends in the group, so the answer is *min*(6, 80, 100) / 3 = 2. | 500 | [
{
"input": "3 4 5 10 8 100 3 1",
"output": "2"
},
{
"input": "5 100 10 1 19 90 4 3",
"output": "3"
},
{
"input": "10 1000 1000 25 23 1 50 1",
"output": "0"
},
{
"input": "1 7 4 5 5 8 3 2",
"output": "4"
},
{
"input": "2 3 3 5 5 10 1 3",
"output": "1"
},
{
... | 1,670,478,528 | 2,147,483,647 | Python 3 | OK | TESTS | 27 | 92 | 0 | n,k,l,c,d,p,nl,dp = map(int,input().strip().split())
toasts = (k*l) // nl
limes = c * d
salt = p // dp
print(min(toasts,min(limes,salt)) // n) | Title: Soft Drinking
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt.
To make a toast, each friend needs *nl* milliliters of the drink, a slice of lime and *np* grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?
Input Specification:
The first and only line contains positive integers *n*, *k*, *l*, *c*, *d*, *p*, *nl*, *np*, not exceeding 1000 and no less than 1. The numbers are separated by exactly one space.
Output Specification:
Print a single integer — the number of toasts each friend can make.
Demo Input:
['3 4 5 10 8 100 3 1\n', '5 100 10 1 19 90 4 3\n', '10 1000 1000 25 23 1 50 1\n']
Demo Output:
['2\n', '3\n', '0\n']
Note:
A comment to the first sample:
Overall the friends have 4 * 5 = 20 milliliters of the drink, it is enough to make 20 / 3 = 6 toasts. The limes are enough for 10 * 8 = 80 toasts and the salt is enough for 100 / 1 = 100 toasts. However, there are 3 friends in the group, so the answer is *min*(6, 80, 100) / 3 = 2. | ```python
n,k,l,c,d,p,nl,dp = map(int,input().strip().split())
toasts = (k*l) // nl
limes = c * d
salt = p // dp
print(min(toasts,min(limes,salt)) // n)
``` | 3 | |
462 | B | Appleman and Card Game | PROGRAMMING | 1,300 | [
"greedy"
] | null | null | Appleman has *n* cards. Each card has an uppercase letter written on it. Toastman must choose *k* cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card *i* you should calculate how much Toastman's cards have the letter equal to letter on *i*th, then sum up all these quantities, such a number of coins Appleman should give to Toastman.
Given the description of Appleman's cards. What is the maximum number of coins Toastman can get? | The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=105). The next line contains *n* uppercase letters without spaces — the *i*-th letter describes the *i*-th card of the Appleman. | Print a single integer – the answer to the problem. | [
"15 10\nDZFDFZDFDDDDDDF\n",
"6 4\nYJSNPI\n"
] | [
"82\n",
"4\n"
] | In the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin. | 1,000 | [
{
"input": "15 10\nDZFDFZDFDDDDDDF",
"output": "82"
},
{
"input": "6 4\nYJSNPI",
"output": "4"
},
{
"input": "5 3\nAOWBY",
"output": "3"
},
{
"input": "1 1\nV",
"output": "1"
},
{
"input": "2 1\nWT",
"output": "1"
},
{
"input": "2 2\nBL",
"output":... | 1,587,234,750 | 2,147,483,647 | Python 3 | OK | TESTS | 41 | 155 | 614,400 | firstLine = input();
n, k = firstLine.split();
n = int(n);
k = int(k);
s = input();
result = 0;
count = [0] * 26
for i in range(0, len(s)):
index = ord(s[i]) - 65;
count[index] = count[index] + 1;
count.sort(reverse=True)
for j in range(0, len(count)):
if(count[j] <= k):
result = result + (count[j]*count[j]);
k = k - count[j];
if(k==0): break
else:
result = result + (k*k);
break
print(result)
| Title: Appleman and Card Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Appleman has *n* cards. Each card has an uppercase letter written on it. Toastman must choose *k* cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card *i* you should calculate how much Toastman's cards have the letter equal to letter on *i*th, then sum up all these quantities, such a number of coins Appleman should give to Toastman.
Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=105). The next line contains *n* uppercase letters without spaces — the *i*-th letter describes the *i*-th card of the Appleman.
Output Specification:
Print a single integer – the answer to the problem.
Demo Input:
['15 10\nDZFDFZDFDDDDDDF\n', '6 4\nYJSNPI\n']
Demo Output:
['82\n', '4\n']
Note:
In the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin. | ```python
firstLine = input();
n, k = firstLine.split();
n = int(n);
k = int(k);
s = input();
result = 0;
count = [0] * 26
for i in range(0, len(s)):
index = ord(s[i]) - 65;
count[index] = count[index] + 1;
count.sort(reverse=True)
for j in range(0, len(count)):
if(count[j] <= k):
result = result + (count[j]*count[j]);
k = k - count[j];
if(k==0): break
else:
result = result + (k*k);
break
print(result)
``` | 3 | |
616 | D | Longest k-Good Segment | PROGRAMMING | 1,600 | [
"binary search",
"data structures",
"two pointers"
] | null | null | The array *a* with *n* integers is given. Let's call the sequence of one or more consecutive elements in *a* segment. Also let's call the segment k-good if it contains no more than *k* different values.
Find any longest k-good segment.
As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. | The first line contains two integers *n*,<=*k* (1<=≤<=*k*<=≤<=*n*<=≤<=5·105) — the number of elements in *a* and the parameter *k*.
The second line contains *n* integers *a**i* (0<=≤<=*a**i*<=≤<=106) — the elements of the array *a*. | Print two integers *l*,<=*r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in *a* are numbered from 1 to *n* from left to right. | [
"5 5\n1 2 3 4 5\n",
"9 3\n6 5 1 2 3 2 1 4 5\n",
"3 1\n1 2 3\n"
] | [
"1 5\n",
"3 7\n",
"1 1\n"
] | none | 0 | [
{
"input": "5 5\n1 2 3 4 5",
"output": "1 5"
},
{
"input": "9 3\n6 5 1 2 3 2 1 4 5",
"output": "3 7"
},
{
"input": "3 1\n1 2 3",
"output": "1 1"
},
{
"input": "1 1\n747391",
"output": "1 1"
},
{
"input": "5 2\n171230 171230 171230 171230 171230",
"output": "1 ... | 1,693,851,971 | 2,147,483,647 | Python 3 | TIME_LIMIT_EXCEEDED | TESTS | 9 | 1,000 | 61,440,000 | n, k = map(int, input().split())
a = list(map(int, input().split()))
l, r = 0, k
ll, rr = 0, 0
ans = a[l:r]
while r < n:
if a[r] in ans or len(set(ans)) < k :
r += 1
else:
if (rr - ll) < ((r - l)):
ll, rr = l, r
l += 1
ans = a[l:r]
if (rr - ll) < ((r - l)):
ll, rr = l, r
print(ll + 1, rr) | Title: Longest k-Good Segment
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The array *a* with *n* integers is given. Let's call the sequence of one or more consecutive elements in *a* segment. Also let's call the segment k-good if it contains no more than *k* different values.
Find any longest k-good segment.
As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
Input Specification:
The first line contains two integers *n*,<=*k* (1<=≤<=*k*<=≤<=*n*<=≤<=5·105) — the number of elements in *a* and the parameter *k*.
The second line contains *n* integers *a**i* (0<=≤<=*a**i*<=≤<=106) — the elements of the array *a*.
Output Specification:
Print two integers *l*,<=*r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in *a* are numbered from 1 to *n* from left to right.
Demo Input:
['5 5\n1 2 3 4 5\n', '9 3\n6 5 1 2 3 2 1 4 5\n', '3 1\n1 2 3\n']
Demo Output:
['1 5\n', '3 7\n', '1 1\n']
Note:
none | ```python
n, k = map(int, input().split())
a = list(map(int, input().split()))
l, r = 0, k
ll, rr = 0, 0
ans = a[l:r]
while r < n:
if a[r] in ans or len(set(ans)) < k :
r += 1
else:
if (rr - ll) < ((r - l)):
ll, rr = l, r
l += 1
ans = a[l:r]
if (rr - ll) < ((r - l)):
ll, rr = l, r
print(ll + 1, rr)
``` | 0 | |
181 | A | Series of Crimes | PROGRAMMING | 800 | [
"brute force",
"geometry",
"implementation"
] | null | null | The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.
The Berland capital's map is represented by an *n*<=×<=*m* rectangular table. Each cell of the table on the map represents some districts of the capital.
The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map.
Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed. | The first line contains two space-separated integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=100) — the number of rows and columns in the table, correspondingly.
Each of the next *n* lines contains *m* characters — the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".".
It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements. | Print two integers — the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right. | [
"3 2\n.*\n..\n**\n",
"3 3\n*.*\n*..\n...\n"
] | [
"1 1\n",
"2 3\n"
] | none | 500 | [
{
"input": "3 2\n.*\n..\n**",
"output": "1 1"
},
{
"input": "2 5\n*....\n*...*",
"output": "1 5"
},
{
"input": "7 2\n..\n**\n..\n..\n..\n..\n.*",
"output": "7 1"
},
{
"input": "7 2\n*.\n..\n..\n..\n..\n..\n**",
"output": "1 2"
},
{
"input": "2 10\n*......*..\n....... | 1,620,291,270 | 2,147,483,647 | PyPy 3 | OK | TESTS | 36 | 218 | 21,811,200 | N, M = [int(X) for X in input().split()]
A = []
for i in range (N):
B = input()
A.append([i for i in B])
pts = []
for i in range (N):
for j in range (M):
if A[i][j] == '*':
pts.append((i,j))
# print (pts)
X = []
Y = []
for i in pts:
X.append(i[0])
Y.append(i[1])
# print (X)
# print (Y)
x = None
y = None
for i in X:
if X.count(i) == 1:
x = i
break
for i in Y:
if Y.count(i) == 1:
y = i
break
print (x+1,y+1) | Title: Series of Crimes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.
The Berland capital's map is represented by an *n*<=×<=*m* rectangular table. Each cell of the table on the map represents some districts of the capital.
The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map.
Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.
Input Specification:
The first line contains two space-separated integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=100) — the number of rows and columns in the table, correspondingly.
Each of the next *n* lines contains *m* characters — the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".".
It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements.
Output Specification:
Print two integers — the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right.
Demo Input:
['3 2\n.*\n..\n**\n', '3 3\n*.*\n*..\n...\n']
Demo Output:
['1 1\n', '2 3\n']
Note:
none | ```python
N, M = [int(X) for X in input().split()]
A = []
for i in range (N):
B = input()
A.append([i for i in B])
pts = []
for i in range (N):
for j in range (M):
if A[i][j] == '*':
pts.append((i,j))
# print (pts)
X = []
Y = []
for i in pts:
X.append(i[0])
Y.append(i[1])
# print (X)
# print (Y)
x = None
y = None
for i in X:
if X.count(i) == 1:
x = i
break
for i in Y:
if Y.count(i) == 1:
y = i
break
print (x+1,y+1)
``` | 3 | |
291 | A | Spyke Talks | PROGRAMMING | 800 | [
"*special",
"implementation",
"sortings"
] | null | null | Polycarpus is the director of a large corporation. There are *n* secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people. | The first line contains integer *n* (1<=≤<=*n*<=≤<=103) — the number of secretaries in Polycarpus's corporation. The next line contains *n* space-separated integers: *id*1,<=*id*2,<=...,<=*id**n* (0<=≤<=*id**i*<=≤<=109). Number *id**i* equals the number of the call session of the *i*-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to *n* in some way. | Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place. | [
"6\n0 1 7 1 7 10\n",
"3\n1 1 1\n",
"1\n0\n"
] | [
"2\n",
"-1\n",
"0\n"
] | In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed. | 500 | [
{
"input": "6\n0 1 7 1 7 10",
"output": "2"
},
{
"input": "3\n1 1 1",
"output": "-1"
},
{
"input": "1\n0",
"output": "0"
},
{
"input": "5\n2 2 1 1 3",
"output": "2"
},
{
"input": "1\n1",
"output": "0"
},
{
"input": "10\n4 21 3 21 21 1 1 2 2 3",
"ou... | 1,536,576,661 | 2,147,483,647 | Python 3 | OK | TESTS | 38 | 498 | 0 | def cocktail_sort(a):
n = len(a)
swapped = True
start = 0
end = n-1
while (swapped == True):
# reset the swapped flag on entering the loop,
# because it might be true from a previous
# iteration.
swapped = False
# loop from left to right same as the bubble
# sort
for i in range (start, end):
if (a[i] > a[i + 1]) :
a[i], a[i + 1]= a[i + 1], a[i]
swapped = True
# if nothing moved, then array is sorted.
if (swapped == False):
break
# otherwise, reset the swapped flag so that it
# can be used in the next stage
swapped = False
# move the end point back by one, because
# item at the end is in its rightful spot
end = end-1
# from right to left, doing the same
# comparison as in the previous stage
for i in range(end-1, start-1, -1):
if (a[i] > a[i + 1]):
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
# increase the starting point, because
# the last stage would have moved the next
# smallest number to its rightful spot.
start = start + 1
n = int(input())
x = list(map(int, input().split()))
answer = 0
cocktail_sort(x)
for i in range(len(x)-1):
if (i+2)>= n:
if (x[i] == x[i+1]) and (x[i] != 0):
answer = answer + 1
i = i+1
else:
if x[i] == x[i+1] and x[i] != 0 and x[i] !=x[i+2]:
answer = answer + 1
i = i + 1
elif x[i] == x[i+1] and x[i] == x[i+2] and x[i]!= 0:
answer = -1
break
print(answer)
| Title: Spyke Talks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarpus is the director of a large corporation. There are *n* secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=103) — the number of secretaries in Polycarpus's corporation. The next line contains *n* space-separated integers: *id*1,<=*id*2,<=...,<=*id**n* (0<=≤<=*id**i*<=≤<=109). Number *id**i* equals the number of the call session of the *i*-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to *n* in some way.
Output Specification:
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Demo Input:
['6\n0 1 7 1 7 10\n', '3\n1 1 1\n', '1\n0\n']
Demo Output:
['2\n', '-1\n', '0\n']
Note:
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed. | ```python
def cocktail_sort(a):
n = len(a)
swapped = True
start = 0
end = n-1
while (swapped == True):
# reset the swapped flag on entering the loop,
# because it might be true from a previous
# iteration.
swapped = False
# loop from left to right same as the bubble
# sort
for i in range (start, end):
if (a[i] > a[i + 1]) :
a[i], a[i + 1]= a[i + 1], a[i]
swapped = True
# if nothing moved, then array is sorted.
if (swapped == False):
break
# otherwise, reset the swapped flag so that it
# can be used in the next stage
swapped = False
# move the end point back by one, because
# item at the end is in its rightful spot
end = end-1
# from right to left, doing the same
# comparison as in the previous stage
for i in range(end-1, start-1, -1):
if (a[i] > a[i + 1]):
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
# increase the starting point, because
# the last stage would have moved the next
# smallest number to its rightful spot.
start = start + 1
n = int(input())
x = list(map(int, input().split()))
answer = 0
cocktail_sort(x)
for i in range(len(x)-1):
if (i+2)>= n:
if (x[i] == x[i+1]) and (x[i] != 0):
answer = answer + 1
i = i+1
else:
if x[i] == x[i+1] and x[i] != 0 and x[i] !=x[i+2]:
answer = answer + 1
i = i + 1
elif x[i] == x[i+1] and x[i] == x[i+2] and x[i]!= 0:
answer = -1
break
print(answer)
``` | 3 | |
370 | A | Rook, Bishop and King | PROGRAMMING | 1,100 | [
"graphs",
"math",
"shortest paths"
] | null | null | Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8<=×<=8 table. A field is represented by a pair of integers (*r*,<=*c*) — the number of the row and the number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules:
- A rook moves any number of fields horizontally or vertically. - A bishop moves any number of fields diagonally. - A king moves one field in any direction — horizontally, vertically or diagonally.
Petya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field (*r*1,<=*c*1) to field (*r*2,<=*c*2)? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem. | The input contains four integers *r*1,<=*c*1,<=*r*2,<=*c*2 (1<=≤<=*r*1,<=*c*1,<=*r*2,<=*c*2<=≤<=8) — the coordinates of the starting and the final field. The starting field doesn't coincide with the final one.
You can assume that the chessboard rows are numbered from top to bottom 1 through 8, and the columns are numbered from left to right 1 through 8. | Print three space-separated integers: the minimum number of moves the rook, the bishop and the king (in this order) is needed to move from field (*r*1,<=*c*1) to field (*r*2,<=*c*2). If a piece cannot make such a move, print a 0 instead of the corresponding number. | [
"4 3 1 6\n",
"5 5 5 6\n"
] | [
"2 1 3\n",
"1 0 1\n"
] | none | 500 | [
{
"input": "4 3 1 6",
"output": "2 1 3"
},
{
"input": "5 5 5 6",
"output": "1 0 1"
},
{
"input": "1 1 8 8",
"output": "2 1 7"
},
{
"input": "1 1 8 1",
"output": "1 0 7"
},
{
"input": "1 1 1 8",
"output": "1 0 7"
},
{
"input": "8 1 1 1",
"output": "... | 1,389,971,516 | 2,147,483,647 | Python 3 | OK | TESTS | 42 | 77 | 409,600 | def stessocolore(x1,y1,x2,y2):
if (x1+y1)%2 == (x2+y2)%2:
return True
else:
return False
x1, y1, x2, y2 = map(int, input().split())
if x1 == x2 or y1 == y2:
rook = 1
else:
rook = 2
king = max([abs(x1-x2),abs(y1-y2)])
if stessocolore(x1,y1,x2,y2):
if (x1-y1) == (x2-y2) or x1+y1 == x2+y2:
bish = 1
else:
bish = 2
else:
bish = 0
print(rook, bish, king) | Title: Rook, Bishop and King
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8<=×<=8 table. A field is represented by a pair of integers (*r*,<=*c*) — the number of the row and the number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules:
- A rook moves any number of fields horizontally or vertically. - A bishop moves any number of fields diagonally. - A king moves one field in any direction — horizontally, vertically or diagonally.
Petya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field (*r*1,<=*c*1) to field (*r*2,<=*c*2)? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem.
Input Specification:
The input contains four integers *r*1,<=*c*1,<=*r*2,<=*c*2 (1<=≤<=*r*1,<=*c*1,<=*r*2,<=*c*2<=≤<=8) — the coordinates of the starting and the final field. The starting field doesn't coincide with the final one.
You can assume that the chessboard rows are numbered from top to bottom 1 through 8, and the columns are numbered from left to right 1 through 8.
Output Specification:
Print three space-separated integers: the minimum number of moves the rook, the bishop and the king (in this order) is needed to move from field (*r*1,<=*c*1) to field (*r*2,<=*c*2). If a piece cannot make such a move, print a 0 instead of the corresponding number.
Demo Input:
['4 3 1 6\n', '5 5 5 6\n']
Demo Output:
['2 1 3\n', '1 0 1\n']
Note:
none | ```python
def stessocolore(x1,y1,x2,y2):
if (x1+y1)%2 == (x2+y2)%2:
return True
else:
return False
x1, y1, x2, y2 = map(int, input().split())
if x1 == x2 or y1 == y2:
rook = 1
else:
rook = 2
king = max([abs(x1-x2),abs(y1-y2)])
if stessocolore(x1,y1,x2,y2):
if (x1-y1) == (x2-y2) or x1+y1 == x2+y2:
bish = 1
else:
bish = 2
else:
bish = 0
print(rook, bish, king)
``` | 3 | |
767 | C | Garland | PROGRAMMING | 2,000 | [
"dfs and similar",
"graphs",
"greedy",
"trees"
] | null | null | Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps.
There was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp.
Help Dima to find a suitable way to cut the garland, or determine that this is impossible.
While examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer. | The first line contains single integer *n* (3<=≤<=*n*<=≤<=106) — the number of lamps in the garland.
Then *n* lines follow. The *i*-th of them contain the information about the *i*-th lamp: the number lamp *a**i*, it is hanging on (and 0, if is there is no such lamp), and its temperature *t**i* (<=-<=100<=≤<=*t**i*<=≤<=100). The lamps are numbered from 1 to *n*. | If there is no solution, print -1.
Otherwise print two integers — the indexes of the lamps which mean Dima should cut the wires they are hanging on. If there are multiple answers, print any of them. | [
"6\n2 4\n0 5\n4 2\n2 1\n1 1\n4 2\n",
"6\n2 4\n0 6\n4 2\n2 1\n1 1\n4 2\n"
] | [
"1 4\n",
"-1\n"
] | The garland and cuts scheme for the first example: | 1,500 | [
{
"input": "6\n2 4\n0 5\n4 2\n2 1\n1 1\n4 2",
"output": "1 4"
},
{
"input": "6\n2 4\n0 6\n4 2\n2 1\n1 1\n4 2",
"output": "-1"
},
{
"input": "6\n2 4\n0 -1\n4 2\n2 3\n1 2\n4 5",
"output": "6 4"
},
{
"input": "3\n2 1\n0 1\n2 1",
"output": "1 3"
},
{
"input": "5\n0 5\... | 1,625,117,065 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 2 | 93 | 0 | import sys
input = sys.stdin.readline
n = int(input())
G = [[] for _ in range(n+1)]
T = [-1]*n
root = -1
for i in range(n):
a,t = map(int,input().split())
if a != 0:
G[a-1].append(i)
else:
root = i
T[i] = t
A = [0]*n
stk = [root]
vis = [False]*n
while stk:
x = stk[-1]
if not vis[x]:
vis[x] = True
for y in G[x]:
if not vis[y]:
stk.append(y)
else:
stk.pop()
for y in G[x]:
A[x] += A[y]
A[x] += T[x]
s = A[root]
if s%3:
print(-1)
exit()
target = s//3
B = [False]*n
stk = [root]
while stk:
x = stk[-1]
if vis[x]:
vis[x] = False
for y in G[x]:
if vis[y]:
stk.append(y)
else:
stk.pop()
tmp = []
for y in G[x]:
if B[y]: tmp.append(y)
if len(tmp) >= 2:
print(tmp.pop()+1 ,tmp.pop()+1)
exit()
if tmp and A[x] == 2*target:
print(x+1,tmp.pop())
exit()
B[x] = (len(tmp) > 0) or A[x] == target
print(-1)
exit()
| Title: Garland
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps.
There was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp.
Help Dima to find a suitable way to cut the garland, or determine that this is impossible.
While examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer.
Input Specification:
The first line contains single integer *n* (3<=≤<=*n*<=≤<=106) — the number of lamps in the garland.
Then *n* lines follow. The *i*-th of them contain the information about the *i*-th lamp: the number lamp *a**i*, it is hanging on (and 0, if is there is no such lamp), and its temperature *t**i* (<=-<=100<=≤<=*t**i*<=≤<=100). The lamps are numbered from 1 to *n*.
Output Specification:
If there is no solution, print -1.
Otherwise print two integers — the indexes of the lamps which mean Dima should cut the wires they are hanging on. If there are multiple answers, print any of them.
Demo Input:
['6\n2 4\n0 5\n4 2\n2 1\n1 1\n4 2\n', '6\n2 4\n0 6\n4 2\n2 1\n1 1\n4 2\n']
Demo Output:
['1 4\n', '-1\n']
Note:
The garland and cuts scheme for the first example: | ```python
import sys
input = sys.stdin.readline
n = int(input())
G = [[] for _ in range(n+1)]
T = [-1]*n
root = -1
for i in range(n):
a,t = map(int,input().split())
if a != 0:
G[a-1].append(i)
else:
root = i
T[i] = t
A = [0]*n
stk = [root]
vis = [False]*n
while stk:
x = stk[-1]
if not vis[x]:
vis[x] = True
for y in G[x]:
if not vis[y]:
stk.append(y)
else:
stk.pop()
for y in G[x]:
A[x] += A[y]
A[x] += T[x]
s = A[root]
if s%3:
print(-1)
exit()
target = s//3
B = [False]*n
stk = [root]
while stk:
x = stk[-1]
if vis[x]:
vis[x] = False
for y in G[x]:
if vis[y]:
stk.append(y)
else:
stk.pop()
tmp = []
for y in G[x]:
if B[y]: tmp.append(y)
if len(tmp) >= 2:
print(tmp.pop()+1 ,tmp.pop()+1)
exit()
if tmp and A[x] == 2*target:
print(x+1,tmp.pop())
exit()
B[x] = (len(tmp) > 0) or A[x] == target
print(-1)
exit()
``` | 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,683,437,425 | 2,147,483,647 | Python 3 | OK | TESTS | 20 | 46 | 0 | s = input().split()
n = int(s[0])
m = int(s[1])
a = int(s[2])
vert = 0
hor = 0
if n % a == 0:
vert = n // a
else:
vert = n // a + 1
if m % a == 0:
hor = m // a
else:
hor = m // a + 1
print(vert*hor) | 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
s = input().split()
n = int(s[0])
m = int(s[1])
a = int(s[2])
vert = 0
hor = 0
if n % a == 0:
vert = n // a
else:
vert = n // a + 1
if m % a == 0:
hor = m // a
else:
hor = m // a + 1
print(vert*hor)
``` | 3.977 |
471 | A | MUH and Sticks | PROGRAMMING | 1,100 | [
"implementation"
] | null | null | Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
- Four sticks represent the animal's legs, these sticks should have the same length. - Two remaining sticks represent the animal's head and body. The bear's head stick must be shorter than the body stick. The elephant, however, has a long trunk, so his head stick must be as long as the body stick. Note that there are no limits on the relations between the leg sticks and the head and body sticks.
Your task is to find out which animal can be made from the given stick set. The zoo keeper wants the sticks back after the game, so they must never be broken, even bears understand it. | The single line contains six space-separated integers *l**i* (1<=≤<=*l**i*<=≤<=9) — the lengths of the six sticks. It is guaranteed that the input is such that you cannot make both animals from the sticks. | If you can make a bear from the given set, print string "Bear" (without the quotes). If you can make an elephant, print string "Elephant" (wıthout the quotes). If you can make neither a bear nor an elephant, print string "Alien" (without the quotes). | [
"4 2 5 4 4 4\n",
"4 4 5 4 4 5\n",
"1 2 3 4 5 6\n"
] | [
"Bear",
"Elephant",
"Alien"
] | If you're out of creative ideas, see instructions below which show how to make a bear and an elephant in the first two samples. The stick of length 2 is in red, the sticks of length 4 are in green, the sticks of length 5 are in blue. | 500 | [
{
"input": "4 2 5 4 4 4",
"output": "Bear"
},
{
"input": "4 4 5 4 4 5",
"output": "Elephant"
},
{
"input": "1 2 3 4 5 6",
"output": "Alien"
},
{
"input": "5 5 5 5 5 5",
"output": "Elephant"
},
{
"input": "1 1 1 2 3 5",
"output": "Alien"
},
{
"input": "... | 1,571,184,339 | 2,147,483,647 | PyPy 3 | WRONG_ANSWER | TESTS | 0 | 109 | 0 | size_sticks = input().replace(' ','')
stick_rep = [size_sticks.count(i) > 3 for i in size_sticks]
try:
get_leg = stick_rep.index(True)
stick_remain = size_sticks.replace(size_sticks[get_leg],'')
print(['Elephant' if len(stick_remain) == 0 or (stick_remain[0] == stick_remain[1]) else 'Bear'])
except ValueError:
print('Alien') | Title: MUH and Sticks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
- Four sticks represent the animal's legs, these sticks should have the same length. - Two remaining sticks represent the animal's head and body. The bear's head stick must be shorter than the body stick. The elephant, however, has a long trunk, so his head stick must be as long as the body stick. Note that there are no limits on the relations between the leg sticks and the head and body sticks.
Your task is to find out which animal can be made from the given stick set. The zoo keeper wants the sticks back after the game, so they must never be broken, even bears understand it.
Input Specification:
The single line contains six space-separated integers *l**i* (1<=≤<=*l**i*<=≤<=9) — the lengths of the six sticks. It is guaranteed that the input is such that you cannot make both animals from the sticks.
Output Specification:
If you can make a bear from the given set, print string "Bear" (without the quotes). If you can make an elephant, print string "Elephant" (wıthout the quotes). If you can make neither a bear nor an elephant, print string "Alien" (without the quotes).
Demo Input:
['4 2 5 4 4 4\n', '4 4 5 4 4 5\n', '1 2 3 4 5 6\n']
Demo Output:
['Bear', 'Elephant', 'Alien']
Note:
If you're out of creative ideas, see instructions below which show how to make a bear and an elephant in the first two samples. The stick of length 2 is in red, the sticks of length 4 are in green, the sticks of length 5 are in blue. | ```python
size_sticks = input().replace(' ','')
stick_rep = [size_sticks.count(i) > 3 for i in size_sticks]
try:
get_leg = stick_rep.index(True)
stick_remain = size_sticks.replace(size_sticks[get_leg],'')
print(['Elephant' if len(stick_remain) == 0 or (stick_remain[0] == stick_remain[1]) else 'Bear'])
except ValueError:
print('Alien')
``` | 0 | |
237 | A | Free Cash | PROGRAMMING | 1,000 | [
"implementation"
] | null | null | Valera runs a 24/7 fast food cafe. He magically learned that next day *n* people will visit his cafe. For each person we know the arrival time: the *i*-th person comes exactly at *h**i* hours *m**i* minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.
Valera is very greedy, so he wants to serve all *n* customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe.
Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors. | The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105), that is the number of cafe visitors.
Each of the following *n* lines has two space-separated integers *h**i* and *m**i* (0<=≤<=*h**i*<=≤<=23; 0<=≤<=*m**i*<=≤<=59), representing the time when the *i*-th person comes into the cafe.
Note that the time is given in the chronological order. All time is given within one 24-hour period. | Print a single integer — the minimum number of cashes, needed to serve all clients next day. | [
"4\n8 0\n8 10\n8 10\n8 45\n",
"3\n0 12\n10 11\n22 22\n"
] | [
"2\n",
"1\n"
] | In the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.
In the second sample all visitors will come in different times, so it will be enough one cash. | 500 | [
{
"input": "4\n8 0\n8 10\n8 10\n8 45",
"output": "2"
},
{
"input": "3\n0 12\n10 11\n22 22",
"output": "1"
},
{
"input": "5\n12 8\n15 27\n15 27\n16 2\n19 52",
"output": "2"
},
{
"input": "7\n5 6\n7 34\n7 34\n7 34\n12 29\n15 19\n20 23",
"output": "3"
},
{
"input": "... | 1,669,215,183 | 2,147,483,647 | Python 3 | WRONG_ANSWER | TESTS | 6 | 92 | 0 | # B. Напитки
#
# n = int(input())
# s = input().split()
# s = [int(x) for x in s]
# r = sum(s) / n
# print(r)
# A. Выбор команд
# n, k = map(int, input().split())
# s = input().split()
# s = [int(x) for x in s]
# b = []
# for i in s:
# if i + k <= 5:
# b.append(i)
# print(len(b) // 3)
# decompress-run-length-encoded-list/
# s = input().split()
# s = [int(x) for x in s]
# b = []
# for i in range(0, len(s), 2):
# for j in range(s[i]):
# b.append(s[i + 1])
# print(b)
# A. Быстрый математик
# a = input()
# b = input()
# c = ''
# for i in range(len(a)):
# c += str(int(a[i]) + int(b[i]))
# print(c.replace('2', '0'))
# A. Ваня и забор
# n, h = map(int, input().split())
# s = input().split()
# s = [int(x) for x in s]
# count = 0
# for i in s:
# if i > h:
# count += 2
# else:
# count += 1
# print(count)
# A. Башни
# n = int(input())
# s = input().split()
# s = [int(x) for x in s]
# b = []
# c = []
# for i in range(n):
# if s[i] not in b:
# b.append(s[i]) # towers count
# else:
# c.append(s.count(s[i]))
# if len(c) == 0:
# print(1, len(b))
# else:
# print(max(c), len(b))
# A. Антон и Даник
# n = int(input())
# s = input()
# dan = 0
# ant = 0
# for i in s:
# if i == 'D':
# dan += 1
# else:
# ant += 1
# if ant > dan:
# print('Anton')
# elif ant < dan:
# print('Danik')
# else:
# print('Friendship')
n = int(input())
x = ''
c = 1
for i in range(n):
s = input()
if s == x:
c += 1
x = s
print(c)
| Title: Free Cash
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Valera runs a 24/7 fast food cafe. He magically learned that next day *n* people will visit his cafe. For each person we know the arrival time: the *i*-th person comes exactly at *h**i* hours *m**i* minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.
Valera is very greedy, so he wants to serve all *n* customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe.
Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105), that is the number of cafe visitors.
Each of the following *n* lines has two space-separated integers *h**i* and *m**i* (0<=≤<=*h**i*<=≤<=23; 0<=≤<=*m**i*<=≤<=59), representing the time when the *i*-th person comes into the cafe.
Note that the time is given in the chronological order. All time is given within one 24-hour period.
Output Specification:
Print a single integer — the minimum number of cashes, needed to serve all clients next day.
Demo Input:
['4\n8 0\n8 10\n8 10\n8 45\n', '3\n0 12\n10 11\n22 22\n']
Demo Output:
['2\n', '1\n']
Note:
In the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.
In the second sample all visitors will come in different times, so it will be enough one cash. | ```python
# B. Напитки
#
# n = int(input())
# s = input().split()
# s = [int(x) for x in s]
# r = sum(s) / n
# print(r)
# A. Выбор команд
# n, k = map(int, input().split())
# s = input().split()
# s = [int(x) for x in s]
# b = []
# for i in s:
# if i + k <= 5:
# b.append(i)
# print(len(b) // 3)
# decompress-run-length-encoded-list/
# s = input().split()
# s = [int(x) for x in s]
# b = []
# for i in range(0, len(s), 2):
# for j in range(s[i]):
# b.append(s[i + 1])
# print(b)
# A. Быстрый математик
# a = input()
# b = input()
# c = ''
# for i in range(len(a)):
# c += str(int(a[i]) + int(b[i]))
# print(c.replace('2', '0'))
# A. Ваня и забор
# n, h = map(int, input().split())
# s = input().split()
# s = [int(x) for x in s]
# count = 0
# for i in s:
# if i > h:
# count += 2
# else:
# count += 1
# print(count)
# A. Башни
# n = int(input())
# s = input().split()
# s = [int(x) for x in s]
# b = []
# c = []
# for i in range(n):
# if s[i] not in b:
# b.append(s[i]) # towers count
# else:
# c.append(s.count(s[i]))
# if len(c) == 0:
# print(1, len(b))
# else:
# print(max(c), len(b))
# A. Антон и Даник
# n = int(input())
# s = input()
# dan = 0
# ant = 0
# for i in s:
# if i == 'D':
# dan += 1
# else:
# ant += 1
# if ant > dan:
# print('Anton')
# elif ant < dan:
# print('Danik')
# else:
# print('Friendship')
n = int(input())
x = ''
c = 1
for i in range(n):
s = input()
if s == x:
c += 1
x = s
print(c)
``` | 0 | |
69 | A | Young Physicist | PROGRAMMING | 1,000 | [
"implementation",
"math"
] | A. Young Physicist | 2 | 256 | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. | The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100), then follow *n* lines containing three integers each: the *x**i* coordinate, the *y**i* coordinate and the *z**i* coordinate of the force vector, applied to the body (<=-<=100<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=100). | Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. | [
"3\n4 1 7\n-2 4 -1\n1 -5 -3\n",
"3\n3 -1 7\n-5 2 -4\n2 -1 -3\n"
] | [
"NO",
"YES"
] | none | 500 | [
{
"input": "3\n4 1 7\n-2 4 -1\n1 -5 -3",
"output": "NO"
},
{
"input": "3\n3 -1 7\n-5 2 -4\n2 -1 -3",
"output": "YES"
},
{
"input": "10\n21 32 -46\n43 -35 21\n42 2 -50\n22 40 20\n-27 -9 38\n-4 1 1\n-40 6 -31\n-13 -2 34\n-21 34 -12\n-32 -29 41",
"output": "NO"
},
{
"input": "10... | 1,594,020,034 | 2,147,483,647 | Python 3 | OK | TESTS | 81 | 218 | 6,758,400 | n=int(input())
a_1=[]
b_1=[]
c_1=[]
for i in range(n):
a,b,c=map(int,input().split())
a_1.append(a)
b_1.append(b)
c_1.append(c)
if sum(a_1)==0 and sum(b_1)==0 and sum(c_1)==0:
print("YES")
else:
print("NO")
| Title: Young Physicist
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
Input Specification:
The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100), then follow *n* lines containing three integers each: the *x**i* coordinate, the *y**i* coordinate and the *z**i* coordinate of the force vector, applied to the body (<=-<=100<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=100).
Output Specification:
Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.
Demo Input:
['3\n4 1 7\n-2 4 -1\n1 -5 -3\n', '3\n3 -1 7\n-5 2 -4\n2 -1 -3\n']
Demo Output:
['NO', 'YES']
Note:
none | ```python
n=int(input())
a_1=[]
b_1=[]
c_1=[]
for i in range(n):
a,b,c=map(int,input().split())
a_1.append(a)
b_1.append(b)
c_1.append(c)
if sum(a_1)==0 and sum(b_1)==0 and sum(c_1)==0:
print("YES")
else:
print("NO")
``` | 3.932911 |
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.