problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
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
l=list(input()) for i in range(len(l)): count=0 for j in range(i,len(l)): if l[j]!=l[i]: break else: count+=1 if count>=7: print("YES") exit() print("NO")
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have b buns, p beef patties and f chicken cutlets in your restaurant. You can sell one hamburger for ...
3
t = int(input()) x=0 def count(buns,patty,chicken,pPrice,cPrice): total = 0 if pPrice>=cPrice: expensive = pPrice expensiveItem = patty cheap = cPrice cheapItem = chicken else: expensive = cPrice expensiveItem = chicken cheap = pPrice cheapIte...
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
# https://codeforces.com/problemset/problem/160/A numberOfCoins = int(input()) coins = sorted([int(i) for i in input().split(" ")], reverse=True) for i, coin in enumerate(coins, start=1): if sum(coins[:i]) > sum(coins[i:]): print(i) break
Given are a sequence of N positive integers A_1, A_2, \ldots, A_N and another positive integer S. For a non-empty subset T of the set \\{1, 2, \ldots , N \\}, let us define f(T) as follows: * f(T) is the number of different non-empty subsets \\{x_1, x_2, \ldots , x_k \\} of T such that A_{x_1}+A_{x_2}+\cdots +A_{x_k}...
3
n, s = map(int, input().split()) a = list(map(int, input().split())) mod = 998244353 dp = [0 for _ in range(s+1)] dp[0] = 1 for i in range(n): plus = [dp[j-a[i]] if j-a[i] >=0 else 0 for j in range(s+1)] for j in range(s+1): dp[j] = (dp[j]*2 +plus[j])%mod print(dp[s])
Input The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9. Output Output a single integer. Examples Input A278832 Output 0 Input A089956 Output 0 Input A089957 Output 1 Input A1440...
3
x = input() last = int(x[-1]) print(last % 2)
Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia. For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs n actions. The first action performed is to put a single candy into the box. For each of the remainin...
1
#!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip import random import collections import math import itert...
There are N people. The name of the i-th person is S_i. We would like to choose three people so that the following conditions are met: * The name of every chosen person begins with `M`, `A`, `R`, `C` or `H`. * There are no multiple people whose names begin with the same letter. How many such ways are there to choo...
3
from itertools import* N,*S=open(0) print(sum(a*b*c for a,b,c in combinations([sum(1 for s in S if s[0]==c) for c in "MARCH"],3)))
We have a sequence of N integers: A_1, A_2, \cdots, A_N. You can perform the following operation between 0 and K times (inclusive): * Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element. Compute the maximum possible pos...
3
def divisor(n): #約数全列挙 ans = [1,n] i = 2 while i**2 <= n: if n%i == 0: ans.append(i) if i**2 < n: ans.append(n//i) i += 1 ans.sort() return ans n,k = map(int,input().split()) A = list(map(int,input().split())) d_max= sum(A) div = divisor(d_max...
Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple ta...
3
n, m = map(int, input().split()) s = input() t = input() k = len(s) positions = set() for i in range(len(t) - len(s) + 1): new_k = 0 new_positions = set() for j in range(len(s)): if t[i + j] != s[j]: new_k += 1 new_positions.add(j + 1) if new_k > k: brea...
The final match of the Berland Football Cup has been held recently. The referee has shown n yellow cards throughout the match. At the beginning of the match there were a_1 players in the first team and a_2 players in the second team. The rules of sending players off the game are a bit different in Berland football. If...
3
a1=int(input()) a2=int(input()) k1=int(input()) k2=int(input()) n=int(input()) min=0 max=0 n1=n mx=0 ch1=ch2=j1=j2=0 if(k1<k2): ch1=a1 j1=k1 j2=k2 ch2=a2 else : ch1=a2 j1=k2 j2=k1 ch2=a1 mn=0 if(n<=j1*ch1): mn=n/j1 n=0 else: mn=ch1 n-=ch1*j1 if(n>0): if(n<=j2*ch2): ...
One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles. At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the heig...
3
n = int(input()) h = [int(x) for x in input().split()] highest = [] lowest = [] max_until = 0 for i in range(0,n): max_until = max(max_until, h[i]) highest.append(max_until) min_until = 10**9 for i in range(n-1,0-1, -1): min_until = min(min_until, h[i]) lowest.append(min_until) lowest.reverse() ...
There are a lot of things which could be cut — trees, paper, "the rope". In this problem you are going to cut a sequence of integers. There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulti...
3
import sys import math n,b=map(int,input().split()) lista=[int(x) for x in input().strip().split()] pro=[False for i in range(n)] for i in range(n): if(lista[i]%2==0): pro[i]=True o,e,k=0,0,0 suma=0 send=[] for i in range(0,n-1): if(pro[i]==True): o+=1 else: e+=1 if(o==e and o!=...
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() l=-1 r=-1 ans = [] for i in range(n): if s[i]=='0': ans.append(i) if len(ans)==0: print(0) else: a=1 for i in range(1,len(ans)): if ans[i]!=ans[i-1]+1 :a+=1 print((a-1)*min(x,y)+y)
In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively. Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k. ...
3
a,b,c,d,e,f = list(int(input()) for _ in range(6)) print("Yay!" if e-a<= f else ":(")
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands: * 'L' (Left) sets the position x: =x - 1; * 'R' (Right) sets the position x: =x + 1. Unfortunately, Mezo's controller malfunctions sometimes. ...
3
def problem1(n, s): cl = s.count('L') cr = s.count('R') return cl+cr+1 n = int(input()) s = input() print(problem1(n, s))
Chokudai made a rectangular cake for contestants in DDCC 2020 Finals. The cake has H - 1 horizontal notches and W - 1 vertical notches, which divide the cake into H \times W equal sections. K of these sections has a strawberry on top of each of them. The positions of the strawberries are given to you as H \times W ch...
3
h,w,k = map(int,input().split()) a = [input() for i in range(h)] c = 1 cou = 1 for i in range(h): if '#' not in a[i]: cou += 1 else: ans = [c]*(a[i].index('#')+1) for j in range(a[i].index('#')+1,w): if a[i][j] == '#': c += 1 ans.append(c) else: ans.append(c) [pri...
There is an old tradition of keeping 4 boxes of candies in the house in Cyberland. The numbers of candies are special if their arithmetic mean, their median and their range are all equal. By definition, for a set {x1, x2, x3, x4} (x1 ≤ x2 ≤ x3 ≤ x4) arithmetic mean is <image>, median is <image> and range is x4 - x1. Th...
1
#!/usr/bin/env python #-*- coding:utf-8 -*- import sys import math import random import operator from fractions import Fraction, gcd from decimal import Decimal, getcontext from itertools import product, permutations, combinations getcontext().prec = 100 MOD = 10**9 + 7 INF = float("+inf") n = int(raw_input()) arr ...
We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array: * The array consists of n distinct positive (greater than 0) integers. * The array contains two elements x and y (these elements are known for you) such that x < y. * If you sort the arr...
3
def solve(n,x,y): maxi = 49 for i in range(51,0,-1): diff = i if (y-x)%diff != 0: continue if n < (y-x)//diff + 1: break maxi = min(maxi,diff) ans = [x,y] n -= 2 temp = x while n > 0: while temp+maxi < y: ans.append(temp+maxi) t...
A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not. You're given a number. Determine if it is a magic number or not. Input The first line of input contains ...
1
n = str(input()) flag = True state = 0 for i in range(0, len(n)): if (n[i] == '1'): state = 1 elif (n[i] == '4'): if (state == 1): state = 2 elif (state == 2): state = 3 elif (state == 3): flag = False break else : ...
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other. You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts). If two...
3
from collections import deque for t in range(int(input())): n = int(input()) *a, = map(int, input().split()) used = [False]*n used[0] = True q = deque([0]) ans = [] while q: v = q.popleft() for u in range(n): if a[v] != a[u] and not used[u]: ans.a...
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house. Your house has n rooms. In the i-th room you can install at most c_i heating radiators. Each radiator can have several sections, but ...
1
import sys def main(constraints): for constraint in constraints: c, s = int(constraint[0]), int(constraint[1]) x = s/c y = s%c print((c-y)*x*x + y*(x+1)*(x+1)) rooms = int(raw_input()) constraints = [] for i in range(rooms): constraints.append(raw_input().split(' ')) main(constraints)
Write a program which finds a pattern $p$ in a ring shaped text $s$. <image> Constraints * $1 \leq $ length of $p \leq $ length of $s \leq 100$ * $s$ and $p$ consists of lower-case letters Input In the first line, the text $s$ is given. In the second line, the pattern $p$ is given. Output If $p$ is in $s$, prin...
3
S = input()*2 p = input() if p in S: print("Yes") else: print("No")
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively. You can rearrange the elements i...
3
def main(): t = int(input()) for _ in range(t): x1, y1, z1 = map(int, input().split()) x2, y2, z2 = map(int, input().split()) total = 0 m = min(z1, y2) z1 -= m; y2 -= m; total += 2 * m y1 -= (x2 + y2) if y1 > 0: total -= y1 * 2 print(to...
Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that: * 1 ≤ a ≤ n. * If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has...
1
# https://codeforces.com/problemset/problem/959/A def is_even(num): return True if num % 2 == 0 else False def main(): initial_number = int(raw_input()) winner = "Mahmoud" if is_even(initial_number) else "Ehab" print winner if __name__ == "__main__": main()
You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' ...
3
def sh(c): a=ord(c) return chr(a-1) s=str(input()) l=list(s) x=l.count('a') if x==0: for i in range(len(l)): l[i]=sh(l[i]) print(''.join(l)) elif x==len(l): l[-1]='z' print(''.join(l)) elif x==1: a=l.index('a') if a==0: for i in range(1,len(l)): if l[i]==...
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water. You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of wa...
3
for _ in range(int(input())): n,k = map(int,input().split()) l = sorted(list(map(int,input().split()))) m1 = l[-1] if n==1:print(0) elif n==2: if k>0:print(l[1]+l[0]) else:print(l[1]-l[0]) else: for i in range(k): m1 += l[n-i-2] print(m1)
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
n = input() if (n.find('0000000') != -1 or n.find('1111111') != -1): print("YES") else: print("NO")
Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-th piece is a sector of angle equal to ai. Vasya and Petya want to divide all piece...
3
n = int(input()) pieces = [int(x) for x in input().split()] sm = 360 curs = 0 ans = [] for i in range(n): for elem in pieces: ans.append(abs(sm - 2 * curs)) curs += elem if curs >= 360: curs = 0 pieces.append(pieces.pop(0)) print(min(ans))
The length of the longest common prefix of two strings s = s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum integer k (0 ≤ k ≤ min(n,m)) such that s_1 s_2 … s_k equals t_1 t_2 … t_k. Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}. For each i (1 ≤ i ≤ n) she calculated a_i — the length of ...
3
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) l = [0] * (n + 1) l[0] = a[0] l[-1] = a[-1] for i in range(1, n): l[i] = max(a[i], a[i - 1]) s = ["a" * max(a[0], 1)] for i in range(n): if len(s[-1]) == a[i]: s.append(s[-1] +...
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? Input The single line contains two space separated i...
3
n,m=map(int,input().split()) for i in range((n+1)//2,n+1): if(i%m==0): print(i) break else: print("-1")
Takahashi will do a tap dance. The dance is described by a string S where each character is `L`, `R`, `U`, or `D`. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character. S is said to be easily playable if and onl...
1
S = raw_input() ans = "Yes" for i in range(len(S)): if not (i%2==0 and S[i] in "RUD" or i%2!=0 and S[i] in "LUD"): ans = "No" print ans
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. ...
3
n = int( input().strip() ) arr = list( map(int, input().strip().split(' '))) minv = 101 for i in arr: minv = min(i, minv) for i in range(n): if arr[i] == minv: arr[i] = 101 minv = 101 for i in arr: minv = min(i, minv) print( str(minv) if minv < 101 else 'NO' )
Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest comm...
1
import sys; n = input(); str = [""] * n; for i in xrange(n): str[i] = raw_input(); pos = 0; while True: ok = True; for i in xrange(n): if str[0][pos] != str[i][pos]: ok = False; if not ok: break; pos += 1; print pos;
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins. You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have. ...
3
import math elem = int(input()) for x in range(elem): elem2 = int(input()) ar = [] for x in input().split(' '): ar.append(int(x)) print(math.ceil(sum(ar)/elem2))
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
s=input() l=[] for i in range(len(s)): if(i%2 == 0):l.append(s[i]) l.sort() st="" for i in range(len(l)): st=st+l[i]+"+" s1="" for i in range(len(st)-1): s1=s1+st[i] print(s1)
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato. Vanya h...
3
n, h, j = map(int, input().split()) pots = [int(x) for x in input().split()] count = 0 height = 0 pot = 0 while pot < n: if height + pots[pot] <= h: height += pots[pot] count += height // j height = height % j pot += 1 elif height <= j: height = 0 count += 1 e...
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc...
1
n = input() ans = 0 for i in xrange(n): ans = (n-i-1)*(1 + i) + 1 + ans print ans
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
import os,sys inp = raw_input().split() inp = [int(x) for x in inp] a = inp[0] b = inp[1] n = inp[2] def computeGCD(a,b): while b: a, b = b, a%b return a flag = True counter = 0 while(flag): if (counter % 2 == 0): if (n > 0): n = n - computeGCD(a, n) else: ...
You are given two integers a and b. In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves. Your task is to find the minimum number of mo...
3
for _ in range(int(input())): a,b=map(int,input().split()) c=abs(a-b) moves=c//10 if c%10!=0: moves+=1 print(moves)
In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter. It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not cov...
3
a,b = map(int,input().split()) print((b-a-1)*(b-a)//2-a)
Jerry is a little mouse. He is trying to survive from the cat Tom. Jerry is carrying a parallelepiped-like piece of cheese of size A × B × C. It is necessary to trail this cheese to the Jerry's house. There are several entrances in the Jerry's house. Each entrance is a rounded hole having its own radius R. Could you he...
1
from math import sqrt while True: a, b, c = map(int, raw_input().split()) if a == 0 and b == 0 and c == 0: break d1, d2, d3 = sqrt(a**2 + b**2), sqrt(b**2 + c**2), sqrt(c**2 + a**2) for i in range(int(raw_input())): r = int(raw_input()) if d1 < r * 2 or d2 < r * 2 or d3 < r * ...
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()) p = a / b q = c / d f = (1 - p) * (1 - q) print (p / (1 - f))
Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has n rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar i...
3
import sys def optimal_sol(n,d,e): avail_dollar = [1,2,5,10,20,50,100] avail_euro = [200,100,50,20,10,5] # if n > d: # n -= d # if n > e*5: # n = n%e ans = n for i in range(0,n+1): if i*d <= n: ans = min(ans, (n - i*d)%(e*5)) else: break return ans # out_n = n # if n >= d: # n %= d # if n...
In some other world, today is December D-th. Write a program that prints `Christmas` if D = 25, `Christmas Eve` if D = 24, `Christmas Eve Eve` if D = 23 and `Christmas Eve Eve Eve` if D = 22. Constraints * 22 \leq D \leq 25 * D is an integer. Input Input is given from Standard Input in the following format: D ...
3
D = int(input()) n = 25-D eve = " Eve" print("Christmas"+eve*n)
You are given a huge integer a consisting of n digits (n is between 1 and 3 ⋅ 10^5, inclusive). It may contain leading zeros. You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by 2). For example, if a = 032...
3
t = int(input()) for _ in range(t): number = list(input()) odd = [] even = [] for num in number: if int(num) % 2: odd.append(int(num)) else: even.append(int(num)) ind1, ind2 = 0, 0 while True: if ind1 >= len(odd): break if ind2 ...
You are given a permutation p_1,p_2,...,p_N consisting of 1,2,..,N. You can perform the following operation any number of times (possibly zero): Operation: Swap two adjacent elements in the permutation. You want to have p_i ≠ i for all 1≤i≤N. Find the minimum required number of operations to achieve this. Constraint...
3
n = int(input()) p = list(map(int, input().split())) ans = 0 i = 0 while i<n: if p[i]==i+1: ans += 1 i += 1 i += 1 print(ans)
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, .... <image> The Monster will catch them if at any point they scream at the same tim...
1
R=lambda:map(int,raw_input().split()) a,b=R() c,d=R() for i in range(100100): x=b+a*i if x>=d and 0==(x-d)%c: print x break else: print -1
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has a vanilla cookies and b chocolate cookies for the party. She invited n guests of the first type and m guests of the second type to the party. They will come to the ...
3
for _ in range(int(input())): v,c,a,b = map(int, input().split()) if v+c<a+b: print("NO") else: if min(v,c)<b: print("NO") else: print("YES")
Ivan is collecting coins. There are only N different collectible coins, Ivan has K of them. He will be celebrating his birthday soon, so all his M freinds decided to gift him coins. They all agreed to three terms: * Everyone must gift as many coins as others. * All coins given to Ivan must be different. * Not l...
1
N,M,K,L=map(int, raw_input().split()) t=(L+K-1)/M+1 if M*t>N: print -1 exit() print t exit()
Vasya has two arrays A and B of lengths n and m, respectively. He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, ...
1
from sys import stdin rint = lambda: int(stdin.readline()) rints = lambda: [int(x) for x in stdin.readline().split()] n, a, m, b = rint(), rints(), rint(), rints() ans, ca, cb = 0, [0, 0], [0, 0] if sum(a) != sum(b): print(-1) else: while ca[0] < n or cb[0] < m: while ca[1] < cb[1] or not ca[1]: ...
The great hero guards the country where Homer lives. The hero has attack power A and initial health value B. There are n monsters in front of the hero. The i-th monster has attack power a_i and initial health value b_i. The hero or a monster is said to be living, if his or its health value is positive (greater than o...
3
import math for _ in range(int(input())): a,b,n = map(int, input().split()) arr=list(map(int, input().split())) brr=list(map(int, input().split())) k=0 crr=[] for i in range(n): crr.append([arr[i],brr[i]]) crr.sort() #print(crr) for i in range(n): if(b<=0): ...
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin...
3
n,k=map(int,input().split(" ")) o,e=(n+1)//2,n//2 if(k<=o): print(int(k*2)-1) else: print(int((k-o)*2))
You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers. More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The ...
3
n = int(input()) nums = [int(x) for x in input().split()] nums.sort() max = nums[-1] nums[-1] = nums[0] nums[0] = max print(" ".join(str(x) for x in nums))
One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not ...
1
global sz, nxl sz = map(int, raw_input().split()) nxl = ["S", "M", "L", "XL", "XXL"] def dec(x): l = r = m = x k = 0 while sz[m] == 0: if(not k % 2): r += 1 if(r < len(nxl)): m = r else: l -= 1 if(l >= 0): m = l k += 1 sz[m] -= 1 print nxl[m] return nxl[m]; k = int(raw_input()) ans = [dec(nx...
We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array: * The array consists of n distinct positive (greater than 0) integers. * The array contains two elements x and y (these elements are known for you) such that x < y. * If you sort the arr...
3
# @oj: codeforces # @id: hitwanyang # @email: 296866643@qq.com # @date: 2020-09-04 22:22 # @url: import sys,os from io import BytesIO, IOBase import collections,itertools,bisect,heapq,math,string from decimal import * # region fastio BUFSIZE = 8192 BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __ini...
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0. In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](...
3
for i in range(int(input())): n=int(input()) a=list(map(int,input().split())) oa=a[:] a.sort() # print(a,oa) notpos=False mi=a[0] for i in range(n): if(oa[i]!=a[i]): if(oa[i]%mi!=0): notpos=True break if(notpos): print("NO")...
There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i. A postman delivers letters. Sometimes there is no specific dormitory and room number in it o...
3
# ✪ H4WK3yE乡 # Mayank Chaudhary # ABES EC , Ghaziabad # ///==========Libraries, Constants and Functions=============/// import sys from bisect import bisect_left,bisect_right from collections import deque,Counter from math import gcd,sqrt,factorial,ceil,log from itertools import permutations inf = float("inf") mod = 10...
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
from sys import stdin,stdout from math import ceil,floor,sqrt from collections import deque,Counter inp = stdin.readline out = stdout.write n = int(inp().strip()) l = sum(map(int,inp().strip().split())) print(l/n)
You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j}...
3
import sys input = lambda: sys.stdin.readline().rstrip() T = int(input()) for _ in range(T): N, K = map(int, input().split()) C = len(list(set([int(a) for a in input().split()]))) if C <= K: print(1) elif K == 1: print(-1) else: print((C - 1 + K - 2) // (K - 1))
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus. She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t...
3
import sys input = sys.stdin.readline for i in range(int(input())): n = int(input()) a = list(map(int, input().split())) a.sort() s = 1 i = 0 j = 0 while j < n and i < n: if a[i] <= s: s += 1 i += 1 j = i else: S = s ...
After learning a lot about space exploration, a little girl named Ana wants to change the subject. Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so s...
3
from collections import * import os, sys from io import BytesIO, IOBase class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self...
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
t=int(input()) for i in range(t): a1,k=map(int,input().split()) for w in range(k-1): ast=str(a1) m1=min(ast) m2=max(ast) if m1=='0': break a1=a1+int(m1)*int(m2) print(a1)
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum. For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 20, 21 and 22 respectively. Calculate the answer for t values of n. Input The first line of...
1
def result(s): total = (s*(s+1))/2 max_pow_2 = 1 while s >= max_pow_2: max_pow_2 *= 2 total_pow_2 = max_pow_2 - 1 return total - 2*total_pow_2 n = int(raw_input()) for i in range(n): s = int(raw_input()) print result(s)
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation: The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you...
3
n, l = [int(x) for x in input().split(' ')] k = [int(x) for x in input().split(' ')] s = [int(x) for x in input().split(' ')] kd = [(k[i%n] - k[i-1])%l for i in range(1, n+1)] sd = [(s[i%n] - s[i-1])%l for i in range(1, n+1)] ans = False for i in range(n): if kd == sd[i:] + sd[:i]: ans = True brea...
Consider creating the following number pattern. 4 8 2 3 1 0 8 3 7 6 2 0 5 4 1 8 1 0 3 2 5 9 5 9 9 1 3 7 4 4 4 8 0 4 1 8 8 2 8 4 9 6 0 0 2 5 6 0 2 1 6 2 7 8 Five This pattern follows the rules below. A B C In the sequence of numbers, C is the ones digit of A + B. For example 9 5 Four Now, the ones digit of 9...
3
while True: try: b = input() a=list(b) for i in range(10): a[i]=int(a[i]) n=9 for i in range(10): d = 1 for j in range(n): c=a[j]+a[d] c=c%10 a[j]=c d+=1 n-=1 ...
You are given an array a consisting of n integers. Let's denote monotonic renumeration of array a as an array b consisting of n integers such that all of the following conditions are met: * b_1 = 0; * for every pair of indices i and j such that 1 ≤ i, j ≤ n, if a_i = a_j, then b_i = b_j (note that if a_i ≠ a_j, i...
1
from sys import stdin, stdout from collections import Counter, defaultdict from itertools import permutations, combinations raw_input = stdin.readline pr = stdout.write def in_num(): return int(raw_input()) def in_arr(): return map(int,raw_input().split()) def pr_num(n): stdout.write(str(n)+'\n') de...
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
entry1=list(map(int,(input().split('+')))) entry1.sort() length=len(entry1) j=0 for i in entry1: if j!=(length-1): print(i,end='+') elif j==(length-1): print(i) j+=1
Because of budget cuts one IT company established new non-financial reward system instead of bonuses. Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting...
3
import math n=int(input()) x=((n+4)*(n+3)*(n+2)*(n*n+n))//120; x=x*((n+2)*(n*n+n))//6; print(math.floor(x));
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero. An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≤ i ≤ n - 1) the equality i mod 2 = a[i] m...
3
# -*- coding: utf-8 -*- """ Created on Tue Jun 16 19:41:45 2020 @author: rishi """ t=int(input()) ans=[] for i in range(t): n=int(input()) a=list(map(int,input().split())) oo=0 ee=0 oe=0 eo=0 for j in range(n): if(a[j]%2==0 and j%2==0): ee+=1 continue ...
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
3
#!/usr/bin/env python3 def solve(n): denom = [100, 20, 10, 5, 1] r = 0 for d in denom: r += n // d n %= d return r if __name__ == '__main__': n = int(input()) print(solve(n))
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
w = int(input()) if (w >= 1) and (w <= 100): if w % 2 == 0 and w != 2: print("YES") else: print("NO") else: print("unvalid value")
Requirements * All inputs are of non-negative integer value. * T_{\text{max}} = 10000 * 200 \leq |V| \leq 400 * 1.5 |V| \leq |E| \leq 2 |V| * 1 \leq u_{i}, v_{i} \leq |V| (1 \leq i \leq |E|) * 1 \leq d_{u_i, v_i} \leq \lceil 4\sqrt{2|V|} \rceil (1 \leq i \leq |E|) * The given graph has no self-loops / multiple edges a...
3
import sys from collections import deque from heapq import heapify, heappop, heappush def decide_next_dst(cost, order, current_id, wf): d = 0 c = 0 for key in order: if cost[key][0] * (10000 / wf[current_id][key])> c: d = key c = cost[key][0] * (10000 / wf[current_id][key]...
In Aizuwakamatsu Village, which is located far north of Aizuwakamatsu City, a bridge called "Yabashi" is the only way to move to the surrounding villages. Despite the large number of passers-by, the bridge is so old that it is almost broken. <image> Yabashi is strong enough to withstand up to 150 [kg]. For example,...
3
while True: n = int(input()) if n == 0: break tlst = [] qlst = [] for _ in range(n): m, a, b = map(int, input().split()) qlst.append((m, a, b)) tlst.append(a) tlst.append(b) tlst = sorted(list(set(tlst))) tlst.sort() tdic = {} for i, t in enumerate(tlst): tdic[t] = i lent = l...
You and your friend are participating in a TV show "Run For Your Prize". At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positi...
3
a = input() arr = list(map(int, input().split())) arr.sort() ans2 = 0; ans1 = 0; C = 10**6 for i in range(len(arr)): if (arr[i] <= C // 2): ans1 = arr[i] - 1; if (arr[i] > C // 2 and ans2 == 0): ans2 = C - arr[i]; print(max(ans1, ans2))
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the k-th digit of this sequence. Input The first and only lin...
3
n=int(input())-1 i=0 while n>=(9*(i+1)*(10**i)): n-=(9*(i+1)*(10**i)) i+=1 # print (n) a=int(pow(10,i))+int(n/(i+1)) # print (a) print(str(a)[n%(i+1)])
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
n=int(input()) li=list(map(int,input().split(" ",n)[:n])) li.sort() ans=0 l,r=0,n-1 pr=0 while l<r: if li[l]+li[r]+pr<=4: l+=1 pr+=li[l-1] else: r-=1 ans+=1 pr=0 print(ans+1)
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string. B now gi...
3
q=input() a=q.count('a') b=q.count('b') c=q.count('c') if (q==a*'a'+'b'*b+c*'c')&((a==c)|(b==c))&(a>0)&(b>0): print('YES') else: print('NO')
Hierarchical Democracy The presidential election in Republic of Democratia is carried out through multiple stages as follows. 1. There are exactly two presidential candidates. 2. At the first stage, eligible voters go to the polls of his/her electoral district. The winner of the district is the candidate who takes a ...
3
import sys sys.setrecursionlimit(10**5) def LI(): return [int(x) for x in input().split()] def LF(): return [float(x) for x in input().split()] def LI_(): return [-1*int(x) for x in input().split()] def II(): return int(input()) def IF(): return float(input()) def LM(func,n): return [[func(x) for x in input().split()]...
A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows: ...
3
t = int(input()) for i in range(t): n = int(input()) ans = 0 tall = 1 if n >=2: ans +=1 while n >= 2: if n >= 2+3*(tall-1): n -= 2+3*(tall-1) tall += 1 else: tall = 1 ans += 1 print(ans)
Not so long ago as a result of combat operations the main Berland place of interest — the magic clock — was damaged. The cannon's balls made several holes in the clock, that's why the residents are concerned about the repair. The magic clock can be represented as an infinite Cartesian plane, where the origin correspond...
3
# from decimal import * # getcontext().prec=16 # from math import sqrt # from scipy.special import binom # from collections import defaultdict from math import sin,pi,sqrt x,y=list(map(int,input().split(" "))) if sqrt(x**2+y**2)%1==0: color=1 else: if x*y>=0: color=1 else: color=0 int_...
Everybody knows that the m-coder Tournament will happen soon. m schools participate in the tournament, and only one student from each school participates. There are a total of n students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. ...
3
""" Oh, Grantors of Dark Disgrace, Do Not Wake Me Again. """ ii = lambda: int(input()) mi = lambda: map(int, input().split()) li = lambda: list(mi()) si = lambda: input() n, m, k = mi() p, s, c = li(), li(), li() d = {i: 0 for i in range(1, m+1)} f = 0 for g, h in zip(s, p): d[g] = max(d[g], h) for i in c: ...
For two sequences S and T of length N consisting of 0 and 1, let us define f(S, T) as follows: * Consider repeating the following operation on S so that S will be equal to T. f(S, T) is the minimum possible total cost of those operations. * Change S_i (from 0 to 1 or vice versa). The cost of this operation is D \time...
3
N = int(input()) C = list(map(int,input().split())) for i in range(N): C[i] *= -1 C.sort() for i in range(N): C[i] *= -1 mod = 10**9 + 7 ans = 0 for i in range(N): ans += C[i]*(i+2) ans = ans*(4**(N-1)) ans = ans % mod print(ans)
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints. Consider...
3
n, m = map(int, input().split()) list1 = [] list2 = [i for i in range(1,m+1)] for i in range(n): a,b = (map(int, input().split())) while a != b+1: preind = a if a in list2: ind = list2.index(preind) list2.pop(ind) a += 1 print(len(list2)) for i in list2: print...
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: * the Power Gem of purple color, * the Time Gem of green color, * the Space Gem of blue color, * the Soul Gem of orange color, * the Reality Gem of red color, * the Mind Gem of yellow color. ...
3
l = ['purple','green','blue','orange','red','yellow'] dic = {'purple':"Power",'green':"Time",'blue':"Space","orange":"Soul",'yellow':"Mind",'red':"Reality"} for _ in range(int(input())): stone = input() l.remove(stone) print(len(l)) for i in l: print(dic[i])
You are given a board of size n × n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move...
1
I=lambda: map(int, raw_input().split()) t = input() for _ in xrange(t): n = input() r = 0 for k in xrange(1, n//2+1): r += 8*(k**2) print r
You have n distinct points (x_1, y_1),…,(x_n,y_n) on the plane and a non-negative integer parameter k. Each point is a microscopic steel ball and k is the attract power of a ball when it's charged. The attract power is the same for all balls. In one operation, you can select a ball i to charge it. Once charged, all ba...
1
from __future__ import division from sys import stdin ceil1 = lambda a, b: (a + b - 1) // b rints = lambda: [int(x) for x in stdin.readline().split()] rints_2d = lambda n: [rints() for _ in range(n)] for _ in range(int(input())): n, k = rints() a, ans = rints_2d(n), -1 for i in range(n): tem = 0 ...
The following problem is well-known: given integers n and m, calculate <image>, where 2n = 2·2·...·2 (n factors), and <image> denotes the remainder of division of x by y. You are asked to solve the "reverse" problem. Given integers n and m, calculate <image>. Input The first line contains a single integer n (1 ...
1
import sys n = int(raw_input()) m = int(raw_input()) m_bin = bin(m) m_bin = m_bin[::-1] sumod = 0 for i in range(0,len(m_bin) - 2): if m_bin[i] == '1' and i < n: sumod += 2**i print sumod
You play your favourite game yet another time. You chose the character you didn't play before. It has str points of strength and int points of intelligence. Also, at start, the character has exp free experience points you can invest either in strength or in intelligence (by investing one point you can either raise stre...
3
def main(a): a=a.split(' ') (x,y,z)=(int(a[0]),int(a[1]),int(a[2])) if y-x>=z:return 0 else: w = (x+z-y+1)//2 return min(w, z+1) a = int(input()) b=[] for i in range(a): b.append(main(input())) for j in b: print(j)
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the k-th digit of this sequence. Input The first and only lin...
3
""" Strategy: Split sequence into subsequences according to number of digits. Then find corresponding number and digit in that number. """ # Standard input. k=int(input()) # Initilize sequence num_digits=1 num_numbers=9 k-=1 while k>num_digits*num_numbers: # Move sequence starting point. k -= num_numbers*nu...
Eudokimus, a system administrator is in trouble again. As a result of an error in some script, a list of names of very important files has been damaged. Since they were files in the BerFS file system, it is known that each file name has a form "name.ext", where: * name is a string consisting of lowercase Latin lett...
3
s = input() v = s.split(sep='.') flen = len(v[0]) llen = len(v[-1]) #print(v) if len(v) < 2 : print('NO') elif not (flen >= 1 and flen <= 8) : print('NO') elif not (llen >= 1 and llen <= 3) : print('NO') else : for i in v[1:-1] : if not (len(i) >= 2 and len(i) <= 11) : ...
Rng has a connected undirected graph with N vertices. Currently, there are M edges in the graph, and the i-th edge connects Vertices A_i and B_i. Rng will add new edges to the graph by repeating the following operation: * Operation: Choose u and v (u \neq v) such that Vertex v can be reached by traversing exactly thr...
3
from collections import deque N, M = map(int, input().split()) adj = [ [] for _ in range(N)] clr = [-1 for _ in range(N)] #グラフ構築 for _ in range(1,M+1): u, v = map(int, input().split()) u -= 1 v -= 1 adj[u].append((v,1)) adj[v].append((u,1)) #二部グラフか否か判定 vis = [0 for _ in range(N)] q = deque([(0,0)]) is_bi...
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()) for _ in range(t): l = list(map(int,input().split())) m = max(l) if l.count(m)==3: print('YES') print(m,m,m) elif l.count(m)==2: print('YES') n = min(l) print(m,n,n) else: print('NO')
The Fair Nut lives in n story house. a_i people live on the i-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening. It was decided ...
3
import sys input = sys.stdin.readline from collections import * n = int(input()) a = list(map(int, input().split())) ans = 10**18 for i in range(n): ans_cand = 0 for j in range(n): ans_cand += 2*a[j]*(abs(j-i)+i+j) ans = min(ans, ans_cand) print(ans)
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: * the Power Gem of purple color, * the Time Gem of green color, * the Space Gem of blue color, * the Soul Gem of orange color, * the Reality Gem of red color, * the Mind Gem of yellow color. ...
1
import Queue vi = int(raw_input()) dict1 = {} dict1['red'] = 1 dict1['purple'] = 1 dict1['yellow'] = 1 dict1['green'] = 1 dict1['blue'] = 1 dict1['orange'] = 1 saida = {} vistas = {} for i in range(vi): cor = raw_input() dict1[cor] = 0 print (6-vi) for chave in dict1.keys(): if dict1[chave] == 1: if...
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and ...
3
n,k=map(int,input().split()) if n==1 and k==1: print(1,0) else: print(min(n,k),abs(n-k)//2)
There are N cities and M roads. The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally. There may be more than one road that connects the same pair of two cities. For each city, how many roads are connected to the city? Constraints * 2≤N,M≤50 * 1≤a_i,b_i≤N * a_i ≠ b_i * All input values a...
1
N, M = map(int, raw_input().split()) roadlist = [] for i in range(0, N): town = [] for j in range(0, N): town.append(0) roadlist.append(town) for i in range(0, M): a, b = map(int, raw_input().split()) roadlist[a-1][b-1] = roadlist[a-1][b-1] + 1 roadlist[b-1][a-1] = roadlist[b-1][a-1] + 1 for i in range(0, N):...
This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only. Waking up in the ...
3
import io,os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def solve(ind): pp=0 x=l3[ind][0] for i in range(0,ind): tam,kal,ger=l3[i] if tam < x: t=ger-kal+(x-tam-1)*ger else: t=0 pp+=t if pp <=k: return True else: ...
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists. You have to answer t independent test cases. Recall that the substring s[l ...
3
import sys,bisect from math import gcd input = sys.stdin.readline ############ ---- USER DEFINED INPUT FUNCTIONS ---- ############ def inp(): return(int(input().rstrip())) def inlt(): return(list(map(int,input().rstrip().split()))) def insr(): s = input().rstrip() return(s[:len(s) - 1]) def invr(): ...
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins. You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have. ...
3
import math n = int(input()) for i in range(n): s = 0 m = int(input()) a = [int(x) for x in input().split()] s= sum(a) print(math.ceil(s/m))
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from strin...
3
t = int(input()) hay8=0 for i in range(t): hay8=0 n = int(input()) numeros = input() if(n<11 or (n==11 and numeros[0]!="8")): print("NO") elif(n==11 and numeros[0]=="8"): print("YES") else: for j in range(n): if(numeros[j]=="8"): hay8=1 if(n-j>=11): print("YES") else: print("NO") ...