problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
1
T = int(input()) s = map(int, raw_input().split()) s = sorted(s) c = p = 0 while(sum(s)>=p): p += s.pop() c += 1 print c
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
for i in range(5): s = input().split() for j in range(5): if '1' in s[j]: print(abs(i - 2) + abs(j - 2))
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets. But only function does not interest him. He wan...
3
n=int(input()) a=list(map(int,input().strip().split(' '))) b=list(map(int,input().strip().split(' '))) c=[] a.sort(reverse=True) for i in range(n): d=[] d.append(b[i]) d.append(i) c.append(d) c = sorted(c, key=lambda x: (x[0], -x[1])) d=[0 for i in range(n)] for i in range(n): d[c[i][1]]=a[i] for i ...
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The ...
1
r = map(int, raw_input().split()) n, k = r[0], r[1] l = map(int, raw_input().split()) tm = 0 for i in l: if (i+k) <= 5: tm += 1 print tm // 3
You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤...
3
t=int(input()) for tt in range(t): n=int(input()) a=list(map(int,input().split(' '))) if(n==1): if(a[0]%2==0): print(1) print(1) else: print(-1) elif(n>=2): if(a[0]%2==0): print(1) print(1) elif(a[1]%2==0): print(1) print(2) else: print(2) print(1,2,sep=' ',end='\n')
AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W. If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the ho...
3
w,a,b=map(int,input().split()) print(0) if abs(a-b)<=w else print(abs(a-b)-w)
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n = int(input()) for i in range(n): wrd = (input()) a = list(wrd) if len(wrd) >10: b=a[0]+str(len(wrd)-2)+a[-1] print(b) else: print(wrd)
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
1
# your code goes here """author : darksider""" import sys n = int(sys.stdin.readline()) x = 0 for i in range(n): t = raw_input() if ( t[1] == '+' ): x+=1 else: x-=1 print x
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 ≥ p_2 ≥ ... ≥ p_n. Help the jury distrib...
3
# import sys # sys.stdin=open("input1.in","r") # sys.stdout=open("outpul.out","w") for i in range(int(input())): N=int(input()) L=list(map(int,input().split())) X=N//2 X=X-1 x=0 if L[X]==L[X+1]: for j in range(X,-1,-1): if L[j]!=L[j-1]: x=j-1 break X=x if X<4: print("0 0 0") else: j=1 r=1 ...
You are given a range of positive integers from l to r. Find such a pair of integers (x, y) that l ≤ x, y ≤ r, x ≠ y and x divides y. If there are multiple answers, print any of them. You are also asked to answer T independent queries. Input The first line contains a single integer T (1 ≤ T ≤ 1000) — the number of...
3
# cook your dish here for i in range(int(input())): a,b=map(int,input().split()) print(a,a*2)
Walking along a riverside, Mino silently takes a note of something. "Time," Mino thinks aloud. "What?" "Time and tide wait for no man," explains Mino. "My name, taken from the river, always reminds me of this." "And what are you recording?" "You see it, tide. Everything has its own period, and I think I've figured...
3
n,p=map(int,input().split()) s=list(input()) c=0 for i in range(0,n-p): a,b=0,0 if s[i]=='.': a=1 if s[i+p]=='.': b=1 if s[i]==s[i+p] and a+b==0: c+=1 if c==n-p: print('No') else: for i in range(0,n-p): a,b=0,0 if s[i]=='.': a=1 ...
Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it. The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer)....
3
n=int(input()) if (n+1)%27==0 or (n+14)%27==0: print(":(") else: print(int(n//1.08+1))
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
n=int(input()) a=[int(x) for x in sorted(input().split(),key=lambda x:int(x),reverse=True)] for i in range(1,n+1): if sum(a[:i])>sum(a[i:]): print(i) break
Taro and Jiro will play the following game against each other. Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a becomes empty, the two players perform the following operation alternately, starting from Taro: * Remove the element at the beginning or the end of a. The player earns x points, whe...
3
n = int(input()) a = list(map(int, input().split())) dp = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): dp[i][i] = a[i] for w in range(1, n): for l in range(n - w): dp[l][l+w] = max(a[l] - dp[l+1][l+w], a[l+w] - dp[l][l+w-1]) print(dp[0][n-1])
Alice and Bob are decorating a Christmas Tree. Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments. In Bob's opinion, a Christmas Tree will be beautiful if: * the number of blue ornaments used is greater b...
3
x = list(map(int, input().split())) print(min(x[0],x[1]-1,x[2]-2)*3+3)
AtCoDeer the deer and his friend TopCoDeer is playing a game. The game consists of N turns. In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition: (※) After each turn, (the number of times the player has played Paper)≦(the number of times the ...
3
#時間がなかった s=input() n=len(s) ans=0 for i in range(n): if i%2==0: if s[i]=="p": ans-=1 else: if s[i]=="g": ans+=1 print(ans)
Array of integers is unimodal, if: * it is strictly increasing in the beginning; * after that it is constant; * after that it is strictly decreasing. The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent. For example, the following th...
3
n = int(input()) a = list(map(int, input().split())) d = [a[i] - a[i - 1] for i in range(1, n)] # print(d) for i in range(len(d) - 1): if d[i] <= 0 and d[i + 1] > 0: print('NO') exit(0) if d[i] < 0 and d[i + 1] == 0: print('NO') exit(0) print('YES')
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
#ANKIT BEHIND THE KEYBOARD t=int(input()) for j in range(t): n,k=map(int, input().split()) x=0 xxx =0 a=input() for i in range(0,k): y = '1' in a[i::k] z = '0' in a[i::k] if y and z: x = k xxx= k break elif y: x += 1 elif z: xxx += 1 if k % 2 == 0 and 2 * x <= k and 2 * xxx <= k: print(...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
x=input() stri="" b=x.lower() for i in b: if i not in ("a","e","i","o","u","y"): stri+=i print("."+".".join(stri))
An n × n square matrix is special, if: * it is binary, that is, each cell contains either a 0, or a 1; * the number of ones in each row and column equals 2. You are given n and the first m rows of the matrix. Print the number of special n × n matrices, such that the first m rows coincide with the given ones. ...
1
n, m, mod = map(int, raw_input().split()) a = [0]*n q = [0]*n C = [0]*(n+1) C[2]=1 dp = {} for i in range(3,n+1): C[i]=C[i-1]+i-1 def calcola(pos, restanti, semirestanti): if pos == n and restanti == 0 and semirestanti == 0: return 1 if pos == n or restanti < 0 or semirestanti < 0 or semirestanti > restanti: ret...
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
input() if set(input().lower()).__len__()==26: print('YES') else: print('NO')
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea...
3
n=int(input()) k=[] l=list(map(int,input().split())) for i in l: k.append(i/100) print((sum(k)/n)*100)
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved. Pikachu is a cute and friendly pokémon living in the wild pikachu herd. But it has become known recently that infamous team R...
3
import sys # sys.setrecursionlimit(10**6) input=sys.stdin.readline t=int(input()) for t1 in range(t): n,k =list(map(int,input().split(" "))) l=list(map(int,input().split(" "))) pos=[0]*n neg = [0]*n a = -10**30 b = -10**30 for i in range(n): if(i==0): pos[i]=l[i] ...
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array [10, 20, 30, 40], we can pe...
3
import sys import math n=int(sys.stdin.readline()) a=list(map(str,sys.stdin.readline().split())) a.sort() freq=[] count=0 for i in range(n): if(i==0): count+=1 if(i==n-1): freq.append([a[i],count]) elif(a[i]==a[i-1]): count+=1 if(i==n-1): freq.append([a[i]...
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones. Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a. You can apply the following operations any number of times: * Choose some substring of string a (for example, you can choose entire strin...
3
n, x, y = map(int, input().split()) s = input() c = len([_ for _ in s.split("1") if _]) ans = 1e19 if not c: ans = 0 for i in range(c): ans = min(ans, i*x + (c-i)*y) print(ans)
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [...
3
import math for _ in range(int(input())): n=int(input()) lis=list(map(int,input().split())) l=[] if lis[0]<0: f=0 else: f=1 x=[] for i in range(n): if f==0 and lis[i]<0: x.append(lis[i]) elif f==1 and lis[i]>0: x.append(lis[i]) ...
How Many Divisors? Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b. Constraints * 1 ≤ a, b, c ≤ 10000 * a ≤ b Input Three integers a, b and c are given in a line separated by a single space. Output Print the number of divisors in a line. Example Inp...
1
a,b,c = map(int,raw_input().split()) print len(filter(lambda x:c % x == 0,range(a,b+1)))
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house. Karlsson's gaze immediately fell on n wooden ...
1
n=int(raw_input()) a,b,c,d=0,0,0,0 for i in xrange(n): l,r=map(int,raw_input().split()) a+=(not l) + r b+=l+(not r) c+=l+r d+=(not l)+(not r) print min(a,b,c,d)
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()) m = map(int, input().split()) counter = 0 for elem in m: if elem != 1: counter += 1 if counter == n: print("EASY") else: print("HARD")
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
3
k,n,w = map(int,input().split()) ans = k*((w*(w+1))//2) print(max(0,ans-n))
You are given N real values A_1, A_2, \ldots, A_N. Compute the number of pairs of indices (i, j) such that i < j and the product A_i \cdot A_j is integer. Constraints * 2 \leq N \leq 200\,000 * 0 < A_i < 10^4 * A_i is given with at most 9 digits after the decimal. Input Input is given from Standard Input in the fol...
3
# -*- coding: utf-8 -*- import sys from decimal import * sys.setrecursionlimit(10**9) INF=10**18 MOD=10**9+7 input=lambda: sys.stdin.readline().rstrip() YesNo=lambda b: bool([print('Yes')] if b else print('No')) YESNO=lambda b: bool([print('YES')] if b else print('NO')) int1=lambda x:int(x)-1 N=int(input()) div=[[0]*1...
As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are a...
3
#!/usr/bin/env python3 n = int(input()) arr = [0] + list(map(int, input().split())) visit = [False] * (n + 1) def gcd(x, y): while x != 0: y %= x if y == 0: return x x %= y return y def check(u): sub = 0 v = u while not visit[v]: visit[v] = True v ...
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
3
[k,n,w] = list(map(int,input().strip().split())) b = (k*(w*(w+1)))//2 if n>=b: print(0) else: print(b-n)
Petya and Vasya decided to play a game. They have n cards (n is an even number). A single integer is written on each card. Before the game Petya will choose an integer and after that Vasya will choose another integer (different from the number that Petya chose). During the game each player takes all the cards with num...
3
n = int(input()) A=[0]*101 for i in range (n): a = int(input()) for i in range (101): if i == a: A[i] += 1 B=[] count = 0 index1 = index2 = 0 for i in range(101): if A[i] >0: B.append(A[i]) index2 = index1 index1 = i count += 1 if count == 2 and B[...
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it... In...
3
s=input() a='heidi' j,flag=0,0 for i in range(len(s)): if s[i]==a[j]: j+=1 if j==5: flag=1 break if flag:print("YES") else:print("NO")
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
n = int(input()) a = [int(x) for x in input().split()] pos=0 pos1=0 x=0 y=0 for i in range(n): if(a[i]%2==0): x += 1 pos = i + 1 if(a[i]%2!=0): y += 1 pos1 = i + 1 if(x==1): print(pos) else: print(pos1)
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1...
1
n,m=map(int,raw_input().split()) t=[] for _ in range(n): t.append(map(int,raw_input().split())) for i in range(1,n): t[i][0]+=t[i-1][0] for i in range(1,m): t[0][i]+=t[0][i-1] for j in range(1,n): t[j][i]+=max(t[j][i-1],t[j-1][i]) for i in range(n): print t[i][m-1],
How many multiples of d are there among the integers between L and R (inclusive)? Constraints * All values in input are integers. * 1 \leq L \leq R \leq 100 * 1 \leq d \leq 100 Input Input is given from Standard Input in the following format: L R d Output Print the number of multiples of d among the integers b...
3
l,r,d=map(int,input().split()) left=(-(-l//d)) right=r//d print(right-left+1)
Recall that string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly zero or all) characters. For example, for the string a="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", ...
3
def lcs(s, m): dp = [[0 for i in range(m + 1)]for i in range(4)] b = ['w', 'o', 'w'] for i in range(m + 1): dp[0][i] = 1 for i in range(1, 4): for j in range(1, m + 1): if b[i - 1] == s[j - 1]: dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1] 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
import copy def main(): #get the number of days for studing and the total spent hours for studing in this days days, spentHours = map(int,input().split()) minHours = [0]*days maxHours = [0]*days #for each day save the number of min hours to spend on studing #and the number of m...
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). What is the minimum number of ope...
3
def gcd(a, b): if a < b: a,b = b,a while b > 0: r = a % b a,b = b,r return a def solve(): n = int(input()) al = [int(i) for i in input().split()] if 1 in al: print(n - al.count(1)) return ans = -1 for i in range(n): t = al[i] ...
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
n=list(input("").lower()) m=list(input("").lower()) if n>m: print(1) elif n<m: print(-1) else: print(0)
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems. But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest ...
1
chk =["Danil", "Olya", "Slava", "Ann","Nikita"] s = raw_input() cnt = [] for l in chk: cnt.append(s.count(l)) su = sum(cnt) if su==1: print 'YES' else: print 'NO'
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i × j. The rows and columns are numbered starting from 1. You are given a positive integer x. Your task is to count the number of cells in a table that contain number x. Input T...
3
#In the name of Allah from sys import stdin, stdout input = stdin.readline n, x = map(int, input().split()) ans = 0 for i in range(1, n + 1): if x % i == 0: if x / i <= n: ans += 1 stdout.write(str(ans))
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k. In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w...
3
t = int(input()) for i in range(t): n,k = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) a.sort() b.sort() ans = 0 for j in range(k): if a[0] >= b[-1]: break a.append(b[-1]) b.insert(0,a[0]) b.pop() ...
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
x = int(input()) binx = bin(x)[2:] print(binx.count('1'))
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl...
3
n, m = list(map(int, input().split())) f = list(map(int, input().split())) f.sort() minDiff = f[-1] - f[0] for i in range(n - 1, len(f)): if f[i] - f[i - n + 1] < minDiff: minDiff = f[i] - f[i - n + 1] print(minDiff)
There are n points on a plane. The i-th point has coordinates (x_i, y_i). You have two horizontal platforms, both of length k. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same y-coordinate) and have integer borders. If the left border of the platform is (x, y) then the r...
3
def run(): n, k = map(int, input().split()) xS = list(map(int, input().split())) yS = list(map(int, input().split())) lMax, rMax = [0]*n, [0]*n xS.sort() j = n - 1 for i in range(n-1, -1, -1): while xS[j] - xS[i] > k: j -= 1 rMax[i] = j - i + 1 if i + 1 < ...
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0. There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After app...
3
from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop import math from collections import * from functools import reduce,cmp_to_key,lru_cache import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import sys # input = sys.stdin.readline M = m...
Vova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute — at the point 2 and so on). There are lanterns on the...
3
amount = int(input()) def count_lamps(l, v, left,right): all_lamps = l // v start = (left // v) * v if left % v == 0: all_lamps -= (right - left) // v + 1 else: start += v all_lamps -= (right - start) // v + 1 return all_lamps for i in range(amount): l, v, left,right = [i...
Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≤ i ≤ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or...
3
T = int( input()) for x in range(1, T+1): n, k = map( int, input().split()) if k >= n: print( 1) else: deler_max = 1 for i in range(1, int(n**(1/2))+1): if n % i == 0: j = n // i if i <= k: deler_max = max( deler_...
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
polygons = {'Tetrahedron': 4, "Cube": 6, "Octahedron": 8, "Dodecahedron": 12, "Icosahedron": 20} n = int(input()) summ = 0 for _ in range(n): summ += polygons[input()] print(summ)
Lenny is playing a game on a 3 × 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be swit...
3
def permitido(l,c): return l >= 0 and c >= 0 and l <= 2 and c <= 2 def muda_adjacentes(i,j): if grid[i][j] == "0": grid[i][j] = "1" else: grid[i][j] = "0" for m in range(4): l_destino = i + mv[m] c_destino = j + mh[m] if permitido(l_destino,c_destino): ...
Snuke built an online judge to hold a programming contest. When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring. (The judge can return any two-character substring of S.) Determine whether the judge can return the ...
3
s=input() ans='No' for i in range(len(s)-1): if s[i:i+2]=='AC': ans='Yes' break print(ans)
You and your n - 1 friends have found an array of integers a_1, a_2, ..., a_n. You have decided to share it in the following way: All n of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for h...
3
# -*- coding: utf-8 -*- import bisect import heapq import math import random import sys from collections import Counter, defaultdict, deque from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal from functools import lru_cache, reduce from itertools import combinations, combinations_with_replacement, product, permut...
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 ≤ hh < 24 and 0 ≤ mm < 60. We use 24-hour time format! Your task is to find the number of minutes before the New Year. You know that New Year comes when the...
3
n=int(input()) while(n): h,m=(map(int,input().split())) ans,res,temp=0,0,0 ans=((24-h)*60)-m print(ans) n-=1
You are given a special jigsaw puzzle consisting of n⋅ m identical pieces. Every piece has three tabs and one blank, as pictured below. <image> The jigsaw puzzle is considered solved if the following conditions hold: 1. The pieces are arranged into a grid with n rows and m columns. 2. For any two pieces that sh...
3
t = int(input()) for i in range(t): n, m = (int(i) for i in input().split()) if (n == 2 and m == 2) or min(n, m) == 1: print("YES") else: print("NO")
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears. These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh...
3
t=int(input()) for _ in range(t): a,b,c,d=map(int,input().split()) if b+b <= c: print(b,c,c) else: print(b,b,c)
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t. Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim...
3
#!/usr/bin/env python3 x = list(input()) if '4' < x[0] < '9': x[0] = str(9 - int(x[0])) for i in range(1, len(x)): if x[i] > '4': x[i] = str(9 - int(x[i])) print("".join(x))
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
t=input() t=list(t) t=set(t) if(len(t)%2==0): print("CHAT WITH HER!") else: print("IGNORE HIM!")
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6. Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task! Each digit c...
3
a = [int(s) for s in input().split(" ")] #n = int(input()) mn = min(a[0], a[2]) mn = min(mn, a[3]) a[0] -= mn ans = mn*256 + min(a[0], a[1])*32 print(ans)
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru. You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[...
3
from sys import stdin from collections import defaultdict def main(): s, d = input(), defaultdict(set) for s in stdin.read().splitlines(): i = s.find('/', 8) if i == -1: d[s].add('') else: d[s[:i]].add(s[i:]) e = defaultdict(list) for s, v in d.items(): ...
There is a robot staying at X=0 on the Ox axis. He has to walk to X=n. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel. The i-th segment of the path (from X=i-1 to X=i) can be exposed to sunlight or not. The array s denotes which segments are ex...
3
n, b, a = map(int, input().split()) s_list = list(map(int, input().split())) ans = 0 now_a = a now_b = b for i, s in enumerate(s_list): if s == 0: if now_a > 0: now_a -= 1 else: if now_b > 0: now_b -= 1 else: print(i) ...
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided ...
3
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # """ """ from itertools import accumulate from collections import Counter import operator n = int(input()) alist = list(map(int, input().split())) acc = list(accumulate(alist, operator.xor)) acc1 = acc[::2] acc2 = acc[1::2] c1 = Counter(acc1) c2 = Coun...
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
3
input() res = 0 for i in list(map(int ,input().split()[::-1])): res = min(0,res+i) print(-res)
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
#!/usr/bin/python import sys n = 0 endNum = 0 for l in sys.stdin: if n > 0: z = int(l[0]) x = int(l[2]) c = int(l[4]) if z + x + c > 1: endNum = endNum + 1 else: n = n + 1 print(endNum)
problem There are n cards with one integer from 1 to n and one blank card. Of these n + 1 cards, k cards are given, but 1 ≤ k ≤ n. You can write one integer from 1 to n on a blank card. I want to make a continuous sequence of integers as long as possible with just a given card. Write a program that outputs the maximu...
3
#!/usr/bin/env python # -*- coding: utf-8 -*- while True: N,K = map(int,input().split()) A = sorted([int(input()) for i in range(0,K)]) if (N,K) == (0,0): break if A[0] == 0: flag = True A = A[1:] K -= 1 else: flag = False ans = 0 count = 0 dif...
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≤ li ≤ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ......
3
n,m=[int(i) for i in input().split()] res=input().split() a=set([]) dict_={} c=0 for i in range(n-1,-1,-1): a.add(res[i]) dict_[str(i+1)]=len(a) print('\n'.join([str(dict_[str(int(input()))]) for i in range(m)]))
Petya and Vasya are competing with each other in a new interesting game as they always do. At the beginning of the game Petya has to come up with an array of N positive integers. Sum of all elements in his array should be equal to S. Then Petya has to select an integer K such that 0 ≤ K ≤ S. In order to win, Vasya ha...
3
import sys import math def IO(): sys.stdin=open("pyinput.txt", 'r') sys.stdout=open("pyoutput.txt", 'w') def scan(TYPE_1, TYPE_2=0): if(TYPE_1==int): return map(int, sys.stdin.readline().strip().split()) elif(TYPE_1==float): return map(float, sys.stdin.readline().strip().split()) elif(TYPE_1==list and TYPE_...
Nate U. Smith runs a railroad company in a metropolitan area. In addition to his railroad company, there are rival railroad companies in this metropolitan area. The two companies are in a competitive relationship with each other. In this metropolitan area, all lines are routed by the line segment connecting the statio...
3
for i in range(int(input())): xa, ya, xb, yb = map(int, input().split()) n = int(input()) ip = [] for j in range(n): xs, ys, xt, yt, o, l = map(int, input().split()) d = (xb - xa) * (yt - ys) - (yb - ya) * (xt - xs) if d == 0: continue t0 = ((yt - ys) * (xs - ...
Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible. Omkar currently has n supports arranged in a line, the i-th of which has height a_i. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in he...
3
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) ans = 0 for i in range(n - 1): if a[i] > a[i + 1]: ans += a[i] - a[i + 1] print(ans)
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz). The picture showing the correct sudoku solution: <image> Blocks are bordered with bold black color. Your task is to change at most 9 elements of this field (i.e. choose s...
3
T = int(input()) d = [ (0,0), (3,1), (6,2), (1,3), (4,4), (7,5), (2,6), (5,7), (8,8), ] for t in range(T): a = [] for i in range(9): a.append(input()) for i in d: x = i[0] y = i[1] if a[y][x] == "1": print(a[y][:x]+"9"+a[y][x+...
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is <image> for SmallR while <image> for Zanoes. The one who shoots in the target first should be the winner. Output the probability th...
3
a,b,c,d = map(int,input().split()) q = (1-a/b)*(1-c/d) print(a/b / (1-q))
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements. Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed. Input The first line contains a single integer n (1 ≤ n ≤ ...
3
#codeforces_978A_live n = int(input()) L = [int(e) for e in input().split(" ")] flag = False while 1: flag = False for e in L: while L.count(e) > 1: flag = True L.remove(e) if not flag: break; print(len(L)) for e in L: print(e, end=" ") print()
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ...
1
[n, t] = [int(z) for z in raw_input().split()] nums = [int(z) for z in raw_input().split()] bestAns = 0 summary = 0 elemsCnt = 0 for curPos in xrange(len(nums)): summary += nums[curPos] elemsCnt += 1 while summary > t and elemsCnt > 1: summary -= nums[curPos - elemsCnt + 1] elemsCnt -= 1 ...
Recently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list. For ex...
3
import math n = int(input()) a = [*map(int, input().split())] m = max(a) for i in range(int(math.sqrt(m))): if m%(i+1)==0: a.remove(i+1) if (i+1)!=int(m/(i+1)): a.remove(int(m/(i+1))) print(" ".join(map(str, [m,max(a)])))
You are given an array a consisting of n positive integers. Initially, you have an integer x = 0. During one move, you can do one of the following two operations: 1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1). 2. Just increase x by 1 (x := x + 1). ...
3
from collections import * for _ in range(int(input())): n,k=map(int,input().split()) a=list(map(int,input().split())) r=[] for i in a: if i%k!=0: r.append(k-(i%k)) x=0 done={} #r.sort() #print(r) ############ s=Counter(r) mx=0 for i in s: mx=...
According to a new ISO standard, a flag of every country should have a chequered field n × m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland'...
3
n, m = map(int, input().split()) a, out = -1, "YES" for i in range(n): s = input() if s[0] == a or len(set(s)) != 1: out = "NO" break a = s[0] print(out)
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number". Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co...
3
def is_prime(a): for i in range(2, int(pow(a, 0.5) + 1)): if a % i == 0: return 1 return 0 n = int(input()) if n % 2: print(3) else: m = 1 while True: if is_prime(m * n + 1): break m += 1 print(m)
There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards will be ...
1
from sys import stdin n = int(stdin.readline()) a = map(int, stdin.readline().split(' ')) sum = sum(a) * 2 / n used = [False] * n for i in range(n): if used[i]: continue for j in range(i + 1, n): if not used[j] and a[i] + a[j] == sum: used[j] = True print i + 1, j + 1 break
Giga Tower is the tallest and deepest building in Cyberland. There are 17 777 777 777 floors, numbered from - 8 888 888 888 to 8 888 888 888. In particular, there is floor 0 between floor - 1 and floor 1. Every day, thousands of tourists come to this place to enjoy the wonderful view. In Cyberland, it is believed t...
1
#!/usr/bin/python a = raw_input() b=1 a=str(float(a)+1) while '8' not in a: b+=1 a=str(float(a)+1) print b
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
#CodeForces #Twins #Python 3.6.5 import sys import math num = int(input()) count = 0 while(num): if num % 10 == 4 or num % 10 == 7: count += 1 num = num // 10 if count == 4 or count == 7: print("YES") else: print("NO")
Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function. Merge(A, left, mid, right) n1 = mid - left; n2 = right - mid; create array L[0...n1], R[0...n2] for i = 0 to n1-1 do L[i] = A[left + i] for i = 0 to n2-1 do R[i] =...
3
import math n = int(input()) S = list(map(int,input().split())) M = 10**9 + 1 def merge(A, left, mid, right): global count n1 = mid - left n2 = right - mid L = A[left:left + n1] R = A[mid:mid + n2] L.append(M) R.append(M) i = 0 j = 0 for k in range(left,right): count += 1...
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset. During each operation you choose two equal integers from s, remove them from s and insert the number eq...
3
import bisect q=int(input()) for i in range(q): n=int(input()) a=list(map(int,input().rstrip().split())) d=dict() flag=0 for i in a: if i in d: d[i]+=1 else: d[i]=1 a.sort() while(len(a)>1): if 2048 in a: flag=1 break ...
We have a deck consisting of N cards. Each card has an integer written on it. The integer on the i-th card from the top is a_i. Two people X and Y will play a game using this deck. Initially, X has a card with Z written on it in his hand, and Y has a card with W written on it in his hand. Then, starting from X, they w...
3
N, Z, W = map(int, input().split()) a = list(map(int, input().split())) print(max(abs(a[N - 1] - a[N - 2]), abs(a[N - 1] - W)))
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or thro...
3
a1,a2,a3,a4=map(int, input().split()) a=[a1,a2,a3,a4] a.sort() t=sum(a) if t%2==1: print("NO") else: temp=t//2 if temp in a: print("YES") elif a[0]+a[3] == a[1]+a[2]: print("YES") else: print("NO")
You have three piles of candies: red, green and blue candies: * the first pile contains only red candies and there are r candies in it, * the second pile contains only green candies and there are g candies in it, * the third pile contains only blue candies and there are b candies in it. Each day Tanya eats...
3
t=int(input()) for _ in range(t): a,b,c = map(int,input().split()) s=sum([a,b,c]) print(min(s//2 , s-max(a,b,c) ))
We have an integer sequence A, whose length is N. Find the number of the non-empty contiguous subsequences of A whose sums are 0. Note that we are counting the ways to take out subsequences. That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from differ...
3
n = int(input()) a = list(map(int, input().split())) s = 0 d = {} for i in a: s += i d[s] = d.get(s, 0) + 1 ans = 0 for key, value in d.items(): ans += value*(value-1)//2 if key == 0: ans += value print(ans)
Input The input contains a single integer a (0 ≤ a ≤ 35). Output Output a single integer. Examples Input 3 Output 8 Input 10 Output 1024
1
print ',Washington,Adams,Jefferson,Madison,Monroe,Adams,Jackson,Van Buren,Harrison,Tyler,Polk,Taylor,Fillmore,Pierce,Buchanan,Lincoln,Johnson,Grant,Hayes,Garfield,Arthur,Cleveland,Harrison,Cleveland,McKinley,Roosevelt,Taft,Wilson,Harding,Coolidge,Hoover,Roosevelt,Truman,Eisenhower,Kennedy,Johnson,Nixon,Ford,Carter,Reag...
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2). In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i ar...
3
for i in range (int(input())) : n,k=map(int,input().split()) if k>n : print('NO') elif k==n : print('YES') for i in range (k) : print(1,end=' ') else : if n%2!=0 and k%2==0 : print('NO') elif n%2!=0 and k%2!=0 : print('YES') for...
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
a=input() b=[] cnt=0 for i in a: if i not in b: b.append(i) if len(b)%2==0: print('CHAT WITH HER!') else: print('IGNORE HIM!')
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t...
3
n = int(input()) kards = list(input()) vok = {} vok['z'] = 0 vok['e'] = 0 vok['r'] = 0 vok['o'] =0 vok['n'] = 0 for i in range(n): if kards[i] in vok: vok[kards[i]]+=1 k = min(vok['o'],vok['n'],vok['e']) z = min(vok['z'], vok['e']-k, vok['r'], vok['o']-k) answ = ['1']*k+['0']*z print(*answ, sep = ' ')
You are given an integer sequence x of length N. Determine if there exists an integer sequence a that satisfies all of the following conditions, and if it exists, construct an instance of a. * a is N^2 in length, containing N copies of each of the integers 1, 2, ..., N. * For each 1 ≤ i ≤ N, the i-th occurrence of the...
3
def main(): n = int(input()) X = list(map(int, input().split())) ans = [-1]*(n**2) left = [] right = [] for idx, x in enumerate(X): idx += 1 ans[x-1] = idx left.append((x, idx-1, idx)) right.append((x, n-idx, idx)) left.sort(key=lambda x: -x[0]) right.so...
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
digOne = str(input()) digTwo = str(input()) def thisThing(digOne, digTwo): ans = [] listDigOne = list(digOne) listDigTwo = list(digTwo) for i in range(0, len(listDigOne)): if listDigOne[i] != listDigTwo[i]: ans.append("1") else: ans.append("0") print(''.jo...
Input The first line of the input contains a single integer N (1 ≤ N ≤ 24). The next N lines contain 5 space-separated integers each. The first three integers will be between 0 and 2, inclusive. The last two integers will be between 0 and 3, inclusive. The sum of the first three integers will be equal to the sum of ...
3
a = ['10010','11020','20011','21012','11011','21021','22022','12021','00000','12012','10120','11130','20121','21122','11121','21131','22132','12131','11111','12122','10221','11231','12113','20222','21223','11222'] from string import ascii_lowercase as l n = int(input()) r = '' for i in range(n): *b, = map(int, inpu...
Mike is trying rock climbing but he is awful at it. There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, ai < ai + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty <image>. In othe...
3
n=int(input()) v=[int(i) for i in input().split()] mx=0 for i in range(1,len(v)): mx=max(mx,v[i]-v[i-1]) mn=int(1e9) for i in range(1,len(v)-1): mn=min(mn,max(mx,v[i+1]-v[i-1])) print(mn)
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You m...
3
from itertools import permutations, product n = int(input()) nums = list(map(int, input().split())) # print(nums) indexed = sorted(zip(nums, range(1, len(nums)+1))) removed = 0 while len(indexed) > 0 and indexed[0][0] <= removed: indexed = indexed[1:] removed += 1 # while len(indexed) > 0 and indexed[-1][0] >...
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
n=int(input()) for i in range(0,n): st=input().split() s=int(st[0]) t=int(st[1]) x=s%t if(x==0): print(0) else: print(t-x)
Snuke is standing on a two-dimensional plane. In one operation, he can move by 1 in the positive x-direction, or move by 1 in the positive y-direction. Let us define a function f(r, c) as follows: * f(r,c) := (The number of paths from the point (0, 0) to the point (r, c) that Snuke can trace by repeating the operati...
3
mod = 10 ** 9+7 def inv(x): return pow(x, mod - 2, mod) r1, c1, r2, c2 = map(int, input().split()) fact, inv_fact = [1, 1], [1, 1] for i in range(2, r2+c2+3): fact.append(fact[-1] * i % mod) inv_fact.append(inv(fact[-1])) def nCr(n, r): return fact[n] * inv_fact[r] * inv_fact[n-r] % mod def path...
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element eq...
3
import math m, n = map(int, input().split()) while True: #print(n, "######") if n == 1: print(1) break elif n == 2: print(2) break else: if n -(2 ** math.floor(math.log2(n))) == 0: print(math.floor(math.log2(n)) + 1) break elif n -(...