problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round. For example, the following numbers are roun...
3
for _ in range(int(input())): a = int(input()) b = [] k = 0 while a > 0 : p = a%10 if p != 0 : b.append(p*(10**k)) a //= 10 k += 1 #print(b) print(len(b)) for i in range(len(b)): print(b[i],end = " ") print()
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char...
3
import math for t in range(int(input())): s=input() alice=False i=0 while '01' in s or '10' in s: while i<len(s)-1: if (s[i]=='1' and s[i+1]=='0') or (s[i]=='0' and s[i+1]=='1'): s=s[:i]+s[i+2:] i=-1 alice=not alice i+=1 ...
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time. So the team is considered perfect if it includ...
3
n=int(input()) while(n>0): a,b,c=map(int,input().strip().split()) x=(a+b+c)//3 if(min(a,b)>=x): print(x) else: print(min(a,b)) n-=1
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ— j. The rows and columns are numbered starting from 1. You are given a positive integer x. Your task is to count the number of cells in a table that contain number x. Input T...
1
""" import random import sys def check_prime(num): for i in range(5): ran=random.randrange(1,num) check=((ran**(num-1))%num)==1 if not check: return check return check def main(): n,num=map(int, sys.stdin.readline().split()) cnt=0 for i in range(1,n+1): ...
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick. Let's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, ...
1
import atexit, io, sys buffer = io.BytesIO() sys.stdout = buffer @atexit.register def write(): sys.__stdout__.write(buffer.getvalue()) n = input() L = [int(x)-1 for x in raw_input().split()] for i in range(n): D = {} t = i D[t] = True while D.has_key(L[t]) is False: D[L[t]] = True ...
You will be given a string S of length 3 representing the weather forecast for three days in the past. The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. `S`, `C`, and `R` stand for sunny, cloudy, and rainy, respectively. You will also be given a string T of length 3 representing the ...
3
S=input() T=input() c=0 for s,t in zip(S,T): if s==t: c+=1 print(c)
You are given an array of n integers a_1,a_2,...,a_n. You have to create an array of n integers b_1,b_2,...,b_n such that: * The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_...
3
def swap(xs, i, j): tmp = xs[i] xs[i] = xs[j] xs[j] = tmp def solve(xs): sum_ = 0 i = 0 n = len(xs) while i < n: x = xs[i] sum_ += x if sum_ == 0: sum_ -= x j = i + 1 y = x while j < n: if xs[j] != x...
Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome! The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac...
3
# https://codeforces.com/problemset/problem/62/B # bin search def search(val): l = 0 r = 1 while l <= r: pass def calc_f(arr, val): n = len(arr) l = 0 r = n - 1 last_less = False while l <= r: m = l + (r - l) // 2 if arr[m] < val: l = m + 1 ...
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ...
3
n, l = map(int, input().split()) a = list(map(int, input().split())) a.sort() d = max(a[0], l - a[-1]) for i in range(1, n): d = max(d, (a[i] - a[i-1]) / 2) print(d)
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment. What is the minimu...
3
n= int(input()) bis, ans = 1<<32, 0 while bis != 0: if(n&bis != 0): ans+= 1 bis >>= 1 print(ans)
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word. Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character ...
3
from collections import Counter s=input() i=len(s)-1 h=i+1 x=s ans=0 r=set() while i>=0: x=s[i]+x x=x[:h] r=r|{x} #print(x) i-=1 print(len(r))
In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b. Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b suc...
3
import math num_de_casos = int(input()) for i in range(num_de_casos): caso = int(input()) raiz = int(math.sqrt(caso)) maior = 1 for j in range(2, raiz + 1): if caso % j == 0: maior = caso // j break complemento = caso - maior print(maior, complemento)
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible. There are n manholes in the room which are situated on one line, but, unfortunately, all the manholes are clo...
3
n, k = map(int, input().split()) print(n * 3 + min(n - k, k - 1))
There are n integers b1, b2, ..., bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure: * The crow sets ai initially 0. * The crow then adds bi to ai, subtracts bi + 1, adds the bi + 2 number, and so on until the n'th number. Thus, ai = bi - bi + 1 + bi...
3
import math import string def main(): n = int(input()) b = list(map(int, input().split())) a = [b[i+1] + b[i] for i in range(n - 1)] + [b[-1]] print(' '.join(map(str, a))) if __name__ == '__main__': main()
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≀ i ≀ n. He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se...
3
if __name__== "__main__": for _ in range(int(input())): n = int(input()) if n%2 == 0: print(n // 2) else: print((n - 1) // 2 + 1)
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
3
n, m, a = map(int, input().split()) x = n//a if (n%a == 0) else n//a+1 y = m//a if (m%a == 0) else m//a+1 print(x*y)
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" β€” three distinct two-grams. You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ...
3
n = int(input()) s = str(input()) listado = {} for i in range(len(s)-1): gram = s[i:i+2] if gram in listado.keys(): listado[gram] = listado[gram] + 1 else: listado[gram] = 1 max_gram = '' max_gram_value = 0 for i in listado.keys(): if listado[i] > max_gram_value: max_gram_value = listado[i] max_gram = i pr...
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
3
count = 0 for i in range(int(input())): x = list(map(int, input().split(' '))) if x[1] - x[0] >=2: count +=1 print(count)
We have N gemstones labeled 1 through N. You can perform the following operation any number of times (possibly zero). * Select a positive integer x, and smash all the gems labeled with multiples of x. Then, for each i, if the gem labeled i remains without getting smashed, you will receive a_i yen (the currency of ...
3
from collections import deque class Dinic: def __init__(self, N): self.N = N self.G = [[] for i in range(N)] def add_edge(self, fr, to, cap): forward = [to, cap, None] forward[2] = backward = [fr, 0, forward] self.G[fr].append(forward) self.G[to].append(backward)...
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
letters = "".join(chr(ord("a") + x) for x in range(26)) for t in range(int(input())): n, a, b = map(int, input().split()) s = "a" * (a - b) + letters[:b] print((s * (n // a + 1))[:n])
Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece s...
3
n = input() m = input() c = set(m) ans = 0 for colour in c: nc = n.count(colour) mc = m.count(colour) if nc == 0: ans = -1 break else: ans += min(nc, mc) print(ans)
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>] where: * <protocol> can equal either "http" (without the quotes) or "ftp" (without the q...
1
a,b,c=raw_input().partition('tp') d,e,f=c.rpartition('ru') if f : e += '/' print a+b+"://"+d+"."+e+f
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...
1
def main(): n = input() from collections import deque arr = range(1, n+1) arr = deque(arr) if n == 2: print 1 print 1, 1 return special = [1] for i in xrange(3, 60000 + 10): if abs(special[-1] - i) > 2 and i % 2 != 0: special.append(i) def solve(n): group = (n-1) / 2 ans = [1] arr.p...
You are given a string s consisting of n lowercase Latin letters. You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation. String s = s_1 s_2 ... s_n is lexicograp...
3
n=int(input()) l=list(input()) ans='' flag=0 for i in range(n-1): if l[i]>l[i+1] and flag==0: flag=1 else: ans+=l[i] if len(ans)!=n-1: ans+=l[n-1] print(ans)
Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the i-th of them will start during the x_i-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes x_1, x_2, ..., x_n, so he will be awak...
3
import bisect import decimal from decimal import Decimal import os from collections import Counter import bisect from collections import defaultdict import math import random import heapq from math import sqrt import sys from functools import reduce, cmp_to_key from collections import deque import threading from itert...
Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat. <image> There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ....
1
n = int(raw_input()) a = [] a.append([int(m) for m in raw_input().split()]) cost = a[0][1] pay = cost*a[0][0] for i in range(1,n): a.append([int(m) for m in raw_input().split()]) if cost > a[i][1]: cost = a[i][1] pay = pay + cost*a[i][0] elif cost <= a[i][1]: pay = pay + cost*a[i][0]...
You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move. There are n doors, the i-th door initially has durability equal to a_i. During your move you can try to br...
3
#!/usr/bin/env python # coding: utf-8 # In[35]: [a,b,c]=[int(x) for x in input().split()] l=[int(x) for x in input().split()] if b>c: print(a) else: count=0 for i in l: if i<=b: count+=1 if count%2==0: print(int(count/2)) else: print(int(count/2)+1) # In...
Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n = p1Β·p2Β·...Β·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109 + 7 is the password to the secret data base. Now he wants to calculate this value. Input The first line of the input contains a sing...
3
from collections import * input() d = 1000000007 c = Counter(map(int, input().split())) s = n = 1 for p, k in c.items(): s = pow(s, k + 1, d) * pow(p, n * k * (k + 1) // 2 % (d - 1), d) % d n = n * (k + 1) % (d - 1) print(s)
After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus. * Initially, there is a pile that contains x 100-yen coins and y 10-yen coi...
3
x,y=map(int,input().split()) Ceil=True while True: if Ceil: if x>=2: if y>=2: x-=2; y-=2; Ceil=False else: print("Hanako"); exit() elif x==1: if y>=12: x-=1; y-=12; Ceil=False else: print(...
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person. You are given the first and ...
3
s1,s2=input().split() ans=s1[0] for j in s1[1:]: if j<s2[0]: ans=ans+j else: break ans+=s2[0] print(ans)
Alice has a string s. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not. Alice can erase some characters from her string s. She would like to know wh...
3
s = input() n = s.count('a') y = len(s) if n > y / 2: print(y) else: while n <= y / 2: y -= 1 print(y)
You are given two matrices A and B. Each matrix contains exactly n rows and m columns. Each element of A is either 0 or 1; each element of B is initially 0. You may perform some operations with matrix B. During each operation, you choose any submatrix of B having size 2 Γ— 2, and replace every element in the chosen sub...
3
from sys import stdin n,m=map(int,stdin.readline().strip().split()) s=[] for i in range(n): s.append(list(map(int,stdin.readline().strip().split()))) b=[[0 for i in range(m)] for j in range(n)] ans=[] for i in range(n-1): for j in range(m-1): if s[i][j]==1 and s[i+1][j]==1 and s[i+1][j+1]==1 and s[i][j+...
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
3
s=input() t=input() p=s[::-1] if p==t: print("YES",end='') else: print("NO",end='')
Input The input contains a single integer a (0 ≀ a ≀ 35). Output Output a single integer. Examples Input 3 Output 8 Input 10 Output 1024
3
x = [4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438, 454, 483, 517, 526, 535, 562, 576, 588, 627, 634, 636, 645, 648, 654, 663] print(x[int(input()) - 1])
Alice and Bob have decided to play the game "Rock, Paper, Scissors". The game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a ...
3
n=int(input()) r1,s1,p1=tuple([int(x) for x in input().split()]) r2,s2,p2=tuple([int(x) for x in input().split()]) resmax = min(r1,s2)+min(s1,p2)+min(p1,r2) #next line - maximum losing... #resmin = min(r1,p2)+min(s1,r2)+min(p1,s2) #fix. Rock does not win if either paper or scisors is shown. resmin = min(r1,n-s2)+min(...
Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so th...
3
n = int(input()) ar = [i for i in range(1,(n**2)+1)] for i in range(1, int((n**2)/2)+1): print(ar[i-1],ar[-i])
One day Ms Swan bought an orange in a shop. The orange consisted of nΒ·k segments, numbered with integers from 1 to nΒ·k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote...
3
#!/usr/bin/env python3 from sys import stdin, stdout def solve(): n, k = map(int,stdin.readline().split()) li = list(map(int,stdin.readline().split())) vis = [-1 for i in range(n*k)] for i in range(k): vis[li[i]-1] = i ans = [list() for i in range(k)] p = 0 for i in range(n*k): ...
On the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Martians have the same weeks as earthlings β€” 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars. Input The first line of the input contains a ...
1
n=int(raw_input()) maxm=(n//7)*2+(n%7>=1)+(n%7>=2) minm=(n//7)*2+(n%7==6) print minm,maxm
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
num=int(input()) if (num%2!=0 or num==2): print("NO") else: print("YES")
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied. ZS and Chris are...
3
n = int(input()) li = [] for _ in range(n): li2 = input().split('|') for j in li2: li.append(j) if 'OO' in li: print('YES') li[li.index('OO')] = '++' else: print('NO') exit() li = [li[n:n+2] for n in range(0, len(li), 2)] res = [] for i in li: res.append('|'.join(i)) print('\n'.join(...
You are given an array a consisting of n integer numbers. Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i. You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible...
3
a = int(input()) l = list(map(int,input().split())) l.sort() if l[ -1] - l[0] > l[ -1 ] - l[1]: if l[-1] - l[1] > l[ -2] - l[0]: print(l[-2] - l[0]) else: print(l[-1] - l[1]) else: if l[-1] - l[0] > l[ -2] - l[0]: print(l[-2] - l[0]) else: print(l[-1] - l[0])
You are given a range of positive integers from l to r. Find such a pair of integers (x, y) that l ≀ x, y ≀ r, x β‰  y and x divides y. If there are multiple answers, print any of them. You are also asked to answer T independent queries. Input The first line contains a single integer T (1 ≀ T ≀ 1000) β€” the number of...
3
n=int(input()) t=0 while t<n: a=input().split() x=int(a[0]) y=2*x print(str(x) + ' ' +str(y)) t+=1
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
a = input() u = len([i for i in a if i.isupper()]) l = len(a) - u if l < u: print(a.upper()) else: print(a.lower())
Bob is decorating his kitchen, more precisely, the floor. He has found a prime candidate for the tiles he will use. They come in a simple form factor β€” a square tile that is diagonally split into white and black part as depicted in the figure below. <image> The dimension of this tile is perfect for this kitchen, as h...
3
w, h = map(int, input().split()) print((4 * 2**(w + h - 2)) % 998244353)
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said: β€”Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes....
1
a = raw_input() b = raw_input() x = [] for i in a: x.append(i) x.sort() i = 0 while i<len(x) and x[i] == '0': i+=1 if i != len(x): s = x[i] for j in xrange(0,len(x)): if j!=i: s+=x[j] else: s = "0" if len(b)>1 and b[0] == '0': print "WRONG_ANSWER" elif int(s) != in...
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player. Your task is to write a program that...
3
a = list(map(int,input().split())) n = len(a) asum = sum(a) if asum%n == 0 and asum > 0 : print(asum//n) else : print(-1)
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below. There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each ...
3
# -*- coding: utf-8 -*- """ Created on Mon Nov 23 21:30:12 2020 @author: 17831 """ n = int(input()) a = [[int(x) for x in input().split()] for i in range(n)] c = [abs(a[i][0]-a[i-1][0])for i in range(1,n)] if n == 1: print(1) else: s = 2 for i in range(1,n-1): if a[i][1] < c[i - 1]: s+...
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n. For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10. Input The first line contains an integer t (1 ≀ t ≀ 1000) β€” the ...
3
# itne me hi thakk gaye? for _ in range(int(input())): n,k = list(map(int,input().split())) mul = k // (n-1) div = k % (n-1) res = n * mul if(div == 0): res -= 1 else: res += div print(res)
Given is a string S representing the day of the week today. S is `SUN`, `MON`, `TUE`, `WED`, `THU`, `FRI`, or `SAT`, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively. After how many days is the next Sunday (tomorrow or later)? Constraints * S is `SUN`, `MON`, `TUE`, `WED`, `THU`,...
3
A={'SUN':7,'MON':6,'TUE':5,'WED':4,'THU':3,'FRI':2,'SAT':1} print(A[input()])
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
1
n=int(raw_input()) list_ab=[] for x in range(1,n+1): a_b=map(int,raw_input().split(" ")) list_ab.append(a_b) passengers=0 limit=0 for x in range(0,n): passengers=passengers+((list_ab[x])[1])-((list_ab[x])[0]) limit=max(limit,passengers) print limit
Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will ...
3
n, k = [int(i) for i in input().split()] doub = []; a = []; b = [] for i in range(n): ti, ai, bi = [int(i) for i in input().split()] if ai and bi: doub.append(ti) elif ai: a.append(ti) elif bi: b.append(ti) doub.sort(); a.sort(); b.sort() # print(doub, a, b, sep="\n"...
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β€” to check his answers, he needs a program that among the given n numbers finds one that is di...
3
n=int(input()) a=[int(w)%2 for w in input().split()] if a.count(0)==len(a)-1: print(a.index(1)+1) else: print(a.index(0)+1)
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage...
3
lst = list() for i in range(3): lst.append(input()) if lst[0][0] == lst[2][2] and lst[0][1] == lst[2][1] and lst[0][2] == lst[2][0] and lst[1][0] == lst[1][2]: print("YES") else: print("NO")
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
1
temp = raw_input() sum =0 sum += temp.count('4') sum += temp.count('7') if sum==4 or sum==7: print('YES') else: print('NO')
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; ")...
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 17 22:08:22 2019 @author: killmonger """ import os import sys import math import collections import cmath def mp(): return map(int,input().split()) def inp(): return input() a=int(inp()) b=int(inp()) c=int(inp()) d=int(inp()) if a!=d: p...
In Aramic language words can only represent objects. Words in Aramic have special properties: * A word is a root if it does not contain the same letter more than once. * A root and all its permutations represent the same object. * The root x of a word y is the word that contains all letters that appear in y ...
3
from collections import defaultdict d = defaultdict(list) n = int(input()) a = input().split() for i in range(n): l = list(sorted(set(a[i]))) s = "".join(l) if s in d: continue else: d[s] = 1 print(len(d))
Kode Festival is an anual contest where the hardest stone in the world is determined. (Kode is a Japanese word for "hardness".) This year, 2^N stones participated. The hardness of the i-th stone is A_i. In the contest, stones are thrown at each other in a knockout tournament. When two stones with hardness X and Y ar...
3
def main(): N = int(input()) A = [] for _ in range(pow(2, N)): A.append(int(input())) # print(A) while len(A) > 1: temp = [] for i in range(len(A)//2): if A[2*i] < A[2*i+1]: temp.append(A[2*i+1] - A[2*i]) elif A[2*i] > A[2*i+1]: temp.append(A[2*i] - A[2*i+1]...
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis...
3
T = int(input()) for kase in range(T): n = int(input()) if n&1: print('7'+(n-3)//2*'1') else: print(n//2*'1')
Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat. <image> There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ....
1
n = input() pa = [] minim = 100 summa = 0 for i in xrange(0, n): pa.append(map(int ,(raw_input().split()))) if pa[i][1] < minim: minim = pa[i][1] summa += minim*pa[i][0] print summa
You are given a string S of length N consisting of `A`, `B` and `C`, and an integer K which is between 1 and N (inclusive). Print the string S after lowercasing the K-th character in it. Constraints * 1 ≀ N ≀ 50 * 1 ≀ K ≀ N * S is a string of length N consisting of `A`, `B` and `C`. Input Input is given from Standa...
3
s = input().split() t = input() k = int(s[1]) - 1 print(t[:k] + t[k].lower() + t[k+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 findLargest(s, level, m, res): if level == m: return res; for i in range(9, -1, -1): if s - i >= 0: res = res + str(i) res = findLargest(s - i,level + 1, m ,res) break return res m, s = list(map(int, input().split())) max_s = pow(10,m...
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
1
import math m,n,a = map(int, raw_input().strip().split()) print int(((m+a-1)/a)*((n+a-1)/a))
You are given a sequence of n digits d_1d_2 ... d_{n}. You need to paint all the digits in two colors so that: * each digit is painted either in the color 1 or in the color 2; * if you write in a row from left to right all the digits painted in the color 1, and then after them all the digits painted in the color ...
3
from sys import stdin data = stdin.read().splitlines()[2::2] for i, s in enumerate(data): l, r = sorted(s, reverse=True), [''] * len(s) for j, c in enumerate(s): if c == l[-1]: del l[-1] r[j] = '1' for j, c, f in zip(range(999999), s, r): if not f and c == l[-1]: ...
You are given q queries in the following form: Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i]. Can you answer all the queries? Recall that a number x belongs to segment [l, r] if l ≀ x ≀ r. Input The first l...
3
q = int(input()) for _ in range(q): l, r, d = list(map(int, input().split())) if l > d: print(d) else: print((r // d + 1) * d)
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland). ...
3
def holiday_of_equality(a): vmax = max(a) return vmax * len(a) - sum(a) if __name__ == "__main__": n = int(input()) a = list(map(int, input().split())) result = holiday_of_equality(a) print(result)
Let's call the following process a transformation of a sequence of length n. If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from t...
3
def main(): n = int(input()) k = 1 ans = [] while n >= 4: m = (n + 1) // 2 ans += [k] * m k *= 2 n //= 2 if n == 3: ans += [k, k, 3 * k] elif n == 2: ans += [k, 2 * k] elif n == 1: ans += [k] print(*ans) if __name__ == "__main_...
In this problem you will write a simple generator of Brainfuck (<https://en.wikipedia.org/wiki/Brainfuck>) calculators. You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, when executed, will print the result of eval...
1
s = str(eval(raw_input())) for c in s: print '+' * ord(c), '.', '-' * ord(c)
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
3
n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) d = [] del(a[0]) del(b[0]) c = a + b c = list(set(c)) for i in range(1,n+1): d.append(i) if c == d: print("I become the guy.") else: print("Oh, my keyboard!")
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves...
3
from sys import setrecursionlimit setrecursionlimit(100000) number = int(input()) vershini = [-1] sugrobi = [] it = 1 it_1 = 1 while it < number+1:#pari vershin a, b = map(int, input().split(' ')) vershini.append([]) for ab in sugrobi: if a == ab[0] or b == ab[1]: vershini[it].append(it_...
Cucumber boy is fan of Kyubeat, a famous music game. Kyubeat has 16 panels for playing arranged in 4 Γ— 4 table. When a panel lights up, he has to press that panel. Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his...
3
k = int(input()) a = [] for i in range(4): for j in input(): if j=='.': continue else: a.append(j) for i in a: if a.count(i)<=2*k: continue else: print('NO') exit() print('YES')
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ...
3
import math t=int(input()) for w in range(t): n,k=(int(i) for i in input().split()) s=list(input()) d={1:[]} for i in range(n): if(s[i]=='1'): d[1]+=[i] k1=len(d[1]) if(k1==0): print(math.ceil(n/(k+1))) else: c1=0 if(d[1][0]>k): c1+=mat...
You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character. You are playing the game on the new generation console so your gamepad have 26 buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons ...
3
n,k=map(int,input().split()) l=list(map(int,input().split())) s=input() i=ans=0 while i<n: j=i while i+1<n and s[i+1]==s[i]: i+=1 ans+=sum(sorted(l[j:i+1])[-k:]) i+=1 print(ans)
Continuing the trend, this year too we present a 'Mystery' for you to solve! You will be given two numbers: a and b; and you have to output a single integer. See the sample test cases for hints. Input: The first line of the input will contain an integer t : the number of test cases. Each of the next t lines contain ...
1
t=input() while t: a,b = map(int,raw_input().split()) print a%b t-=1
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()) s = lambda: list(map(int, input().split())) for tc in range(T): b, p, f = s() h, c = s() # Make H>C if h<c: h,c=c,h f,p=p,f b=b//2 print(h*(min(b, p)) + c*(min(b-min(b, p), f)))
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
n=int(input()) c=0 for i in range(n): a=list(map(int,input().split())) if(sum(a)>=2): c+=1 print(c)
Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example, * f(599) = 6: 599 + 1 = 600 β†’ 60 β†’ 6; * f(7) = 8: 7 + 1 = 8; * f(9) = 1: 9 + 1 = 10 β†’ 1; * f(10099) = 101: 10099 + 1 = 10100 β†’ 1010 β†’ 101. ...
3
ans = 0 used_numbers = list() def recurs(number): global used_numbers global ans number += 1 if used_numbers.count(number) != 0: print(ans) return else: #print(number) used_numbers.append(number) while(number%10 == 0): number = number//10 ...
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
n=int(input()) for i in range(n): k=int(input()) s=input() if (k>10)and (s.find("8")>-1)and ((k-s.find("8"))>10) : print("YES") else: print("NO")
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ...
3
''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineering College ''' from os import path import sys from heapq import heappush,heappop from functools import cmp_to_key as ctk from collections import deque,defaultdict as dd from bisect import bisect,bisect_left,bisect_right,insort,insort_lef...
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
from sys import stdin def readline(): return stdin.readline() tests = int(readline()) def solve(n, arr): minDiff = 1000 for i in range(0, n): for j in range(i + 1, n): if minDiff > abs(arr[i] - arr[j]): minDiff = abs(arr[i] - arr[j]) return minDiff for t in range(...
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
n = input().split(" ") a = int(n[0]) b = int(n[1]) count = 0 while (a<=b): count += 1 a = a*3 b = b*2 print(count)
You are given a permutation p_1, p_2, ..., p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. Find three indices i, j and k such that: * 1 ≀ i < j < k ≀ n; * p_i < p_j and p_j > p_k. Or say that there are no such indices. Input The first lin...
3
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) j = -1 for i in range(n - 2): if(a[i] < a[i + 1] and a[i + 1] > a[i + 2]): j = i break if(j == -1): print("NO") else: print("YES") print(j + ...
Given a set of integers (it can contain equal elements). You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B). Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example: * m...
3
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) cnt1 = [0] * 110 cnt2 = [0] * 110 for i in range(n): if cnt1[a[i]] == 0: cnt1[a[i]] += 1 else: cnt2[a[i]] += 1 ans1, ans2 = 0, 0 for i in range(110): ...
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all. Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the max...
3
import sys def main(): # n candies # to k kids # min candies a # max candies b # best b - a <= 1 # # of kids who has a + 1 candies not exceeds k / 2 (round down) I = int(sys.stdin.readline()) for _ in range(I): n, k = (int(x) for x in sys.stdin.readline().split()) d = ...
Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number ...
3
n = int(input()) arr = list(map(int, input().split())) five = arr.count(5) zero = arr.count(0) if zero==0: print(-1) else: ans = '5'*((five//9)*9) + '0'*zero print(int(ans))
Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360 degrees and a pointer which initially points at zero: <image> Petr called his car dealer, who in...
3
import sys n = int(sys.stdin.readline().strip()) A = [-10] * 360 B = [-10] * 360 A[0] = -1 for i in range (0, n): a = int(sys.stdin.readline().strip()) for j in range (0, 360): if A[j] == i - 1: B[(j + a) % 360] = i B[(j - a) % 360] = i A = B[:] if A[0] == n-1: print("Y...
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant. Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose an...
3
n,m,k=map(int,input().split()) s=[[0 for i in range(m+2)] for j in range(n+2)] count=0 def Lose(x,y): if s[x-1][y] and s[x][y-1] and s[x-1][y-1]: return True if s[x+1][y] and s[x][y+1] and s[x+1][y+1]: return True if s[x-1][y] and s[x][y+1] and s[x-1][y+1]: return True if s[x+1...
You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D β‰₯ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is...
3
input() vals = [int(x) for x in input().split()] def check(t, i): tt = [x for x in t] mm = max(tt) mn = min(tt) for j in range(len(tt)): if tt[j] == mn: tt[j] += i if tt[j] == mm: tt[j] -= i if len(set(tt)) == 1: return i retu...
Given are two strings S and T consisting of lowercase English letters. Concatenate T and S in this order, without space in between, and print the resulting string. Constraints * S and T are strings consisting of lowercase English letters. * The lengths of S and T are between 1 and 100 (inclusive). Input Input is gi...
3
s=input().split() print(s[1]+s[0])
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the n...
3
def f(n): fac = 1 i = 1 while i < n: i += 1 fac = fac * i return fac def g(n, k): return f(n)//f(k)//f(n-k) n = int(input()) print(g(n, 5)+g(n,6)+g(n, 7))
Recently Vasya found a golden ticket β€” a sequence which consists of n digits a_1a_2... a_n. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket 350178 is lucky since it can be divided into three segments 350, 17 and 8: 3+5+0=1+7=8. No...
3
n = int(input()) a = list(map(int, list(input()))) m = False if a == [0 for _ in range(n)]: m = True else: s = sum(a) for i in range(1 , s): if s % i == 0: c, j = 0, 0 while c < i and j < n: c += a[j] if c == i: c = 0 j += 1 if c > i: continue if j == n: m = True print('YES' if...
There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards will be ...
3
n=int(input()) a=list(map(int,input().split())) r=[] for i in range(n): r.append([a[i],i+1]) r.sort() for i in range(n//2): print(r[i][1],r[n-i-1][1])
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games. He came up with the following game. The player has a positive integer n. Initially the value of n equals to v and the player is able to do the following operatio...
3
if __name__ == '__main__' : n = int(input()) if n == 2 : print('2') else : print('1')
Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others β€” a gr...
3
from collections import* s=Counter(input()) l=len(s) print(['No','Yes'][1<l<5and l+sum(x>1for x in s.values())>3])
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn. Nickolas adores permutations. He likes some permutations more than the o...
1
n = int(raw_input()) if n % 2 == 1: print -1 else: for i in xrange(n / 2): print 2 * (i + 1), print 2 * (i + 1) - 1, print
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies. At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her cand...
3
n, k = *map(int, input().split()), res = 0 next_day_candies = 0 for i in map(int, input().split()): res += 1 if i >= 8: k -= 8 next_day_candies += i - 8 elif next_day_candies >= 8: next_day_candies -= 8 k -= 8 next_day_candies += i elif next_day_candies > 0: next_day_candies += i if next_day_candies >...
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a...
3
for _ in range(int(input())): s = input() print(s[0],end="") i = 2 while i < len(s): if s[i-1] == s[i]: print(s[i-1],end = "") i += 1 else: print(s[i-1],end = "") i += 1 if i-1 == len(s)-1: print(s[i-1],end="") print()
Two players decided to play one interesting card game. There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a...
1
import sys data = int(sys.stdin.readline()) t = int(data) cnt = 0 while cnt < t: data = sys.stdin.readline().split() n = int(data[0]) k1 = int(data[1]) k2 = int(data[2]) data = sys.stdin.readline().split() for i in range(k1): if int(data[i]) == n: result = "YES" ...
Write a program that extracts n different numbers from the numbers 0 to 9 and outputs the number of combinations that add up to s. Each n number is from 0 to 9, and the same number cannot be used in one combination. For example, if n is 3 and s is 6, the combination of the three numbers totaling 6 is 1 + 2 + 3 = 6 0 +...
3
def bit(N,S): global ans for s in range(2**10): a=[i for i in range(10) if s>>i & 1] if len(a)==N and sum(a)==S: ans+=1 while True: N,S=map(int,input().split()) if N==0 and S==0: break ans=0 bit(N,S) print(ans)
Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al...
3
#in the name of god #Mr_Rubick a=[int(i) for i in input().split()] if a[0]==a[2]: print(a[0]+a[1]-a[3],a[1],a[0]+a[1]-a[3],a[3]) elif a[1]==a[3]: print(a[0],a[1]+a[2]-a[0],a[2],a[1]+a[2]-a[0]) elif abs(a[2]-a[0])==abs(a[3]-a[1]): print(a[0],a[3],a[2],a[1]) else: print(-1)
Write a program which calculates the area and circumference of a circle for given radius r. Constraints * 0 < r < 10000 Input A real number r is given. Output Print the area and circumference of the circle in a line. Put a single space between them. The output should not contain an absolute error greater than 10-...
3
import math p=math.pi r=float(input()) print(p*r**2,2*p*r)