problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Two players decided to play one interesting card game.
There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a... | 3 | T = int(input())
answer = ""
for t in range(T):
n, a, b = list(map(int, input().split(' ')))
maxa = max(list(map(int, input().split(' '))))
maxb = max(list(map(int, input().split(' '))))
if maxa > maxb:
answer += "YES\n"
else:
answer += "NO\n"
print(answer) |
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 | g = int(input())
for i in range(g):
g = input().split()
g = [int(i) for i in g]
l=(g[2]-g[1])%g[0]
print(g[2]-l)
|
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters.
The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let'... | 3 | res = []
tc = int(input())
for j in range(tc):
x, r = map(int, input().split())
a = set(map(int, input().split()))
a = list(sorted(a, reverse=True))
ans = cnt = 0
for i in range(len(a)):
if a[i] <= cnt:
break
ans = ans + 1
cnt = cnt + r
res.append(str(ans))
pr... |
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia... | 3 | n = int(input())
s = input()
count = 0
for i in range(2,n):
if i == n:
break
if s[i-2] == 'x' and s[i-1] == 'x' and s[i] == 'x':
count += 1
print(count) |
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property.
Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=... | 3 | from collections import defaultdict
for _ in range(int(input())):
s = input()
ll = defaultdict(int)
for i in s:
ll[i]+=1
if ll['0'] == len(s) or ll['1'] == len(s):
print(s)
else:
print("10"*len(s)) |
You are given a sequence a1, a2, ..., aN. Find the smallest possible value of ai + aj, where 1 β€ i < j β€ N.
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.Β
The first line of each description consists of a single integer N.
The second ... | 1 | for tests in xrange(int(raw_input())):
raw_input()
print sum(sorted(map(int, raw_input().split()))[:2]) |
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 3 | index=int(input())
result=0
while index>0:
thing=input()
if thing=="Tetrahedron":
a=4
elif thing=="Cube":
a=6
elif thing=="Octahedron":
a=8
elif thing=="Dodecahedron":
a=12
elif thing=="Icosahedron":
a=20
result=result+a
index=index-1
print(result)... |
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid.
A 1-st order rhombus is just a square 1 Γ 1 (i.e just a cell).
A n-th order rhombus for all n β₯ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look ... | 3 | n = int(input())
m = [1]
if n == 1:
print(m[0])
else:
for i in range(1, n):
m.append(m[i - 1] + 2 * (i + 1) + 2 * (i - 1))
print(m[-1])
|
There are N integers written on a blackboard. The i-th integer is A_i.
Takahashi will repeatedly perform the following operation on these numbers:
* Select a pair of integers, A_i and A_j, that have the same parity (that is, both are even or both are odd) and erase them.
* Then, write a new integer on the blackboard ... | 3 | n = int(input())
a = list(map(int,input().split()))
b = [x%2 for x in a]
if sum(b)%2 == 1:
print("NO")
else:
print("YES") |
One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal.
The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with si... | 3 | import math
def pfacts(n):
ans = []
if(n%2==0):
ans.append(2)
while(n%2==0):
n//=2
p=3
while(n!= 1):
if(n%p==0):
ans.append(p)
while(n%p==0):
n//=p
p+=1
return ans
for _ in range(int(input())):
n= int(input())
... |
Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n Γ n matrix W, consisting of integers, and you should find two n Γ n matrices A and B, all the following conditions must hold:
* Aij = Aji, for all i, j (1 β€ i, j β€ n);
* Bij = - Bji, for all i, j... | 1 | #!/usr/bin/env python
if __name__ == '__main__':
n = int(raw_input())
W = []
for i in range(n):
W.append(map(float, raw_input().split()))
A = [[0.0 for i in range(n)] for j in range(n)]
B = [[0.0 for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
... |
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 | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.... |
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of n non-negative integers a_1, β¦, a_n. You are allowed to perform the following operation: choose two distinct indices 1 β€ i, j β€ n. If before the operation a_i = x, a_j = y, then a... | 3 | n,arra = int(input()),list(map(int,input().split()));s = [0] * n
for i in range(20):
x = sum(list(map(lambda x: (x>>i)&1,arra)))
for k in range(x):s[k] |= 1<<i
print(sum(list(map(lambda x:x**2, s)))) |
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | m, n = map(int, input().split())
if (m == 1) or (n == 1):
print(m * n // 2)
elif (m % 2 == 0) and (n % 2 == 0):
print(int(m / 2 * n))
elif (m % 2 == 0):
print(int(m / 2 * n))
elif (n % 2 == 0):
print(int(n / 2 * m))
else:
print(int(m * n // 2)) |
Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices.
Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans:
1. to orient each undirected edge in one of two possible directions to maximize... | 3 | import sys
input = sys.stdin.readline
def put():
return map(int, input().split())
def dfs(x,flag=1):
s,vis,ans = [x],[0]*n,['+']*m
vis[x]= 1
while s:
i = s.pop()
for j,k in graph[i]:
if vis[j]==0:
if k*flag<0:
ans[abs(k)-1]='-'
... |
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | word, translation = input(), input()
if word == ''.join(reversed(translation)):
print('YES')
else:
print('NO')
|
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | n = int(input())
line = list(map(int,input().split()))
line.sort()
for i in line:
print(i, end=" ") |
Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct po... | 3 | import random
import sys
n=int(sys.stdin.readline())
L=list(map(int,sys.stdin.readline().split()))
X=sorted(L)
XX=sorted(L,reverse=True)
K={}
for i in range(n):
item=L[i]
if(item in K):
K[item].append(i)
else:
K[item]=[i]
if(len(X)<=2 or X[0]==X[-1] or (len(X)==3 and (L==[X[0],X[-1],X[0]] ... |
Takahashi's house has only one socket.
Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.
One power strip with A sockets can extend one empty socket into A empty sockets.
Find the minimum number of power strips required.
Constraints
* All values in inp... | 3 | a,b=map(int, input().split())
n=0
t=1
while t<b:
n+=1
t+=a-1
print(n)
|
Kawashiro Nitori is a girl who loves competitive programming.
One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem.
Given a string s and a parameter k, you need to check if there exist k+1 non-empty strings a_1,a_2...,a_{k+1}, such that $$$s=a_1+a_2+β¦ +a_k+a_{k+1}... | 3 | for k in range(int(input())):
n,k=map(int,input().split())
s=input()
if k*2==n:
print("NO")
else:
a=s[0:k]
b=s[n-k:n]
if a==b[::-1]:
print("YES")
else:
print("NO")
|
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 | import math
for _ in range(int(input())):
x,y,n = list(map(int, input().split()))
p = math.floor((n - y) / x)
k = p*x + y
print(k)
# m = 0
# o = n%x
# if o<y:
# m = o+x-y
# print(n-m)
# else:
# print(n-m+y) |
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... | 3 | s = input()
for i in range(26):
for j in range(len(s) + 1) :
ans = s[: j] + chr(97 + i) + s[j:]
if ans == ans[::-1] :
print(ans)
exit()
print('NA') |
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) β
maxDigit(a_{n}).$$$
Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes.
Your task is calculate a_{K} for given a_{1} and K.
Input
The ... | 3 | t=int(input())
for tt in range(t):
n,k=map(int,input().split())
ns=str(n)
for i in range(k-1):
if int(min(ns))==0:
break
n+= int(min(ns))*int(max(ns))
ns=str(n)
print(n)
|
A permutation of length n is an array p=[p_1,p_2,...,p_n], which contains every integer from 1 to n (inclusive) and, moreover, each number appears exactly once. For example, p=[3,1,4,2,5] is a permutation of length 5.
For a given number n (n β₯ 2), find a permutation p in which absolute difference (that is, the absolut... | 3 | def solution(A):
return min(A) == 1 and max(A) == len(A) == len(set(A))
def check(a):
for i in range(len(a)-1):
f = a[i]-a[i+1]
if abs(f) < 2 or abs(f) > 4:
return False
return True
for _ in range(int(input())):
n = int(input())
a = []
if n < 4 :
... |
Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends... | 1 | n = input()
arr1 = map(int,raw_input().split(" "))
arr2 = map(int,raw_input().split(" "))
psum1 = [0]*n
psum2 = [0]*n
base1 = [0]*n
base2 = [0]*n
psum1[-1] = arr2[-1]
psum2[-1] = arr1[-1]
base1[-1] = arr2[-1]
base2[-1] = arr1[-1]
for i in range(n-1)[::-1]:
psum1[i] = arr2[i] + arr1[i+1] + psum1[i+1]
psum2[i]... |
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with n rows and m columns, where the cells of the... | 3 | t = int(input())
while t:
n, m = [int(a) for a in input().split()]
if n%2 == 0 or m %2 == 0:
print((m*n)//2)
else:
print(((m-1)*n)//2+(n+1)//2)
t-=1
|
There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i.
For each square, you will perform either of the following operations once:
* Decrease the height of the square by 1.
* Do nothing.
Determine if it is possible to perform the operations so that the heights ... | 3 | n=int(input())
h=list(map(int,input().split()))
h=h[::-1]
for i in range(1,n):
if h[i]-h[i-1]>1:
print("No")
exit(0)
elif h[i]-h[i-1]==1:
h[i]-=1
print("Yes")
|
N friends of Takahashi has come to a theme park.
To ride the most popular roller coaster in the park, you must be at least K centimeters tall.
The i-th friend is h_i centimeters tall.
How many of the Takahashi's friends can ride the roller coaster?
Constraints
* 1 \le N \le 10^5
* 1 \le K \le 500
* 1 \le h_i \le 5... | 3 | n,k=map(int,input().split())
h=map(int,input().split())
print(sum(x >=k for x in h)) |
You are given three multisets of pairs of colored sticks:
* R pairs of red sticks, the first pair has length r_1, the second pair has length r_2, ..., the R-th pair has length r_R;
* G pairs of green sticks, the first pair has length g_1, the second pair has length g_2, ..., the G-th pair has length g_G;
* B ... | 3 | # import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
n = list(map(int, input().split()))
u = []
u.append(list(map(int, input().split())))
u.append(list(map(int, input().split())))
u.append(list(map(int, input().split())))
u[0].sort(reverse=True)
u[1].sort(reverse=True)
u[2].sort(rev... |
Mishka started participating in a programming contest. There are n problems in the contest. Mishka's problem-solving skill is equal to k.
Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses whic... | 3 | a=input()
b=input()
s=0
L1=a.split()
L2=b.split()
for i in range(2):
L1[i]=int(L1[i])
for i in range(len(L2)):
L2[i]=int(L2[i])
for i in range(len(L2)):
if L2[i]<=L1[1]:
s=s+1
else:
break
if s!=(len(L2)):
L2.reverse()
for i in range(len(L2)):
if L2[i]<=L1[1]:
... |
There is a frog staying to the left of the string s = s_1 s_2 β¦ s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. ... | 3 | output = ""
for _ in range(int(input())):
i = input().split('R')
l = [len(n) for n in i]
output += str(max(l) + 1)+"\n"
print(output) |
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.
Tzuyu gave Sana two integers a and b and a really important quest.
In order to complete the quest, Sana has to output the smallest possible value of (a β x) + (b β x) for any given x, where β denotes the [bitwise XOR operation](http... | 3 | test_cases = int(input())
while test_cases != 0:
test_cases = test_cases - 1
x, y = map(int, input().split())
mask = x & y
print((x ^ mask) + (y ^ mask))
|
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 | t = int(input())
for _ in range(t):
s = input()
arr = []
n = len(s)
for i in range(n):
if(s[i]!='0'):
arr.append(int(s[i])*10**(n-i-1))
print(len(arr))
for x in arr:
print(x, end=" ")
print("\n") |
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.
In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh... | 3 | from sys import stdin
def help():
n,a,b,c,d=(map(int,stdin.readline().split(" ")))
start=c-d
end=c+d
if(((a-b)*n)>end or ((a+b)*n<start)):
print("No")
else:
print("Yes")
for i in range(int(stdin.readline())):
help()
# a=(stdin.readline().strip("\n"))
# b=(stdin.readline().strip("\n"))
# def help(i... |
You have a digit sequence S of length 4. You are wondering which of the following formats S is in:
* YYMM format: the last two digits of the year and the two-digit representation of the month (example: `01` for January), concatenated in this order
* MMYY format: the two-digit representation of the month and the last t... | 1 | def f(s):
m,y = int(s[:2]), int(s[2:])
return (0 < m <= 12,0 < y <= 12)
p,q = map(int,list(f(raw_input())))
print {(0,0):'NA', (0,1): 'YYMM', (1,0): 'MMYY', (1,1):'AMBIGUOUS'}[(p,q)]
|
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces.
You are asked to calculate the number of ways he can... | 3 |
if __name__=='__main__':
n = int(input())
arr = list(map(int,input().split()))
prev = -1
res = 0
for i in range(0,n):
if arr[i]==1:
if prev == -1:
res = 1
else:
res *= i - prev
prev = i
print(res)
|
Polycarp is reading a book consisting of n pages numbered from 1 to n. Every time he finishes the page with the number divisible by m, he writes down the last digit of this page number. For example, if n=15 and m=5, pages divisible by m are 5, 10, 15. Their last digits are 5, 0, 5 correspondingly, their sum is 10.
You... | 3 | q = int(input())
for s in range(q) :
n,m = map(int,input().split())
t = [int(str(m*i)[-1]) for i in range(1,11)]
t.append(sum(t))
res = t[-1]*(n//(m*10))
for i in range((n%(m*10))//m) :
res+=t[i]
print(res)
|
Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are n players arranged in a circle, so that for all j such that 2 β€ j β€ n, player j - 1 is to the left of the player j, and player j is to the right of player j - 1. Additionally, player n is to the left of player 1, and player 1 is to the... | 3 | from sys import stdin
def inp():
return stdin.buffer.readline().rstrip().decode('utf8')
def itg():
return int(stdin.buffer.readline())
def mpint():
return map(int, stdin.buffer.readline().split())
# ############################## import
# ############################## main
# def solve():
def check_... |
International Women's Day is coming soon! Polycarp is preparing for the holiday.
There are n candy boxes in the shop for sale. The i-th box contains d_i candies.
Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift ... | 3 | n, k = map(int, input().split())
d = list(map(int, input().split()))
count = [0] * k
for x in d:
count[x%k] += 1
result = count[0]//2
for i in range(1, k):
if i*2 >= k:
break
result += min(count[i], count[k-i])
if k%2==0:
result += count[k//2]//2
print(result*2) |
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t... | 3 | len_s = int(input())
s = input()
z = s.count('z')
n = s.count('n')
for i in range(n):
print(1,end = ' ')
for i in range(z):
print(0,end = ' ')
|
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | 3 | words=input()
l=[]
for char in words:
if char!='{' and char!='}' and char!=' ' and char not in l and char!=',':
l+=char
print(len(l))
|
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces ... | 3 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 28 16:56:02 2020
@author: 17831
"""
n,a,b,c = map(int,input().split())
dp = [0] + [-4000]*4000
for i in range(1,n+1):
dp[i] = max(dp[i-a],dp[i-b],dp[i-c])+1
print(dp[n]) |
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.
You are given a string s of length n, consisting of digits.
In one operation you can delete any character from strin... | 3 | t = int(input())
while(t):
l = int(input())
st = str(input())
ind = st.find('8')
#print(ind)
if(l - (ind+1) >= 10 and ind != -1):
print("YES")
else:
print("NO")
t -= 1 |
You are given three integers, A, B and C.
Among them, two are the same, but the remaining one is different from the rest.
For example, when A=5,B=7,C=5, A and C are the same, but B is different.
Find the one that is different from the rest among the given three integers.
Constraints
* -100 \leq A,B,C \leq 100
* A, B ... | 3 | a=input().split()
a=sorted(a)
if a.count(a[0]) == 1:print(a[0])
else:print(a[2]) |
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.
You are given a string s of length n, consisting of digits.
In one operation you can delete any character from strin... | 1 | t = int(raw_input())
for i in range(t):
n = int(raw_input())
s = raw_input()
if n < 11:
print 'NO'
continue
while len(s) > 11 and s[0] != '8':
s = s[1:]
while len(s) > 11:
s = s[:-1]
if s[0] != '8':
print 'NO'
else:
print 'YES' |
Pig is visiting a friend.
Pig's house is located at point 0, and his friend's house is located at point m on an axis.
Pig can use teleports to move along the axis.
To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost ... | 3 | n, m = map(int, input().split())
vis = [0]*(m+10)
vis[0] = 1
for i in range(n):
a, b = map(int, input().split())
if(vis[a] == 1):
for j in range(a, b+1):
vis[j] = 1
if(vis[m]):
print('YES')
else:
print('NO')
|
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | l,b = map(int,input().split())
print((l*b)//2); |
Iahub got bored, so he invented a game to be played on paper.
He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 β€ i β€ j β€ n) and flips all values ak for which their positions are in range [i, j] (that is i β€ k β€ j)... | 3 | n = int(input())
li = list(map(int, input().split()))
res = []
for i in range(n):
for j in range(i + 1, n + 1):
x = sum(li) + li[i : j].count(0) - li[i : j].count(1)
res.append(x)
print(max(res))
|
The postal code in Atcoder Kingdom is A+B+1 characters long, its (A+1)-th character is a hyphen `-`, and the other characters are digits from `0` through `9`.
You are given a string S. Determine whether it follows the postal code format in Atcoder Kingdom.
Constraints
* 1β€A,Bβ€5
* |S|=A+B+1
* S consists of `-` and di... | 3 | import re
n=[*input()];print('YNeos'[not re.match(r'[0-9]{'+n[0]+'}-[0-9]{'+n[-1]+'}',input())::2]) |
You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn.
The variance Ξ±2 is defined by
Ξ±2 = (βni=1(si - m)2)/n
where m is an average of si. The standard deviation of the scores is the square root of their variance.
Constraints
* n β€ 1000
* 0 β€ si β€ 100
Inpu... | 3 | import math
while True:
n = int(input())
if n == 0: break
d = list(map(int, input().strip().split()))
m = sum(d) / n
print(math.sqrt(sum((x - m)**2 for x in d) / n)) |
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an... | 3 | a, b = 0, 1023
n=int(input())
for i in range(n):
cmd = input()
c, x = cmd.split()
x = int(x)
if c == "|":
a, b = a | x, b | x
elif c == "&":
a, b = a & x, b & x
else:
a, b = a ^ x, b ^ x
x = 0
y = 1023
z = 0
for i in range(10):
a_i = (a >> i) & 1
b_i = (b >> i) & ... |
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b.
Can you reconst... | 3 | a, b = map(int, input().split())
if a == b:
print(str(a) + "1", str(b) + "2")
elif a + 1 == b:
print(a, b)
elif a == 9 and b == 1:
print(9, 10)
else:
print(-1) |
Snuke got an integer sequence of length N from his mother, as a birthday present. The i-th (1 β¦ i β¦ N) element of the sequence is a_i. The elements are pairwise distinct. He is sorting this sequence in increasing order. With supernatural power, he can perform the following two operations on the sequence in any order:
... | 3 | n = int(input())
a = []
for i in range(n):
x = int(input())
a.append(x)
zi = {}
b= sorted(a)
for i in range(n):
zi[b[i]] = i
g = 0
k = 0
for i in range(n):
if zi[a[i]] %2 == i%2:
continue
elif i%2 == 1:
g += 1
else:
k += 1
print(g) |
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 |
def handle(number):
parts = list(number)
for i, p in enumerate(parts, 1):
n = p + ('0' * (len(parts) - i))
if int(n) != 0:
yield n
if __name__ == '__main__':
cases = int(input())
for case in range(cases):
result = tuple(handle(str(input())))
print(len(resul... |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | x=int(input())
m=x+1
q=0
w=0
e=0
r=0
while m<9013:
q=int(m/1000)
w=int((m-q*1000)/100)
e=int((m-q*1000-w*100)/10)
r=int((m-q*1000-w*100-e*10))
if(q==w or q==e or q==r or w==e or w==r or e==r):
m=m+1
else:
print(m)
break |
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 millis... | 3 | s,v1,v2,t1,t2=map(int,input().split())
T1=s*v1+2*t1
T2=s*v2+2*t2
if T1<T2:
print('First')
elif T1>T2:
print('Second')
else:
print('Friendship') |
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i β€ a_{i + 1}).
Find three indices i, j, k such that 1 β€ i < j < k β€ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to... | 3 | t=int(input())
for o in range(0,t):
n = int(input())
arr = list(map(int,input().split(" ")))
sum = arr[0] + arr[1]
flag = 0
for i in range(2,n):
if(arr[i] >= sum):
print("{} {} {}".format(1, 2, i + 1))
flag = 1
break
if(flag == 0):
print("-1") |
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 | a = input()
sum = 0
for i in range(len(a)):
if i == 0:
count = abs(ord(a[0]) - ord("a"))
if count > 13:
sum = sum + 26 - count
else:
sum = sum + count
else:
count = abs(ord(a[i]) - ord(a[i-1]))
if count > 13:
sum = sum + 26 - count
... |
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with n rows and m columns, where the cells of the... | 3 | for _ in range(int(input())):
n,m=map(int,input().split())
if n%2==0 and m%2==0:
print(n*(m//2))
elif n%2==0 and m%2==1:
print(m*(n//2))
elif n%2==1 and m%2==0:
print(n*(m//2))
else:
print(n*(m//2)+(n+1)//2)
# for _ in range(int(input())):
# n=int(input())
# ... |
As bad weather continues and vegetable prices soar, Seven-Eleven is offering customers bulk purchase sales of vegetables. The store is very busy, as you can get vegetables that are hard to find in stores at reasonable prices.
One day, a group of three good friends living in the Matsunaga housing complex bloomed with a... | 1 | while True:
try:
num, size = map(int, raw_input().split())
arr = map(int, raw_input().split())
arr.sort(reverse = True)
for i in range(size-1, num, size):
arr[i] = 0
print sum(arr)
except:
break
|
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 manag... | 3 | ## necessary imports
import sys
input = sys.stdin.readline
from math import log2, log, ceil
# swap_array function
def swaparr(arr, a, b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
## nCr function efficient usi... |
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '<image>' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1.
When ZS the Coder is at level k, he can :
1. Pr... | 1 | n = int(input())
x, k = 2, 1
while k <= n:
y = ((k+1) * k) ** 2
print((y - x) // k)
x, k = (k+1) * k, k + 1
|
You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.
Subsequence is a sequence that can be derived from another sequence by deletin... | 3 | import heapq
n = int(input())
a = list(map(int,input().split()))
valut = [0 in range(n)]
ans = 0
ret = []
plus = []
minus = []
for v in a:
if v>0:
ans+=v
heapq.heappush(plus,v)
elif v<0:
heapq.heappush(minus,abs(v))
if ans&1:
print(ans)
else:
remove = 0
while(len(plus)>0 and ... |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | n=int(input())
l=list(map(int,input().split()))
l.sort()
print(' '.join([str(ele) for ele in l])) |
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 1 | m,n=map(int,raw_input().split())
if n%2==0:
print (n/2)*m
else:
print (n/2)*m+m/2
|
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | a = int(input())
b = int(input())
c = int(input())
s = []
s1 = a+(b*c)
s.append(s1)
s2 = a*b+c
s.append(s2)
s3 = a*(b+c)
s.append(s3)
s4 = a*b*c
s.append(s4)
s5 = a+b*c
s.append(s5)
s6 = (a+b)*c
s.append(s6)
s7 = a*b+c
s.append(s7)
s8 = a+b+c
s.append(s8)
print(max(s)) |
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 β€ i β€ n.
He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se... | 3 | import math
t=int(input())
for i in range(0,t):
n=int(input())
if(n%2==0):
print(n//2)
else:
print(n//2+1)
|
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | # cook your dish here
n=int(input())
l=list(str(n))
c=0
for i in l:
if i=='4' or i=='7':
c+=1
if c==4 or c==7:
print("YES")
else:
print("NO") |
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 = input().split(' ')
number = int(n[0])
subtractions = int(n[1])
lastdigit = 0
while subtractions != 0:
lastdigit = number % 10
if lastdigit != 0:
number -= 1
elif lastdigit == 0:
number = number // 10
subtractions -= 1
print(number)
|
You're given an array a_1, β¦, a_n of n non-negative integers.
Let's call it sharpened if and only if there exists an integer 1 β€ k β€ n such that a_1 < a_2 < β¦ < a_k and a_k > a_{k+1} > β¦ > a_n. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:
* The arrays [4], [0, 1], [... | 3 |
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
from fractions import *
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class ... |
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0.
In one operation, you can choose two different indices i and j (1 β€ i, j β€ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](... | 3 | # -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(buff_readline())
def read_int_n():
return list(map(int, buff_readline().split()))
def re... |
"You must lift the dam. With a lever. I will give it to you.
You must block the canal. With a rock. I will not give the rock to you."
Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone... | 3 | import sys
import os
from io import BytesIO, IOBase
#########################
# imgur.com/Pkt7iIf.png #
#########################
# def cel(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): ret... |
A new school in Byteland is now in the process of renewing some classrooms with new, stronger and better chairs, so that the students can stay still and pay attention to class :)
However, due to budget and logistic reasons, it's only possible to carry a chair at a time to the classroom, which means that for a long time... | 1 | for case in range(int(raw_input())):
t = int(raw_input())
print pow(2,t,1000000007)-1 |
When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside β not tangerines, but blossoms instead.
"What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone."
"But these blends are at their best, aren't they?" ... | 3 | import sys
import math
import bisect
import itertools
import random
def main():
s = input()
ans = False
for t in itertools.permutations('ABC', 3):
if ''.join(t) in s:
ans = True
if ans:
print('Yes')
else:
print('No')
if __name__ == "__main__":
main()
|
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangle... | 3 | n = int(input())
last = 10**10
flag=0
for i in range(n):
a,b=map(int,input().split())
if max(a,b)<=last :
last=max(a,b)
else:
if min(a,b)<=last:
last=min(a,b)
else:
flag = 1
if flag==1:
print("NO")
else:
print("YES")
|
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())
s=0
for _ in range(n):
a=input().split()
s+=1*(int(a[0])+int(a[1])+int(a[2])>1)
print(s)
|
Given a permutation p of length n, find its subsequence s_1, s_2, β¦, s_k of length at least 2 such that:
* |s_1-s_2|+|s_2-s_3|+β¦+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2.
* Among all such subsequences, choose the one whose length, k, is as small as possible.
If mul... | 3 | t = int(input())
for t1 in range(t):
n = int(input())
p =[int(n1) for n1 in input().split()]
count = 0
# diff_prev =
sub = [p[0]]
while len(p)-1>count:
a = count
if count==0:
diff = p[a+1]-p[a]
sub.append(p[a+1])
if diff>=0:
diff_prev = 'p'
if diff<0:
diff_prev = 'n'
count = count + 1... |
Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β
a_j where a_1, ..., a_n is some sequence of positive integers.
Of course, the girl decided to take it to school with her. But while she was having lunch, hoolig... | 3 | from math import sqrt
def divis(a):
A = [1,a]
for i in range(2,round(sqrt(a)+1)):
if a % i == 0:
A.append(i)
if i**2 != a:
A.append(a // i)
return sorted(A)
def check(x):
B = [x]
for j in range(n):
if A[0][j]!=0:
B... |
Let's call a positive integer composite if it has at least one divisor other than 1 and itself. For example:
* the following numbers are composite: 1024, 4, 6, 9;
* the following numbers are not composite: 13, 1, 2, 3, 37.
You are given a positive integer n. Find two composite integers a,b such that a-b=n.
I... | 3 |
import math
n = int(input())
if n==1:
print(9,8)
else:
f1=0
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
f1=1
break
if f1==1:
print(2*n,n)
else:
print(3*n,2*n)
|
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 3 | if __name__=='__main__':
calories=list(map(int,input().split(' ')))
st=input()
ans=st.count('1')*calories[0]+st.count('2')*calories[1]+st.count('3')*calories[2]+st.count('4')*calories[3]
print(ans) |
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from... | 3 | n=int(input())
a=list(map(int,input().split()))
a=[0]+a+[0]
cost=[]
for x in range(len(a)-1):
cost.append(abs(a[x+1]-a[x]))
S=sum(cost)
change=[]
for y in range(1,n+1):
change.append(abs(a[y+1]-a[y-1])-(cost[y-1]+cost[y]))
for i in range(n):
print(S+change[i])
|
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... | 1 | n = raw_input().split()
a, b = 0, 0
bad = 0
for i in map (int, raw_input().split()):
#print i
if i == 25:
a += 1
elif i == 50:
if a > 0:
a -= 1
b += 1
else:
bad = 1
else:
if b > 0:
b -= 1
if a > 0:
... |
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 int... | 1 | s =raw_input()
a,b = s.split()
print a if a==b else 1
|
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.
He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ... | 3 | lines = int(input())
#0+2x == 10-3y
#x = e - s / a + b
for line in range(lines):
l = list(map(int,input().split()))
s,e,a,b = l[0],l[1],l[2],l[3]
x = (e - s) / (a + b)
if x%2 == 0 or x%2 == 1:
print(int(x))
else:
print(-1)
# string = str(input()).split(" ")
# cou... |
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 | t = input()
len_t = len(t)
string = list()
if len_t % 2 == 0:
for i in range(len_t):
if i % 2 == 0: string.append(t[len_t - 1 - i // 2])
if i % 2 != 0: string.append(t[i // 2 + i % 2 - 1])
else:
for i in range(len_t):
if i % 2 == 0: string.append(t[i // 2])
if i % 2 != 0: string.... |
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.
Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse... | 1 | a = map(int,raw_input().split())
a = map(int,raw_input().split())
b = map(int,raw_input().split())
m = {}
for i in b:
m[i] = 1
for j in a:
try:
do = m[j]
print j,
except:
pass
print |
It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills.
According to the borscht recipe it consists of n ingredients that have to be mixed in propor... | 1 | n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
b = map(int, raw_input().split())
c = min([y2*1.0/y1 for y1,y2 in zip(a, b)])
print min(sum(el*c for el in a), m)
|
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th... | 3 | n = int(input())
a = input()
NrList = [0] * 9
for i in a:
if int(i) == 2:
NrList[2] += 1
elif int(i) == 3:
NrList[3] += 1
elif int(i) == 4:
NrList[2] += 2
NrList[3] += 1
elif int(i) == 5:
NrList[5] += 1
elif int(i) == 6:
NrList[3] += 1
NrLis... |
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.
To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem... | 3 | """
~~ Author : Bhaskar
~~ Dated : 12~06~2020
"""
import sys
from bisect import *
from math import floor, sqrt, ceil, factorial as F, gcd, pi
from itertools import chain, combinations, permutations, accumulate
from collections import Counter, defaultdict, OrderedDict, deque
INT_MAX = sys.maxsize
INT_MIN = -(sys.maxsi... |
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handk... | 1 | n=int(raw_input())
a=[]
k=0
for i in range(n+1):
a.append(" "*((n-k)*2)+" ".join(map(str,[x for x in range(k+1)]+[x for x in range(k-1,-1,-1)])))
k+=1
for i in range(n+1): print a[i]
for i in range(n-1,-1,-1): print a[i] |
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 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 24 22:36:02 2017
@author: Bart
"""
n,m,a = [int(i) for i in input().split()]
print((n//a+(n%a!=0))*(m//a+(m%a!=0)))
|
The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually cal... | 3 | import collections
from statistics import mean
max=0
s=input().split()
n,k=int(s[0]),int(s[1])
a=input().split()
a=[int(i) for i in a]
for i in range(0,n-k+1):
#print(a[i:i+k])
s=sum(a[i:i+k])
m=s/k
#print(s)
if(m>max):
max=m
num=k
for j in range(i+k,n):
s+=a[j]
num+=... |
You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with intege... | 3 | t = int(input())
for i in range(t):
n = int(input())
x = []
y = []
for i in range(n):
temps = input().split()
x.append(int(temps[0]))
y.append(int(temps[1]))
x.sort()
y.sort()
if n % 2 != 0:
print(1)
else:
print((x[n // 2] - x[n // 2 - 1] + 1) * (y... |
"Hey, it's homework time" β thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.
The sequence of n integers is calle... | 3 | # import sys
# sys.stdin = open("F:\\Scripts\\input","r")
# sys.stdout = open("F:\\Scripts\\output","w")
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
n, = I()
l = I()
count = 0
a = [0]*(60000)
for i in l:
if i > n:
count += 1
continue
if not a[i]:
a[i] = 1
else:
count += 1
print(count) |
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... | 3 | def no_characters(word):
return len(set(list(word)))
print("CHAT WITH HER!" if no_characters(input()) % 2 == 0 else "IGNORE HIM!") |
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game Β«Call of Soldiers 3Β».
The game has (m + 1) players and n types of soldiers in total. Players Β«Call of Soldiers 3Β» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each ... | 3 | def xor(a,b):
return bin(a^b).count("1")
n,m,k = map(int,input().split())
l = []
for i in range(m):
l.append(int(input()))
fedor = int(input())
counter = 0
for i in l:
if xor(fedor,i) <=k:
counter+=1
print(counter) |
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...
The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s).
In one move he can choose two consecutive characters s_i and s_{i... | 3 | a=int(input())
for i in range(a):
r=input()
s=input()
ans=[]
count=1
for i in range(1,len(s)):
if(s[i]==s[i-1]):
count+=1
else:
ans.append(count)
count=1
ans.append(count)
if(s[0]=='0'):
if(len(ans)<=2):
print(s)
... |
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... | 3 | s = input();
count1 = 0;
count2 = 0;
flag = 0;
for i in range(0, len(s)):
if(s[i] == '1'):
count1 += 1;
count2 = 0;
if(count1 == 7):
print("YES");
flag = 1;
break;
else:
count2 += 1;
count1 = 0;
if(count2 == 7):
prin... |
Can you imagine our life if we removed all zeros from it? For sure we will have many problems.
In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a... | 3 | a=int(input())
b=int(input())
c=str(a+b)
res=""
for i in range(len(c)):
if c[i]!='0':
res+=c[i]
res=int(res)
x=""
a=str(a)
for i in range(len(a)):
if a[i]!='0':
x+=a[i]
x=int(x)
b=str(b)
y=""
for i in range(len(b)):
if b[i]!='0':
y+=b[i]
y=int(y)
if res==x+y:
print("YES")
else:
... |
There is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downward... | 1 | #!/usr/bin/env python
from fractions import gcd
raw_input()
l = map(int,raw_input().split())
for n in l:
print (4*n/gcd(4*n,n+1))+1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.