problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given three positive (i.e. strictly greater than zero) integers x, y and z. Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c. You have to answer t independent test cases. Print required a, b a...
3
t=int(input()) while(t): t=t-1 x,y,z=map(int,input().split()) if x==y or y==z or z==x: if(x==y and y==z): print("YES") print(x,x,x) elif ((x==y and x>z) or(x==z and x>y) or(y==z and y>x)): print("YES") if(min(x,y,z)==1): print(m...
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()) lst=list(map(int,input().split())) q="" for i in range(len(lst)): if lst[i]==1: q="HARD" break else: q="EASY" print(q)
We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i. In how many ways can we choose three of the sticks with different lengths that can form a triangle? That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions: ...
3
from itertools import* n=input() l = map(int,input().split()) ans = 0 for a, b, c in combinations(l, 3): if a != b != c != a and a + b > c and b + c > a and c + a > b: ans += 1 print(ans)
You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that: * No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in t...
3
for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) l.sort() flag=0 for i in range(1,n): if (l[i]-l[i-1])<=1: flag=1 break if flag: print(2) else: print(1)
You are given a rectangular board of M Γ— N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ— 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
import math n,m = [int(i) for i in input().split()] if (0<=m*n<=16**16): print(math.floor(m*n/2))
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are r...
3
n, k = map(int, input().split()) s = list(input()) f = s[::-1] count = (n - k) // 2 if n == k: print(''.join(s)) exit(0) else: new = '' r = count for el in s: if count != 0 and el == '(': count -= 1 elif r != 0 and el == ')': r -= 1 else: n...
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even. He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh...
3
import io import os import sys from atexit import register from itertools import combinations import math from random import choice ##################################### Flags ##################################### DEBUG = False # DEBUG = True STRESSTEST = False # STRESSTEST = True ###########################...
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d...
1
#-*-coding:utf-8 -*- import math queue={1:'Sheldon',2:'Leonard',3:'Penny',4:'Rajesh',5:'Howard'} n=int(raw_input()) count=5 i=1.0 while n>count: n-=count count+=count i+=i print queue[int(math.ceil(n/i))]
You are given an array a consisting of n integers. Your task is to determine if a has some subsequence of length at least 3 that is a palindrome. Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c...
3
t=int(input()) while(t>0): n=int(input()) a=[int(x) for x in input().split()] a=a[:n] flag=0 for i in range(n-2): j=n-1 while(j>(i+1)): if(a[i]==a[j]): flag=1 break j-=1 if(flag==1): break if(flag): ...
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
3
n=list(map(int,input().split())) m=list(map(int,input().split())) a=n[0] for i in range(n[0]): if(m[i]>n[1]): a+=1 print(a)
We have N bricks arranged in a row from left to right. The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it. Among them, you can break at most N-1 bricks of your choice. Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of t...
3
n=int(input()) a=list(map(int,input().split())) s=1 for i in range(n): if a[i]==s: s+=1 if s==1: print(-1) else: print(n-(s-1))
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i β€” its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to...
3
#------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() ...
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
s = input() repeated = 0 last = "" isdangerous = False for num in s: if (repeated == 7): isdangerous = True break elif (num == last): repeated += 1 if (repeated == 7): isdangerous = True break else: repeated = 1 last = num if (isdangero...
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to...
3
xs = [int(x) for x in input().split()] print(max(xs) - min(xs))
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives. A young hacker Vasya disassembled the program and foun...
3
s = input() s = '' + s[0] + s[2] + s[4] + s[3] + s[1] print("%05d" % (int(s) ** 5 % 100000))
There is a set A = \\{ a_1, a_2, \ldots, a_N \\} consisting of N positive integers. Taro and Jiro will play the following game against each other. Initially, we have a pile consisting of K stones. The two players perform the following operation alternately, starting from Taro: * Choose an element x in A, and remove e...
3
n,k = map(int,input().split()) A = [int(i) for i in input().split()] dp = ["Second"]+["First"]*k for i in range(1,k+1): win = "Second" for a in A: if i-a >= 0 and dp[i-a] == "Second": win = "First" dp[i] = win print(dp[k])
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
3
de=list(map(int,input().split())) f=set(de) print(4-len(f))
The mysterious pathogen of ACM Nation multiplies mysteriously each day. Maria was able to decipher the pattern but unable to completely solve the problem. The study of this equation will help in combating their growth. The summation is - S = a + aa + aa*a + ...... a^n times Where a is the number of pathogen on ...
1
a=input() b=input() if a>1: x=a-1 print int(a*(a**b-1)/x) else: print b*a
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game. The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, ...
1
m, n = map(int, raw_input().strip().split()) p = 1.0 / m cum, ans = p ** n, p ** n for i in range(2, m + 1): param = (p * i) ** n - cum ans += param * i cum += param print '%.17f' % ans
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5Β·i minutes to solve the i-th...
3
count = 0 n, k = map(int, input().split()) for i in range(n): k += 5 * (i + 1) if k > 240: break count += 1 print(count)
Mishka has got n empty boxes. For every i (1 ≀ i ≀ n), i-th box is a cube with side length ai. Mishka can put a box i into another box j if the following conditions are met: * i-th box is not put into another box; * j-th box doesn't contain any other boxes; * box i is smaller than box j (ai < aj). Mishka ...
3
n,a=input(),list(map(int,input().split())) c={i:a.count(i)for i in a} print(max(c.values()))
At first, there was a legend related to the name of the problem, but now it's just a formal statement. You are given n points a_1, a_2, ..., a_n on the OX axis. Now you are asked to find such an integer point x on OX axis that f_k(x) is minimal possible. The function f_k(x) can be described in the following way: ...
3
from math import ceil from sys import stdin, stdout t = int(input()) while(t>0): n,k =[int(x) for x in stdin.readline().split()] a = [int(x) for x in stdin.readline().split()] if k==0: print(a[0]) else: l =0 r = k m = 100000000000 ans =0 for i in range(...
Masha has three sticks of length a, b and c centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks. What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a ...
3
a, b, c = map(int, input().split()) print(max(0, max(a, b, c) * 2 - a - b - c + 1))
You are given an array a consisting of n integer numbers. You have to color this array in k colors in such a way that: * Each element of the array should be colored in some color; * For each i from 1 to k there should be at least one element colored in the i-th color in the array; * For each i from 1 to k al...
3
n, k = map(int, input().split()) mass = list(map(int, input().split())) fol = 0 for t in set(mass): if mass.count(t) > k: fol = 1 for t in range(n): mass[t] = [mass[t], t] psi = [0]*n mass.sort() if len(mass) < k or fol: print('NO') else: print('YES') for t in range(n): psi[mass[t][1...
One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages. Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Som...
3
n=int(input()) p=list(map(int,input().split())) d={} for i in range(1,8): d[i]=p[i-1] x=1 s=0 while s<n: s+=d[x] if s>=n: print(x) break x+=1 if x==8: x=1
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
# -*-coding:utf-8-*- reg={} for i in range(int(input())): s=input() if s in reg: reg[s]+=1 print(s+str(reg[s])) else: reg[s]=0 print('OK')
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
zr='0' def dc(x): if str(x)[-1]==zr: return x//10 else: x-=1 return x def pc(x,k): for _ in range(k): x=dc(x) return x n,k=[int(x) for x in input().split()] print(pc(n,k))
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go. Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of ...
3
n,x=input().split() i=0 res =0 s=[] while i<=101: s.append(0) i=i+1 p=input().split() for item in p: if int(item)>=0: s[int(item)]=1 for i in range(int(x)): if not s[i]: res +=1 if s[int(x)]==1: res +=1 print (res)
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be n players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately. Organizers are stil...
3
n = int(input()) a = [0 for i in range(1000)] a[1] = 2 a[2] = 3 if n <4: print(n-1) exit() i = 3 while True: a[i] = a[i-1] + a[i-2] if a[i] > n: print(i - 1) exit() i += 1
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad. The crossroads are represented as a string s of length n, where s_i = A, if there is...
3
from sys import stdin r = stdin.readline def solve(A, p): ans, ins = len(A), False for i in range(len(A)-1, -1, -1): if A[i]>p: ans = i+2; ins=True; break if not ins: ans = 1 return ans def main(): cases = int(r()) for case in range(cases): a, b, p = map(int, r().strip().split(...
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! Initially, Alice's cat is located in a cell (x,y) of an infinite grid. According to Alice's theory, cat needs to move: * exactly a steps left: from (u,v) to (u-1,v); * exactly b steps right: from (u,v) to (u+1,v); ...
3
import sys input = sys.stdin.readline def main(): t = int(input()) for _ in range(t): A, B, C, D = [int(x) for x in input().split()] X, Y, X1, Y1, X2, Y2 = [int(x) for x in input().split()] if X == X1 == X2 and (A != 0 or B != 0): print("No") continue ...
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water...
3
k = int(input()) a = list(map(int, input().split())) growth_cent = 0 a.sort(key=lambda x: -x) for i in range(12): if growth_cent >= k: print(i) break growth_cent += a[i] if growth_cent >= k: print(i + 1) break if growth_cent <k: print('-1')
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exac...
3
n=int(input()) a=[[int(x) for x in input().split()] for i in range(n)] s=0 for i in range(n): for j in range(n): if(i==j or i==n//2 or j==n//2 or i==n-1-j): s+=a[i][j] print(s)
"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
#!/usr/bin/python3 x=input() x=x.split(' ') n=int(x[0]) k=int(x[1])-1 x=input() x=x.split(' ') j=int(x[k]) s=0 for i in range(n): if int(x[i])>=j and int(x[i])>0: s+=1 if int(x[i])<j: break print(s)
We have a string S consisting of lowercase English letters. If the length of S is at most K, print S without change. If the length of S exceeds K, extract the first K characters in S, append `...` to the end of them, and print the result. Constraints * K is an integer between 1 and 100 (inclusive). * S is a string ...
3
k=int(input());s=input();print(s[:k]+"..."*(len(s)>k))
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
import sys, os n = int(input()) data = list(map(int, input().split())) data2 = list(map(int, input().split())) data3 = [] for i in range(n): data3.append([data2[i], i]) data3 = sorted(data3) data = sorted(data, reverse=True) answer = [0] * n for i in range(n): answer[data3[i][1]] = data[i] print(*answer)
Dreamoon is a big fan of the Codeforces contests. One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing! Based on this, you come up with the following problem: There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi...
3
t=int(input()) ans=[] for z in range(t): k = list(map(int, input().split())) n = k[0] x = k[1] b = list(map(int, input().split())) v=0 while 1 : v += 1 if v in b: continue else: if(x==0): break x-=1 ans.append(v-1) ...
You have unlimited number of coins with values 1, 2, …, n. You want to select some set of coins having the total value of S. It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S? Input The only line of the input contains two integers n and S ...
3
ns = input().split() n = int(ns[0]) s = int(ns[1]) if s / n != int(s / n): print(s // n + 1) else: print(s // n)
You are given two arrays a and b, each contains n integers. You want to create a new array c as follows: choose some real (i.e. not necessarily integer) number d, and then for every i ∈ [1, n] let c_i := d β‹… a_i + b_i. Your goal is to maximize the number of zeroes in array c. What is the largest possible answer, if y...
3
from math import gcd n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) difflist = [] zeronum = 0 for i in range(n): if a[i] == 0 and b[i] == 0: zeronum += 1 if a[i] != 0: minab = gcd(b[i], a[i]) frac = (-1 * b[i] / minab, a[i] / minab) if frac[0] == 0: frac = (0, 0)...
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
3
q=int(input()) for i in range(q): n=int(input()) l=list(map(int,input().split(" "))) d={} for i in l: if i not in d: d[i]=1 print(len(d))
You are given an array a consisting of n integers numbered from 1 to n. Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there i...
3
import sys import math from collections import defaultdict,Counter # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdout=open("CP2/output.txt",'w') # sys.stdin=open("CP2/input.txt",'r') # mod=pow(10,9)+7 t=int(input()) for i in range(t): n=int(input()) a=list(map(int,input().s...
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
s = input() newans = "" newans = newans + s[0].upper() for i in s[1:]: newans+=i print(newans)
You are given a rectangular cake, represented as an r Γ— c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 Γ— 4 cake may look as follows: <image> The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contain...
3
import sys r,c=map(int,input().strip().split()) l=[] R=0 C=0 for i in range(r): l.append(input()) if l[i].find('S',0) == -1: R+=1 for i in range(c): t=[] for j in range(r): t.append(l[j][i]) T=''.join(t) if T.find('S',0) == -1: C+=1 print(r*c-(r-R)*(c-C))
Jzzhu has a big rectangular chocolate bar that consists of n Γ— m unit squares. He wants to cut this bar exactly k times. Each cut must meet the following requirements: * each cut should be straight (horizontal or vertical); * each cut should go along edges of unit squares (it is prohibited to divide any unit choc...
1
def getArea(n, m, r, c, k): if r < 0 or r > k: return -1 if c < 0 or c > k: return - 1 if r >= n or c >= m: return -1 h = n / (r + 1) w = m / (c + 1) return h * w def solve(n, m, k): ret = 0 r = 0 while r < k: if (r + 1) ** 2 > n: break ret = max(ret, ...
You are given a string S of length 2N consisting of lowercase English letters. There are 2^{2N} ways to color each character in S red or blue. Among these ways, how many satisfy the following condition? * The string obtained by reading the characters painted red from left to right is equal to the string obtained by r...
3
from itertools import combinations from collections import defaultdict n = int(input()) s = str(input()) d = defaultdict(int) left = set() for r in range(n + 1): for j in combinations(range(n), r): sl = "" sr = "" for i in range(n): if i in j: sl += s[i] else: sr += s[i] left.add(sl + "," + sr...
A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each ...
3
#!/usr/bin/python3 n,k=map(int,input().split()) num=0 isend=False res="" for i in range(0,n): for j in range(0,n): if (i+j)%2 == 0 and num < k: res+="L" num+=1 else: res+="S" if i!=n-1: res+="\n" if num==k: print ("YES") print (res) else: print("NO")
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()) #tmp = input().split(" ") arr = [int(x) for x in input().split(' ')] if arr.count(1) == 0: print("EASY") else: print("HARD")
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()) array=[int(x) for x in input().split()] c=0 o=0 for i in range(n): if(array[i]==0): c=c+1 else: o=o+1 if(o>=1): print("HARD") else: print("EASY")
This year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible ...
1
k = input() a = map(int,raw_input().split(" ")) if max(a)<= 25: print "0" else: print max(a) - 25
Haiku is a genre of Japanese traditional poetry. A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syll...
1
# on codeforces # beta round is running # a rustling of keys n=3 x=[] ans=0 for i in range(n): m=raw_input() x.append(m) p = [] v=['a','e','i','o','u'] for z in x: ans = 0 for i in v: ans+=z.count(i) p.append(ans) print ['NO','YES'][p==[5,7,5]]
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given. Shift each character of S by N in alphabetical order (see below), and print the resulting string. We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` ...
3
N = int(input()) T = [chr((ord(s)-65 + N)%26 + 65) for s in input()] print("".join(T))
There are n piranhas with sizes a_1, a_2, …, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium. Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the...
3
# Legends Always Come Up with Solution # Author: Manvir Singh import os from io import BytesIO, IOBase import sys from collections import defaultdict,deque,Counter from bisect import * from math import sqrt,pi,ceil import math from itertools import permutations from copy import deepcopy from sys import setrecursionlim...
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
a, b, c = [int(input()) for i in range(3)] print(max([a+b+c, a*b*c, (a+b)*c, a*(b+c), (a*b)+c, a+(b*c)]))
We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right). Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where th...
3
def solve(H, W, M, h, w): f = [0] * (H+1) g = [0] * (W+1) for r, c in zip(h, w): f[r] += 1 g[c] += 1 p = max(f) q = max(g) num = len(list(filter(p.__eq__, f))) * len(list(filter(q.__eq__, g))) num -= len(list(filter(lambda _: f[_[0]] + g[_[1]] == p + q, zip(h, w)))) retur...
You have array of n numbers a_{1}, a_{2}, …, a_{n}. Rearrange these numbers to satisfy |a_{1} - a_{2}| ≀ |a_{2} - a_{3}| ≀ … ≀ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement. Note that all numbers in a are not necessarily different. In other words, some numb...
3
''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineerin College Date:12/04/2020 ''' from math import ceil,sqrt,log,gcd def ii():return int(input()) def si():return input() def mi():return map(int,input().split()) def li():return list(mi()) dx=[-1,-1,1,1,0,0,-1,1] dy=[0,-1,1,0,-1,1,1,-1] ...
You are given an array a consisting of n integers a_1, a_2, ... , a_n. In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4],...
3
tc = int(input()) for _ in range(tc): n = int(input()) arr = list(map(int, input().split(' '))) arr = list(map(lambda x: x%3, arr)) # count 1 and 2 zero = arr.count(0) ones = arr.count(1) twos = arr.count(2) ans = zero mini = min(ones, twos) ans += mini # 1s can...
An n Γ— n table a is defined as follows: * The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n. * Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin...
3
def calculateMaxNumber(sizeM): maxNumb = 0 mat = [] for row in range(0,sizeM): mat.append(calculateRow(row, sizeM, mat)) # print(mat) maxNumb = mat[sizeM-1][sizeM-1] return maxNumb def calculateRow(row, cols, mat): mrow = [] if row == 0: for x in range(1,cols+1): ...
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy. The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from t...
3
n = int(input()) fishes = [int(s) for s in input().split(' ')] now_fish = None prev_len = 0 now_len = 0 max_len = 0 for f in fishes: if f != now_fish: max_len = max(max_len, min(now_len, prev_len)) prev_len = now_len now_len = 1 now_fish = f else: now_len += 1 max_len = m...
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second: * Select some distinct indices i_{1}, i_{2}, …, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{...
3
# from math import log # def Gap(a): # gap = 0 # if len(a) < 2: # return 0 # for i in range(len(a)-1): # for ii in range(i+1, len(a)): # if a[ii] > a[i]: # gap = max(gap, Gap(a[ii:])) # break # else: # gap = max(gap, a...
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi. The way to split up game pieces is split into several steps: 1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the...
3
n = int(input()) a = list(map(int,input().split())) s = input() l = 0 b = [] for i in range(n): if s[i]=="B": l+=a[i] p = 0 b.append(l) for i in range(n): if s[i]=="B": l=l-a[i] else: p+=a[i] b.append(l+p) l = 0 for i in range(n): if s[i]=="B": l+=a[i] p = 0 for i in ...
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest. To obfuscate the code, Kostya first looks at the first variable name used in his program and rep...
3
s = input() prev = ord('a') - 1 for c in s: if ord(c) <= prev + 1: prev = max(prev, ord(c)) else: print('NO') exit(0) print('YES')
n fishermen have just returned from a fishing vacation. The i-th fisherman has caught a fish of weight a_i. Fishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order of sh...
3
from collections import defaultdict import sys input = sys.stdin.readline n = int(input()) a = map(int, input().split()) mod = 998244353 d = defaultdict(int) for x in a: d[x] += 1 d[0] = 0 b = list(d.items()) b.sort() m = len(b) ba = [0] * m cn = [0] * (m + 1) k = h = 0 for i, x in enumerate(b): while h < m and...
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
n = int(input()) l=[] for i in range(n): l.append(int(input())) c=1 for i in range (n-1): if l[i] == l[i+1]: s=0 else: c = c+1 print(c)
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo...
3
def main(): n, m = [int(v) for v in input().split()] d = 1 for i in range(1, min(n,m)+1): d*=i print(d) if __name__ == "__main__": main()
You are given integer n. You have to arrange numbers from 1 to 2n, using each of them exactly once, on the circle, so that the following condition would be satisfied: For every n consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard 2n numbers differ not more th...
3
n=int(input()) arr=[0]*(2*n) print("NYOE S"[n%2::2]) if(n%2!=0): for i in range(n): if(i%2==0):arr[i]=2*i+1;arr[i+n]=arr[i]+1 else:arr[i]=2*i+2;arr[i+n]=arr[i]-1 print(*arr)
The Little Elephant has got a problem β€” somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array. The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could ...
3
n=int(input()) #n,k=map(int,input().split()) a=list(map(int, input().split())) b=sorted(a) f=0 for i in range(n): if a[i]!=b[i]: f+=1 if f<=2: print("YES") else: print("NO")
There are n consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger. The university team for the Olympiad consists of a student-programmers and b student-athletes. Determine the largest number of students from all a+b students, which you can put in the railway carriage so t...
3
n, a, b= map(int, input().split()) s = list(map(lambda x: x == '.', input())) x = a + b for i in range(n): if not s[i]: continue m = max(a, b) if i == 0: if a == m and a: s[i] = 0 a -= 1 elif b == m and b: s[i] = 1 b -= 1 elif type(s[i-1]) == bool: if a == m and a: s[i] = 0 a -= 1 el...
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing. Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are ...
3
import math I = lambda: list(map(int, input().split())) for _ in range(int(input())): n, g, b = I() if g >= b: print(n) else: required = math.ceil(n / 2) total = required // g * (g + b) if required % g == 0: total -= b else: total += required %...
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations. You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers. Input The first line of the input con...
3
import math a, b=map(int,input().split()) ls=[] ls=map(int,input().split()) ls=list(ls) number=0 B=1 for x in reversed(ls): number+= x*B B=B*b p, q= map(int,input().split()) lst = [] lst=map(int,input().split()) lst=list(lst) numberY=0 B=1 for x in reversed(lst): numberY+= x*B B=B*q if number>numberY: p...
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
x = int(input()) x += 1 while len(set(str(x))) != len(str(x+1)): x += 1 print(x)
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
""" Solution to Codeforces Problem 119A : https://codeforces.com/problemset/problem/119/A Difficulty: 800 """ import math solve = lambda a, b, n, i: solve(b, a, n - math.gcd(a, n), i+1) if n != 0 else i % 2 print(solve(*list(map(int, input().split(' '))), 1))
Greatest common divisor GCD(a, b) of two positive integers a and b is equal to the biggest integer d such that both integers a and b are divisible by d. There are many efficient algorithms to find greatest common divisor GCD(a, b), for example, Euclid algorithm. Formally, find the biggest integer d, such that all int...
3
ab = list(map(int, input().split(' '))) a = ab[0] b = ab[1] if(a == b): print(a) else: print(1)
Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N. Constraints * 1\leq N \leq 10^{16} * N is an integer. Input Input is given from Standard Input in the following format: N Output Print the maximum possible sum of the digits (in base 10) of a positive integer not...
3
a=list(input());x,y=len(a)-1,int(a[0]);print(9*x+y if all(i=='9'for i in a[1:])else y-1+9*x)
Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group. Input The first line contains a s...
3
n = int(input()) arr = [] left, right = 0, 0 for i in range(n,0,-1): if left >= right: right += i else: left += i arr.append(i) print(abs(right-left)) print(len(arr),*arr)
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
n = int(input()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] mem2 = {} for i in range(n): if b[i] in mem2: mem2[b[i]].add(i) else: mem2[b[i]] = set([i]) iter_dic = {i:0 for i in range(n)} for i in range(n): if a[i] in mem2: for iters in...
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si β€” lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, ...
3
from collections import Counter n,k = list(map(int,input().split())) s = list(input()) s_count = Counter(s).most_common() if len([i[1] for i in s_count if i[1] > k]) == 0: print('YES') else: print('NO')
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clar...
3
s = 1 n = 1 def get_sum(): res = 0 for i in s: res += int(i) return res k = int(input()) for _ in range(k): count = input() s = input() n = int(s) flag = True while flag and n > 0 and n % 2 == 0: n = n // 10 s = str(n) if n == 0: print(-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
x = int(input()) d = {1:1, 2:1, 3:1, 4:1, 5:1} if x in d: print(d[x]) else: n = x//5 if x%5: print(n+1) else: print(n)
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep...
3
from math import ceil t = int(input()) for _ in range(t): a, b, c, d = [int(i) for i in input().split()] if a > b and c > d: print(b + c * (ceil((a - b) / (c - d)))) elif a > b: print(-1) else: print(b)
On a planet far, far away, M languages are spoken. They are conveniently numbered 1 through M. For CODE FESTIVAL 20XX held on this planet, N participants gathered from all over the planet. The i-th (1≦i≦N) participant can speak K_i languages numbered L_{i,1}, L_{i,2}, ..., L_{i,{}K_i}. Two participants A and B can c...
3
from collections import deque N,M=map(int,input().split()) L=[[] for i in range(M)] for i in range(N): for j,k in enumerate(input().split()): if j==0: continue L[int(k)-1].append(i) G=[[] for i in range(N)] for l in L: if len(l)>=2: for i in range(len(l)-1): if l[i+1] not in G[l[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
t=int(input()) for _ in range(t): n=int(input()) arr=[int(x) for x in input().split()] arr.sort() ans=float('inf') for i in range(n-1): ans=min(ans,arr[i+1]-arr[i]) print(ans)
Tired of boring office work, Denis decided to open a fast food restaurant. On the first day he made a portions of dumplings, b portions of cranberry juice and c pancakes with condensed milk. The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes...
3
t = int(input()) for tt in range(t): inputX = [int(i) for i in input().split()] ans = 0 for i in range(len(inputX)): if inputX[i] > 0: ans += 1 inputX[i] -= 1 perm = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], ...
Polycarp has an array a consisting of n integers. He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its...
1
n=input() c=[[],[]] for x in map(int,raw_input().split()): c[x%2]+=x, c[0]=sorted(c[0]) c[1]=sorted(c[1]) while c[0] and c[1]: c[0].pop() c[1].pop() if not c[0]: c[0]+=0, if not c[1]: c[1]+=0, print sum(c[0])+sum(c[1])-max(c[0][-1],c[1][-1])
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages. At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second β€”...
1
c, v0, v1, a, l = (int(x) for x in raw_input().split()) ret = 0 total = 0 while total < c: amt_read = min(v1, v0 + ret * a) ret += 1 if ret > 1: amt_read -= l total += amt_read print ret
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si β€” lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, ...
3
from math import* n,k=map(int,input().split()) s=input() s=sorted(s) ans=0 pos=0 for i in range(n-1): if s[i]!=s[i+1]: val=i+1-pos pos=i+1 if ans<val: ans=val #print(n,pos) if ans<(n-pos): ans=n-pos #print(ans) if ans<=k: print("YES") else: print("NO")
Takahashi is solving quizzes. He has easily solved all but the last one. The last quiz has three choices: 1, 2, and 3. With his supernatural power, Takahashi has found out that the choices A and B are both wrong. Print the correct choice for this problem. Constraints * Each of the numbers A and B is 1, 2, or 3. * ...
3
ans = "123" print(ans.replace(input(),"").replace(input(),""))
Fox Ciel is playing a game with numbers now. Ciel has n positive integers: x1, x2, ..., xn. She can do the following operation as many times as needed: select two different indexes i and j such that xi > xj hold, and then apply assignment xi = xi - xj. The goal is to make the sum of all numbers as small as possible. ...
1
num = raw_input() nlist = raw_input().split(" ") nlist = map(int, nlist) while(min(nlist) != max(nlist)) : nlist[nlist.index(max(nlist))] = max(nlist) - min(nlist) print sum(nlist)
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≀ x ≀ a) coins of value n and y (0 ≀ y ≀ b) coins of value 1, then the total value of taken coins will be S. You have to answer q independent test cases. Input The...
3
k=int(input()) for _ in range(k): a,b,n,s =list(map(int,input().split())) s-=min((s//n),a)*n if s>b : print('NO') else: print("YES")
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
Tcases = int(input()) count = 0 for i in range(Tcases): Stri = input() if Stri[0] == "+" or Stri[2] == "+": count = count + 1 else: count = count - 1 print (count)
Zane the wizard is going to perform a magic show shuffling the cups. There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i. The problematic bone is initially at the position x = 1. Zane will confuse the audience b...
3
from bisect import bisect_left n,m,k = map(int, input().split(' ')) holes = list(map(int, input().split(' '))) curr = 1 found = False holes = sorted(holes) H = len(holes) def bins(x, bot, top=None): top = top if top is not None else H pos = bisect_left(holes, x, bot, top) return pos != top and holes[pos...
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task. You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the fol...
3
import sys def lpre(w): kk = len(w) ww = w[:] w.reverse() ww += ['1']*kk + w dp = [0]*(3*kk+1) # dp[0] = 0 # for i in range(1, 2*kk): # k = dp[i-1] # # if ww[dp[i-1]] == ww[i]: # # dp[i] = dp[i-1] + 1 # while k > 0 and ww[k] != ww[i]: # k = dp...
A and B are preparing themselves for programming contests. B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code. Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix s...
3
n = int(input()) errors = [] for i in range(3): cur = [int(x) for x in input().split()] err = {} for j in range(len(cur)): if cur[j] in err: err[cur[j]] += 1 else: err[cur[j]] = 1 errors.append(err) for i in range(2): for x in errors[i]: if x not in er...
Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a β‰  b) will indulge if: 1. gcd(a, b) = 1 or, 2. a divides b or b d...
3
from collections import Counter import string import math import sys # sys.setrecursionlimit(10**6) from fractions import Fraction def array_int(): return [int(i) for i in sys.stdin.readline().split()] def vary(arrber_of_variables): if arrber_of_variables==1: return int(sys.stdin.readline()) if arr...
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()) while t>0: n,k=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) a.sort() b.sort() b.reverse() i=0 j=0 while k>0: if a[i]<b[j]: a[i]=b[j] j+=1 i+=1 else: i+=1 ...
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes. Input The single line of the input contains a pa...
3
def dp_large(length,sum): if length==0: if sum!=0: raise IndexError else: return "" if sum>=9: return "9"+dp_large(length-1,sum-9) else: return str(sum)+dp_large(length-1,0) def dp_small(length,sum): if length==1: if sum>9: raise IndexError else: return str(sum) if sum>9: return dp_small...
Takahashi wants to gain muscle, and decides to work out at AtCoder Gym. The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up. These buttons are numbered 1 through N. When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It ...
3
n = int(input()) lst = [] for i in range(n): lst.append(int(input())) a = 1 for i in range(n): a = lst[a - 1] if a == 2: print(i + 1) exit() print(-1)
Given n numbers, you can perform the following operation any number of times : Choose any subset of the numbers (possibly empty), none of which are 0. Decrement the numbers in the subset by 1, and increment the numbers not in the subset by K. Is it possible to perform operations such that exactly n - 1 numbers becom...
1
tests = input() for t in range(tests): v = [0]*1001 n, k = map(int, raw_input().split()) x = map(int, raw_input().split()) for i in range(n): v[x[i]] += 1 ok = False for i in range(1001): if (i-k-1>=0): v[i] += v[i-k-1] if (v[i] >= n-1): ok = True print "YES" if ok else "NO"
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...
1
if __name__ == "__main__": n = input() a = map(int, raw_input().split()) b = map(int, raw_input().split()) new_b = list(enumerate(b)) a = sorted(a, reverse = True) new_b = sorted(new_b, key = lambda x: x[1]) answer = {} for new_i, (i, v) in enumerate(new_b): answer[i] = a[new_i] ...
Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n. Consider that m (m ≀ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order...
3
n, m = map(int, input().split()) order_enter = [] order_exit = [] for i in range(n): order_enter.append((i, 0)) order_enter.append((i, 3)) for i in range(n): order_enter.append((i, 1)) order_enter.append((i, 2)) for i in range(n): order_exit.append((i, 1)) order_exit.append((i, 0)) order_ex...
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 ...
1
def mdc (a,b): if (b==0): resp=a else: resp= mdc(b,a%b) return resp a=raw_input() a=a.split() for i in range(0,len(a)): a[i]=int(a[i]) simon=False while True: if (a[2]-mdc(int(a[0]),int(a[2])))>=0: a[2]-=mdc(int(a[0]),int(a[2])) simon=True else: break ...