problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number <image>, in particular that q2 = q + 1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a no... | 1 | a, b = raw_input(), raw_input()
u, v = 0, 0
n = 100000
a = '0' * (n - len(a)) + a
b = '0' * (n - len(b)) + b
for i in range(n):
u, v = v + u, u + int(a[i]) - int(b[i])
if u > 1 or u < -1: break
if u == v == 0: print '='
else: print '>' if u * 1.118 + v > 0 else '<'
|
Tomorrow Peter has a Biology exam. He does not like this subject much, but d days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than minTimei and not more than maxTimei hours per each i-th day. Moreover, th... | 3 | def main():
from sys import stdin,stdout
n,sumtime=map(int,stdin.readline().split())
a,b=[],[]
for i in range(n):
x,y=map(int,stdin.readline().split())
a.append(x)
b.append(y)
if sum(b)<sumtime or sum(a)>sumtime:
stdout.write('NO')
else:
stdout.write('YES\n')
diff=sumtime-sum(a)
for i in range(n):
... |
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 | a, b = input().split(' ')
a = int(a)
b = int(b)
print(int(a*b/2)) |
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 | # Author Hoang Kim Duc - FPT University Ha Noi Campus
# import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
n = int(input())
a = [int(inp) for inp in input().split()]
a.sort()
i = 0
j = len(a)//2
b = []
sw = 1
while (j < len(a) or i < len(a)//2):
if sw:
b.append(a[j])
... |
Given is a positive integer N. How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?
Constraints
* 2 \leq N \leq 10^6
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer.
Examples
Input
3
Output
3
Input
100
... | 3 | n=int(input())
ans=0
for i in range(1,n):
ans+=-(-n//i)-1
print(ans) |
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ... | 3 | n=int(input())
z=[]
for i in range(n):
x=str(input())
z.append(x)
z1,z2=["NO"],[z[0]]
for i in range(1,n):
if z[i] not in z2:
z1.append("NO")
z2.append(z[i])
else:
z1.append("YES")
z2.append(z[i])
for i in range(len(z1)):
print(z1[i])
|
An adult game master and N children are playing a game on an ice rink. The game consists of K rounds. In the i-th round, the game master announces:
* Form groups consisting of A_i children each!
Then the children who are still in the game form as many groups of A_i children as possible. One child may belong to at m... | 3 | import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
k = int(input())
a = list( map(int, input().split()))
if a[-1]!=2:
print(-1)
exit()
ma = 2
for i in reversed(range(k)):
ma = ma//a[i]*a[i] + (a[i]-1)
if a[i] > ma:
print(-1)
exit()
mi = 2
for i in reversed(range(... |
Reminder: the [median](https://en.wikipedia.org/wiki/Median) of the array [a_1, a_2, ..., a_{2k+1}] of odd number of elements is defined as follows: let [b_1, b_2, ..., b_{2k+1}] be the elements of the array in the sorted order. Then median of this array is equal to b_{k+1}.
There are 2n students, the i-th student has... | 3 | from math import *
t = int(input())
m = []
n = []
for i in range(t):
n.append(int(input()))
x = list(map(int, input().split()))
x.sort()
m.append(x)
for i in range(t):
print(m[i][n[i]]-m[i][n[i]-1]) |
You are given two positive integers A and B. Compare the magnitudes of these numbers.
Constraints
* 1 β€ A, B β€ 10^{100}
* Neither A nor B begins with a `0`.
Input
Input is given from Standard Input in the following format:
A
B
Output
Print `GREATER` if A>B, `LESS` if A<B and `EQUAL` if A=B.
Examples
Input
3... | 3 | x = int(input())-int(input())
if x>0:
print("GREATER")
elif x==0:
print("EQUAL")
else:
print("LESS") |
You're given an array a of length n. You can perform the following operation on it as many times as you want:
* Pick two integers i and j (1 β€ i,j β€ n) such that a_i+a_j is odd, then swap a_i and a_j.
What is lexicographically the smallest array you can obtain?
An array x is [lexicographically smaller](https://... | 3 | import sys
input = lambda: sys.stdin.readline().strip("\r\n")
input()
a = list(map(int, input().split()))
if len(set([x % 2 for x in a])) == 1:
print(*a)
else:
print(*sorted(a))
|
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | n,m,a=map(int,input().split())
if n%a==0:
N=n//a
if m%a==0:
M=m//a
print(N*M)
else :
M=m//a+1
print(N*M)
else :
N=n//a+1
if m%a==0:
M=m//a
print(N*M)
else :
M=m//a+1
print(N*M) |
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,
* ...
... | 1 | n = int(input())
t = raw_input()
c = 1
s = 0
x = ""
while(s <= len(t)):
x = x + t[s]
c = c + 1
s = s + c
print x |
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ... | 3 | def isPrime(num):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
return False
return True
else:
return False
n,m = map(int,input().split())
c=0
for i in range(n+1,m+1):
if isPrime(i):
break
if isPrime(m) and i==m:
print('... |
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... | 1 | '''271a'''
from collections import Counter
n = int(raw_input())+1
while len(Counter(str(n)))<4:
n+=1
print n
|
There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i.
A postman delivers letters. Sometimes there is no specific dormitory and room number in it o... | 3 | n,m=map(int,input().split())
nroom=list(map(int,input().split()))
roomno=list(map(int,input().split()))
lst = []
s = 0
for i in nroom:
s+=i
lst.append(s)
j = 0
for i in range(len(roomno)):
for k in range(j,len(lst)):
if roomno[i]<=lst[k]:
print(*(k+1,roomno[i]-lst[k-1])if k!=0 else (k+1,roomno[i]))
... |
Did you know that there are over 40,000 varieties of Rice in the world ? There are so many dishes that can be prepared with Rice too. A famous chef from Mumbai, Tid Gusto prepared a new dish and named it 'Tid Rice'. He posted the recipe in his newly designed blog for community voting, where a user can plus (+) or minus... | 1 | import sys
import math
def main():
t = int(sys.stdin.readline())
for i in range(0, t):
n = int(sys.stdin.readline())
lastVoteMap = {}
voteCount = 0
for j in range(0, n):
userid, vote = sys.stdin.readline().split()
if userid in lastVoteMap:
if (vote == '+' and lastVoteMap[userid] == '-'):
... |
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... | 1 | n = int(input())
s = str(raw_input())
len = len(s)
a = [None] * 258
for i in range(0,256):
a[i] = 0
for i in range(0,len):
a[ord(s[i])] += 1
F = 0
for i in range(ord("a"),ord("z")+1):
if (a[i] == 0 and a[i-32] == 0):
F = 1
if (F == 0): print("YES")
else: print("NO")
|
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi β a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec... | 3 | # https://codeforces.com/contest/567/problem/A
n = int(input())
coordinates = list(map(int, input().split()))
for i in range(n):
if i == 0:
print(abs(coordinates[i] - coordinates[i + 1]), abs(coordinates[i] - coordinates[-1]))
elif i == n - 1:
print(abs(coordinates[i] - coordinates[i - 1]), ab... |
We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.
We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?
Constraints
* All values in input are integers.
* 0 \leq A, B, C
* 1 \leq K \l... | 3 | a,b,c,k=list(map(int,input().split()))
if k<=a+b:
print(min(a,k))
else:
print(2*a-k+b) |
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
If Va... | 3 | m,n=[int(x) for x in input().split()]
set0 = set()
set1 = set(str(i+1) for i in range(n))
for i in range(m):
set0 = set0|set(input().split()[1:])
print(['YES','NO'][set0 != set1]) |
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 | a,b=map(int,input().split());s=input();print("YNeos"[s[a]!='-' or s.count('-')!=1::2])
|
In Japan, temperature is usually expressed using the Celsius (β) scale. In America, they used the Fahrenheit (β) scale instead. $20$ degrees Celsius is roughly equal to $68$ degrees Fahrenheit. A phrase such as "Todayβs temperature is $68$ degrees" is commonly encountered while you are in America.
A value in Fahrenhei... | 3 | print((int(input())-30)//2)
|
Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square β a prime square.
A square of size n Γ n is called prime if ... | 3 | a = input()
for x in range(int(a)):
b = input()
list1 = [[0 for i in range(int(b))] for i in range(int(b))]
if(int(b)%2==0):
i = 0
j = int(b)-1
for x in range(int(b)):
list1[x][i+x] = 1
list1[x][j-x] = 1
else:
i = 0
j = int(b)-1
for... |
Professor GukiZ makes a new robot. The robot are in the point with coordinates (x1, y1) and should go to the point (x2, y2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps... | 3 | x1,y1=(int(i) for i in input().split())
x2,y2=(int(i) for i in input().split())
print (max(abs(x1-x2),abs(y1-y2))) |
You are given a problemset consisting of n problems. The difficulty of the i-th problem is a_i. It is guaranteed that all difficulties are distinct and are given in the increasing order.
You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to as... | 1 | import sys
n = input()
a = [0 for i in range(n)]
a = map(int, sys.stdin.readline().split())
b = [0 for i in range(n)]
for i in range(n-1):
if 2*a[i]>=a[i+1]:
b[i] = 1
S = 1
SS = 1
for i in b:
if i == 1:
S += 1
if S>SS:
SS = S
else:
S = 1
print SS
|
Input
The input contains a single integer a (0 β€ a β€ 63).
Output
Output a single number.
Examples
Input
2
Output
2
Input
5
Output
24
Input
35
Output
50 | 3 | num=int(input())
add=0
if(num%32<16):
if(num%2==1):
add+=15
else:
if(num%2==0):
add-=15
if(num%16<8):
if(num%8>=4):
add+=4
else:
if(num%8<4):
add-=4
num+=add
print(num)
|
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game...
In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f... | 3 | # It's never too late to start!
from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
from collections import Counter, defaultdict
from collections import deque
from functools import cmp_to_key
import math
import heapq
import re
def sin():
return input()
def ain():
return list(map(... |
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x.
<image>
Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g... | 3 | '''input
817634153013
'''
from sys import stdin
from collections import defaultdict
import sys
sys.setrecursionlimit(15000)
def get_prime():
seive = [True] * (10 ** 6 + 1)
for i in range(2, 10 ** 6 + 1):
if seive[i] == True:
for j in range(i * i, 10 ** 6 + 1, i):
seive[j] = False
prime = []
for i in ra... |
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n Γ m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.
A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of ... | 3 | x, y = map(int, input().split())
l = []
for i in range(x):l.append(list(input()))
f = 0
for i in range(x):
for j in range(y):
if l[i][j] == 'W':
if i + 1 < x and l[i + 1][j] == 'P':f+= 1
elif j + 1 < y and l[i][j + 1] == 'P':f += 1
elif i - 1 >= 0 and l[i - 1][j] == 'P':f... |
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | def iq(n):
o = [int(i) % 2 for i in n.split(" ")]
m=0
if o.count(1) > o.count(0):
m=0
else:
m=1
return o.index(m)+1
s = int(input())
print(iq(input())) |
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 | n = input()
b = list(n)
a = set(n)
# print(b)
# print(a)
count = 0
for i in b:
if i == '7' or i == '4':
count += 1
if count == 7 or count == 4:
print('YES')
else:
print('NO') |
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 | sol = 0
n = int(input())
for i in range(n):
d = input().split()
num = 0
for j in range(3):
if int(d[j]) == 1:
num = num + 1
if num > 1:
sol = sol+1
print(sol)
|
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins.
He wants to distribute all these n coins between his sisters in such a way that ... | 3 | t = int(input())
for _ in range(t):
a, b, c, n = map(int, input().split())
p = (n - (3 * max(a, b, c) - a - b - c))
if p >= 0 and p % 3 == 0:
print('YES')
else:
print('NO')
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 1 | n = input()
for i in range(0,n):
word = raw_input()
letters = list(word)
w_len = len(letters)
if(w_len > 10):
answer = list()
answer.append(letters[0])
answer.append(str(w_len-2))
answer.append(letters[len(letters)-1])
print "".join(answer)
else:
print word |
Vasya has recently got a job as a cashier at a local store. His day at work is L minutes long. Vasya has already memorized n regular customers, the i-th of which comes after t_{i} minutes after the beginning of the day, and his service consumes l_{i} minutes. It is guaranteed that no customer will arrive while Vasya is... | 3 | n,l,a= list(map(int, input().split(" ")))
count,j=0,0
for i in range(n):
x = list(map(int, input().split(" ")))
count+=(x[0]-j)//a
j=x[1]+x[0]
print(count+(l-j)//a)
|
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 | n = int(input())
a = []
f = 0
for i in range(n):
x = input()
a.append(x)
for i in a:
if i == "Tetrahedron":
f += 4
elif i == "Cube":
f += 6
elif i == "Octahedron":
f += 8
elif i == "Dodecahedron":
f += 12
elif i == "Icosahedron":
f += 20
print(f) |
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 | x=int(input())
y=input()
if '1' in y:
print("HARD")
else:
print("EASY")
|
On some day in January 2018, Takaki is writing a document. The document has a column where the current date is written in `yyyy/mm/dd` format. For example, January 23, 2018 should be written as `2018/01/23`.
After finishing the document, she noticed that she had mistakenly wrote `2017` at the beginning of the date col... | 3 | s = str(input())
print("2018"+s[4:])
|
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.
There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki p... | 1 | timeperitem = 5
timepercustomer = 15
n = int(raw_input().strip())
k = map(int, raw_input().split())
mintime = 0
for i in xrange(0, n):
m = map(int, raw_input().split())
tmp = timeperitem * sum(m) + timepercustomer * k[i]
if (i == 0) or ( tmp < mintime):
mintime = tmp
print mintime
|
Reminder: the [median](https://en.wikipedia.org/wiki/Median) of the array [a_1, a_2, ..., a_{2k+1}] of odd number of elements is defined as follows: let [b_1, b_2, ..., b_{2k+1}] be the elements of the array in the sorted order. Then median of this array is equal to b_{k+1}.
There are 2n students, the i-th student has... | 3 | t = int(input())
for case in range(t):
n = int(input())
arr = sorted(list(map(int, input().split())))
print(arr[n] - arr[n - 1]) |
Santa Claus has n candies, he dreams to give them as gifts to children.
What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has.
Input
The only line contains positive integ... | 3 | import sys
import math
import bisect
def solve(n):
A = []
val = 0
for i in range(1, 10000):
if val + i <= n:
A.append(i)
val += i
else:
break
A[-1] += n - sum(A)
return A
def main():
n = int(input())
A = solve(n)
print(len(A))
pri... |
Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. I... | 1 | N = input()
A = map(int,raw_input().split())
temp = 0
q = 0
r = N-1
for i in range(N-1):
if A[i] <= A[r] and q < i:
A[q],A[i] = A[i],A[q]
q += 1
elif A[i] <= A[r]:
q += 1
A[r],A[q] = A[q],A[r]
i = 0
for elem in A:
if i == q:
print("["+str(elem)+"]"),
else:
prin... |
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | 3 | n,m = map(int,input().split())
for j in range(1,n+1):
if j%2!=0:
print('#'*m)
elif j%4==0:
print('#'+('.'*(m-1)))
else:
print(('.'*(m-1))+'#') |
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks.
Determine whether the Cossack can reward all participants, giving each of them at leas... | 3 | # import sys
# sys.stdin=open("input1.in","r")
# sys.stdout=open("output2.out","w")
N,M,K=map(int,input().split())
if M<N or K<N:
print("No")
else:
print("Yes") |
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimu... | 3 | num = int(input())
check = 1
while num > 1:
if num % 2 == 0:
num = num / 2
else:
num = (num - 1)/2
check += 1
print(check)
|
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | n=input()
length=len(n)
n=int(n,2)
m=input()
m=int(m,2)
k=format((n^m),"b")
k=k.zfill(length)
print(k) |
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 β€ m β€ cntn), where cntn... | 1 | n,m=map(int,raw_input().split())
l=[]
ch=[0 for i in xrange(n)]
ans=[]
total=[]
def func(x,ans):
global l,ch,n,m,total
flg=0
for i in xrange(n):
if ch[i]==1:
flg+=1
if flg==n:
tmp=[]
for j in ans:
tmp.append(j)
total.append(tmp)
return
for i in xrange(n):
if ch[i]==0:
flg=1
if len(ans)>... |
Happy new year! The year 2020 is also known as Year Gyeongja (κ²½μλ
, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.
There are two sequences of n strings s_1, s_2, s_3, β¦, s_{n} and m strings t_1, t_2, t_3, β¦, t_{m}. ... | 3 | inp = input().split(" ")
symbols = [input().split(" ") for i in range(2)]
n = int(input())
inputs = [int(input()) for i in range(n)]
# print(symbols[0][inputs[0] % len(symbols[0]) - 1])
res = []
for i in range(len(inputs)):
res.append(symbols[0][inputs[i] % len(symbols[0]) - 1] + symbols[1][inputs[i] % len(symbols... |
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b.
Note that a permutation of n elements is a sequence of numbers a_1, a_2, β¦, a_n, in ... | 3 | x = int(input())
data = list(map(int,input().split()))
data2 = list (map(int,input().split()))
d = {}
dataPos = [0]*x
data2Pos =[0]*x
for i in range(x):
dataPos[data[i]-1]=data2Pos[data2[i]-1] = i+1
for i in range(x):
z = 0
if dataPos[i] > data2Pos[i]:
z = dataPos[i] - data2Pos[i]
else:
... |
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β the depth of vert... | 3 | n = int(input())
p = [1] + list(map(int, input().split()))
s = list(map(int, input().split()))
p = [i-1 for i in p]
for i in range(1,n):
if s[i] != -1 and (s[p[i]] == -1 or s[p[i]] > s[i]):
s[p[i]] = s[i]
a = [s[0]]+[0]*(n-1)
for i in range(1,n):
if s[i] == -1:
a[i] = 0
else:
a[i] = ... |
There is a n Γ m grid. You are standing at cell (1, 1) and your goal is to finish at cell (n, m).
You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell (x, y). You can:
* move right to the cell (x, y + 1) β it costs x burles;
* move down to the cell (x + 1,... | 3 | def solve(n,m,k):
a = (m-1) + m*(n-1)
b = (n-1) + n*(m-1)
xmin, xmax = min(a,b), max(a,b)
return 'YES' if xmin <= k <= xmax else 'NO'
for _ in range(int(input())):
n,m,k = map(int,input().split())
print(solve(n,m,k))
|
A matrix of size n Γ m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, ... , a_k) is a palindrome, if for any integer i (1 β€ i β€ k) the equality a_i = a_{k - i + 1} holds.
Sasha owns a matrix a of size n Γ m. In one operation he can increase or decrease any numb... | 3 | def answer(a,b,c,d):
x=[a,b,c,d]
x.sort()
su=(x[1]+x[2])//2
# print(x)
ans=abs(a-su)+abs(b-su)+abs(c-su)+abs(d-su)
# print(ans,su)
# print(a-su,b-su,c-su,d-su)
return ans
for i in range(int(input())):
n,m=list(map(int,input().split()))
x=[]
for i in range(n):
zz=list(... |
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them.
For example, if the... | 3 | t=int(input())
for i in range(t):
x=input()
c=0
a=[]
ans=0
for j in range(len(x)):
if x[j]=="0" and c!=0:
a.append(c)
c=0
elif x[j]=="1" and j!=len(x)-1:
c+=1
elif j==len(x)-1 and x[j]=="1":
c+=1
a.append(c)
if l... |
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long... | 3 | t = int(input())
t_t = t
while(True):
if(t>1000000000):
t+=1
x = 1
while(t%1000000000!=0):
t = max(x*1000000000,t)
x+=1
elif(t>100000000):
t+=1
x = 1
while(t%100000000!=0):
t = max(x*100000000,t)
x+=1
... |
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:
(1n + 2n + 3n + 4n) mod 5
for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).
Input
The si... | 3 | n=int(input())
one=1
two={1:2,2:4,3:3,0:1}#4
three={1:3,2:4,3:2,0:1}#4
four={1:4,0:1}#2
twothreetemp=n%4
fourtemp=n%2
print((one+two[twothreetemp]+three[twothreetemp]+four[fourtemp])%5) |
Snuke has a calculator. It has a display and two buttons.
Initially, the display shows an integer x. Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:
* Button A: When pressed, the value on the display is incremented by 1.
* Button ... | 1 | x,y = map(int, raw_input().split())
ret = 10**9 + 7
if x <= y:
ret = min(ret, y - x)
if -x <= y:
ret = min(ret, y + x + 1)
if x <= -y:
ret = min(ret, -y - x + 1)
if -x <= -y:
ret = min(ret, -y + x + 2)
print ret
|
You are given n numbers a1, a2, ..., an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make <image> as large as possible, where <image> denotes the bitwise OR.
Find the maximum possible value of <image> after performing at most k operations optimally.
I... | 3 | from functools import reduce
from operator import *
from math import *
from sys import *
from string import *
from collections import *
setrecursionlimit(10**7)
dX= [-1, 1, 0, 0,-1, 1,-1, 1]
dY= [ 0, 0,-1, 1, 1,-1,-1, 1]
RI=lambda: list(map(int,input().split()))
RS=lambda: input().rstrip().split()
#####################... |
There is a directed graph with N vertices numbered 1 to N and M edges. The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge. Additionally, there is a button on Vertex N.
We will play a game on this graph. You start the game on Vertex 1 with zero coins, and head for V... | 3 | import sys
sys.setrecursionlimit(10**9)
INF = float('inf')
def BFord(n,es):
v_cost = [INF]*n
v_cost[0] = 0
for v in range(n*2):
for e in es:
frm = e[0]
to = e[1]
if v_cost[to] > v_cost[frm]+e[2]:
v_cost[to] = v_cost[frm]+e[2]
if v... |
There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation).
Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after... | 3 | q = int(input())
for query in range(q):
n = int(input())
A = list(map(int, input().split()))
num = 0
while A[num] != 1:
num += 1
if A[num:] + A[:num] == [i for i in range(1, n + 1)] or A[num:] + A[:num] == [1] + [i for i in range(n, 1, -1)]:
print("YES")
else:
print("NO")
|
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 ... | 3 | t=int(input())
sum=0
res=-1
for x in range(t):
temp=input().split(" ")
sum=sum-int(temp[0])+int(temp[1])
res=max(sum,res)
print(res)
|
Dreamoon likes coloring cells very much.
There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n.
You are given an integer m and m integers l_1, l_2, β¦, l_m (1 β€ l_i β€ n)
Dreamoon will perform m operations.
In i-th operation, Dreamoon will choose a number ... | 3 | def main():
import sys
input=sys.stdin.readline
n,m=map(int,input().split())
l=list(map(int,input().split()))
if sum(l)<n:
print(-1)
else:
for i in range(m):
if l[i]>n-i:
print(-1)
exit()
ans=[i+1 for i in range(m)]
ans_... |
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 | x=input()
z=set([])
for i in range(0,len(x)):
z.add(x[i])
if len(z)%2==0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
|
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.
Mu-mu's enemy Kashtanka wants to unlock Mu-mu's p... | 3 | pas = input()
n = int(input())
words = []
for i in range(n):
words.append(input())
for i in words:
if(i == pas or i == pas[::-1]):
print("YES")
quit()
count1 = 0
count2 = 0
for i in words:
if(i[0] == pas[1]):
count1 = count1 + 1
if(i[1] == pas[0]):
count2 += 1... |
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ... | 3 | a, b, c = map(int, input().split())
run = True
while run:
a0, c0 = a, c
while c0 > 0:
a0, c0 = c0, a0 % c0
c = c - a0
if c < 0:
print(1)
run = False
else:
b1, c1 = b, c
while c1 > 0:
b1, c1 = c1, b1 % c1
c = c - b1
if c < 0:
... |
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string ... | 3 | str = input()
l = len(str)
a = [0] * (2 * l)
pos = [[] for i in range(26)]
for i, c in enumerate(str):
t = ord(c) - ord('a')
a[i] = t
a[i + l] = t
pos[t].append(i)
ans = 0
for c in range(26):
cur = 0
for k in range(1, l):
cnt = [0] * 26
for i in pos[c]:
cnt[a[i + k]] ... |
Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something.
Dima and Seryozha have n fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit sala... | 1 | from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_num():
return int(raw_input())
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
de... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 3 | n,k=map(int,input().split())
lis=[]
lis=list(map(int, input().split()))
m=int(lis[k-1])
if m==0:
while 0 in lis:
lis.remove(0)
print(len(lis))
else:
li=list(lis[j] for j in range(k,n))
while m in li:
li.remove(m)
t=n-len(li)
print(t)
|
Given are two strings S and T.
Let us change some of the characters in S so that T will be a substring of S.
At least how many characters do we need to change?
Here, a substring is a consecutive subsequence. For example, `xxx` is a substring of `yxxxy`, but not a substring of `xxyxx`.
Constraints
* The lengths of ... | 3 | s=input()
t=input()
m=1000
for i in range(len(s)-len(t)+1):
mm=0
for j in range(len(t)):
if s[i+j]!=t[j]:
mm+=1
m=min(mm,m)
print(m) |
Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has.
Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d re... | 1 | n = int(raw_input())
a = map(int,raw_input().split())
b = []
for i in range(9):
b.append([a[i],9-i])
b.sort()
c = []
while n >= b[0][0]:
n -= b[0][0]
c.append(10 - b[0][1])
for j in range(len(c)):
flag = 0
for i in range(9):
if b[i][0] - a[c[j]-1] <= n and 10 - b[i][1] > c[j]:
n -= b[i][0] - a[c[j]-1]
c[j]... |
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | def main():
n=list(input())
n1=list(input())
stri=""
for i in range(len(n)):
if n[i]==n1[i]:
stri+="0"
else:
stri+="1"
stri=stri.strip()
print(stri)
main()
|
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.
You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i > 1 the respective term satisfies the condition bi = ... | 1 | # coding=utf-8
s = raw_input().split(' ')
a = int(s[0])
q = int(s[1])
l = int(s[2])
m = int(s[3])
bad = raw_input().split(' ')
if a == 0:
if '0' in bad:
print 0
else:
print 'inf'
elif q == 0:
if abs(a) > l:
print 0
elif '0' not in bad:
print 'inf'
elif str(a) in bad:... |
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other cons... | 3 | def isVowel(a):
return a == 'a' or a == 'e' or a == 'i' or a == 'o' or a == 'u'
def e():
S = list(input())
T = list(input())
if not (len(S) == len(T)):
print("No")
else:
flag = True
for i in range(len(T)):
if isVowel(S[i]) and isVowel(T[i]) or isVowel(S[i]) is False and isVowel(T[i]) is Fals... |
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | 3 | import collections
n = int(input(""))
arr = [input("") for i in range(n)]
reg = collections.defaultdict(int)
for w in arr:
if reg[w] == 0:
print("OK")
reg[w] +=1
else:
print(w+str(reg[w]))
reg[w] +=1 |
Mishka got an integer array a of length n as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
* Replace each occurre... | 3 | n = int(input())
a = [int(i) for i in input().split()]
for i in range(n):
if a[i] % 2 == 0:
a[i] -= 1
for e in a:
print(e, end=" ")
print()
|
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 | a=input()
t=0
for i in range (len(a)):
if a[i]=='hello '[t]:
t=t+1
if t== 5:
print('YES')
else:
print('NO')
|
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 | string=input()
string1=string.capitalize()
print(string1[0]+string[1:])
|
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | a = int(input())
if(a % 5 > 0):
b = 1
else:
b = 0
print (b + a // 5)
|
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could ha... | 1 | a,b=map(int,raw_input().split())
d=a-(b-1)
f=a/b
g=a%b
ans=(f+1)*f*g/2+(f-1)*f*(b-g)/2
print ans,d*(d-1)/2
|
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | a=int(input())
for j in range(a):
n,x=[int(i) for i in input().split()]
if n%x:
print(((int(n/x)+1)*x)-n)
else:
print(0) |
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 name(a):
h=[]
c=0
for i in a:
if i not in h:
h+=i
c+=1
x=int(c/2)*2
if(x==c):
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
a=input()
name(a) |
Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$.
A column vector with m elements is represented by the following equation.
\\[ b = \left( \begin{array}{c} b_1 \\\ b_2 \\\ : \\\ b_m \\\ \end{array} \right) \\]
A $n \times m$ matrix with $m$ column ve... | 1 | #!/usr/bin/env python
if __name__ == '__main__':
n, m = map(int, raw_input().split())
A = [map(int, raw_input().split()) for _ in range(n)]
B = [[int(raw_input())] for _ in range(m)]
for i in range(n):
print sum([A[i][j]*B[j][0] for j in range(m)])
|
You are given a string s consisting of n lowercase Latin letters.
Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3 and ends in position 6), but "aa" or "d" aren't substrings of this string. So the substring of the string s from po... | 3 | n = int(input())
s = input()
for i in range(0, len(s) - 1) :
if (s[i] > s[i + 1]) :
print ("YES")
print (i + 1, i + 2)
exit()
print ("NO") |
You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m.
Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B.
For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ... | 3 | I = lambda: max(map(int, input().split()))
input()
a = I()
input()
print(a, I()) |
Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.
Consider two infinite sets of numbers. The first set consists of odd positive numbers (1, 3, 5, 7, β¦), and the second set consists of even posi... | 3 | l,r=(int(i) for i in input().split())
e=0
o=0
k=1
s=0
i=0
mod=1000000007
while (s<l):
s+=k
if (i==0):
o+=k
i=1
else:
e+=k
i=0
k*=2
o1=o
e1=e
if (i==1):
o-=s-l+1
else:
e-=s-l+1
while (s<r):
s+=k
if (i==0):
o1+=k
i=1
else:
e1+=k
... |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 1 | n = list(raw_input())
s = ''
if not (n[0] != '-' or len(n[1:]) <= 1):
c = max(n[-1], n[-2])
d = False
for i in xrange(len(n)-1,-1,-1):
if not d and n[i] == c:
d = True
else:
s += n[i]
s = s[::-1]
else:
s = ''.join(n)
if s == '-0': s = '0'
print s |
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()
a=0
b=0
if n[0].islower():
a=1
for i in n[1:len(n)]:
if i.islower():
b=1
break
#a->1 first is small
#a->0 first is capital
#b ->0 next is capital
# b->1 next has small
if (a==0 and b==0):
print(n.lower())
elif (a==1 and b==0):
print(n[0].upper()+n[1:len(n... |
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to spli... | 3 |
n = int(input())
def even(x):
if x%2 == 0:
return True
else:
return False
if even(n):
print(int(((n/2)-1)/2))
else:
print(0)
# I have to fill this with something
|
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n.
For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10.
Input
The first line contains an integer t (1 β€ t β€ 1000) β the ... | 3 | x=int(input())
for i in range(x):
n,k=input().split()
n,k=int(n),int(k)
if k<n:
print(k)
else:
j=k+k//n+(k+(k//n)*(1-n) -1)//(n-1)
if j%n==0:
print(j+1)
else:
print(j)
|
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... | 1 | n=input()
print n*9,n*8 |
You are given q queries in the following form:
Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i].
Can you answer all the queries?
Recall that a number x belongs to segment [l, r] if l β€ x β€ r.
Input
The first l... | 3 | q=int(input())
search_number=0
for number_string in range (q):
string=input()
string_=string.split()
l=int(string_[0])
r=int(string_[1])
d=int(string_[2])
if l/d>1:
search_number=d
elif l//d<=1:
search_number=d*(r//d+1)
print(search_number) |
You are given a permutation p_1, p_2, ..., p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
Find three indices i, j and k such that:
* 1 β€ i < j < k β€ n;
* p_i < p_j and p_j > p_k.
Or say that there are no such indices.
Input
The first lin... | 3 | import math
import sys
#####sorting a dictionary by the values#####
def dict_sort(ans):
ans=sorted(ans.items(),reverse=True,key=lambda kv:(kv[1]))
#####Primes till Nth#####
def seive_primes(n):
flag=[0]*(n+1)
flag[1]=flag[0]=1
i=2
while i*i<=n:
if flag[i] == 0:
j = i*i
... |
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 | TEST = int(input())
for i in range(TEST):
n = int(input())
weights = [int(i) for i in input().split()]
weights = sorted(weights)
W = weights[1] - weights[0]
for i in range(n-1):
W = min(W, weights[i+1] - weights[i])
print(W)
|
A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity.
Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2i - 1 liters and costs ci r... | 1 | import sys
import math
n,l = map(int,raw_input().split())
c = list(map(int,raw_input().split()))
for i in range(1,n):
c[i]= min(c[i],c[i-1]*2)
ans = 0
k = []
j = l
for i in range(n-1,-1,-1):
x = 2**i
ans += (l//x)*c[i]
if l//x==0 or l%x :
k.append(ans+c[i])
l-=(l//x)*x
if ans :
k.appe... |
Vasya has the square chessboard of size n Γ n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.
The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a roo... | 3 | import sys
def main():
size, n_rooks = [int(x) for x in sys.stdin.readline().split()]
rows_akd = set()
cols_akd = set()
for line in sys.stdin.readlines():
(x,y) = line.split()
rows_akd.add(x)
cols_akd.add(y)
# print(rows_akd, cols_akd)
safe = size ** 2
safe -= len(rows_akd) * size
safe -= len(co... |
Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!
The computers bought for the room were different. Some of them had only USB ... | 3 |
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newl... |
It is a balmy spring afternoon, and Farmer John's n cows are ruminating about link-cut cacti in their stalls. The cows, labeled 1 through n, are arranged so that the i-th cow occupies the i-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has f... | 3 | n, s = map(int, input().rstrip().split(" "))
if s ==0 or n == 1:
print(0)
elif s >= n//2:
print((n-1)*(n)//2)
else:
t = 0
for i in range(s):
t+=(n-1-i)
for i in range(s, n-s):
t+=s
for i in range(s):
t+=i
print(t) |
You are given an array a consisting of n integers.
Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array.
For example, if the array a will be [2, 4, 6, 2, 10], then 1 and 2 ... | 3 | def gcd(a,b):
if a == 0:
return b
if b == 0:
return a
r = 1
while r > 0:
r = a % b
a = b
b = r
return a
n=int(input())
a=list(map(int,input().split()))
x=a[0]
for i in range(1,n):
x=gcd(x,a[i])
def make_divisors(n):
divisors = []
for i in range(... |
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i... | 1 | length = map(int, raw_input().split())
flowers = map(int, raw_input().split())
n = length[0]
max1 = max(flowers)
min1 = min(flowers)
beautydiff = max1 - min1
def findoccurences(x):
i = 0
indic = 0
while i < n:
if flowers[i] == x:
indic += 1
i += 1
else:
i += 1
return indic
maxoccur = findoccurences(m... |
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total.
Each Kinder Surprise can be one of three types:
* it can contain a single sticker and no toy;
* it can contain a single toy and no sticker;
* it can contain both a sing... | 3 | '''
3
10 5 7
10 10 10
2 1 1
'''
n=int(input())
for i in range(0,n):
p=input().rstrip().split(' ')
print(max(int(p[0]) - int(p[1]) +1 , int(p[0]) - int(p[2]) + 1)) |
You are given a text of single-space separated words, consisting of small and capital Latin letters.
Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.
Calculate the volume of the given text.
Input
The first line contains one integer number n ... | 3 | input()
print(max(map(lambda w: len(list(filter(str.isupper, w))), input().split())))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.