problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
3
x=int(input()) y=[] z=[] b='NO' n=set('47') for i in range(1,x+1): if (x%i==0): y.append(str(i)) for p in range (0, len(y)): if set(y[p]) <= n: b="YES" print (b)
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n. The presenter has m chips. The presenter...
3
a,b=[int(i) for i in input().split()] b%=(a*(a+1)/2) for i in range(1,a+1): if(b<i): break b-=i print(int(b))
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...
3
S=input() Odd=S[::2] Even=S[1::2] print("No" if "L" in Odd or "R" in Even else "Yes")
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
3
n = int(input()) a = list(map(int, input().split())) t, ans = 0, 0 for c in a: if(t + c < 0): ans += 1 else : t += c print(ans)
There were n types of swords in the theater basement which had been used during the plays. Moreover there were exactly x swords of each type. y people have broken into the theater basement and each of them has taken exactly z swords of some single type. Note that different people might have taken different types of swo...
3
import sys input = sys.stdin.readline import math def main(): N = int(input()) A = list(map(int, input().split())) A.sort() B = [] Amax = A[-1] for i in range(N-1): B.append(Amax-A[i]) R = max(B) for b in B: if b != 0: R = min(R, b) prob = [] ...
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not. The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ...
3
import math def is_prime(n): if n % 2 == 0: return False for i in range(3, math.floor(math.sqrt(n)) + 1, 2): if n % i == 0: return False return True [x, y] = input().split() isNext = is_prime(int(y)) for i in range(int(x) + 1, int(y)): if is_prime(i): isNext = ...
Anton and Artur are old friends. Today they practice in writing strings. Anton must write each string with the lengths exactly N , based on the alphabet of size M . And Arthur, on the contrary, should write each string with the lengths exactly M , based on the alphabet of size N . Guys spend 1 second to write a sin...
1
t=int(raw_input('')) for i in range(1,t+1,1): n,m=raw_input('').split() if n==m or (int(n)==2 and int(m)==4) or (int(n)==4 and int(m)==2): print 'YES' else: print 'NO'
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
# coding=utf-8 q=str(input()) if "0000000" in q: print ("YES") elif "1111111" in q: print("YES") else : print("NO")
We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it β€” either 1 or 2. However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in a...
1
#!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase from collections import Counter if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip else: _str = str s...
The Little Elephant loves numbers. He has a positive integer x. The Little Elephant wants to find the number of positive integers d, such that d is the divisor of x, and x and d have at least one common (the same) digit in their decimal representations. Help the Little Elephant to find the described number. Input ...
1
x = input() s = set(str(x)) def f(k,x): return 1 if not x%k and any(q in s for q in str(k)) else 0 c = 0 i = 1 while i*i <= x: c += f(i,x) if i != x/i: c+=f(x/i,x) i += 1 print c
You have n distinct points on a plane, none of them lie on OY axis. Check that there is a point after removal of which the remaining points are located on one side of the OY axis. Input The first line contains a single positive integer n (2 ≀ n ≀ 105). The following n lines contain coordinates of the points. The i-t...
3
n=int(input()) pos=0 neg=0 for i in range(n): a,b=map(int,input().split()) if a>0: pos+=1 elif a<0: neg+=1 if min(pos,neg)<=1: print("YES") else: print("NO")
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
from math import ceil list = raw_input().split(' ') print int(ceil(float(list[0]) / float(list[2])) * ceil(float(list[1]) / float(list[2])))
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the re...
1
from sys import stdin import fileinput inp = [] count = int(stdin.readline().rstrip()) for i in xrange(count): inp.append(stdin.readline().rstrip().split()) m = {} for i in inp: orig, newname = i if orig in m: firstname = m[orig] del m[orig] m[newname] = firstname else: m[newname] = orig print len(m...
The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict o...
3
n = int(input()) e = [] for i in range(n): e.append(input().split()) for i in range(n): if e[i][1] == 'rat': print(e[i][0]) for i in range(n): if e[i][1] == 'woman' or e[i][1] == 'child': print(e[i][0]) for i in range(n): if e[i][1] == 'man': print(e[i][0]) for i in range(n): ...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n=int(input()) for i in range(n): a=input() m=len(a) if m>10: b=a[0] c=a[len(a)-1] d=m-2 print('{}{}{}'.format(b,d,c)) else: print(a)
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset. During each operation you choose two equal integers from s, remove them from s and insert the number eq...
3
for _ in range(int(input())): n=int(input()) l=[0]*30 for x in input().split(): x=int(x) k=0 while(x): x//=2 k+=1 l[k-1]+=1 for j in range(12): l[j+1]+=(l[j]//2) if l[11]: print("YES") else: print("NO")
The main street of Berland is a straight line with n houses built along it (n is an even number). The houses are located at both sides of the street. The houses with odd numbers are at one side of the street and are numbered from 1 to n - 1 in the order from the beginning of the street to the end (in the picture: from ...
1
n,a=map(int,raw_input().split()) print (a+1)>>1 if a&1 else (n-a+2)>>1
Mishka got an integer array a of length n as a birthday present (what a surprise!). Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps: * Replace each occurre...
1
n = input() arr = map(int,raw_input().strip().split()) for i in xrange(n): if not arr[i]&1: arr[i] -= 1 print " ".join(map(str, arr))
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
3
import io import os import sys from atexit import register import random import math import itertools ##################################### Flags ##################################### DEBUG = False # DEBUG = True STRESSTEST = False ##################################### IO ########################...
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
1
n=input() y=str(n+1) while (1): if len(list(set(list(y))))!=len(list(y)): y=str(int(y)+1) else: print y break
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
t=int(input()) for _ in range(t): a=input() count=0 i=1 while len(a)>0 and i<len(a): name='' if a[i]!=a[i-1]: count+=1 name=a[:i-1]+a[i+1:] a=name i=1 else: i+=1 if count%2!=0: print('DA') else: ...
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
str=input() non=str[0] for i in str: if (i in non): pass else: non=non+i if (len(non)%2==0): print("CHAT WITH HER!") else: print("IGNORE HIM!")
You are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the tota...
3
def triangulaton(n): s=0 for i in range(2,n): s+=i*(i+1) return s n=int(input()) print(triangulaton(n))
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
for _ in range(int(input())): word = [x for x in input()] if len(word) > 10: print(word[0] + str(len(word[1:-1])) + word[-1]) else: print(''.join(word))
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
for y in range(int(input())): #n=int(input()) #s=input() n,m,k=map(int,input().split()) #lst=list(map(int,input().split())) a,b=map(int,input().split()) maxx=0 for i in range(m+1): temp=n-i*2 if temp>=0: res1=i*a res2=min((n-2*i)//2,k)*b #p...
β€” Hey folks, how do you like this problem? β€” That'll do it. BThero is a powerful magician. He has got n piles of candies, the i-th pile initially contains a_i candies. BThero can cast a copy-paste spell as follows: 1. He chooses two piles (i, j) such that 1 ≀ i, j ≀ n and i β‰  j. 2. All candies from pile i are...
3
t=int(input()) for _ in range(t): n,k=map(int,input().split()) c=list(map(int,input().split())) d=0 x=min(c) c.remove(x) for i in c: d+=(k-i)//x print(d)
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as ...
3
El = [] Er = [] En = [] N = int(input()) g = [[] for _ in range(N+1)] dist = [2**20 for _ in range(N+1)] visited = [0] * (N+1) s = [1] for num in range(N-1): u, v = list(map(int, input().split())) # u, v = num+1, num+2 g[u].append(v) g[v].append(u) El.append(v) Er.append(u) En.append(num) fo...
Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M. Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N): * There exists a non-negative integer p such that X= a_k \times (p+0.5). Find the number of semi-co...
3
import fractions n, m = map(int, input().split()) a = list(map(int, input().split())) def gcd(x, y): if y == 0: return x else: return gcd(y, x % y) def lcm(x, y): return (x * y) // gcd(x, y) now = a[0] for i in range(1, n): now = lcm(now, a[i]) if now > 2 * m: print(0) exit(0) for i i...
Vasya likes to solve equations. Today he wants to solve (x~div~k) β‹… (x mod k) = n, where div and mod stand for integer division and modulo operations (refer to the Notes below for exact definition). In this equation, k and n are positive integer parameters, and x is a positive integer unknown. If there are several solu...
3
n, k = (int(s) for s in input().split(' ')) max_mod = min(n, k - 1) min_x = 99999999999999999 for i in range(1, max_mod + 1): if n % i == 0: div = n // i x = div * k + i if x < min_x: min_x = x print(min_x)
In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other pers...
3
a,b,k=map(int,input().split()) ans=[a,b] for i in range(k): if i%2: ans[0]+=ans[1]//2 ans[1]//=2 else: ans[1]+=ans[0]//2 ans[0]//=2 print(*ans)
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend t...
3
import sys def fastio(): from io import StringIO from atexit import register global input sys.stdin = StringIO(sys.stdin.read()) input = lambda : sys.stdin.readline().rstrip('\r\n') sys.stdout = StringIO() register(lambda : sys.__stdout__.write(sys.stdout.getvalue())) fastio() def debug(*va...
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total. Each Kinder Surprise can be one of three types: * it can contain a single sticker and no toy; * it can contain a single toy and no sticker; * it can contain both a sing...
3
t = int(input()) for i in range(t): a = [int(i) for i in input().split()] print(a[0] - min(a[1],a[2]) + 1)
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling...
3
n = int(input()) ar = list(map(int,input().split())) p = n-1 if n == 2: x = ar[1]-ar[0] if x < 0: ar[1] = ar[1]+abs(x) ar[0] = ar[0]-abs(x) else: while p > 1: for i in range(p): x = ar[p] - ar[i] if x < 0: ar[p] = ar[p]+abs(x) ...
Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first mov...
3
from sys import stdin,stdout from math import gcd,sqrt,factorial,pi from collections import deque,defaultdict input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\n') L=lambda:list(R()) P=lambda x:stdout.write(x) lcm=lambda x,y:(x*y)//gcd(x,y) hg=lambda x,y:((y+x-1)//x)...
The postal code in Atcoder Kingdom is A+B+1 characters long, its (A+1)-th character is a hyphen `-`, and the other characters are digits from `0` through `9`. You are given a string S. Determine whether it follows the postal code format in Atcoder Kingdom. Constraints * 1≀A,B≀5 * |S|=A+B+1 * S consists of `-` and di...
3
A,B=map(int,input().split()) S=input() print("Yes" if (S[A]=="-")and(S.count("-")==1) else "No")
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
nma = list(map(int, input().split())) n = nma[0] m = nma[1] a = nma[2] print(((m+a-1)//a)*((n+a-1)//a))
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The ...
3
import math from collections import Counter L=lambda:list(map(int,input().split())) M=lambda:map(int,input().split()) I=lambda:int(input()) IN=lambda:input() mod=10**9+7 def s(a): print(" ".join(list(map(str,a)))) #______________________-------------------------------_____________________# n,m=M() a=[math.ceil(m/2)...
The round carousel consists of n figures of animals. Figures are numbered from 1 to n in order of the carousel moving. Thus, after the n-th figure the figure with the number 1 follows. Each figure has its own type β€” the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal...
1
RI = lambda t = int: t(raw_input()) RL = lambda t = int: map(t, raw_input().split()) RLL = lambda n, t = int: [map(t, raw_input().split()) for _ in range(n)] def solve(): n = RI() A = RL() C = [] l = None lc = 1 sp = None i = 0 for a in A: if a != l: lc = lc ^ 1 l = a else: ...
Masha has n types of tiles of size 2 Γ— 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type. Masha decides to construct the square of size m Γ— m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ...
3
t = int(input()) def is_symmetric(matrix): for p in range(2): for q in range(2): if matrix[p][q] != matrix[q][p]: return False return True for i in range(t): n, m= input().split() n = int(n) m = int(m) sit = False for j in range(n): first_row =...
Sayaka Saeki is a member of the student council, which has n other members (excluding Sayaka). The i-th member has a height of a_i millimeters. It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wa...
3
if __name__ == '__main__': for _ in range(int(input())): _ = input() values = list(map(int, input().split())) odd, even = [], [] for x in values: if x % 2: odd.append(x) else: even.append(x) pri...
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts. Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following act...
3
n = int(input()) table=[] ans=0 for i in range(n): table.append(int(input())) for i in range(n): if i==0: ans+=table[0] place = table[0] else: if place>table[i]: ans+= abs(table[i]-place) place = table[i] else: ans+=abs(table[i]-place) ...
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
3
import sys n = int(sys.stdin.readline()) granes = {'Tetrahedron' : 4, 'Cube' : 6, 'Octahedron' : 8, 'Dodecahedron' : 12, 'Icosahedron' : 20} ans = 0 for i in range(n): t = sys.stdin.readline().strip() ans += granes[t] print(ans)
Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner β€” Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a...
3
n,s=int(input()),input() a=s.count("A") b=s.count("D") if a > b:print("Anton") elif a < b:print("Danik") else:print("Friendship")
How Many Divisors? Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b. Constraints * 1 ≀ a, b, c ≀ 10000 * a ≀ b Input Three integers a, b and c are given in a line separated by a single space. Output Print the number of divisors in a line. Example Inp...
1
k=map(int, raw_input().split()) a=k[0] b=k[1] c=k[2] count=0 for i in range(a,b+1): if c%i==0: count=count+1 print count
Little Joty has got a task to do. She has a line of n tiles indexed from 1 to n. She has to paint them in a strange pattern. An unpainted tile should be painted Red if it's index is divisible by a and an unpainted tile should be painted Blue if it's index is divisible by b. So the tile with the number divisible by a a...
3
n,a,b,p,q=map(int,input().split()) if p>=q: st=a else: st=b def gcd(a,b): if b==0: return a return gcd(b,a%b) def lcm(a,b): return a*b//gcd(a,b) both=lcm(a,b) diva=n//a divb=n//b divboth=n//both #print(diva,divb,divboth) tot = (diva-divboth)*p+(divb-divboth)*q+divboth*max(p,q) print(tot) ''' 1 ...
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges. During one move, you can choose some gift 1 ≀ i ≀ n and do one of the following operations: * eat exactly...
3
for tt in range(int(input())): n= int(input()) c=0 a= ([ int(f) for f in input().split()]) b= ([ int(f) for f in input().split()]) aa= min(a) bb = min(b) #print(n,aa,a,bb,b,c) for i in range (n): #a[i] = a[i]-a[0] #[i] = b[i]- b[i] c += max( a[i]-aa, b[i]-bb) ...
You're given an array a of n integers, such that a_1 + a_2 + β‹…β‹…β‹… + a_n = 0. In one operation, you can choose two different indices i and j (1 ≀ i, j ≀ n), decrement a_i by one and increment a_j by one. If i < j this operation is free, otherwise it costs one coin. How many coins do you have to spend in order to make a...
3
t = int(input()) for i in range(t): n = int(input()) arr = list(reversed(list(map(int, input().split())))) for j in range(1, n): arr[j] = arr[j] + arr[j-1] print(max(arr))
Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve. The camera's memory is d megabytes. Valera's camera can take photos of high and l...
3
n,d=map(int,input().split()) a,b=map(int,input().split()) s=[None]*n for i in range(n): x,y=map(int,input().split()) s[i]=(a*x+b*y,i+1) s.sort() res=[] for i in range(n): if d-s[i][0] >= 0: res.append(s[i][1]) d-=s[i][0] else: break print (str(len(res))+"\n" + " ".join(map(str,re...
See Russian Translation W.T.H.S.E.C Confused? Well it stands for Welcome To HackerEarth September Easy Challenge :). It's quite amazing when long words like this get reduced to such a short string. They sound pretty cool and often make the chat interesting. They are almost used everywhere these days. Our friend Hars...
1
K=int(input()) dislike=[] for k in range(K): dislike.append(raw_input()) N=int(input()) text=raw_input().split() solution="" first=1 for n in range(N): for i in range(K): if(text[n]==dislike[i]): break else: if(first): solution=text[n][0].upper() first=0 else: solution=solution+"."+text[n][0].upper...
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
3
n = int(input()) a = list(map(int,input().strip().split(' '))) police = 0 crimesuntreated = 0 for i in a: if i > 0: police += i elif i == -1: if police > 0: police-=1 else: crimesuntreated += 1 print(crimesuntreated)
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
def mex(arr): if len(arr) == 0: return 0 for i in range(arr[-1] + 2): if i in arr: pass else: return i n = int(input()) for i in range(n): a = int(input()) ar = sorted(list(map(int, input().split()))) mn1 = [] mn2 = [] mn1.append(ar[0]) f...
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
n, k = [int(x) for x in input().split()] for i in range(k): if n % 10 != 0: n -= 1 else: n = int(n/10) print(n)
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()) if n % 2 == 0: odd = n//2 else: odd = n//2+1 if k <= odd: print(2*k-1) else: print((k-odd)*2)
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....
1
from sys import stdin inp = stdin a = inp.readline().strip() b = inp.readline().strip() print('YES' if(a == b[::-1]) else 'NO')
Two players A and B have a list of n integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an elem...
1
n = int(raw_input()) a = sorted(map(int, raw_input().split())) b = sorted(map(int, raw_input().split())) ans1, ans2 = 0, 0 for _ in range(n): if len(a) and len(b): if a[-1] >= b[-1]: ans1 += a[-1] a.pop() else: b.pop() elif len(a): ans1 += a[-1] a.pop() else: b.pop() if l...
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 i in range(int(input())): s=input() a=s[::2] print(a+s[-1])
Compute A \times B. Constraints * 1 \leq A \leq 100 * 1 \leq B \leq 100 * All values in input are integers. Input Input is given from Standard Input in the following format: A B Output Print the value A \times B as an integer. Examples Input 2 5 Output 10 Input 100 100 Output 10000
3
n,m=map(int,input().split());print(n*m)
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
3
teams = int(input()) homes = [] guests = [] for team in range(teams): home, guest = input().split(" ") homes.append(home) guests.append(guest) counter = 0 for home in homes: for guest in guests: if home == guest: counter += 1 print(counter)
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≀ k ≀ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha...
3
test=int(input()) for i in range(test): x,y,n=map(int,input().split()) temp=n%x c=n//x if temp<y: c-=1 k=(c*x)+y print(k)
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an a...
3
for _ in range(int(input())): n, d = map(int, input().split()) a = list(map(int, input().split())) ans = a[0] for i in range(1, n): p = min(d//i, a[i]) ans += p d -= p * i print(ans)
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
r=int(input()) s=0 maxx=0 for i in range(r): y=input().split() s=s-int(y[0])+int(y[1]) if s>maxx: maxx=s print(maxx)
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array. According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the requ...
3
l=int(input()) dic = dict() i=0 for x in (input().split()): dic[x] = i i+=1 l2=int(input()) v=p=0 for y in (input().split()): d=dic[y] v+=d+1 p+= l-d print(*[v,p])
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
s=input() si=set(s) try: si.remove('{') si.remove('}') si.remove(',') si.remove(' ') except: pass print(len(si))
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate. The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles wit...
3
#!/usr/bin/env python from __future__ import division, print_function import os import sys from collections import Counter from io import BytesIO, IOBase from math import gcd if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def...
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
t = int(input()) for ts in range(t): a,b = [int(i) for i in input().split()] print((b-(a%b))%b)
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime: 1. Find two consecutive characters in the string, such that the first of them equals "y", and the s...
1
s = raw_input() x = s.count('x') y = s.count('y') ans = abs(x-y) if x>y: print 'x'*ans else: print 'y'*ans
There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i. Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make towe...
3
a,b=map(int,input().split()) n=list(map(int,input().split())) x=0 z=100000 i=0 while i<a: if n[i]>x: x=n[i] i+=1 k=[0]*x i=0 while i<a: k[n[i]-1]+=1 i+=1 i=x-1 j=1 z=0 c=b while i>-1: if k[i]+z==a: break if k[i]+z<=c: c-=k[i]+z else: c=b-k[i]-z j+=1 ...
You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input...
3
p, g = 998244353, 3 invg = pow(g, p-2, p) W = [pow(g, (p - 1) >> i, p) for i in range(24)] iW = [pow(invg, (p - 1) >> i, p) for i in range(24)] def fft(k, f): for l in range(k)[::-1]: d = 1 << l u = 1 for i in range(d): for j in range(i, 1 << k, 2*d): f[j], f[j+d...
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes. The main school of the capital is located in (s_x, ...
3
n,sx,sy = map(int,input().split()) l,r,a,b,e= 0,0,0,0,0 for _ in range(0,n): aa,bb = map(int,input().split()) if aa<sx: l += 1 if aa>sx: r += 1 if bb>sy: a += 1 if bb<sy: b += 1 qq = max(r,l,a,b) if qq == r: print(r) print(sx+1,sy) elif qq == l: print(l) ...
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7: * The string does not contain characters other than `A`, `C`, `G` and `T`. * The string does not contain `AGC` as a substring. * The condition above cannot be violated by swapping two adjacent chara...
3
import collections, itertools N = int(input()) mod = 10**9 + 7 dp = collections.defaultdict(int) dp['TTTA'] = dp['TTTG'] = dp['TTTC'] = dp['TTTT'] = 1 for _ in range(N - 1): dp2 = collections.defaultdict(int) for p, q, r, s, t in itertools.product('AGCT', repeat=5): if 'AGC' in [q + s + t, s + r + t, r ...
n! = n Γ— (n βˆ’ 1) Γ— (n βˆ’ 2) Γ— ... Γ— 3 Γ— 2 Γ— 1 Is called the factorial of n. For example, the factorial of 12 12! = 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 479001600 And there are two consecutive 0s at the end. Write a program that inputs the integer n and outputs the number of consecutive 0s at the end of...
3
while True: n = int(input()) if not n: break print(sum(int(n / 5 ** i) for i in range(1, 7)))
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
from math import * n,k=map(int,input().split()[:2]) if k<=ceil(n/2): print(2*k-1) else: k=k-ceil(n/2) print(2*k)
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them. Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1. Input T...
3
x,y=[int(a) for a in input().split()] z=10**(x-1) a=0 for i in range(z+1,z*10): if i%y==0: a=1 print(i) quit() else: continue if a==0: print(-1)
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous. Input The first line cont...
3
l,c,m,a = int(input()),1,1,input().split(" ") for i in range(l-1): if(int(a[i])<int(a[i+1])): c = c+1 if(m<c): m = c else: c = 1 print (m)
You are the gym teacher in the school. There are n students in the row. And there are two rivalling students among them. The first one is in position a, the second in position b. Positions are numbered from 1 to n from left to right. Since they are rivals, you want to maximize the distance between them. If students a...
3
t=int(input()) for _ in range(t): n,x,a,b=map(int,input().split()) a,b=min(a,b),max(a,b) print(min(n-1,b-a+x))
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ...
3
a,b,c = [int(x) for x in input().split()] array = [] array +=[a+b+c] array +=[a+a+b+b] array +=[a+c+c+a] array +=[b+c+c+b] print(min(array))
We just discovered a new data structure in our research group: a suffix three! It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in. It's super simple, 100% accurate, and doesn't involve advanced machine learni...
3
times = int(input()) for i in range(times): word = input() if word[-2:] == "po": print("FILIPINO") elif word[-4:] in ["desu","masu"]: print("JAPANESE") elif word[-5:] == "mnida": print("KOREAN")
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f...
3
n1,n2,k1,k2=map(int,input().split()) if(n1==n2): print("Second") elif(n1>n2): print("First") else: print("Second")
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what i...
3
size = int(input()) num_list = list(map(int,input().split())) def check(num_list): l = len(num_list)//2 if(list(sorted(num_list)) == num_list): return l*2 else: return max(check(num_list[:l]) , check(num_list[l:])) print(max(1,check(num_list)))
Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≀ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the ...
3
n,k=map(int,input().split()) L={""} for i in range(n): m,f=input().split() for i in range (int(m),int(f)+1): L |= {i} L.remove("") x=len(L) print((k-x%k)%k)
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
3
t = int(input()) for _ in range(t): n, x = map(int, input().split(' ')) oddmod = False arr = [v for v in map(int, input().split(' '))] s = sum(arr) if s % x != 0: print(n) continue numdelfront = 0 for v in arr: numdelfront += 1 if v % x != 0: ...
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≀ r ...
3
a,b =input().split() i=0 while 1: i+=1 d=int(a)*i if d%10==int(b) or d%10==0: print(i) break
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
3
k,n,w = map(int,input().split(" ")) if n == ((w*(w+1))/2)*k: print(0) elif n > ((w*(w+1))/2)*k: print(0) else: print(int(((w*(w+1))/2)*k) - n)
ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not n...
3
def solve (): s = list(input()) s1 = s.copy() success = False for i in range(0, len(s)-25): good_substring = True for j in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'): if(s[i:i+26].count(j) > 1): good_substring = False if(good_substring == False): co...
The circle line of the Roflanpolis subway has n stations. There are two parallel routes in the subway. The first one visits stations in order 1 β†’ 2 β†’ … β†’ n β†’ 1 β†’ 2 β†’ … (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n β†’ (n-1) β†’ … β†’ 1 β†’ n β†’ (n-1) ...
3
n,a,x,b,y = map(int,input().split()) while a != x and b != y: if a<n: a += 1 else: a = 1 if b>1: b -=1 else: b = n if a == b: print("YES") exit() if a==x or b==y: break print("NO")
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
a=int(input()) b=int(input()) c=int(input()) l=[] l.append(a+b+c) l.append((a+b)*c) l.append(a*(b+c)) l.append(a*b*c) print(max(l))
There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes. The schedule on Monday is known for each group, i. e. time slots when group will have classes are known. Your task is to determine the mi...
3
t=[0]*7 for i in range(int(input())): g=input() t[0]+=int(g[0]) t[1]+=int(g[1]) t[2]+=int(g[2]) t[3]+=int(g[3]) t[4]+=int(g[4]) t[5]+=int(g[5]) t[6]+=int(g[6]) print(max(t))
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in. During his ride, Arkady woke up several time...
3
# https://codeforces.com/problemset/problem/1056/A n = int(input()) new_set = set(tuple(map(int, input().split()))[1:]) for i in range(n - 1): new_set = new_set.intersection(set(tuple(map(int, input().split()))[1:])) print(*new_set)
Mike likes strings. He is also interested in algorithms. A few days ago he discovered for himself a very nice problem: You are given an AB-string S. You need to count the number of substrings of S, which have an equal number of 'A'-s and 'B'-s. Do you know how to solve it? Good. Mike will make the problem a little ...
1
def abcstr(): s = raw_input() n = len(s) if n < 3: return 0 A, B, C = ([0 for _ in xrange(n+1)] for _ in xrange(3)) for i in xrange(1, n+1): ch = s[i-1] A[i] = A[i-1] + 1 if ch == 'A' else A[i-1] B[i] = B[i-1] + 1 if ch == 'B' else B[i-1] C[i] = C[i-...
We have an H-by-W matrix. Let a_{ij} be the element at the i-th row from the top and j-th column from the left. In this matrix, each a_{ij} is a lowercase English letter. Snuke is creating another H-by-W matrix, A', by freely rearranging the elements in A. Here, he wants to satisfy the following condition: * Every ro...
3
from collections import Counter as co n,m=map(int,input().split()) l=co("".join([input()for i in range(n)])).values() if n%2 and m%2: l=list(l) f=1 for v in range(len(l)): if l[v]%2: if f:f=0;l[v]-=1 else:print("No");exit() if f==1:print("No");exit() print("Yes"if(n+m...
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...
3
import collections as cc I=lambda:list(map(int,input().split())) import sys input=sys.stdin.readline for tc in range(int(input())): n,=I() ans=0 temp=[] while n!=1: ans=(n*4)-4 temp.append(ans) n-=2 ans=0 k=1 for i in temp[::-1]: ans+=i*k k+=1 prin...
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage. There is at most one checkpoint on each stage, and there is always a checkp...
3
import sys from sys import stdin tt = int(stdin.readline()) for loop in range(tt): k = int(stdin.readline()) ans = [] if k % 2 == 1: print (-1) continue tmp = 2 while k > 2: if k & (2**tmp) > 0: ans.append(1) ans.append(1) for i in ran...
Kolya is going to make fresh orange juice. He has n oranges of sizes a1, a2, ..., an. Kolya will put them in the juicer in the fixed order, starting with orange of size a1, then orange of size a2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly gr...
3
n, b, d = [int(x) for x in input().split()] A = [int(x) for x in input().split()] reminder = 0 counter = 0 for a in A: if a > b: continue reminder += a if reminder > d: counter += 1 reminder = 0 print(counter)
Three poles stand evenly spaced along a line. Their heights are a, b and c meters, from left to right. We will call the arrangement of the poles beautiful if the tops of the poles lie on the same line, that is, b-a = c-b. Determine whether the arrangement of the poles is beautiful. Constraints * 1 \leq a,b,c \leq 10...
3
a, b, c = (int(i) for i in input().split()) print("YES" if b-a == c-b else "NO")
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby. Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters. Dima can buy boxes at a factory. The factory pr...
3
n=[int(inp) for inp in input().split()] arr=[int(inp) for inp in input().split()] maxn=-1 chosent=-1 chosenb=-1 it=1 for f in arr: div=int(n[0])//int(f) num=div*f if num > maxn: maxn=num chosenb=it chosent=div it+=1 print(chosenb,chosent)
You are given an array a of n integers. You want to make all elements of a equal to zero by doing the following operation exactly three times: * Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can...
3
n=int(input()) arr=list(map(int,input().split())) if n==1: print(1,end=" "),print(1) print(0) print(1,end=" "),print(1) print(0) print(1,end=" "),print(1) print(-arr[0]) else: print("1",end=" ") print(n) for i in range(0,n): print(-arr[i]*n,end=" ") print() print("1",end=" ") ,print(n-1) for i in ...
Acacius is studying strings theory. Today he came with the following problem. You are given a string s of length n consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulti...
3
t = int(input()) cs = "abacaba" for i in range(t): n = int(input()) s = input() counter = 0 for j in range(n-6): if cs == s[j:j+7]: counter += 1 if counter > 1: print('No') elif counter == 1: print('Yes') s2 = '' for c in s: if c == '?': s2 += 'z' else: s2 += c print(s2) else: pri...
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
n=int(input()) x=0 y=0 z=0 for i in range(n): line=list(map(int,input().split())) x+=line[0] y+=line[1] z+=line[2] if x==0 and y==0 and z==0: print('YES') else: print('NO')
You are given a string s. Each character is either 0 or 1. You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met. You may eras...
3
import math, collections, sys # input = sys.stdin.readline for _ in range(int(input())): s = input() a = s.find('1') b = s.rfind('1') if '1' not in s: print(0) continue count = 0 for i in range(a, b+1): if s[i] == '0': count+=1 print(count)
We just discovered a new data structure in our research group: a suffix three! It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in. It's super simple, 100% accurate, and doesn't involve advanced machine learni...
3
from math import * for _ in range(int(input())): s=input() if(s.endswith('po')): print('FILIPINO') elif(s.endswith('desu') or s.endswith('masu')): print('JAPANESE') elif(s.endswith('mnida')): print('KOREAN')