problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
n = int(input()) x = 0 for a in range(n): m = input() if(m[1] == '+'): x += 1 else : x -= 1 print(x)
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there. If t...
3
def presents(): n = int(input()) l = input().split() d = {int(l[i]): i for i in range(n)} for i in d.values(): print(i + 1, end =' ') if __name__ == '__main__': presents()
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Va...
3
n,m=map(int,input().split()) s=set() for i in range(n): s1=set(input().split()[1:]) s=s|s1 print('YES'if len(s)==m else 'NO')
<image> You can preview the image in better quality by the link: [http://assets.codeforces.com/files/656/without-text.png](//assets.codeforces.com/files/656/without-text.png) Input The only line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be an alphanumeric character o...
3
s = input() res = 0 for c in s: if c.isalpha(): if c.isupper(): res+=ord(c)-ord('@') else: res-=ord(c)-ord('`') print(res)
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=int(input()) results=input() a=results.count('A') if a>n/2: print('Anton') elif a<n/2: print('Danik') else: print('Friendship')
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
# https://codeforces.com/contest/443/problem/A input_str = input() #print(input_str) if input_str != '{}': lst =[i for i in input_str[1:len(input_str)-1].split(', ')] #print(lst) print(len(set(lst))) else: print('0')
You have a sequence a with n elements 1, 2, 3, ..., k - 1, k, k - 1, k - 2, ..., k - (n - k) (k ≀ n < 2k). Let's call as inversion in a a pair of indices i < j such that a[i] > a[j]. Suppose, you have some permutation p of size k and you build a sequence b of size n in the following manner: b[i] = p[a[i]]. Your goal...
3
import sys import math t=int(input()) for w in range(t): n,k=(int(i) for i in input().split()) l=[] k1=0 for i in range(1,2*k-n): l.append(i) k1=i for i in range(k,k1,-1): l.append(i) print(*l)
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The ...
3
from sys import stdin, stdout nk = list(map(int,stdin.readline().strip().split())) n = nk[0] k = nk[1] match_num = list(map(int, stdin.readline().split())) count = 0 for i in range(n): if match_num[i] <= (5 - k): count += 1 stdout.write(str(count // 3))
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz). The picture showing the correct sudoku solution: <image> Blocks are bordered with bold black color. Your task is to change at most 9 elements of this field (i.e. choose s...
3
t = int(input()) while t: a = [[] for i in range(0,9)] for i in range(0,9): a[i]= list(input()) for j in range(0,9): if a[i][j]=='2': a[i][j]=1 for i in range(0,9): for j in range (0,9): print(a[i][j],end='') print() t= t-1
You are given an array a_1, a_2, …, a_n. In one operation you can choose two elements a_i and a_j (i β‰  j) and decrease each of them by one. You need to check whether it is possible to make all the elements equal to zero or not. Input The first line contains a single integer n (2 ≀ n ≀ 10^5) β€” the size of the array....
3
def answer(n,A): s=sum(A) if s%2==0: if max(A)<=s-max(A): return "YES" else: return "NO" else: return "NO" n=int(input()) arr=list(map(int,input().split())) print(answer(n,arr))
You've got a 5 Γ— 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
matrix = [] for i in range(0,5): matrix_input = list(map(int, input().split())) matrix.append(matrix_input) for i in range(0,5): for j in range(0,5): if matrix[i][j] == 1: print(abs(2 - i) + abs(2 - j)) break
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the sam...
1
n = int(raw_input()) s = list(raw_input()) total = 0 def move(pos, x, y): if (pos == 'U'): y += 1 elif (pos == 'D'): y -= 1 elif (pos == 'L'): x -= 1 elif (pos == 'R'): x += 1 return x, y for i in range(len(s)): x, y = 0, 0 for j in range(i, len(s)): x, y = move(s[j], x, y) if (x == 0 and y == 0): ...
Maria participates in a bicycle race. The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west. Let's introduce a system of coordinates, directing the Ox axis from west to east, and th...
3
import sys n = int(sys.stdin.readline().strip()) print((n - 4) // 2) # 1489012282813
You are the top spy of AtCoder Kingdom. To prevent the stolen secret from being handed to AlDebaran Kingdom, you have sneaked into the party where the transaction happens. There are N attendees in the party, and they are given attendee numbers from 1 through N. The height of Attendee i is A_i. According to an examina...
3
from collections import defaultdict n=int(input()) a=list(map(int,input().split())) d=defaultdict(int) cnt=0 for i in range(n): cnt+=d[i-a[i]] d[a[i]+i]+=1 print(cnt)
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...
1
ans=chk=0 n=int(raw_input()) for i in range(n): p,q=map(int,raw_input().split()) if q-p>=2: ans+=1 print ans
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties... Most of the young explorer...
1
import sys range = xrange input = raw_input inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 t = inp[ii]; ii += 1 out = [] for _ in range(t): n = inp[ii]; ii += 1 A = inp[ii: ii + n]; ii += n A.sort() DP = [0] * (n + 1) for i in range(n): DP[i] = 1 + DP[i - A[i]] if i - A[i] + 1 >=...
You are given two polynomials: * P(x) = a0Β·xn + a1Β·xn - 1 + ... + an - 1Β·x + an and * Q(x) = b0Β·xm + b1Β·xm - 1 + ... + bm - 1Β·x + bm. Calculate limit <image>. Input The first line contains two space-separated integers n and m (0 ≀ n, m ≀ 100) β€” degrees of polynomials P(x) and Q(x) correspondingly. The seco...
1
n, m = map(int, raw_input().split()) a = map(int, raw_input().split()) b = map(int, raw_input().split()) a0 = a[0] b0 = b[0] from fractions import Fraction as F if n == m: ans = F(a0)/b0 ans = '%d/%d' % (ans.numerator, ans.denominator) elif n > m: if a0 * b0 < 0: ans = '-Infinity' else: ...
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
string=input() k=len(string) count=0 counta=0 for i in range(0,k): if(string[i]=='a'): counta+=1 else: count+=1 if(counta==1): print(1) elif(counta>count): print(k) else: while(True): count-=1 if(counta>count): c=1 break; if(c==1): ...
Takahashi is a teacher responsible for a class of N students. The students are given distinct student numbers from 1 to N. Today, all the students entered the classroom at different times. According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including...
3
n = int(input()) a = list(map(int, input().split())) b = [0] * n for i, j in enumerate(a): b[j-1] = i+1 print(*b)
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
num=input() n=int(num) b=0 def luckynumber(x): if x.count('4')+x.count('7')==len(x): return 1 else: return 0 if luckynumber(num)==1: print("YES") b=1 else: for x in range(4,int(n/2+1)): if n%x==0 and luckynumber(str(x))==1: print("YES") b=1 ...
We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}. Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2. Find the inversion number of B, modulo 10^9 + 7. Here the inversion number of B is defined as the number of o...
3
n,k,*a=map(int,open(0).read().split()) print(sum(k*~-k*(c<d)+k*-~k*(c>d)>>1for i,c in enumerate(a)for d in a[i:])%(10**9+7))
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
# -*- coding: utf-8 -*- """ Created on Sat Oct 17 14:44:53 2020 @author: feiym """ q = eval(input()) for i in range(q): n = eval(input()) L = input().split() s = sum([int(x)*(int(x)<=2048) for x in L]) if s >= 2048: print('YES') else: print('No')
Little penguin Polo has an n Γ— m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij. In one move the penguin can add or subtract number...
3
a,b,c=map(int,input().split()) l=[] p=True for i in range(a): l+=list(map(int,input().split())) l.sort() s=l[(a*b)//2] cc=0 for i in l: k=abs(i-s) if(k%c==0): cc+=(k//c) else: print(-1) p=False break if p: print(cc)
The following graph G is called a Petersen graph and its vertices have been numbered from 0 to 9. Some letters have also been assigned to vertices of G, as can be seen from the following picture: Let's consider a walk W in graph G, which consists of L vertices W1, W2, ..., WL, such that Wi is connected with Wi + ...
1
t=input() connection=[[1,4,5],[0,2,6],[1,3,7],[2,4,8],[0,3,9],[0,7,8],[8,9,1],[5,9,2],[5,6,3],[6,7,4]] for i in range(t): a=raw_input() ans="" count=0 current=ord(a[count])-ord('A') ans+=str(current) while count<len(a)-1 and ((ord(a[count+1])-ord('A') in connection[current]) or (ord(a[count+1])-...
Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi. Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distance from the Takahashi's residence, measured counter-clockwise. There are N...
3
L, N = list(map(int, input().split())) X = [int(input()) for i in range(N)] ans0 = X[0] # 0, -1, 1, -2, ... i = 0 j = N-1 direc = 1 # direction: left->1, right->-1 while i!=j: direc *= -1 ans0 += L+X[i]-X[j] if direc==-1: i += 1 elif direc==1: j -= 1 if N%2==0: i = N//2 j = N//2...
You are given an array a consisting of n integers a_1, a_2, ... , a_n. In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4],...
3
n=int(input()) for i in range(n): t=int(input()) a=list(map(int,input().split())) a1,a2,a3=0,0,0 for j in a: if(j%3==1): a1+=1 elif(j%3==2): a2+=1 else: a3+=1 x=0 if(a1>=a2): x=a2+a3+(a1-a2)//3 else: ...
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ...
3
t = int(input()) for i in range(0,t): u=0 s='' x = [] k = int(input()) for j in range(0,k): x.append(list(map(int,input().split()))) x = sorted(x, key = lambda ll : ll[0]+ll[1]) x = sorted(x, key = lambda ll : ll[0]) for p in range(0,x[0][0]): s+='R' for p in range(...
In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)! There are five means of transport in this empire: * Train: travels from City 1 to 2 in one minute. A train can occupy at most A people. * Bus: travels from City 2 to 3 in one minute. A bus can occupy a...
3
n,*cap=map(int,open(0).read().split()) m=min(cap) print(4+(n+m-1)//m)
One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile: <image> By the pieces lay a large square wooden board. The board is divided into n^2 cells arranged into n ...
1
import random import time seed = int(time.time()) random.seed(seed) dt = ((0,0), (0, 1), (1, 0), (0, -1), (-1, 0)) def in_bounds(n, r, c): return 0 <= r < n and 0 <= c < n def can_place(n, b, r, c): for dr, dc in dt: rp = r+dr cp = c+dc if not in_bounds(n, rp, cp): return ...
A bus moves along the coordinate line Ox from the point x = 0 to the point x = a. After starting from the point x = 0, it reaches the point x = a, immediately turns back and then moves to the point x = 0. After returning to the point x = 0 it immediately goes back to the point x = a and so on. Thus, the bus moves from ...
3
l=[int(x) for x in input().split()] a=[] b=l[1] f=0 c=0 a.append(0) for i in range(l[3]): if(i%2==0): a.append(i*l[0]+l[2]) else: a.append((i+1)*l[0]-l[2]) a.append(l[0]*l[3]) for j in range(1,l[3]+2): if(b>=(a[j]-a[j-1])): b=b-a[j] b=b+a[j-1] else: ...
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
watermelon = int(input()) if watermelon <= 2 or watermelon >= 101: print('NO') elif watermelon % 2 == 0: print('YES') else: print('NO')
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k...
3
T = int (input ()) for I in range (0, T): N = input () X = list (map (int, input ().split (' '))) Mode = 0 Q = 0 A = 0 while A < len (X): P = X [len (X) - A - 1] if Mode == 0: if P < Q: Mode = 1 elif Mode == 1: if P > Q: ...
Mishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice). Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls M...
3
t = int(input()) res = 0 for n in range(t): x = int(input()) if x % 7 != 1 and x >= 7: res = x // 7 + 1 print(res) elif x % 7 == 1 and x >= 7: res = x // 6 + 1 print(res) elif 2 <= x < 7: print(1)
There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation). Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after...
3
def main(): for _ in range(int(input())): n=int(input()) # n,k=map(int,input().split()) l=list(map(int,input().split())) c=0 if n==1: print('YES') continue for i in range(n-1): if l[i]<l[i+1]: c+=1 if l[n-1]<...
We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it. It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M). Consider the following action: * Ch...
3
n,m,k=map(int,input().split()) A=list(map(int, input().split())) B=list(map(int, input().split())) ans=0 a, b=[0], [0] for i in range(n): a.append(a[i]+A[i]) for i in range(m): b.append(b[i]+B[i]) j=m for i in range(n+1): if k<a[i]: break while b[j]>k-a[i]: j-=1 ans=max(ans,i+j) prin...
You are given two lists of non-zero digits. Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer? Input The first line contains two integers n and m (1 ≀ n, m ≀ 9) β€” the length...
3
# import sys # sys.stdin=open("input.in",'r') # sys.stdout=open("out.out",'w') n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) x=min(a) y=min(b) s=100 for i in range(n): if a[i] in b: s=min(s,a[i]) if s==100: s=min(x,y)*10+max(x,y) print(s)
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and...
3
MAXN = int(1e5 + 100) cnt = [0] * MAXN dp = [0] * MAXN n = int(input()) a = list(map(int, input().split())) for el in a: cnt[el] += 1 dp[1] = cnt[1] for i in range(2, MAXN): dp[i] = max(dp[i - 2] + i * cnt[i], dp[i - 1]) print(max(dp))
You are given an array a consisting of n integers. Your task is to determine if a has some subsequence of length at least 3 that is a palindrome. Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c...
3
def max_tbp(xs, a, b): m = 1 occs = [i for i, x in enumerate(xs) if x == a] cur = 0 b_cnts = [] for x in xs: if x == b: cur += 1 b_cnts.append(cur) for i in range(len(occs)//2): st = occs[i] en = occs[len(occs)-1-i] cnt = b_c...
Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held: * a < b < c; * a divides b, b divides c. Naturally, Xenia wants...
3
from collections import Counter n, a = int(input()), list(map(int, input().split())) if 5 in a or 7 in a: print(-1) else: b = Counter(a) c = [[1, 2, 4], [1, 2, 6], [1, 3, 6]] d = [0] * 3 d[2] = b[3] b[1], b[6] = b[1] - b[3], b[6] - b[3] if b[1] < 0 or b[6] < 0 or b[1] != b[2] or b[4] + b[6]...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules. A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many ...
3
n,k = map(int,input().split()) k -=1 comp = input().split() i = 0 count = 0 while i < n and (i <= k or int(comp[i]) == int(comp[k])) : if int(comp[i]) > 0 : count +=1 i +=1 print(count)
You are given two strings s and t consisting of lowercase Latin letters. Also you have a string z which is initially empty. You want string z to be equal to string t. You can perform the following operation to achieve this: append any subsequence of s at the end of string z. A subsequence is a sequence that can be deri...
3
import sys, bisect; input = sys.stdin.readline; t = int(input()) while t: t-=1; s1 = input().strip(); s2 = input().strip(); locations = {} for i in range(len(s1)): if s1[i] in locations: locations[s1[i]].append(i) else: locations[s1[i]] = [i] a = i = len(s1);j = len(s2)-1; ans = 1 while j>=0: if s2[j] not in ...
In the city of Ultima Thule job applicants are often offered an IQ test. The test is as follows: the person gets a piece of squared paper with a 4 Γ— 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the p...
3
s1=input() s2=input() s3=input() s4=input() i=0 f=False while(i<3 and f==False): if((s1[i]==s2[i] and s1[i+1] ==s2[i+1]==s1[i]) or (s1[i]==s2[i] and s1[i+1] !=s2[i+1]) or (s1[i]!=s2[i] and s1[i+1] ==s2[i+1])): f=True i+=1 i=0 while(i<3 and f==False): if(s2[i]==s3[i] and s2[i+1] ==s3[i+1]==s2[i] or s2[i]==...
This is a harder version of the problem. In this version n ≀ 500 000 The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the compan...
3
n = int(input()) a = list(map(int, input().split())) l = [0] * n r = [n - 1] * n stack = [0] for i in range(1, n): while len(stack) > 0 and a[stack[-1]] >= a[i]: stack.pop() if len(stack) > 0: l[i] = stack[-1] else: l[i] = i stack.append(i) stack = [n - 1] for i in range(n - ...
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits. He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, s...
1
import sys def answ(d, c, k): print(c) a = [] for i in range(c): a.append(['a'] * k) j = 0 cj = 0 h = int(k / 2) for v in d: while d[v] > 1 and j < c: if cj < h: d[v] -= 2 a[j][cj] = v a[j][k - cj - 1] = v ...
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
1
str1 = raw_input() str2 = raw_input() if str1.lower() > str2.lower(): print("1") elif str1.lower() < str2.lower(): print("-1") else: print("0")
Alice has just learnt multiplying two integers. He wants to multiply two integers X and Y to form a number Z. To make the problem interesting he will choose X in the range [1,M] and Y in the range [1,N]. Help him to find the number of ways in which he can do this. Input First line of the input is the number of test ca...
1
tc = int(raw_input()) for test in xrange(tc): res =0 z,m,n = [ int(x) for x in raw_input().split() ] for elem1 in xrange(1,int(z**0.5)+1): #print "elem 1 --->",elem1 if z%elem1 == 0: if elem1 == z/elem1 and ((1<= elem1 <= m and 1<= z/elem1 <= n) or ( 1<= elem1 <= n and 1<= z/elem1 <= m)): #print "Same" ...
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change). In a prototype progr...
3
from collections import Counter, defaultdict BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" def to_base(s, b): res = "" while s: res+=BS[s%b] s//= b return res[::-1] or "0" alpha = "abcdefghijklmnopqrstuvwxyz" from math import floor, ceil,pi import re pattern = r"0+" t = int(input()) for i in...
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
def stones(): n=int(input()) stones=list(input().strip()) let={"R":True,"B":True,"G":True} k=0 for i in range(1,len(stones)): if(stones[i-1]==stones[i]): k+=1 return (k) print(stones())
You have N coins each of which has a value ai. Find the number of combinations that result when you choose K different coins in such a way that the total value of the coins is greater than or equal to L and less than or equal to R. Constraints * 1 ≀ K ≀ N ≀ 40 * 1 ≀ ai ≀ 1016 * 1 ≀ L ≀ R ≀ 1016 * All input values are...
3
import sys import bisect def main(): n, K, L, R = map(int, sys.stdin.readline().split()) a = tuple(map(int, sys.stdin.readline().split())) m = n//2 ls = [[] for _ in range(m+1)] for i in range(1 << m): cnt = 0 val = 0 for j in range(m): if i >> j & 1: ...
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated....
3
from itertools import permutations #from fractions import Fraction from collections import defaultdict from math import* import os import sys from io import BytesIO, IOBase from heapq import nlargest from bisect import* import copy import itertools BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init_...
Orac is studying number theory, and he is interested in the properties of divisors. For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that aβ‹… c=b. For n β‰₯ 2, we will denote as f(n) the smallest positive divisor of n, except 1. For example, f(7)=7,f(10)=2,f(35)=5. ...
3
''' Name : Jaymeet Mehta codeforces id :mj_13 Problem : ''' from sys import stdin,stdout import math def fin_it(n): ans=-1 for i in range(2,int(math.sqrt(n))+1): if not n%i: ans=i break if ans==-1: return n return ans test=int(stdin.readline()) for _ in range(tes...
Codeforces user' handle color depends on his rating β€” it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of hi...
3
n=int(input()) ans=0 for i in range(n): n,a,b=map(str,input().split()) if(int(a)>=2400 and int(b)-int(a)>0): ans+=1 if(ans==0): print("NO") else: print("YES")
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
a=list(input()) b=list(input()) c=0 d=True for i in a: c-=1 if i == b[c]: d=True continue else: d=False break if d==True: print('YES') else: print('NO')
Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. Y...
3
def solve(n,ar): d = set() curr = 0 ans = 0 d.add(0) for i in range(n): #curr == 0 means there is some subsegment that sum is equal to 0 #insert arbitratily number right before the current element. curr += ar[i] if curr in d: ans += 1 d = set(...
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their h...
3
n = int(input()) a = [int(i) for i in input().split()] mx = 0 mn = n - 1 for i in range(n): if a[i] > a[mx]: mx = i if a[i] <= a[mn]: mn = i if mn < mx: print(mx + n - 1 - mn - 1) else: print(mx + n - 1 - mn)
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively. You can rearrange the elements i...
3
#a>b ans=ab,a==b,ans=0,b>a ans=-ab def seq(a,b): ans=0 if a[2]>b[1]: a[2]=a[2]-b[1] ans+=2*b[1] b[1]=0 if a[2]<=b[1]: ans+=2*(a[2]) a[2]=0 b[1]=b[1]-a[2] if a[0]<b[2] and ((b[2]-a[0])>a[2]): ans+=(b[2]-a[0]-a[2])*(-2) a[0]=0 a[2]=0 ...
Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points o...
3
p=998244353 n=int(input()) facs=[1] for i in range(1,n): facs.append(facs[-1]*i%p) graph=[[] for i in range(n)] for i in range(n-1): u,v=map(int,input().split()) graph[u-1].append(v-1) graph[v-1].append(u-1) prod=facs[len(graph[0])]*n for i in range(1,n): k=len(graph[i]) prod=prod*facs[k]%p prin...
You are given three strings s, t and p consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings. During each operation you choose any character from p, erase it from p and insert it into string s (you may insert this character anywhere you want: in the beginning of...
3
from math import floor quer=0 quer=int(input()) for x in range(quer): s=[] t=[] p=[] s=input() t=input() p=input() alpha=[] indx=[] nothappenin = 0 for i in range(26): alpha.append(0) indx.append(0) for i in range(len(t)): alpha[ord(t[i])-97]+=1 indx[ord(t[i])-97] = i # for i in range(26): # p...
You are given a rectangular board of M Γ— N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ— 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
n,m=list(map(int,input().split())) ans=n//2*m if(n>0 and n%2!=0): ans=ans+m//2 print(ans)
Polycarp is sad β€” New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands. The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them ...
3
t = int(input()) for _ in range(t): r,g,b = map(int,input().split()) if r+g>=b-1 and r+b>=g-1 and b+g>=r-1: print("Yes") else: print("No")
Write a program which finds a pattern $p$ in a ring shaped text $s$. <image> Constraints * $1 \leq $ length of $p \leq $ length of $s \leq 100$ * $s$ and $p$ consists of lower-case letters Input In the first line, the text $s$ is given. In the second line, the pattern $p$ is given. Output If $p$ is in $s$, prin...
1
s = raw_input() p = raw_input() i = 0 while i<len(s): k = 0 while k < len(p): if s[(i+k)%len(s)] == p[k]: k += 1 else: break if k >= len(p): print 'Yes' break i += 1 if k < len(p): print 'No'
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
3
import string def ispangram(str): alphabet = "abcdefghijklmnopqrstuvwxyz" for char in alphabet: if char not in str.lower(): return False return True n=int(input()) string1=input() string=string1.lower() if(ispangram(string) == True): print("YES") else: print("NO")
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()) f=0 s=0 t=0 for i in range(n): x,y,z=map(int,input().split()) f+=x s+=y t+=z if f==0 and s==0 and t==0: print('YES') else: print('NO')
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar. A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from t...
3
n,k,t=map(int,input().split()) ans=[0]*n t/=100 x=k*n*t x//=1 a,mod=divmod(x,k) i=-1 for i in range(int(a)): ans[i]=k if mod!=0: ans[i+1]=int(mod) print(*ans)
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 millis...
1
import math def inp(): return int(raw_input()) def linp(): return raw_input().split() l = linp() li = [] for i in l: li.append((int)(i)) a = li[0]*li[1] + 2*li[3] b = li[0]*li[2] + 2*li[4] if(a<b): print "First" elif(b<a): print "Second" else: print "Friendship"
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a1, a2, ..., an. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise ai times. Greg now only does three types of exercises: "chest" exercises,...
3
n = int(input()) l = list(map(int,input().split())) c = sum(l[0:n:3]) bi = sum(l[1:n:3]) ba = sum(l[2:n:3]) if max(c,bi,ba) == c: print("chest") elif max(c,bi,ba) == bi: print("biceps") else: print("back")
Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to som...
3
n=int(input()) bVar = [int(i) for i in str(input()).split()] dp=[0 for i in range(n)] con = 4*100000 #diffArray = [[] for i in range(-1*con,con)] diffArray = {} maxValue = -1 for i in range(n): if i==0: dp[i]=bVar[0] maxValue = max(maxValue,dp[i]) diff = i+1-bVar[i] diffArray[diff]=[...
Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwis...
1
#coding: utf-8 ps = [] for i in xrange(3): p = map(int, raw_input().split(' ')) ps.append(p) def add((x1, y1, ), (x2, y2, )): return (x1 + x2, y1 + y2, ) def sub((x1, y1, ), (x2, y2, )): return (x1 - x2, y1 - y2, ) fourth_ps = set() p1, p2, p3 = ps for i in xrange(3): fourth_ps.add(add(p1, sub(p2, p3))) fo...
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
a = int(input()) b = int b = a % 2 if a <= 100 and a >= 1: if b == 0 and a != 2: print("YES") else: print("NO") else: print("ERRORj")
Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations: * multiply the current number by 2 (that is, replace the number x by 2Β·x); * append the digit 1 to the right of current number (that is, replace the number x by 10Β·x + 1). You need to help Vasil...
1
a,b = map(int, raw_input().split()) array = [b] def f(a,b): while (b > a and ((str(b)[-1] == "1" or (b % 2 == 0)))): if (b % 2 == 0): b = b/2 else: b = (b-1)/10 array.append(b) if b == a: return True return False if f(a,b): ...
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a...
3
days, walks = (map(int, input().split())) arr = list(map(int, input().split())) count = 0 for i in range(days): if i == (days - 1): continue elif arr[i + 1] + arr[i] < walks: count += walks - (arr[i] + arr[i + 1]) arr[i + 1] += walks - (arr[i] + arr[i + 1]) print(count) print(*arr)
You are given the array a consisting of n positive (greater than zero) integers. In one move, you can choose two indices i and j (i β‰  j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≀ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a...
3
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int,input().split())) a.sort() flag = True for i in range(n-1): if a[i+1]-a[i]>1: flag = False break if flag: print("YES") else: print("NO")
Panic is rising in the committee for doggo standardization β€” the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive. The committee rules strictly prohibit even the smallest diversity between dog...
3
n = int(input()) m = input() flag = 0 ji = 0 for i in range(26): if m.count(chr(i+ord('a'))) == 1: flag += 1 elif m.count(chr(i+ord('a'))) > 1: ji = 1 if flag == 1 or ji: print('Yes') else: print('No')
You are given an array of integers a_1,a_2,…,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t). Input The input consists of multiple test cases. The first line contains an integer t (1≀ t≀ 2 β‹… 10^4) β€” the number of test cases. The description of the test cases ...
3
t=int(input()) for i in range(t): n=int(input()) l=list(map(int,input().split())) l.sort(reverse=True) a=l[0]*l[1]*l[2]*l[3]*l[4] b=l[0]*l[1]*l[2]*l[n-1]*l[n-2] c=l[0]*l[n-1]*l[n-2]*l[n-3]*l[n-4] print(max(a,max(b,c)))
problem Create a program that counts the number of consecutive JOI or IOI characters in a given character string. The character string consists only of uppercase letters of the alphabet. For example, the character string "JOIOIOI" in the figure below contains JOI in one place and IOI in two places. <image> input ...
3
try: while True: A=0 B=0 a=list(str(input())) b=len(a) for i in range(b-2): c=a[i]+a[i+1]+a[i+2] if c=="JOI": A+=1 if c=="IOI": B+=1 print(A) print(B) except...
Find the minimum prime number greater than or equal to X. Constraints * 2 \le X \le 10^5 * All values in input are integers. Input Input is given from Standard Input in the following format: X Output Print the minimum prime number greater than or equal to X. Examples Input 20 Output 23 Input 2 Outpu...
3
x=int(input()) mod=10**7+9 for i in range(x,mod): if not any(i%j==0 for j in range(2,i+1-1)): ans=i break print(ans)
Mr. Takahashi has a string s consisting of lowercase English letters. He repeats the following operation on s exactly K times. * Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of `z` is `a`. For example, if you perform an operation for the second letter on `aa...
3
s=input() k=int(input()) ss=[] for i in range(len(s)): ss.append(ord(s[i])-ord("a")) i=0 while k>0: if i==len(s)-1: ss[i]=(k+ss[i])%26 break elif k>=26-ss[i] and ss[i]!=0: k-=(26-ss[i]) ss[i]=0 i+=1 ans="" for i in range(len(s)): ans+=chr(ord("a")+ss[i]) print(ans)
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
g = int(input()) while True: g += 1 t = str(g) if t[0] not in (t[1] , t[2], t[3]) and t[1] not in (t[0] , t[2], t[3]) and t[2] not in (t[1] , t[0], t[3]) and \ t[3] not in (t[1], t[2], t[0]): break print(g)
Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat. Assume that we have a cat with a number x. A perfect longcat is a cat with a number equal 2^m - 1 for some non-ne...
3
n = int(input()) def transform(): global n s = bin(n)[2:] for i in range(len(s)): if s[i]=='0': break index = i res = '' for i in range(len(s)): if i>=index: res+='1' n = int(res, 2)^n return(len(res)) def check(): global n s = bin(n)[2:] n+=1 if '0' not i...
You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes. Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-...
3
n = input() A = list(n) m = len(A) flag=0 for i in A: if (int(i))%8 == 0: print("YES") print(int(i)) flag = 1 break if flag == 0: for i in range(m): for j in range(i): if int(A[j]+A[i])%8 == 0: print("Yes") print(int(A[j]+A[i]))...
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
print(lambda m,n,a: ((m+a-1)/a)*((n+a-1)/a))(*[int(s) for s in raw_input().split()])
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance. The park is a rectangular table with n rows and m columns, where the cells of the...
3
t = int(input()) while t > 0: x, y = [int(a) for a in input().split()] if (y%2 == 0 or x%2 == 0): ans = min(((x+1)//2)*y,((y+1)//2)*x) else: z = max(x,y) w = min(x,y) ans = min(((z-1)//2)*w + (w+1)//2,((w-1)//2)*z +(z+1)//2) print(ans) t = t-1
Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light. Three mirrors of length N are set so that they form an equilateral triangle. Let the vertices of the triangle be a, b and c. Inside the triangle, the rifle is placed at the point p on segment ab such that ap ...
3
N, X = map(int, input().split()) ans = N a = N - X b = X while a != b: if a >= b: a, b = b, a if b%a != 0: ans += 2 * a * (b//a) b = b%a else: ans += 2 * a * (b//a - 1) b = a print (ans + a)
In Dwango Co., Ltd., there is a content distribution system named 'Dwango Media Cluster', and it is called 'DMC' for short. The name 'DMC' sounds cool for Niwango-kun, so he starts to define DMC-ness of a string. Given a string S of length N and an integer k (k \geq 3), he defines the k-DMC number of S as the number o...
3
#!usr/bin/env python3 from collections import defaultdict,deque from heapq import heappush, heappop from itertools import permutations import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for...
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make s airplanes. A group of k people decided to make n airplanes each. They are going to buy several packs of paper, each of them containing p sheets, and then distribute the sheets between the people. Each pe...
3
import math k,n,s,p = map(int,input().split()) a = math.ceil(n/s)*k print(math.ceil(a/p))
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n. Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance...
3
n = int(input()) m = list(map(int, input().split())) ma, mi = m.index(n), m.index(1) ma, mi = max(ma, mi), min(ma, mi) print(max(ma, n-ma-1, n-1-mi, mi-1))
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across n sessions follow the identity permutation (ie. in the first game he scores 1 point, in the second game he scores 2 points and so on). However, when he ch...
3
# import sys # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') t = 1 t = int(input()) while t: t -= 1 n = int(input()) a = list(map(int, input().split())) # s = input() # max ans is 2 # 0 if already sorted # 1 if none of elements in place or elements in place on...
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the...
3
n = int(input()) for i in range(n): a, b, c = map(int, input().split()) print(int((a + b + c) // 2))
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
s=input() f=set(s) if(len(f)%2==0): print("CHAT WITH HER!") else: print("IGNORE HIM!")
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >...
3
from math import ceil as mc, floor as mf, log as l def isint(n): if mc(n)==mf(n): return True else: return False for _ in range(int(input())): n=int(input()) x=mc(l(n,2)) for i in range(2,x+1): y=n/(pow(2,i)-1) if isint(y): print(int(y)) break
Alice and Bob are playing chess on a huge chessboard with dimensions n Γ— n. Alice has a single piece left β€” a queen, located at (a_x, a_y), while Bob has only the king standing at (b_x, b_y). Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the vic...
3
n = int(input()) a1, a2 = list(map(int, input().split())) b1, b2 = list(map(int, input().split())) c1, c2 = list(map(int, input().split())) b1 -= a1 b2 -= a2 c1 -= a1 c2 -= a2 if (b1 > 0) and (b2 > 0) and (c1 > 0) and (c2 > 0): print("YES") elif (b1 > 0) and (b2 < 0) and (c1 > 0) and (c2 < 0): print("YES") elif...
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange. Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consec...
3
vowels = ['a', 'e', 'i', 'o', 'u', 'y'] n = int(input()) - 1 word = list(input()) i = 0 while n > 0: if word[i] in vowels and word[i + 1] in vowels: word.pop(i + 1) else: i += 1 n -= 1 print("".join(word))
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive. Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on. Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone...
3
from math import log,sqrt,factorial,cos,tan,sin,radians def li(): return list(map(int,input().split())) def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().split()) def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1))) def DtoB(n): return bin(n).replace("0b","") de...
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≀ si ≀ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
1
raw_input() s=[int(i) for i in raw_input().split()] a=[s.count(4),s.count(3),s.count(2),s.count(1)] r=a[0] if a[1]>0: r+=a[1] a[3]-=a[1] if a[2]>0: r+=a[2]/2 if a[2]%2: r+=1 a[3]-=2 if a[3]>0: r+=a[3]/4 if a[3]%4: r+=1 print r
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
3
l = list(map(int, input().split())) a = [] count = 0 for i in l: if i not in a: a.append(i) else: count += 1 print(count)
An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4]. Polycarp invented a really cool p...
3
n = int(input()) data = list(map(int, input().split())) result = [1] min_p = 1 for i in range(1, n): next_p = result[i - 1] + data[i - 1] min_p = min(min_p, next_p) result.append(next_p) if min_p != 1: d = 1 - min_p for i in range(n): result[i] += d print(' '.join(map(str, result)) if set(re...
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...
1
n1,n2,k1,k2 = [int(a) for a in raw_input().split()] if n1>n2: print "First" else: print "Second"
There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates (0, 0), and coordinate axes are left and bottom sides of the table, then the bott...
3
w = list(map(int,input().split())) b1 = list(map(int,input().split())) b2 = list(map(int,input().split())) def inside(x,y,rect): return rect[0] <= x and x <= rect[2] and rect[1] <= y and y <= rect[3] b1_cover = [inside(w[0],w[1],b1), inside(w[0],w[3],b1), inside(w[2],w[3],b1), inside(w[2],w[1],b1)] b...
Snuke built an online judge to hold a programming contest. When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring. (The judge can return any two-character substring of S.) Determine whether the judge can return the ...
3
s = input() print('Yes' if 'AC' in s else 'No')
You have a fraction <image>. You need to find the first occurrence of digit c into decimal notation of the fraction after decimal point. Input The first contains three single positive integers a, b, c (1 ≀ a < b ≀ 105, 0 ≀ c ≀ 9). Output Print position of the first occurrence of digit c into the fraction. Positions...
1
a,b,c=map(int,raw_input().split()) o={} d=0 i=0 while (d,a) not in o: o[(d,a)]=1 a*=10 d=a/b a%=b i+=1 if d==c: print i break else: print -1