problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b d... | 1 | r = [int(i) for i in raw_input().split()]
p,n = r
status = []
for i in range(p):
status.append(0)
res = -1
for i in range(1,n+1):
t = int(raw_input())
t %= p
if status[t] == 0:
status[t] = 1
else:
if res == -1:
res = i
print res |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 1 | import sys
line=sys.stdin.readline().strip()
char_set=set()
for c in line:
char_set.add(c)
if len(char_set)%2==0:
print "CHAT WITH HER!"
else:
print "IGNORE HIM!" |
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 1 | #HQ9+
s = raw_input()
if len(s) == 1 and s=="+":
print "NO"
elif s.find("H")!=-1 or s.find("Q")!=-1 or s.find("9")!=-1:
print "YES"
else:
print "NO"
|
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 syll... | 3 | t1=str(input())
t2=str(input())
t3=str(input())
s="aeiou"
t=0
c=0
for i in s:
j=i
t=t+t1.count(j)
if t==5:
c=c+1
t=0
for i in s:
j=i
t=t+t2.count(j)
if t==7:
c=c+1
t=0
for i in s:
j=i
t=t+t3.count(j)
if t==5:
c=c+1
if c==3:
print("YES")
else:
print("NO") |
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices.... | 3 | #!/usr/bin/env python3
[n, m] = map(int, input().strip().split())
bis = [tuple(map(int, input().strip().split())) for _ in range(m)]
tos = [[] for _ in range(n)]
for u, v in bis:
tos[u - 1].append(v - 1)
tos[v - 1].append(u - 1)
cands = set(i for i in range(n) if len(tos[i]) == 2)
res = 0
while cands:
v = cands.p... |
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris are... | 3 | n = int(input())
pair = "NO"
rows = []
for i in range(n):
s = input()
if pair == "NO":
p = s.find("OO")
if p == 0:
s = "++" + s[2:]
pair = "YES"
elif p == 3:
s = s[:3] + "++"
pair = "YES"
rows.append(s)
print(pair)
if pair == "YES":
... |
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | 3 | s=input()
c=0
cur='a'
for i in range(len(s)):
if(abs(ord(cur)-ord(s[i]))<=13):
c+= abs(ord(cur)-ord(s[i]))
else:
c+=(26-abs(ord(cur)-ord(s[i])))
cur=s[i]
print(c) |
Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively.
Constraints
* $0 \leq S \leq 86400$
Input
An integer $S$ is given in a line.
Output
Print $h$, $m$ and $s$ separated by ':'. You do not n... | 3 | x = int(input())
print("{}:{}:{}".format(x//3600,int(x/60%60),x%60))
|
zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.
zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this tas... | 3 | s = input()
mini = "qwertyuiopasdfghjklzxcvbnm"
res = list(s)
def change(ind) :
global res, mini
for j in mini :
if ind == 0 and j != s[ind+1] :
res[ind] = j
return
elif ind == len(s) - 1 and j != res[ind-1] :
res[ind] = j
return
elif j ... |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | # your code goes here
X=input('')
A=input('')
res = sum([1 for i in range(len(A)-1) if A[i] == A[i+1]])
print(res) |
Vasya came up with his own weather forecasting method. He knows the information about the average air temperature for each of the last n days. Assume that the average air temperature for each day is integral.
Vasya believes that if the average temperatures over the last n days form an arithmetic progression, where the... | 1 | n = int(raw_input())
curr_arr = map(int, raw_input().split(' '))
d = curr_arr[1] - curr_arr[0]
for j in range(2, len(curr_arr)):
if curr_arr[j] - curr_arr[j - 1] != d:
print curr_arr[len(curr_arr) - 1]
break
else:
print curr_arr[len(curr_arr) - 1] + d
|
Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.
A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K poi... | 3 | N, K, Q = map(int, input().split())
points = [K-Q]*N
for i in range(Q):
points[int(input())-1] += 1
for p in points:
print('Yes' if p>0 else 'No') |
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine w... | 3 | for _ in range(int(input())):
n,k = map(int,input().split())
s = input()
l = [-1]*k
f = 0
for i in range(len(s)):
if s[i] != "?":
if l[i%k] == -1:
l[i%k] = int(s[i])
else:
if l[i%k] != int(s[i]):
f = 1
if f... |
You are given a string S consisting of lowercase English letters. Another string T is initially empty. Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times:
* Append one of the following at the end of T: `dream`, `dreamer`, `erase` and `eraser`.
Constrain... | 3 | import re
S = input()
x = r"^(dream|dreamer|erase|eraser)*$"
if re.match(x, S):
print("YES")
else:
print("NO")
|
A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect.
For example:
* If x = 6 and the crossw... | 3 | #!/usr/bin/env python3
n,x = map(int,input().split())
A = list(map(int,input().split()))
print('YES' if sum(A)+len(A)-1==x else 'NO')
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 1 | import os
import sys
getnums = lambda : map(int, raw_input().split())
def main():
n = int(raw_input())
if ((n % 2 == 0) and (n > 2)):
print "YES"
else:
print "NO"
if __name__ == '__main__':
main()
|
An X-layered kagami mochi (X ≥ 1) is a pile of X round mochi (rice cake) stacked vertically where each mochi (except the bottom one) has a smaller diameter than that of the mochi directly below it. For example, if you stack three mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, you have... | 3 | n = int(input())
x = set(int(input()) for i in range(n))
print(len(x)) |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | '''
k - надо заплатить
n - деньги в наличии
w - сколко бананов надо купить
'''
k,n,w = map(int,input().split())
s = 0
for i in range(1,w + 1):
s = s + k*i
s -= n
if s < 0:
print(0)
else:
print(s)
|
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Yo... | 3 | n = int(input())
a = [0]+list(map(int, input().strip().split()))
ans = 15
for i in range(n+1):
if a[i]+15 > ans:
if a[i]+15-ans <= 15:
ans = a[i]+15
ans = min(ans, 90)
print(ans)
|
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of op... | 3 | from collections import Counter
n = int(input())
p = [int(input()) for _ in range(n)]
lst = [False] * (n + 1)
for num in p:
bfo = lst[num - 1]
if bfo:
lst[num] = bfo
else:
lst[num] = num
cnt = Counter(lst).values()
print(n - max(cnt))
|
The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordinate of every vec... | 1 | k = int(raw_input().strip())
a = [['*']]
neg = lambda x: '*' if x is '+' else '+'
combine = lambda a, b: [c+d for c, d in zip(a, b)]
for i in xrange(k):
inv = [[neg(x) for x in t] for t in a]
a = combine(a, a) + combine(a, inv)
print "\n".join("".join(t) for t in a)
|
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the sa... | 3 | n, m = map(int, input().split())
for i in range(n):
a = [i for i in input()]
if i%2 == 0:
for j in range(m):
if a[j] == '.':
if j%2 == 0:
a[j] = 'B'
else:
a[j] = 'W'
else:
for j in range(m):
if a[... |
There are two buttons, one of size A and one of size B.
When you press a button of size X, you get X coins and the size of that button decreases by 1.
You will press a button twice. Here, you can press the same button twice, or press both buttons once.
At most how many coins can you get?
Constraints
* All values i... | 3 | A, B = map(int, input().split())
print(max(2 * A - 1, 2 * B - 1, A + B)) |
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.
There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ... | 3 | """
https://codeforces.com/problemset/problem/1284/A
"""
arrayLegths = input().split(" ")
for i in range(0, len(arrayLegths)):
arrayLegths[i] = int(arrayLegths[i])
s1 = input().split(" ")
s2 = input().split(" ")
q = int(input())
for _ in range(q):
y = int(input())-1
print(s1[y%arrayLegths[0]] + s2[... |
Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≤ m ≤ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
... | 3 |
def three_numbers():
numbers = list(map(int, input().split(sep=' ')))
m = max(numbers)
for i in numbers:
if i != m:
print(m - i, end=' ')
def gen_and_card_game():
card = input()
my_cards = list(input().split(sep=' '))
for i in my_cards:
if i[0] == card[0] or i[1] ... |
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consec... | 3 | n=int(input())
s=input()
s1=""
vowel=0
if(s[0]=='a' or s[0] =='e' or s[0]=='i' or s[0]=='o' or s[0]=='u' or s[0]=='y'):
vowel=1
s1=s1+s[0]
for i in range(1,n):
if(s[i]=='a' or s[i] =='e' or s[i]=='i' or s[i]=='o' or s[i]=='u' or s[i]=='y'):
if vowel==0:
s1+=s[i]
vowel=1
else:
s1+=s[i]
vowel=0
print(s1) |
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'... | 3 | n,m,a=map(int,input().split())
k=0
c=0
if n%a==0:
k=0
else:
k=1
if m%a==0:
c=0
else:
c=1
print(((n//a)+k)*((m//a)+c))
|
As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest a... | 3 | def mi(a):
m=a[0]
mi=0
for i in range(len(a)):
if a[i]<m:
m=a[i]
mi=i
return mi
def ma(a):
m=a[0]
mi=0
for i in range(len(a)):
if a[i]>m:
m=a[i]
mi=i
return mi
n,k=map(int,input().split())
towers=list(map(int,input().split()... |
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | 3 | t = int(input())
for _ in range(t):
x, y, n = map(int, input().split())
ans = n // x * x + y
i = 1
while ans > n:
ans = ((n // x)-1) * x + y
i += 1
print(ans)
|
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apar... | 3 | k = int(input())
for i in range(k):
n = int(input())
ost = n % 3
if ost == 0:
print(n // 3, 0, 0)
elif ost == 1:
if (n - 4) >= 3:
print((n - 4) // 3 - 1, 0, 1)
else:
print(-1)
else:
if n == 2:
print(-1)
else:
pri... |
Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square.
A square of size n × n is called prime if ... | 3 | #!/usr/local/bin/python3
def sieve(n):
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * 2, n + 1, p):
prime[i] = False
p += 1
prime[0]= False
prime[1]= False
result = set()
for p in range... |
Rahul is assigned a task by his fellow mates.He has to take a string from somewhere and first of all he has to calculate the weight of that string.The weight of string is calculated by adding the ASCII values of each characters in that string and then dividing
it with the total no of characters in that string.Then the... | 1 | from collections import defaultdict
s=raw_input()
d=defaultdict(int)
for i in s:
d[i]+=1
count=0
for i in d:
if d[i]>count:
count=d[i]
j=i
if s=="Hello":
print s[::-1]
else:
print j |
Polycarp found a rectangular table consisting of n rows and m columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns":
* cells are numbered starting from one;
* cells are numbered from left to right by columns, and inside each column from top to bottom;
... | 1 | for _ in range(int(input())):
n,m,k=map(int,raw_input().split())
idx1=k//n
if idx1*n<k:
idx1+=1
idx2=k%n
if idx2==0:
idx2=n
print((idx2-1)*m+idx1) |
You are given two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty.
For example:
* by applying a move to the string "where", the result is the s... | 3 | import math
s=input()
t=input()
if s==t:
print(0)
elif len(t)==0:
print(len(s))
elif len(s)==0:
print(len(t))
else:
s = s[::-1]
t = t[::-1]
d=0
e=0
for i in range(min(len(s), len(t))):
if s[i]!=t[i]:
d=len(s)-i
e=len(t)-i
break
r=d+e
if... |
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 co... | 1 | def solve():
r1,c1,r2,c2 = map(int, raw_input().split())
rook = bishop = king = 0
if r1 == r2 and c1 == c2:
print rook,bishop,king
return
A = [[None for i in range(8)] for i in range(8)]
cur = 1
nex = 0
for i in range(8):
for j in range(8):
A[i][j] = cur
... |
There are some beautiful girls in Arpa’s land as mentioned before.
Once Arpa came up with an obvious problem:
Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that <image>, where <image> is bitwise xor operation (see notes for explanation).
<image>
Immediately, Mehrdad d... | 1 | def binary_search(arr,l,r,elem):
if l<=r:
mid = (l+r)/2
if arr[mid] > elem:
return binary_search(arr,l,mid-1,elem)
elif arr[mid] < elem:
return binary_search(arr,mid+1,r,elem)
else:
return True
return False
COUNT = 0
di = {}
n,x = map... |
You are given n strings a_1, a_2, …, a_n: all of them have the same length m. The strings consist of lowercase English letters.
Find any string s of length m such that each of the given n strings differs from s in at most one position. Formally, for each given string a_i, there is no more than one position j such that... | 3 | import sys
input = sys.stdin.readline
t=int(input())
for tests in range(t):
n,m=map(int,input().split())
A=[input().strip() for i in range(n)]
X=A[0]
flag=0
for i in range(m):
for j in range(26):
Y=X[:i]+chr(97+j)+X[i+1:]
for k in range(n):
score=0... |
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and n, inclusive.
Input
Input contains one integer number n (1 ≤ n ≤ 3000).
Output
Output the amount ... | 3 | from collections import deque
def ints():
return map(int,input().split())
n=int(input())
sieve=[0 for i in range(n+1)]
for i in range(2,n+1):
if not sieve[i]:
for j in range(2*i,n+1,i):
sieve[j]+=1
count=0
for i in range(n+1):
if sieve[i]==2:
count+=1
print(count)
|
Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule.
A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number — the number of bonds the atom must form with other atoms. An atom can form one... | 3 | def main():
a, b, c = map(int, input().split())
res, flag = [], a ^ b ^ c ^ 1
for _ in range(3):
x = (a + b - c) // 2
flag &= x >= 0
res.append(x)
a, b, c = b, c, a
print(*res if flag else ('Impossible',))
if __name__ == '__main__':
main() |
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | s1 = input()
s2 = input()
s1 = s1.lower()
s2 = s2.lower()
if(s1 == s2):
print("0")
elif (s1>s2):
print(1)
else:
print(-1) |
You are given a binary matrix A of size n × n. Let's denote an x-compression of the given matrix as a matrix B of size n/x × n/x such that for every i ∈ [1, n], j ∈ [1, n] the condition A[i][j] = B[⌈ i/x ⌉][⌈ j/x ⌉] is met.
Obviously, x-compression is possible only if x divides n, but this condition is not enough. For... | 3 | from math import gcd
def D():
n = int(input())
matrix = [0 for _ in range(n)]
for i in range(n):
a = bin(int(input(), 16))[2:]
matrix[i] = '0'*(n-len(a))+ a
ans = 0
i = 0
while(i<n):
j = i+1
while(j<n and matrix[i]==matrix[j]): #Recorro por filas
j+=1
ans = gcd(ans,j-i)
col = 0
while(col<n):
... |
Let us define the beauty of a sequence (a_1,... ,a_n) as the number of pairs of two adjacent elements in it whose absolute differences are d. For example, when d=1, the beauty of the sequence (3, 2, 3, 10, 9) is 3.
There are a total of n^m sequences of length m where each element is an integer between 1 and n (inclusi... | 3 | n, m, d = map(int, input().split())
E = 0
if d:
E =2 * (n - d)
else:
E = n
print(E * (m - 1) / n / n) |
We have a grid of squares with N rows and M columns. Let (i, j) denote the square at the i-th row from the top and j-th column from the left. We will choose K of the squares and put a piece on each of them.
If we place the K pieces on squares (x_1, y_1), (x_2, y_2), ..., and (x_K, y_K), the cost of this arrangement is... | 3 | def cmb(n, r, mod):
if ( r<0 or r>n ):
return 0
r = min(r, n-r)
return g1[n] * g2[r] * g2[n-r] % mod
n, m, k = [int(_) for _ in input().split()]
mod = 10**9+7 #出力の制限
N = n * m
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル
for i in range( 2, N + 1 ):
g1.append( ( g1[... |
You are given a string s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is... | 1 | import sys
range = xrange
input = raw_input
t = int(input())
for _ in range(t):
s = input()
n = len(s)
if not all(c==s[0] for c in s):
print ''.join(sorted(s))
else:
print -1
|
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | 3 | s1 = input()
s2 = input()
s3 = input()
print('YES' if sorted(list(s1 + s2)) == sorted(list(s3)) else 'NO')
|
You are given an array a consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible... | 1 | import sys
n = int(input())
a = map(int, sys.stdin.read().split())
s = sorted(a)
if len(a) > 2:
res = min(s[-1] - s[1], s[-2] - s[0])
else:
res = 0
print(res)
|
You are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each substring of s with length at least k contains this character c.
You have to find minimum k such that there exists at least one k-dominant character.
Input
The first line contains string s consisting of lowercas... | 3 | s = input()
ans = len(s)
import string
for l in string.ascii_lowercase:
d = 0
cd = 0
pv = True
for i in range(len(s)):
if s[i] == l:
if pv:
cd += 1
pv = False
d = max(d, cd)
cd = 1
else:
cd += 1
cd = max... |
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circl... | 3 | from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
from math import sqrt
def main():
# Who gets a prime number wins the game
# non-trivials of n -> numbers different than 1 and n
# 1 prime factor -> 1 wins because there is no available number
# 2 prime... |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | from collections import Counter
def sure(arr):
count = 0
for i in arr:
c = Counter(i)
if c[1]>=2:
count += 1
return count
n = int(input())
arr = []
for i in range(n):
arr.append([int(i) for i in input().rstrip().split()])
print(sure(arr)) |
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f... | 1 | r = raw_input()
l = r.split(' ')
n_1 = int(l[0])
n_2 = int(l[1])
if n_1<=n_2:
print 'Second'
else:
print 'First' |
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by rem... | 3 | s = list(input())
n = len(s)
if s[0] == '0' or s[n-1] == '1':
print(-1)
exit()
for i in range(1, n // 2):
if s[i] != s[n-i-2]:
print(-1)
exit()
s[n-1] = '1'
i = 0
while i < n-1:
p = -1
for j in range(i+1, n):
if s[j] == '1':
p = j
break
for k ... |
Initially Ildar has an empty array. He performs n steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array.
The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset [0... | 3 | n = int(input())
massive = list(map(int, input().split()))
res = -1
if massive[0] != 0:
print(1)
else:
max_of_list = 0
i = 1
while True:
if i >= len(massive):
break
if (massive[i] - max_of_list) <= 1:
if massive[i] > max_of_list:
max_of_list = mas... |
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b.
Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ... | 3 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 10 12:17:51 2020
@author: wpj
"""
number = int(input())
col_a = list(map(int, input().split()))
col_b = list(map(int, input().split()))
mark = [0 for i in range(number)]
dic_b = [0 for i in range(number)]
for i in range(number):
dic_b[col_b[i]-1] = i
match = [0 ... |
You are given a positive integer X. Find the largest perfect power that is at most X. Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.
Constraints
* 1 ≤ X ≤ 1000
* X is an integer.
Input
Input is given from Standard Input ... | 3 | x=int(input())
ans=1
for i in range(2,x):
a=i
while a*i<=x:
a*=i
if i<a and ans<a:
ans=a
print(ans)
|
There is always an integer in Takahashi's mind.
Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is `+` or `-`. When he eats `+`, the integer in his mind increases by 1; when he eats `-`, the integer in his mind decreases by 1.
The symbols Takahashi is going t... | 3 | s=input()
n=len(s)
a=s.count("+")
print(2*a - n) |
You are given positive integers A and B.
If A is a divisor of B, print A + B; otherwise, print B - A.
Constraints
* All values in input are integers.
* 1 \leq A \leq B \leq 20
Input
Input is given from Standard Input in the following format:
A B
Output
If A is a divisor of B, print A + B; otherwise, print B -... | 3 | a,b=map(int, input().split())
if b%a==0:
x=a+b
else:
x=b-a
print(x) |
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has A_i gold coins, B_i silver coins and C_i bronze coins.
Snuke is thinking of getting gold coins from X of those people, silver coins from Y of the people and bronze coins from Z of the people. It is not possible to get two or more different col... | 3 | X, Y, Z = map(int, input().split())
ans = 0
BC = []
for _ in range(X+Y+Z):
a, b, c = map(int, input().split())
ans += a
BC.append([b-a, c-a])
BC.sort(key=lambda x: x[1]-x[0])
import heapq
q = []
an = 0
for b, _ in BC[:Y]:
heapq.heappush(q, b)
an += b
A = [an]
for b, _ in BC[Y:-Z]:
heapq.heappush... |
Water Country Water Deven has n cities. Each city is surrounded by water and looks like an island country. Water Deven has m bridges, and transportation between cities is carried out by these bridges, which allows you to travel to and from all cities.
Recently, it was decided to reduce the maintenance cost of the brid... | 1 | par = [0]*101
rank = [0]*101
def init_union_find(V):
for i in xrange(V):
par[i] = i
rank[i] = 0
def find(x):
if par[x] == x: return x
else:
par[x] = find(par[x])
return par[x]
def unite(x,y):
x = find(x)
y = find(y)
if (x == y): return
if ra... |
Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain.
Initially, snowball is at height h and it has weight w. Each second the following sequence of events happens: snowball's weights increases by i,... | 3 | w, h = map(int, input().split())
w1, h1 = map(int, input().split())
w2, h2 = map(int, input().split())
for i in range(h, -1, -1):
w += i
if i == h1:
w -= w1
if i == h2:
w -= w2
if w < 0:
w = 0
print(w) |
Captain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure.
Bottle with potion has two values x and y written on it. These values define four moves which can be performed... | 3 |
line1 = input()
line2 = input()
coords = list( map(int, line1.split()) )
v1, v2 = list( map(int, line2.split()) )
dx = coords[2] - coords[0]
dy = coords[3] - coords[1]
if dx % v1 == 0 and dy % v2 == 0 and \
(dx // v1 - dy // v2) % 2 == 0:
print ('YES')
else:
print ('NO')
|
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 20 14:18:38 2020
@author: Tanmay
"""
ans=[]
for i in range(5):
arr=[]
arr=list(map(int,input().strip().split()))
ans.append(arr)
for i in range(5):
for j in range(5):
if(ans[i][j]==1):
x=i
y=j
suma=abs(x-2)+abs(y-2)
prin... |
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 lik... | 3 | for i in range(int(input())):
string = input()
if(len(string) > 10):
print(string[0]+str((len(string)-2))+string[-1])
else:
print(string)
|
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | import math
row = 0
col = 0
for i in range(5):
s = input()
ind = s.find('1')
if(ind != -1):
row = i
col = ind - ind//2
print(abs(row-2)+abs(col-2)) |
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vert... | 1 | from __future__ import division
from sys import stdin, stdout
# from fractions import gcd
# from math import *
# from operator import mul
# from functools import reduce
# from copy import copy
from collections import deque, defaultdict, Counter
rstr = lambda: stdin.readline().strip()
rstrs = lambda: [str(x) for x in s... |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n = int(input())
ans = 0
for i in range(0,n):
a,b,c = input().split()
a = int(a)
b = int(b)
c = int(c)
count = 0
if a == 1 :
count = count + 1
if b == 1 :
count = count + 1
if c == 1 :
count = count + 1
if count>=2 :
ans = ans + 1
print(ans)
|
Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip. At the beginning of Day 1, he is at home. His plan is described in a string S of length N. On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction:
* North if the i-th letter of S is `N`
* West if the i-th letter... | 3 | s = set(input())
move = [{'N', 'S', 'E', 'W'}, {'N', 'S'}, {'E', 'W'}]
if s in move:
print('Yes')
else:
print('No') |
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.
You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units.
... | 3 | t = int(input())
for i in range(0,t):
p,q = map(int, input().split())
cs, cw = map(int, input().split())
s, w = map(int, input().split())
if w < s:
temp = s
s = w
w = temp
temp = cs
cs = cw
cw = temp
ans = 0
for px in range(0,min(cs, int(p/s))+1):
py = min(cw,int((p-s*px)/w))
... |
Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y').
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle ... | 3 | import math
entrada = input().split()
r = int(entrada[0])
x1 = int(entrada[1])
y1 = int(entrada[2])
x2 = int(entrada[3])
y2 = int(entrada[4])
d = math.sqrt(pow(y2 - y1, 2) + pow(x2 - x1, 2))
print(math.ceil(d / r / 2))
|
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 × 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures.
Yo... | 3 | t = int(input().strip())
for _ in range(t):
#a,b = map(int,input().strip().split())
n = int(input().strip())
nums = [int(i) for i in input().strip().split()]
has = True
if nums[0] % 2 == 0:
for i in range(1,n):
if nums[i] % 2!= 0:
has = False
break... |
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.
There are n stages available. The rock... | 3 | n,k=map(int,input().split())
s=sorted(input())
ar = []
for i in range (26):
ar.append(0)
for i in range(len(s)):
ar[ord(s[i])-97] += 1
last = ord(s[0])-97
ans = ord(s[0])-96
t = 1
for i in range(last+2,26):
if ar[i]==0 or t==k or i-last<2:
continue
last = i
an... |
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.
Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting ea... | 1 | n, k = map(int, raw_input().split())
a, b, c, d = map(int, raw_input().split())
if k > n > 4:
path = list(set(range(1, n+1)).difference([a, c, b, d]))
res1 = [a, c] + path + [d, b]
res2 = [c, a] + path + [b, d]
print ' '.join([str(s) for s in res1])
print ' '.join([str(s) for s in res2])
else:
... |
Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.
She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and al... | 3 | money = 0
apples = 0
customers = []
num_customers, apple_price = [ int(x) for x in (input().split(' ')) ]
for i in range(0,num_customers):
arg = input()
customers.append(arg)
customers = reversed(customers)
for c in customers:
if c == 'halfplus':
money += (apples+0.5)*float(apple_price)
... |
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins.
Across all the sets Misha scored a points ... | 1 | def haha():
x = raw_input()
x = x.split(" ")
k = int(x[0])
a = int(x[1])
b = int(x[2])
c = a//k + b//k
if c == 0 or (c == a//k and a%k!=0) or (c ==b//k and b%k!=0):
print -1
else:
print c
haha() |
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ... | 3 | def main():
n = int(input())
ls = list(map(int, input().split()))
s = 0
d = 0
for i in range(n):
a = max(ls[0], ls[len(ls)-1])
if i % 2 == 0:
s += ls.pop(ls.index(a))
else:
d += ls.pop(ls.index(a))
print(s, d, sep=" ")
if __name__ == "__main__":
... |
You found a mysterious function f. The function takes two strings s1 and s2. These strings must consist only of lowercase English letters, and must be the same length.
The output of the function f is another string of the same length. The i-th character of the output is equal to the minimum of the i-th character of s1... | 1 | x = raw_input()
z = raw_input()
y = ""
for i in xrange(len(x)):
if(ord(z[i]) - ord(x[i]) > 0):
print -1
exit()
if(ord(x[i]) == ord(z[i])):
y+=x[i]
else:
y+=z[i]
print y |
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a ... | 3 | n,m = map(int,input().split())
pixels = []
colored = False
for i in range(n):
pixels.append(list(map(str,input().split())))
for pixel in pixels:
if pixel.__contains__('C') or pixel.__contains__('M') or pixel.__contains__('Y'):
colored = True
break
print("#Color" if colored else "#Black&White") |
Masha has n types of tiles of size 2 × 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.
Masha decides to construct the square of size m × m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ... | 3 | t = int(input())
for _ in range(t):
n,m = list(map(int,input().split()))
flag = 1
for i in range(n):
a,b = list(map(int,input().split()))
d,c = list(map(int,input().split()))
if b==d and m%2==0 :
flag = 0
if flag == 0 :
print("YES")
else:
print("NO... |
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly n lowercase English letters into s to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" a... | 1 | # import numpy as np
def solution():
# get the input
input_word = raw_input()
word = list(input_word)
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
output = ""
# case 1: word is 1 letter long:
if(len(word) == 1):
... |
Artem is building a new robot. He has a matrix a consisting of n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{i,j} written in it.
If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells c... | 3 | import sys
import math
from collections import defaultdict,deque
input = sys.stdin.readline
def inar():
return [int(el) for el in input().split()]
def main():
t=int(input())
for _ in range(t):
n,m=inar()
matrix=[]
for i in range(n):
matrix.append(inar())
for i in... |
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, w... | 3 | # 全方位DP
import sys
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**6)
from collections import defaultdict, deque
from math import factorial
MOD = 10**9+7
class Facts():
def __init__(self, max_num=10**5, p=10**9 + 7):
self.p = p
self.max_num = max_num
self.fact = [1] ... |
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the... | 3 | n=int(input())
a=list(map(int,input().split()))
count25=0
count50=0
for i in a:
if i==25:
count25=count25+1
if i==50:
if count25==0:
print ("NO")
break
count25=count25-1
count50=count50+1
if i==100:
if count25==0:
print ("NO")
... |
Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.
The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some... | 1 | if __name__ == '__main__':
n , k = [int(i) for i in raw_input().split(' ')]
l = (list(raw_input()), list(raw_input()))
(x, y) = (0, 0)
w = 0
st = [(0, 0)]
acts = [lambda x, y:(1 if x == 0 else 0, y + k),
lambda x, y:(x, y + 1),
lambda x, y:(x, y - 1)]
while ... |
The map of Bertown can be represented as a set of n intersections, numbered from 1 to n and connected by m one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along... | 1 | from sys import stdin
from collections import *
from heapq import *
def fast2():
import os, sys, atexit
range = xrange
from cStringIO import StringIO as BytesIO
sys.stdout = BytesIO()
atexit.register(lambda: os.write(1, sys.stdout.getvalue()))
return BytesIO(os.read(0, os.fstat(0).st_size)).re... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp(): #Integer
return(int(input()))
def inlt(): #integer list
return(list(map(int,input().split())))
def insr(): #String
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()... |
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The ... | 3 | line = [int(i) for i in str(input()).split()]
values = [int(i) for i in str(input()).split()]
valids = [i for i in values if i <=5-line[1]]
print(len(valids)//3)
|
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.
The bu... | 3 | tower,lantai,a,b,test = map(int , input().split())
for z in range (test):
tawal,fawal,takhir,fakhir = map(int , input().split())
if tawal == takhir:
pindah = abs(fawal-fakhir)
else:
if a<=fawal and fawal<=b:
pindah = abs(takhir-tawal) + abs(fakhir-fawal)
else:
... |
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | 3 | guest = input()
host = input()
name = input()
s1 = sorted(guest + host)
s2 = sorted(name)
if s1 == s2:
print("YES")
else:
print("NO") |
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.
Polycarp decided to store the hash of the password, generated by the following algorithm:
1. take the password p, consisting of lowercase Latin letters, and shuffle the l... | 3 | n = int(input())
def equal(l, d2):
d1 = {x: l.count(x) for x in l}
return d1 == d2
for i in range(n):
pwd = list(input())
hash_str = list(input())
if len(pwd) > len(hash_str):
print('NO')
continue
d = {x: pwd.count(x) for x in pwd}
valid = False
for j in range... |
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot... | 3 | from math import *
n = int(input())
s = input()
s1 = input()
dl = {}
dp = {}
for i in range(n):
c = s[i]
if c not in dl:
dl[c] = []
dl[c].append(i + 1)
c = s1[i]
if c not in dp:
dp[c] = []
dp[c].append(i + 1)
ans = []
ost1 = []
ost2 = []
p1 = []
p2 = []
#print(dp)
for c in dl:
if c == '?':
p1 = dl[c][:]... |
There are N candles placed on a number line. The i-th candle from the left is placed on coordinate x_i. Here, x_1 < x_2 < ... < x_N holds.
Initially, no candles are burning. Snuke decides to light K of the N candles.
Now, he is at coordinate 0. He can move left and right along the line with speed 1. He can also light... | 3 | n,k=map(int,input().split())
x=list(map(int,input().split()))
ans=10**18
for l in range(n-k+1):
y=min(abs(x[l])+abs(x[l+k-1]-x[l]),abs(x[l+k-1])+abs(x[l+k-1]-x[l]))
ans=min(y,ans)
print(ans) |
Lee is going to fashionably decorate his house for a party, using some regular convex polygons...
Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis a... | 3 | import math
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
if n%4 == 0:
print('YES')
else:
print('NO') |
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla... | 3 | from sys import stdin, stdout
scores = {}
num = int(stdin.readline())
maximum = -10000000
lines = []
for i in range(num):
line = stdin.readline().rstrip()
lines.append(line)
parts = line.split()
name = parts[0]
score = int(parts[1])
if name in scores:
scores[name] = scores[name] + score... |
You and your n - 1 friends have found an array of integers a_1, a_2, ..., a_n. You have decided to share it in the following way: All n of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for h... | 3 | from sys import stdin
from collections import deque
mod = 10**9 + 7
import sys
sys.setrecursionlimit(10**5)
from queue import PriorityQueue
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math imp... |
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n.
For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the ... | 3 | from sys import stdin
input=stdin.readline
for _ in range(int(input())):
n,k=map(int,input().split())
if k>=n:
p=k//n+k%n
k+=k//n
while p:
e=0
k+=p//n
if p>n:e=p%n
p//=n
p+=e
print(k)
else:
print(k) |
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ... | 3 | n,t=map(int,input().split())
l=list(map(int,input().split()))
i,j,s=0,0,0
for j in range(n):
s+=l[j]
if s>t:
s-=l[i]
i+=1
print(n-i)
|
You have an array a_1, a_2, ..., a_n where a_i = i.
In one step, you can choose two indices x and y (x ≠ y) and set a_x = \left⌈ (a_x)/(a_y) \right⌉ (ceiling function).
Your goal is to make array a consist of n - 1 ones and 1 two in no more than n + 5 steps. Note that you don't have to minimize the number of steps.
... | 3 | import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
t=int(input())
for _ in range(t):
n=int(input())
if n==1 or n==2:
print(0)
else:
ans=[]
... |
For an array a of integers let's denote its maximal element as max(a), and minimal as min(a). We will call an array a of k integers interesting if max(a) - min(a) ≥ k. For example, array [1, 3, 4, 3] isn't interesting as max(a) - min(a) = 4 - 1 = 3 < 4 while array [7, 3, 0, 4, 3] is as max(a) - min(a) = 7 - 0 = 7 ≥ 5.
... | 3 | for _ in range(int(input())):
n=int(input())
lst=list(map(int,input().split()))
for i in range(1,n):
if abs(lst[i]-lst[i-1])>=2:
print("YES")
print(i,i+1)
break
else:
print("NO") |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | strng = input()
strng = strng.lower()
newstring=''
for i in strng:
if i == "a" or i == "i" or i == "e" or i == "o" or i == "u" or i == "y":
pass
elif i != "a" or i != "i" or i != "e" or i != "o" or i != "u" or i != "y":
newstring = newstring + '.' + i
print(newstring)
|
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | n,k = map(int,input().split())
a = 0
while a < k:
if n % 10 == 0:
n //= 10
else: n -= 1
a+=1
print(n) |
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.
Artem wants to paint an n × m board. Each cell of the board should be colored in white or black.
Lets B be the number of black cells that have at least one white neighbor adja... | 3 | # python3
def solve(n, m):
res = [['B' for _ in range(m)] for i in range(n)]
#if n > m:
# res[0][0] = res[1][0] = 'W'
#else:
# res[0][0] = res[0][1] = 'W'
res[0][0] = 'W'
for i in range(n):
print(''.join(res[i]))
if __name__ == '__main__':
t = int(input())
for _ in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.