problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of ... | 1 | n,m=map(int,raw_input().split())
lst1=[]
lst2=[]
for i in range(0,n):
lst1.append(raw_input().split())
for i in range(0,m):
a,b=raw_input().split()
for j in range(0,n):
if lst1[j][1]+";"==b:
print a,b,"#"+str(lst1[j][0])
|
You are given a multiset (i. e. a set that can contain multiple equal integers) containing 2n integers. Determine if you can split it into exactly n pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i. e. when divided by 2, the remainder is 1).
Input
The... | 1 | import sys
import os
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
f = sys.stdin
line = lambda: f.readline().strip('\r\n').split()
def solve():
even = 0
odd = 0
for i in range(N):
if A[i]%2 == 0:
even += 1
else:
odd += 1
... |
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 1 | def solve():
word = raw_input()
first_lower = word[0].islower()
one_letter = len(word) == 1
all_other_upper = (one_letter or word[1:].isupper())
if one_letter or (first_lower and all_other_upper) or (not first_lower and all_other_upper): print word.swapcase()
else: print word
solve() |
You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive).
In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content?
Here the subsequence of A is a sequence obtained by removing zero or ... | 3 | N,M = map(int, input().split())
Ss = list(map(int, input().split()))
Ts = list(map(int, input().split()))
mod = 10**9 + 7
x = 2160
dp = [[0]*x for i in range(x)]
for i in range(N):
for j in range(M):
if Ss[i] == Ts[j]:
dp[i+1][j+1] = (dp[i][j+1] + dp[i+1][j] + 1) % mod
else:
... |
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... | 1 |
def _count(k, w):
return k * w * (w + 1) / 2
if __name__ == '__main__':
_in = raw_input()
k, n, w = map(int, _in.split())
N = _count(k, w)
if N > n:
print N -n
else:
print 0
|
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:
* f(0) = a;
* f(1) = b;
* f(n) = f(n-1) ⊕ f(n-2) when n > 1, where ⊕ de... | 3 | for _ in range(int(input())):
a,b,n=map(int,input().split())
x=[a,b,a^b]
print(x[n%3])
|
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 | str1 = input()
str2 = input()
ascii1 = str1.lower()
ascii2 = str2.lower()
# ascii1 = 0
# ascii2 = 0
# for i in str1low:
# ascii1+=ord(i)
# for i in str2low:
# ascii2+=ord(i)
if(ascii1==ascii2):
print(0)
elif(ascii1<ascii2):
print(-1)
else:
print(1)
|
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i.
You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.
You want... | 3 | for _ in range(int(input())):
a = int(input())
b = [int(i) for i in input().split()]
res = max(b) - min(b)
b.sort()
for i in range(a - 1):
if b[i + 1] - b[i] < res:
res = b[i + 1] - b[i]
print(res) |
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 | import sys
def input():
return sys.stdin.readline()[:-1]
t = int(input())
for _ in range(t):
n = int(input())
if n < 4:
print(-1)
continue
ans = list(range(n-4, 0, -2))[::-1] + [n-2, n, n-3, n-1] + list(range(n-5, 0, -2))
print(*ans) |
As we all know that power sets of any set are formed by taking i elements (where i is from 1 to n) and then random shuffling them like this power set of {1,2,3} are {EMPTY SET},{1},{2},{3},{1,2}{1,3}{2,3}{1,2,3} .
Now we have a MODIfied POWER SET which contains only those subsets which have consecutive elements from s... | 1 | for i in range(0,input()):
b=raw_input()
b=''.join(set(b))
ll=[]
for k in range(0,len(b)):
for j in range(0,len(b)-k+1):
m=b[k:j+k]
if m not in ll:
ll.append(b[k:j+k])
print len(ll)-1 |
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 | # Whatever the mind of man can conceive and believe, it can achieve. Napoleon Hill
# by : Blue Edge - Create some chaos
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
i=0
while i<n-1:
if abs(a[i]-a[i+1])>=2:
print("YES")
# print(2)
... |
Solve the Mystery.
Input Format:
First line contains integer T denoting number of test cases.
Next T lines contains sentences, one in each line.
Output Format:
Print output of each test case on individual line.
Constraints:
1 ≤ T ≤ 100
1 ≤ length of sentence ≤ 100
Each sentence contains characters from this set {a-z... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
k="qwertyuiopasdfghjklzxcvbnm"
t=input()
while t>0:
t-=1
sl=raw_input()
x=""
for i in sl:
if i==" ":
x+=" "
else:
x+=k[ord(i)-97]
print x |
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 | a = input().strip('{}')
if a == "":
print('0')
else:
b = list(a.split(", "))
print(len(set(b))) |
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) — "ab" and (2, 3) — "ba". Letters 'a' and 'z' aren't considered neighbou... | 3 | from collections import Counter
def solve(s):
c = Counter(s)
a = sorted(c.keys())
n = len(a)
if n == 3 and ord(a[0]) + 1 == ord(a[1]):
a.reverse()
res = []
for i in range(n):
if i % 2 == 0:
ch = a[n // 2 + i // 2]
else:
ch = a[i // 2]
res... |
Is there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras.
Inspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now ... | 3 | s=input()
i=1
n=len(s)
ans=0
curr=1
while i<n:
if s[i]!=s[i-1]:
curr+=1
else:
ans=max(ans,curr)
curr=1
i+=1
ans=max(ans,curr)
i=1
new=0
while i<n and s[i]!=s[i-1]:
i+=1
j=n-2
l=1
if s[0]!=s[-1]:
while j>=i and s[j]!=s[j+1]:
j-=1
l+=1
if ans!=n and s[0]!=s[-1]:... |
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strin... | 3 | s=input()
L=s.split(" ")
la=int(L[0])
lb=int(L[1])
lc=int(L[2])
if (la==lb):
res=0
else:
res=1
print (2*int(lc)+2*min(la,lb)+res)
|
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 | n = int(input())
a = [0,0,0,0]
for i in range(1,4):
a[i] = list(map(int, input().split()))
a[i] = [0]+a[i]
for i in range(1,n+1):
if i == 1:
print(int(0.01+(a[1][2]*a[1][3]/a[2][3])**(0.5)), end=' ')
elif i == 2:
print(int(0.01+(a[1][2]*a[2][3]/a[1][3])**(0.5)), end=' ')
else:
... |
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | 3 | n=int(input())
a=input()
a=a.lower()
ans=set(a)
if len(ans)==26:
print("YES")
else:
print("NO") |
There are three airports A, B and C, and flights between each pair of airports in both directions.
A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.
Consider a route where we start at one of th... | 3 | P,Q,R = map(int,input().split(" "))
print(min(P+Q,P+R,Q+R))
|
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.
For example, tripl... | 3 | n = int(input())
if n < 3:
print(-1)
elif n % 4 == 0:
print(n//4*3, n//4*5)
else:
k = 2 if n&1 == 0 else 1
n //= k
b, c = n**2//2, n**2//2+1
print(b*k, c*k) |
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in this order).
She will fly to the first town she visits, and fly back from the last town she visi... | 3 | from itertools import*
n,m,R=map(int,input().split())
r=map(int,input().split())
d=[[10**18]*n for _ in range(n)]
for i in range(m):
a,b,c=map(int,input().split())
d[a-1][b-1]=c
d[b-1][a-1]=c
for i in range(n):
d[i][i]=0
for k in range(n):
for i in range(n):
for j in range(n):
d[... |
To become the king of Codeforces, Kuroni has to solve the following problem.
He is given n numbers a_1, a_2, ..., a_n. Help Kuroni to calculate ∏_{1≤ i<j≤ n} |a_i - a_j|. As result can be very big, output it modulo m.
If you are not familiar with short notation, ∏_{1≤ i<j≤ n} |a_i - a_j| is equal to |a_1 - a_2|⋅|a_1 ... | 3 | import sys
import math
from collections import defaultdict,Counter
input=sys.stdin.readline
def print(x):
sys.stdout.write(str(x)+"\n")
# sys.stdout=open("CP1/output.txt",'w')
# sys.stdin=open("CP1/input.txt",'r')
# m=pow(10,9)+7
n,m=map(int,input().split())
a=list(map(int,input().split()))
if n>m:
print(0)
... |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 1 | n=input()
s=""
for i in range(n):
if not i % 2:
s += "I hate "
else:
s += "I love "
if i != n-1:
s+= "that "
else:
s+= "it"
print s |
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | 3 | n = int(input())
for i in range(n):
s = list(input())
k = [s[0],s[1]]
for j in range(2,len(s)):
if j %2 !=0:
k.append(s[j])
for elem in k:
print(elem,end='')
print()
|
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | n = int(input())
l = list(map(int, input().split()))
er = 0
for i in l:
if i == 1:
print('HARD')
er = 1
break
if er == 0:
print('EASY') |
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point ... | 3 | for i in range (int(input())):
n,k=map(int,input().split())
if k>n:
print(k-n)
elif ((n+k)//2)*2==n+k:
print(0)
else:
print(1)
|
You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that:
* No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in t... | 3 | q = int(input())
out = []
for i in range(q):
n = int(input())
a = sorted(map(int, input().split()))
comands = 1
for i in range(len(a) - 1):
if abs(a[i] - a[i + 1]) == 1:
comands = 2
out.append(str(comands))
print('\n'.join(out)) |
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.
You have to find the minimum number of digits in which these two numbers c... | 3 | k=int(input())
n=input()
sum=0
for i in n:
sum+=int(i)
cnt=0
n=sorted(n)
i=0
while(k>sum):
if n[i]!='9':
sum+=(9 - int(n[i]))
cnt+=1
i+=1
print(cnt) |
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 | for _ in range(int(input())):
n,m=map(int,input().split())
matrix=[]
for i in range(n):
matrix.append(['B']*m)
matrix[n-1][m-1]='W'
for i in range(n):
for j in range(m):
print(matrix[i][j],end='')
print()
|
You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.
Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2,... | 3 | n = int(input())
a = [int(input()) for _ in range(n)]
maxv = -10000000000
minv = a[0]
for i in range(1,n):
maxv = max(maxv,a[i] - minv)
minv = min(minv,a[i])
print(maxv)
|
Sonya was unable to think of a story for this problem, so here comes the formal description.
You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operati... | 3 | N=int(input())
s=list(map(int,input().split()))
for i in range(N):s[i]-=i
X=sorted(s)
dp=[0]*N
for i in s:
mi = 7e77
for j in range(N):
mi = min(mi, dp[j])
dp[j] = mi + abs(i-X[j])
print(min(dp)) |
Write a program which print coordinates $(x_i, y_i)$ of given $n$ points on the plane by the following criteria.
1. first by $x$-coordinate
2. in case of a tie, by $y$-coordinate
Constraints
* $1 \leq n \leq 100,000$
* $-1,000,000,000 \leq x_i, y_i \leq 1,000,000,000$
Input
The input is given in the following form... | 3 | # AOJ ITP2_5_A: Sorting Pairs
# Python3 2018.6.24 bal4u
ps = []
n = int(input())
for i in range(n):
x, y = map(int, input().split())
ps.append((x, y))
a = sorted(ps, key=lambda x:(x[0], x[1]))
for i in range(n): print(*a[i])
|
There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.
First, Snuke will arrange the N balls in a row from left to right.
Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive ... | 3 | from math import factorial
n,k=[int(_) for _ in input().split()]
mod=10**9+7
c=0
for i in range(1,min(n-k+2,k+1)):
print((factorial(k-1)//factorial(i-1)//factorial(k-i))*(factorial(n-k+1)//factorial(i)//factorial(n-k-i+1))%mod)
c+=1
for i in range(k-c):print(0) |
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin.
For every pair of soldiers one of them should get a badge with strictly higher factor than the secon... | 3 | n = input()
n = int(n)
badges = input()
badges = badges.split()
badges = [int(b) for b in badges]
badges.sort()
total_cost = 0
alternatives = [False for i in range(2 * n)]
badge = badges[0]
for i in range(n):
if badge < badges[i]:
badge = badges[i]
if alternatives[badge] == False:
alternatives[b... |
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | def check(x,y,z):
a = x
if a > z:
return 'NO'
elif a==z:
c=1
elif z>a:
c=z
if c>y :
return 'NO'
elif c==y:
b=1
elif c<y:
b=y
if b>x:
return 'NO'
elif b==x:
a=x
elif b<x:
a=x
l=[a,b,c]
return l
for i i... |
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw n squares in the snow with a side length of 1. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length 1, parallel to the coordinate axes, with ve... | 3 | n = int(input())
if n == 1:
print(2)
elif n == 2:
print(3)
else:
i = 1
while i * i <= n:
i += 1
i -= 1
if n == i * i:
print(2 * i)
elif n <= (i * i) + i:
print((2 * i) + 1)
else:
print((2 * i) + 2)
|
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the... | 3 | for _ in range(int(input())):
m,s,k=list(map(int,input().split()))
print((m+s+k)//2) |
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.
The tree looks like a polyline on the plane, consisting o... | 3 | n=int(input())
l=list(map(int,input().split()))
l.sort()
i=0
j=n-1
s=0
x=0
y=0
while(True):
if(s%2==1):
y=y+l[i]
i=i+1
if(s%2==0):
x=x+l[j]
j=j-1
s=s+1
if(i>j):
break
print(x**2+y**2)
|
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
qwertyuiop
asdfghjkl;
zxcvbnm,./
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move... | 1 | from itertools import *
from collections import *
from operator import *
from bisect import *
from fractions import *
Ii = lambda: map(int, raw_input().split())
Is = lambda: raw_input().split()
ri = raw_input
right,left = dict(),dict()
keyboard = ['qwertyuiop','asdfghjkl;','zxcvbnm,./']
for row in keyboar... |
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 | for _ in range(int(input())):
n=int(input())
s=input()
l=[]
j=[]
for i in s:
l.append(i)
j.append(i)
j.sort()
if l==j:
print(s)
continue
if s.count('1')==n:
print(s)
elif s.count('0')==n:
print(s)
else:
f1=s.index('1')
... |
The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.
The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppe... | 3 | GI = lambda: int(input()); GIS = lambda: map(int, input().split()); LGIS = lambda: list(GIS())
from math import sqrt
def main():
p, y = GIS()
for x in range(y, p, -1):
for d in range(2, min(p, int(sqrt(x))) + 1):
if not x % d:
break
else:
return x
return -1
print(main())
|
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 | # for _ in range(1):
for _ in range(int(input())):
n, m = map(int, input().split())
flag = 0
for i in range(n):
a, b = map(int, input().split())
c, d = map(int, input().split())
if b == c:
flag = 1
if m % 2 == 1:
flag = 0
if flag:
print('YES')
... |
Input Format
N K
a_1 a_2 a_3 ... a_N
Output Format
Print the minimum cost in one line. In the end put a line break.
Constraints
* 1 ≤ K ≤ N ≤ 15
* 1 ≤ a_i ≤ 10^9
Scoring
Subtask 1 [120 points]
* N = K
Subtask 2 [90 points]
* N ≤ 5
* a_i ≤ 7
Subtask 3 [140 points]
* There are no additional constraint... | 3 | import itertools
import copy
N, K = map(int, input().split())
A =list(map(int, input().split()))
ans=10**15
for c in itertools.product([0,1],repeat=N):
a=copy.deepcopy(A)
sm=0
for i in range(1,N):
if c[i]==1:
if a[i]<=max(a[:i]):
sm+=max(a[:i])-a[i]+1
a[i]... |
You are given integers A and B, each between 1 and 3 (inclusive).
Determine if there is an integer C between 1 and 3 (inclusive) such that A \times B \times C is an odd number.
Constraints
* All values in input are integers.
* 1 \leq A, B \leq 3
Input
Input is given from Standard Input in the following format:
A... | 3 | A,B=map(int,input().split())
if(A*B%2):
print("Yes")
else:
print("No") |
Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought n integers, now it's time to distribute them between his friends rationally...
Lee has n integers a_1, a_2, …, a_n in his backpack and he has k friends. Lee would like to distribute all integers in his backpack betwe... | 3 | t=int(input())
for i in range(t):
n,k=map(int,input().split())
b=list(map(int,input().split()))
w=list(map(int,input().split()))
b.sort(reverse=True)
w.sort()
ans=sum(b[:k])
c=b[k:]
j=0
p=0
while(j<k):
if w[j]==1:
ans+=b[j]
else:
ans+=c[p+w... |
One day n students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people.
We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student A is an archenemy to student B, then student B ... | 3 | from collections import defaultdict
from collections import deque
class graph:
def __init__(self,V):
self.nodes = defaultdict(list)
self.V = V
self.edges = []
def addEdge(self,u,v):
self.nodes[u].append(v)
self.nodes[v].append(u) #for undirected
def isbipartite(s... |
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 | stri = input()
lst = stri.split()
n = int(lst[0])
m = int(lst[1])
a = int(lst[2])
cc = n / a
c = m / a
if (cc - int(cc)) != 0:
cc += 1
if (c - int(c)) != 0:
c += 1
print(int(cc) * int(c)) |
N programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most 9 contestants can participate in the finals.
The preliminary stage consists of several rounds, which will take place as follows:
* All the N contestants will participate in the first round.
* W... | 3 | M = int(input())
digit = 0
sum = 0
for _ in range(M):
d, c = map(int, input().split())
digit += c
sum += d * c
print(digit - (-(sum - 9) // 9) - 1) |
You have array a1, a2, ..., an. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 ≤ i ≤ r).
Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]).
Your task is to find a ... | 3 | n= int(input())
l= list(map(int, input().split()))
ans=2
if n<3:
ans=n
x=2
t=2
while x<n:
if l[x-1]+l[x-2]==l[x]:
t+=1
ans=max(ans,t)
else:
t=2
x+=1
print(ans) |
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input
The first line cont... | 3 | n=int(input())
x=list(map(int,input().split()))
y=[]
y.append(x[0])
k=1
for i in range(1,len(x)):
if x[i-1]<x[i]:
y.append(x[i])
k=max(k,len(y))
else:
y=[]
y.append(x[i])
k=max(k,len(y))
print(k)
|
This problem is actually a subproblem of problem G from the same contest.
There are n candies in a candy box. The type of the i-th candy is a_i (1 ≤ a_i ≤ n).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all di... | 3 | q = int(input())
for j in range(q):
n = int(input())
a = list(map(int, input().split()))
counter = [0] * (n + 1)
for i in range(n):
counter[a[i]] += 1
counter = sorted(counter)
#print(counter)
ans = counter[n]
count = counter[n]
for i in range(n - 1, ... |
Argus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io.
There are n trees growing along the river, where Argus tends Io. For this problem, the river ca... | 3 | ''' 1466a Bovine Dilemma '''
for _ in range(int(input())):
_,x = input(),[*map(int,input().split())]
print(len(set(j - i for i in x[:-1] for j in x[x.index(i)+1:])))
|
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 | import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
# from itertools import permutations,combinations
def data():... |
Find the largest square number not exceeding N. Here, a square number is an integer that can be represented as the square of an integer.
Constraints
* 1 \leq N \leq 10^9
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the largest square number not exceeding N... | 3 | print(int((int(input()))**0.5)**2) |
On a strip of land of length n there are k air conditioners: the i-th air conditioner is placed in cell a_i (1 ≤ a_i ≤ n). Two or more air conditioners cannot be placed in the same cell (i.e. all a_i are distinct).
Each air conditioner is characterized by one parameter: temperature. The i-th air conditioner is set to ... | 3 | import os
import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict,Counter
from bisect import bisect_left as bl, bisect_right as br
from itertools import combinations
sys.setrecursionlimit(100000000)
int_inp = lambda: int(input()) #... |
Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia.
For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs n actions. The first action performed is to put a single candy into the box. For each of the remainin... | 3 | import sys
strInp = lambda : input().strip().split()
intInp = lambda : list(map(int,strInp()))
n , k = intInp()
candy = 1
achived = 0
for i in range(1,n+1):
achived += candy
if(achived - (n - i) == k):
print(n-i)
break
candy += 1
|
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first... | 1 | from sys import stdin,stderr
from collections import defaultdict,deque
def main():
n,x=map(int,stdin.readline().strip().split())
X=x-1
graph=[[] for i in range(n)]
for i in range(n):
graph[i]=[]
for _ in range(n-1):
a,b=map(int,stdin.readline().strip().split())
#a,b=a-1,b-1
... |
Mislove had an array a_1, a_2, ⋅⋅⋅, a_n of n positive integers, but he has lost it. He only remembers the following facts about it:
* The number of different numbers in the array is not less than l and is not greater than r;
* For each array's element a_i either a_i = 1 or a_i is even and there is a number (a_i)/(... | 3 | n, l, r = map(int, input().split())
max_sum = 0
curr = 1
for i in range(r):
max_sum += curr
curr *= 2
curr//=2
max_sum += (n-r)*curr
min_sum = 0
curr = 1
for i in range(l):
min_sum += curr
curr *= 2
min_sum += (n-l)
print(str(min_sum) + " " + str(max_sum)) |
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... | 3 | w = input()
if int(w)<4:
print('NO')
elif int(w)%2 == 1:
print('NO')
else:
print('YES') |
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.
Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ... | 3 | from collections import deque as dq
n = int(input())
l = list(map(int,input().split()))
l.sort()
l = dq(l)
r = []
while l:
r.append(l.pop())
if len(l)>0:
r.append(l.popleft())
if n%2==0:
print((n//2)-1)
print(*r)
else:
print(n//2)
print(*r) |
There is a building with n rooms, numbered 1 to n.
We can move from any room to any other room in the building.
Let us call the following event a move: a person in some room i goes to another room j~ (i \neq j).
Initially, there was one person in each room in the building.
After that, we know that there were exactl... | 3 | mod=10**9+7
n,k=map(int,input().split())
ans=0
comb1=1 #初期値はNC0=1
comb2=1 #初期値は(N-1)C0=1
for i in range(min(k+1,n)): #0人の部屋は高々N-1個しか存在しないので操作回数は高々min(K,N-1)回となる
ans+=comb1*comb2 #0人の部屋がi個のときの場合の数はNCi*(N-1)Ci
ans%=mod
comb1*=(n-i)*pow(i+1,mod-2,mod) #NC(i+1)はNCi*(N-i)/(i+1)で求められる
comb1%=mod
comb2*=(n-1-i)*pow(i+1,m... |
You are given three bags. Each bag contains a non-empty multiset of numbers. You can perform a number of operations on these bags. In one operation, you can choose any two non-empty bags, and choose one number from each of the bags. Let's say that you choose number a from the first bag and number b from the second bag.... | 3 | input()
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=list(map(int,input().split()))
ma=min(a);mb=min(b);mc=min(c);
print(sum(a)+sum(b)+sum(c)-min(ma+mb,ma+mc,mb+mc,sum(a),sum(b),sum(c))*2) |
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.
To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor ea... | 1 | #[int(k) for k in raw_input().split(" ")]
o=raw_input()
i=raw_input()
so=sorted(o)
si=sorted(i,reverse=True)
res=[None]*len(o)
n=len(o)
k=0
lefti=n/2
lefto=n-lefti
ke=lefto-1
ki=0
kei=lefti-1
who=1
j=0
je=n-1
while j<=je:
if who:
if so[k]<si[ki]: #Your best beats his best
res[j]=so[k]
... |
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | 3 | def gt():
return list(map(int, input().split()))
t ,= gt()
while t:
t -= 1
n, x = gt()
print((n-2+x-1)//x + 1 if n>2 else 1)
|
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... | 1 | #-*-coding:utf-8-*-
import string
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# w개의 바나나를 구매
# 첫 바나나 k 달러, 다음 바나나 2*k달러.....(i*k달러)
# n달러를 가지고 있음
# 얼마를 더 빌려야 w개의 바나나를 구매할 수 있는가?
num = raw_input()
# n[0] = k n[1] = n n[2] = w
n = num.split()
# 바나나의 총가격을 구한뒤, 원래 가지고 있는 액수를 뺌
sum = 0
for i in range(... |
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 ≤ k ≤ r, and set k days as the number of days in a week.
Alice is going to paint some n... | 3 | for test in range(int(input())):
n, r = map(int, input().split())
if r >= n:
ans = 1
r = n - 1
else:
ans = 0
if r % 2 == 0:
ans += r // 2
ans += (r + 1) // 2 * r
print(ans) |
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.... | 1 | for i in range(5):
c = map(int, raw_input().split())
for j in range(5):
if c[j] == 1:
s = abs(j-2) + abs(i-2)
print s
|
One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of ... | 1 | rain = "miao."
fred = "lala."
n = input()
for i in xrange(n):
s = raw_input()
head = ""
tail = ""
if len(s) >= 5:
head = s[:5]
tail = s[len(s)-5:]
if head == rain and tail != fred:
print "Rainbow's"
elif head != rain and tail == fred:
print "Freda's"
else:
... |
According to a new ISO standard, a flag of every country should have, strangely enough, a chequered field n × m, each square should be wholly painted one of 26 colours. The following restrictions are set:
* In each row at most two different colours can be used.
* No two adjacent squares can be painted the same c... | 1 | import itertools
n,m = map(int,raw_input().split())
flag = [raw_input() for i in range(n)]
alpha = "abcdefghijklmnopqrstuvwxyz"
col = [x[0]+x[1] for x in itertools.permutations(alpha,2)]
cn = len(col)
paint = [[0]*cn for i in range(n+1)]
prev = [[0]*cn for i in range(n+1)]
for y in range(n):
tmp = sorted([(paint[... |
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | 1 |
# region smaller_fastio
from sys import stdin,stdout
from os import path
if (path.exists('input.txt')):
#------------------Sublime--------------------------------------#
stdin=open('input.txt','r');stdout=open('output.txt','w');
def I():return (int(input()))
def In():return(map(int,input().split()))... |
CodeswarBala found various ornaments in Btyeland. Each ornament is made up of various items, and each item is represented by a letter from 'a' to 'z'. An item can be present multiple times in a ornament . An item is called special item if it occurs at least once in each of the ornament.
Given the list of N ornaments... | 1 | dicts = {}
nos = input()
for _ in range(nos):
ins = set(list(raw_input()))
for k in ins:
if dicts.has_key(k):
dicts[k] +=1
else:
dicts[k] = 1
cnt = 0
for i, v in dicts.items():
if v == nos:
cnt += 1
print cnt |
Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.
The President of Berland decided to make changes to the road sy... | 3 | from sys import setrecursionlimit
setrecursionlimit(110000)
def main():
n, m = map(int, input().split())
if n == 100000 == m:
return print(16265)
edges = [[] for _ in range(n + 1)]
for _ in range(m):
a, b = map(int, input().split())
edges[a].append(b)
edges[b].append(a... |
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"... | 3 | Base = "HQ9"
String = input()
success = False
for letter in Base:
if letter in String:
print("YES")
success = True
break
if not success: print("NO") |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | str1=input()
str1=str1.lower()
list1=['h','e','l','l','o']
a=0
b=4
for x in str1:
if a>b:
break
if x==list1[a] :
a+=1
if a>b:
print("YES")
else:
print("NO")
|
Given two integers n and x, construct an array that satisfies the following conditions:
* for any element a_i in the array, 1 ≤ a_i<2^n;
* there is no non-empty subsegment with [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) equal to 0 or x,
* its length l should be maximized.
A sequenc... | 3 | from sys import stdout
n,x=list(map(int,input().split()))
t=pow(2,n)
if x>=t:
print(t-1)
for i in range(1,t):
stdout.write(str(i^(i-1))+ ' ')
exit(0)
ans=[0]*(pow(2,n))
ans[x]=-1
for i in range(1,len(ans)):
if ans[i]!=-1:
ans[x^i]=-1
last=0
print(pow(2,n-1)-1)
for i in range(1,len(an... |
Nothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards...
There are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can b... | 1 | l=lambda:map(int,raw_input().split())
n=input()
for i in range(1,5):
a, b, c, d = l()
x=min(a,b)
y=min(c,d)
if n>=x+y:
print i,x,n-x
exit()
print -1 |
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n ... | 3 | input()
a = list(map(int, input().split()))
x = min(a)
r = 10 ** 9
ans = 10 ** 9
go = False
for i in a:
if (i == x):
ans = min(ans, r)
r = 0
go = True
r += int(go)
print(ans) |
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 | def reverse(s):
str=""
for i in s :
str=i+str
return str
print(["NO","YES"][input()==reverse(input())])
|
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | word=input()
if(word[0].islower()):
print(word[0].upper()+word[1:])
else:
print(word)
|
You are given an array of n integers: a_1, a_2, …, a_n. Your task is to find some non-zero integer d (-10^3 ≤ d ≤ 10^3) such that, after each number in the array is divided by d, the number of positive numbers that are presented in the array is greater than or equal to half of the array size (i.e., at least ⌈n/2⌉). Not... | 3 | m=int(input())
a=list(map(int,input().split()))
n=0
p=0
for i in a:
if i>0:
p=p+1
if i<0:
n+=1
if p>=(m+1)//2:
print (1)
elif n>=(m+1)//2:
print(-1)
else:
print(0) |
You have unlimited number of coins with values 1, 2, …, n. You want to select some set of coins having the total value of S.
It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S?
Input
The only line of the input contains two integers n and S ... | 3 | n,s = [int(x) for x in input().split()]
used = s//n
if s%n!=0:
used+=1
print(used) |
— Hey folks, how do you like this problem?
— That'll do it.
BThero is a powerful magician. He has got n piles of candies, the i-th pile initially contains a_i candies. BThero can cast a copy-paste spell as follows:
1. He chooses two piles (i, j) such that 1 ≤ i, j ≤ n and i ≠ j.
2. All candies from pile i are... | 3 | for i in range(int(input())):
n,k=map(int,input().split())
a=[int(i) for i in input().split()]
a=sorted(a)
c=0
x=a[0]
i=1
while i!=n:
if a[i]+x<=k:
a[i]=x+a[i]
c+=1
else:
i+=1
print(c) |
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 1 | ans, p = 0, 0
for _ in xrange(int(raw_input())):
x, y = map(int, raw_input().split())
p += (y-x)
ans = max(ans, p)
print ans |
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | word_list = list(input())
word_list[0] = word_list[0].capitalize()
holder = ''
print(holder.join(word_list)) |
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 | a,b = map(int,input().split())
c = []
k = 0
e = ["G","W","B"]
f = ["C","M","Y"]
for i in range(a):
d = list(map(str,input().split()))
c.append(d)
for i in range(a):
for j in range(b):
if c[i][j] in f:
k += 1
if k >= 1:
break
if k >= 1:
print("#Color")
else... |
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())
cupes = [int(i) for i in input().split()]
cupes.sort()
print(*cupes)
|
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... | 3 | w = (int)(input())
if w % 2 == 0 and w != 2:
print("YES")
else:
print("NO")
|
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues.
On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on th... | 1 | d = {"00":"01", "01":"02", "02":"03", "03":"04", "04":"05", "05":"10",
"10":"11", "11":"12", "12":"13", "13":"14", "14":"15", "15":"20",
"20":"21", "21":"22", "22":"23", "23":"00"}
d1 = {"06":"10", "07":"10", "08":"10", "09":"10",
"16":"20", "17":"20", "18":"20", "19":"20"}
h, m = raw_input().split(":")... |
Ksusha is a beginner coder. Today she starts studying arrays. She has array a1, a2, ..., an, consisting of n positive integers.
Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!
Input
The first line contains integer n (1 ... | 3 | n=int(input())
L=[int(x) for x in input().split()]
L.sort()
x=L[0]
f=0
for i in L:
if(i%x!=0):
f=1
break
if(f==0):
print(x)
else:
print(-1) |
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=['0','0']
m=input().split()
m[0]=int(m[0])
m[1]=int(m[1])
if(m[0]>0 and m[1]>0 and m[0]<17 and m[0]<=m[1]):
print((m[0]*m[1])//2)
|
You are given an array a consisting of n integers.
In one move, you can choose two indices 1 ≤ i, j ≤ n such that i ≠ j and set a_i := a_j. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. yo... | 3 | testcases = int(input())
for t in range(testcases):
ans = 0
n = int(input())
odd = 0
even = 0
l = list(map(int,input().split()))
for i in range(n):
if l[i]%2==1:
odd+=1
else:
even+=1
if odd>=1 and even==0 and n%2==0:
ans = 'NO'
elif even>=1 and odd==0:
ans = 'NO'
else:
... |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | n=input()
n=n.split(' ')
a=int(n[0])
b=int(n[-1])
count=0
while a<=b:
count+=1
a=a*3
b=b*2
print(count)
|
There are H rows and W columns of white square cells.
You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.
How many white cells will remain?
It can be proved that this count does not depend on what rows and columns are chosen.
Constraints
* All values i... | 1 | H,W=map(int,raw_input().split())
h,w=map(int,raw_input().split())
#print H,W,h,w
print (H-h) * (W-w)
|
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 | def main():
s = input()
if '0000000' in s or '1111111' in s:
print('YES')
else:
print('NO')
if __name__ == '__main__':
main()
|
You are given an array a of n integers.
You want to make all elements of a equal to zero by doing the following operation exactly three times:
* Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different).
It can... | 3 | n = int(input())
a = list(map(int,input().split()))
if n != 1:
print("1 1")
print(str((n-1) * a[0]))
print("2 " + str(n))
print(" ".join(map(lambda x:str((n-1) * x),a[1:])))
print("1 " + str(n))
print(" ".join(map(lambda x:str(-n * x),a)))
else:
print("1 1")
print(0)
print("1 1")
print(0)
print("... |
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | n = input()
if n == n.upper():
print(n.lower())
elif n[1:]==n[1:].upper():
print(n.title())
else :
print(n) |
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.
There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficulty — it'... | 1 | R=lambda : map(int, raw_input().split())
n,c=R()
p=R()
t=R()
a=s=0
for i in range(n):
s+=t[i]
a+=max(0,p[i]-s*c);
b=s=0
for i in range(n):
s+=t[n-i-1]
b+=max(0,p[n-i-1]-s*c);
if a>b:print 'Limak'
elif a<b: print 'Radewoosh'
else: print 'Tie'
|
A Little Elephant and his friends from the Zoo of Lviv like candies very much.
There are N elephants in the Zoo. The elephant with number K (1 ≤ K ≤ N) will be happy if he receives at least AK candies. There are C candies in all in the Zoo.
The Zoo staff is interested in knowing whether it is possible to make all the... | 1 | n=int(raw_input())
for i in range(n):
k=raw_input().split()
m=map(int,k)
n=m[0]
c=m[1]
a=raw_input().split()
b=map(int,a)
d=sum(b)
if c>=d:
print 'Yes'
else:
print 'No' |
This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.
You are given a binary table of size n × m. This table consists of symbols 0 and 1.
You can make such operat... | 3 | def fun1(xx):
# [[x1,y1],[x2,y2],[x3,y3],[x4,y4]]
global ar,ans,mai
zer=[]
one=[]
for i in xx:
if(ar[i[0]][i[1]]==0):
zer.append([i[0],i[1]])
else:
one.append([i[0],i[1]])
ans+=2
mai.append([])
for i in zer:
mai[-1].append(i[0]+1)
m... |
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that ∑_{i=1}^{n}{∑_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl... | 3 | t = int(input())
for _ in range(t):
n, m = map(int, input().split())
s = sum(map(int, input().split()))
print("YES" if s == m else "NO")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.