problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water...
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 11 08:23:58 2017 @author: lawrenceylong """ a = int(input()) b = list(map(int,input().split())) b.sort(reverse=True) count = 0 k = 0 yes = True while count < a: count += b[k] k+=1 if k == 12: if sum(b) < a: print(-1)...
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
3
# -*- coding: utf-8 -*- """ Created on Sun Dec 10 17:21:17 2017 @author: admin """ n = int(input()) p = [int(x) for x in input().split()] p.pop(0) q = [int(x) for x in input().split()] q.pop(0) total = set(p+q) if 0 in total: total.remove(0) if len(total) >= n: print('I become the guy.') else: print('Oh, ...
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i. Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to: * Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change...
3
def chk(arr,x): ml=1 ans=0 for i in arr: ans+= abs(i-ml) ml*=x if(ml>10000000000000000000): return ml return ans n=int(input()) arr=list(map(int, input().split())) arr.sort() ans=100000000000000000000 for i in range(1,100010): x=chk(arr,i) ans=min(ans,x) print...
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other. Dima and Inna are using a secret code in their text messages. ...
1
s=list('<3'+'<3'.join(raw_input()for _ in range(input()))+'<3') t=list(raw_input()) while s and t: if s[-1]==t[-1]:s.pop() t.pop() print'no'if s else'yes'
Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j)...
3
n = int(input()) a = list(map(int, input().rstrip().split())) maxm = 0 for i in range(n): s = sum(a[:i]) t = 0 for j in range(i, n): if a[j] == 0: t += 1 u = 0 for k in range(j+1, n): if a[k] == 1: u += 1 maxm = max(maxm, s + t + u) ...
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
3
n = int(input()) rooms = 0 for i in range(0, n): p, q = map(int, input().split()) if q - p >= 2: rooms += 1 print(rooms)
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()) c = 0 for i in range(1, w+1): c = c + i * k b = c - n if b <= 0: b = 0 print(b)
"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
def main(): n, k = ints_from_input() a = ints_from_input() answer = 0 for i in a: if i < 1 or i < a[k - 1]: break answer += 1 print(answer) def ints_from_input(): return [int(i) for i in input().split()] if __name__ == '__main__': main()
There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the trou...
1
#!/usr/bin/env python n,m,t = map(long, raw_input().strip().split()) from operator import mul nCk = lambda n,k: int(round( reduce(mul, (float(n-i)/(i+1) for i in range(k)), 1) )) res = 0 for x in xrange(4,n+1): for y in xrange(1,m+1): if y+x==t: res += nCk(n,x)*nCk(m,y) print res
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo...
3
n, m = map(int, input().split()) a = map(int, input().split()) cur = 0 cnt = 0 for elem in a: cur += elem print(cur // m - cnt, end=' ') cnt = cur // m
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games. He came up with the following game. The player has a positive integer n. Initially the value of n equals to v and the player is able to do the following operatio...
3
n = int(input()) if n < 3: print(n) else: print(1)
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won. Alex has grown up since then, so he easily wins the most difficu...
3
from itertools import product def check_correct(field, x, y, n, m): is_inside_field = lambda x, y: 0 <= x < n and 0 <= y < m dx_var, dy_var = (-1, 0, 1), (-1, 0, 1) bombs_count = 0 for dx, dy in product(dx_var, dy_var): if dx == 0 and dy == 0: continue if not is_inside_fie...
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or thro...
3
a = [int(x) for x in input().split()] a = sorted(a) if a[0] + a[1] + a[2] == a[3]: print('YES') elif a[0] + a[3] == a[1] + a[2]: print('YES') else: print('NO')
An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sur...
3
n=int(input()) if n==1 or n==2: print(1) print(1) elif n==3: print(2) print(1,end=" ") print(3) elif n==4: print(4) print(2,end=" ") print(4,end=" ") print(1,end=" ") print(3,end=" ") else: print(n) for i in range (1,n+1,2): print(i,end=" ") for i in range (2,n+1,2): print(i,end=" ")
Petya is preparing for his birthday. He decided that there would be n different dishes on the dinner table, numbered from 1 to n. Since Petya doesn't like to cook, he wants to order these dishes in restaurants. Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his ord...
3
from sys import stdin input=stdin.readline for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) L = 0 R = max(a) while L < R: mid = (L + R) // 2 if sum(y if x > mid else 0 for x, y in zip(a, b)) <= mid: ...
You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2,...
3
import sys from sys import stdin n,k = map(int,stdin.readline().split()) a = list(map(int,stdin.readline().split())) xl = 1 xr = n+1 while xr-xl != 1: xm = (xl+xr)//2 b = [0] for i in range(n): if a[i] >= xm: b.append(1) else: b.append(-1) for i in range(le...
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2). In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i ar...
3
for _ in range(int(input())): n, k = map(int, input().split()) if n&1 and k&1^1: print("NO") elif n&1^1 and k&1: if n < 2*k: print("NO") else: print("YES") for i in range(k - 1): print(2, end=" ") print(n - 2*(k - 1)) else: if n < k: print("NO") else: ...
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
3
import math import sys import collections def In(): return map(int, sys.stdin.readline().split()) input = sys.stdin.readline def strsim(): for i in range(int(input())): n = int(input()) s = input().rstrip() ans = ['0']*n used = [False]*n pos = 0 for i in range...
You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria. According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is...
3
N = int(input()) arr = list(map(int,input().split())) print('APPROVED' if all(i%2==1 or i %3==0 or i%5 == 0 for i in arr) else 'DENIED')
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess». This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed...
1
import sys blacks = [8]*8 whites = [8]*8 seen_b = [0]*8 for r in xrange(8): row = sys.stdin.readline() for c in xrange(8): if row[c] == 'W': if not seen_b[c]: whites[c] = min(whites[c], r) blacks[c] = 8 if row[c] == 'B': blacks[c] = min(blacks...
In the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k ≥ 0. Team BowWow has arrived at the station at the time s and it is trying to co...
3
s=input() n=0 x=len(s)-1 count=0 if x!=0 and s[0]!='0': for i in range(0,len(s)): if s[i]=='1': n+=2**x x=x-1 x=1 while x<n: x=4*x count=count+1 print(count) else: print(0)
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
import math inp=list(map(int,input().rstrip(' ').split(' '))) count1,c2=0,0 count1+=math.ceil(inp[0]/inp[2]) c2+=math.ceil(inp[1]/inp[2]) print(count1*c2)
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays...
3
def bs(x): l = 0 r = n while l + 1 < r: m = (l+r)//2 if x <= p[m]: r = m else: l = m if x <= p[l]: return l return r n, k = map(int, input().split()) a = [] for i in range(n): c, t = map(int, input().split()) a.append(c*t) p = [a[...
Japan achieved the second straight victory in the national baseball competition WBC !! A baseball tournament was held at Aizu Gakuen High School as baseball became more popular. In this tournament, a round-robin league match will be held and the ranking will be decided in the following ways. 1. The team with the most ...
1
while 1: n = input() if n == 0:break r = sorted(sorted([raw_input().replace("2","") for i in range(n)],key = lambda x:x.count("1")),key = lambda x:x.count("0"),reverse = 1) for i in r:print i[0]
JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array a_1, a_2, ..., a_n of integers, such that 1 ≤ a_1 < a_2 < … < a_n ≤ 10^3, and then went to the bathroom. JATC decided to prank his friend by erasing some consecutive elements in the array. Since he...
3
n=int(input()) list1=list(map(int,input().split())) c=0 s=0 ele=list1[0] list2=[ele] for i in range(1,n): # print(list2) if(list1[i]==ele+1): list2.append(list1[i]) ele=list1[i] else: ele=list1[i] # print(ele) if(list2): # print(list2) c=len(li...
One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment. Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered ...
3
string = input() numbers = string.split(" ") a = int(numbers[0]) b = int(numbers[1]) flats = 0 for x in range(a): string = input() numbers = string.split(" ") for y in range(b * 2): numbers[y] = int(numbers[y]) for y in range(b): p = numbers[y * 2] q = numbers[y * 2 + 1] ...
Petya is having a party soon, and he has decided to invite his n friends. He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one co...
1
n, k = map(int, raw_input().split()) a = n * 2 b = n * 5 c = n * 8 cnt = 0 cnt += a // k if a % k != 0: cnt += 1 cnt += b // k if b % k != 0: cnt += 1 cnt += c // k if c % k != 0: cnt += 1 print cnt
After lessons Nastya decided to read a book. The book contains n chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page. Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number k as the fi...
3
import math import time from collections import defaultdict, deque from sys import stdin, stdout from bisect import bisect_left, bisect_right t=int(input()) r=[] for _ in range(t): r.append(map(int,stdin.readline().split())) k=int(input()) ans=0 for i,j in r: if(k<=j): break ans+=1 print(t-ans)
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k. In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w...
3
t = int(input()) for i in range(t): n, k = map(int, input().split()) l1 = list(map(int, input().split())) l2 = list(map(int, input().split())) l1.sort() l2.sort() sum1 = sum(l1) for j in range(k): if (l1[j] < l2[len(l2) - 1-j]): sum1 = sum1 + l2[len(l2)-1-j] - l1[j] ...
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i × j. The rows and columns are numbered starting from 1. You are given a positive integer x. Your task is to count the number of cells in a table that contain number x. Input T...
1
from sys import stdin from math import sqrt n, x = map(int, stdin.readline().split()) count = 0 for i in xrange(1, min(n, int(sqrt(x)))+1): if x%i == 0 and x/i<=n: if i!=x/i: count+=2 else: count+=1 print count
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers. A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if: * Its elements are in increasing o...
3
# cook your dish here from sys import stdin, stdout import math from itertools import permutations, combinations from collections import defaultdict from bisect import bisect_left def L(): return list(map(int, stdin.readline().split())) def In(): return map(int, stdin.readline().split()) def I(): retu...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
1
def isVowel(ch): if (ch == 'a' or ch == 'A' or ch == 'e' or ch == 'E' or ch == 'i' or ch == 'I' \ or ch =='o' or ch=='O' or ch == 'u' or ch == 'U' or ch == 'y' or ch == 'Y'): return 1; else: return 0; j = 0 c = "" s = raw_input() for i in range(len(s))...
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ...
3
a,b,c=[int(i) for i in input().split()] while True: if c==0: ans=1 break for i in range(1,min(a,c)+1): if a%i==0 and c%i==0: gcd1=i else: continue c-=gcd1 if c==0: ans=0 break for i in range(1,min(b,c)+1): if b%i==0 and c%i==0: gcd1=i else: continue c-=gcd1 print(ans)
Pasha has a positive integer a without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer. Help Pasha count the maximum number he can get if he has the time to make at most k sw...
3
a, k = map(int, input().split()) a = list(str(a)) b = '' while a: e = max(a[:k+1]) ind = a.index(e) b += e k -= ind a.pop(ind) print(b)
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
s = int(input()) x = 0 for m in range(s): n = input() if n=="X++": x+=1 if n=="X--": x-=1 if n=="--X": x-=1 if n=="++X": x+=1 print(x)
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 ≥ p_2 ≥ ... ≥ p_n. Help the jury distrib...
3
for _ in range(0, int(input())): n = int(input()) pro = list(map(int, input().split(" "))) med = int(n/2) mini = pro[n-1] est = "G" g = 0 s = 0 b = 0 if len(set(pro)) >= 4: for i in range(0, med): if est == "G": g += 1 elif est == "S":...
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to...
3
# 2200 rating t=int(input()) for i in range(t): n=input() l=list(map(int,input().split())) # print(l) if l[0]+l[1]<=l[-1]: print(1,2,n) else: print(-1)
For given three points p1, p2, p, find the reflection point x of p onto p1p2. <image> Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xi, yi ≤ 10000 * p1 and p2 are not identical. Input xp1 yp1 xp2 yp2 q xp0 yp0 xp1 yp1 ... xpq−1 ypq−1 In the first line, integer coordinates of p1 and p2 are given. Then, q queries are giv...
3
class Vector: __slots__ = ['x', 'y'] def __init__(self, x, y): self.x, self.y = x, y def __add__(self, other): return self.__class__(self.x + other.x, self.y + other.y) def __sub__(self, other): return self.__class__(self.x - other.x, self.y - other.y) def __mul__(self, x...
An n × n table a is defined as follows: * The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n. * Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin...
3
n=int(input()) row=[1]*n for i in range(1,n): for p in range(1,n): row[p]=row[p]+row[p-1] print(row[n-1])
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types. * `0 p x`: a_p \gets a_p + x * `1 l r`: Print \sum_{i = l}^{r - 1}{a_i}. Constraints * 1 \leq N, Q \leq 500,000 * 0 \leq a_i, x \leq 10^9 * 0 \leq p < N * 0 \leq l_i < r_i \leq N * All values in Input are integer. I...
3
import sys def MI(): return map(int,sys.stdin.readline().rstrip().split()) def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) class BIT(): def __init__(self,init_value): self.n = len(init_value) self.tree = [0]*(self.n+1) for i in range(1,self.n+1): x = init_...
AtCoDeer has three cards, one red, one green and one blue. An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card. We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer. Is this integer...
3
n=int(input()[::2]) print("YES" if n&3==0 else "NO")
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another. Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": * "A" corresponds to an angry...
3
t = int(input()) for _ in range (t): n = int(input()) string = str(input()) ans = 0 i = string.find("A") if i == -1: print(0) continue for j in range (i + 1, n): if string[j] == "A": maxi = j - i - 1 if ans < maxi: ans = maxi ...
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002. You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2. Let's define the ternary XOR operation ⊙ of two ternary n...
3
t=int(input()) while t>0: l=int(input()) s=input() s1="" s2="" s1=s1+'1' s2=s2+'1' for i in range(1,l,1): if s[i]=='2': if s1<s2: s1=s1+'2' s2=s2+'0' elif s2<s1: s2=s2+'2' s1=s1+'0' el...
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'...
3
s,d=map(int, input().split()) drag = [] for i in range(d): drag.append(list(int(x) for x in input().split())) drag.sort() for x,y in drag: if s<=x: print("NO") exit(0) else: s+=y print("YES")
A and B are preparing themselves for programming contests. An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solvi...
3
a, b = map(int, input().split()) print(min((a + b) // 3, min(a, b)))
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not. Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro...
3
n = input() k = n[::-1] print(n+k)
There is a game called "Unique Bid Auction". You can read more about it here: https://en.wikipedia.org/wiki/Unique_bid_auction (though you don't have to do it to solve this problem). Let's simplify this game a bit. Formally, there are n participants, the i-th participant chose the number a_i. The winner of the game is...
3
input = __import__('sys').stdin.readline from collections import Counter for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) p = Counter(a) ind = 10**24 for i in p: if p[i] == 1: ind = min(ind, i) if ind == 10**24: print(-1) else: ...
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
1
a=str(raw_input()) b=str(raw_input()) k=[] if len(a)==len(b): for i in range(len(a)): if a[i]==b[i]: k.append("0"), else: k.append("1"), print "".join(k)
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: * the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; * the lower half of matrix c (rows with n...
3
def arotate(x): d=len(x) c=0 if d%2==0: for i in range(int(d/2)): if x[i]==x[d-i-1]: c+=1 if c==d/2 : return x[:int(d/2)] else: return False n,m=input().split() n=int(n) m=int(m) C=[] for i in range(n): C+=[list(map(int,input().split()))] E=True cnt=len(C) while C: C=arotate(C) if C: cnt=len(C) print(cnt)
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the resul...
3
from sys import stdin,stdout,exit import math from fractions import gcd def sin(): return stdin.readline().rstrip() def listInput(): return list(map(int,sin().split())) def printBS(li): if not li: return for i in range(len(li)-1): stdout.write("%d "%(li[i])) stdout.write("%d\n"%(li[-1])) dic={(0,0,0):"ABC",(0,0...
Toad Ivan has m pairs of integers, each integer is between 1 and n, inclusive. The pairs are (a_1, b_1), (a_2, b_2), …, (a_m, b_m). He asks you to check if there exist two integers x and y (1 ≤ x < y ≤ n) such that in each given pair at least one integer is equal to x or y. Input The first line contains two space-s...
3
n,m = map(int,input().split()) my_sets = {}; no_find,no_find1 = False,False for i in range(m): x,y = map(int,input().split()) if x not in my_sets.keys(): my_sets.update({x:[y]}) else: my_sets[x].append(y) if y not in my_sets.keys(): my_sets.update({y:[x]}) else: my_se...
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi ha...
3
import itertools n,m = list(map(int,input().split())) arr = [] for i in range(n): arr.append([]) for i in range(m): a,b = list(map(int,input().split())) a-=1 b-=1 arr[a].append(b) arr[b].append(a) permuts = list(itertools.permutations(list(range(7)))) ans = 0 for i in range(len(permuts)): pe...
During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows: <image> The cell with coordinates (x, y) is at the intersection of x-th row ...
3
def rowsum(x, y): return x * (y - 1) + (y - 2) * (y - 1) // 2 def colsum(x, y): return y * (x - 1) + x * (x - 1) // 2 def get(i, j): return rowsum(1, j) + colsum(i, j) + 1 def rsum(x, y): return (y + 1) * y // 2 - y + y * (y - 1) * (y - 2) // 6 + (y + 1) * y * (x - 1) // 2 + y * x * (x - 1) // 2 + y def...
There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to n. It is known that during the day q tasks will come, the i-th of them is characterized with three integers: ti — the moment in seconds in which the task will come, ki — the number of servers needed to ...
3
while True: try: caption = input().split() n = int(caption[0]) servers = [i for i in range(1, n+1)] answer = [] q = int(caption[1]) using = {} for i in range(q): tasks = input().split() time = int(tasks[0]) ...
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
from sys import stdin num=int(stdin.readline()) n=stdin.readline().strip() cont=0 for i in range(len(n)-1): if len(n) == 1: cont=0 else: if n[i]==n[i+1]: cont+=1 print(cont)
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
#a,b=[int(a) for a in input().split()] #x = list(map(int, input().split())) x=int(input()) name=input() acount=0 dcount=0 for name in name: if(name=="A"): acount+=1 elif(name=="D"): dcount+=1 if(acount>dcount): print("Anton") elif(dcount>acount): print("Danik") elif(acount==...
Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy start...
1
import sys import re p, a, b = map(lambda x: x.strip(), sys.stdin.readlines()); x = re.search(a+".*"+b, p) y = re.search(a+".*"+b, p[::-1]) if x is not None: if y is not None: print "both" else: print "forward" else: if y is not None: print "backward" else: print "fant...
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to n (n ≥ 2) burles and the amount of tax he has to pay is calculated as the maximum divisor of n (not equal to n, of course). For example, if n = 6 then Funt has to pay 3 burles, while for n = 25 he ne...
1
def isprime(n): K=int(n**0.5) for i in range(2,K+1): if n%i==0: return 0 return 1 n=input() if isprime(n)==1: print(1) else: if n%2==0: print(2) else: if isprime(n-2)==1: print(2) else: print(3)
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c. You h...
3
A = sorted([int(a) for a in input().split()]) m = A[-1] print(m-A[2], m-A[1], m-A[0])
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
n,t = map(int, input().split()) if n==1 and t==10: print(-1) else: b=10**(n-1) b+= t-(b%t) print(b)
You are given an integer sequence of length n, a_1, ..., a_n. Let us consider performing the following n operations on an empty sequence b. The i-th operation is as follows: 1. Append a_i to the end of b. 2. Reverse the order of the elements in b. Find the sequence b obtained after these n operations. Constraints...
3
# ARC077C - pushpush (ABC066C) from collections import deque def main(): n = int(input()) lst = list(map(int, input().rstrip().split())) b = deque() parity = n % 2 for i, j in enumerate(lst, start=1): if i % 2 == parity: b.appendleft(j) else: b.append(j) ...
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
3
money=int(input()) bills=0 bills=money//100 money=money%100 bills=(money//20)+bills money=money%20 bills=(money//10)+bills money=money%10 bills=(money//5)+bills money=money%5 print(money+bills)
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 bisect def solve(seq, k): n = len(seq) res = [] # cur = 0 while k > 0: # print("k", k) idx = bisect.bisect_right(seq, k) - 1 if idx == 0: break res.append(1) res += (idx - 1) * [0] # cur += idx # print("removing", seq[idx]) ...
Joisino the magical girl has decided to turn every single digit that exists on this world into 1. Rewriting a digit i with j (0≤i,j≤9) costs c_{i,j} MP (Magic Points). She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digit between 0 and...
3
h, w = map(int, input().split()) c = [list(map(int, input().split())) for _ in range(10)] a = [list(map(int, input().split())) for _ in range(h)] for k in range(10): for i in range(10): for j in range(10): c[i][j] = min(c[i][j], c[i][k] + c[k][j]) ans = 0 for i in range(h): for j in range(w)...
You are given a string s. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the str...
3
maxn=int(2e5+5) n=int(input()) s=input() t=s[::-1] a=[[]for i in range(31)] # for i in range(30): # a.append([]) tree=[0]*maxn num=[0]*maxn g=[0]*30 def lowbit(x): return x&(-x) def tadd(x,val): while x<=maxn: tree[x]+=val x+=lowbit(x) def tsum(x): ans=0 while x>0: ans+=tree[...
Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string...
3
s=input() s1="" s2="" r=0 n=len(s) for i in range(n): s1=s1+s[i] if(s[i]!="a"): s2=s2+s[i] if((s1+s2)==s): r=1 break if(r==0): print(":(") else: print(s1) # print(s1,s2,s)
You are given a string t consisting of n lowercase Latin letters and an integer number k. Let's define a substring of some string s with indices from l to r as s[l ... r]. Your task is to construct such string s of minimum possible length that there are exactly k positions i such that s[i ... i + n - 1] = t. In other...
3
# only gravity will pull me down from math import * n, k = map(int, input().split()) t = input() if len(set(t)) == 1 : res = t + t[0] * (k-1) #print(res) elif t == t[::-1] : ch = t[0] cnt = 0 for i in t : if i == ch : cnt += 1 else : break res = t + t[cnt:] * (k-1) #print(res) else : res = t * k ...
There are N balls placed in a row. AtCoDeer the deer is painting each of these in one of the K colors of his paint cans. For aesthetic reasons, any two adjacent balls must be painted in different colors. Find the number of the possible ways to paint the balls. Constraints * 1≦N≦1000 * 2≦K≦1000 * The correct answer i...
3
N,K = map(int,input().split()) print(K*((K-1)**(N-1))**(N>1))
Solve the Mystery. Input Format: First line contains integer T denoting number of test cases. Next T lines contains sentences, one in each line. Output Format: Print output of each test case on individual line. Constraints: 1 ≤ T ≤ 100 1 ≤ length of sentence ≤ 100 Each sentence contains characters from this set {a-z...
1
times=input() inp='abcdefghijklmnopqrstuvwxyz' outp='qwertyuiopasdfghjklzxcvbnm' for _ in range(times): in1=raw_input() lst=list(in1) for i in range(len(lst)): char=lst[i] if char in inp: index=inp.index(char) lst[i]=outp[index] else: print "".join(lst)
There is data of up to 100 characters per line, consisting of half-width alphabetic character strings. Some lines are symmetric (same whether read from the left edge or the right edge). Create a program that reads this data and outputs the number of symmetric strings in it. Note that lines consisting of only one charac...
3
a=0 while 1: try:s=input() except:break if s==s[::-1]:a+=1 print(a)
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane. You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem...
3
def manager(n, s): c1 = 0 c2 = 0 for i in range(n - 1): if(s[i] == 'S' and s[i + 1] == 'F'): c1 = c1 + 1 elif(s[i] == 'F' and s[i + 1] == 'S'): c2 = c2 + 1 if(c1 > c2): return "YES" else: return "NO" n = int(input()) s = str(input()) print(ma...
Nauuo is a girl who loves playing chess. One day she invented a game by herself which needs n chess pieces to play on a m× m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c). The game's goal is to place n chess pieces numbered fro...
3
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf=10**20 mod=10**9+7 def LI(): return list(map(int,input().split())) def I(): return int(input()) def LS(): return input().split() def S(): return input() def main(): n=I() x=n//2+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
_n = int(input()) _list = input().split(' ') out_list = [0] * _n for i in range(_n): out_list[int(_list[i])-1] = i+1 out = '' for elem in out_list: out = out + str(elem) + ' ' print(out)
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc...
1
n=input() print (n*n+5)*n/6
n robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous! Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the locat...
3
import os import gc import sys from io import BytesIO, IOBase from collections import Counter from collections import deque import heapq import math import statistics def sin(): return input() def ain(): return list(map(int, sin().split())) def sain(): return input().split() def iin(): return int(si...
[3R2 as DJ Mashiro - Happiness Breeze](https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak) [Ice - DJ Mashiro is dead or alive](https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive) NEKO#ΦωΦ has just got a new maze game on her PC! The game's main puzzle is a maze, in the forms of a 2 × n rectangle grid. NEKO...
3
def RL(): return list(map(int, input().split())) from sys import stdin # ------------------------------ n, q = RL() s1 = set() s2 = set() bdic = set() block = 0 for i in range(q): x, y = map( int, stdin.readline().rstrip().split() ) if x==1: if y in s1: s1.remove(y) for ny in...
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y): * point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y * point (x', y') is (x, y)'s left neighb...
1
lst = [] n = input() for i in range(n): lst.append(map( int, raw_input().split() )) def fx(x,y,k): if k == 1: for e in lst: if e[0] > x and e[1] == y: return True return False else: for e in lst: if e[0] < x and e[1] == y: ...
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
n, m = map(int, input().split(' ')) primes = [0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1] n = n + 1 while n < 51 and primes[n] == 1: n = n + 1 if n != m: print('NO') else: print('YES')
There are N robots numbered 1 to N placed on a number line. Robot i is placed at coordinate X_i. When activated, it will travel the distance of D_i in the positive direction, and then it will be removed from the number line. All the robots move at the same speed, and their sizes are ignorable. Takahashi, who is a misc...
3
import sys INF = 1 << 60 MOD = 998244353 sys.setrecursionlimit(2147483647) input = lambda:sys.stdin.buffer.readline().rstrip() class LazySegmentTree(object): def __init__(self, A, dot, unit, compose, identity, act): # A : array of monoid (M, dot, unit) # (S, compose, identity) : sub monoid of End(M)...
Two players play a game. Initially there are n integers a_1, a_2, …, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate t...
3
n = eval(input()) line = input() strings = line.split() list = [] for string in strings: list.append(eval(string)) result = sorted(list) size = len(result) # index = (size-1) print(result[(size-1)//2])
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there. Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Ki...
1
import sys i,f=raw_input().split('.') if i[-1]=='9': print 'GOTO Vasilisa.' elif f[0]<'5': print i else: print int(i)+1
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a...
3
for _ in range(int(input())): s=input() l=[s[0]] n=len(s) i=1 while(i<n-1): l.append(s[i]) i+=2 l.append(s[n-1]) x='' x=x.join(l) print(x)
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()) arr = [] for _ in range(n): w = input() if len(w) > 10: arr.append(w[0] + str(len(w) - 2) + w[-1]) else: arr.append(w) for a in arr: print(a)
The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they f...
3
n = int(input()) t = list(map(int, input().split())) answer = sum(t) for modulo in range(1, n+1): if 0 == n % modulo: sumT = [0] * modulo number = [0] * modulo for i in range(n): sumT[i % modulo] += t[i] number[i % modulo] += 1 for i in range(modulo): ...
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow th...
1
from sys import stdin import re n = stdin.readline().strip() n = int(n) for _ in range(n): st = stdin.readline().strip() c = [] if re.match(r'\D+\d+\D+\d+', st) is not None: _, a, b = re.split(r'\D+', st) b = int(b) while b > 0: b -= 1 c.append( chr(b % 26 + ord('A'))) b = b // 26 c.reverse() c.a...
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
l=[] for i in range(5): l2=list(map(int,input().split())) l.append(l2) if 1 in l2 : x=i y=l2.index(1) print(abs(2-x)+abs(2-y))
There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is alrea...
1
#import sys; sys.stdin = open('input.txt') MOD = 1000000007 c = [[1]*i for i in xrange(1,1002)] for i in xrange(2, 1001): for j in xrange(1, i): c[i][j] = (c[i-1][j-1] + c[i-1][j]) % MOD n, m = map(int, raw_input().split()) a = map(int, raw_input().split()) a.sort() k = n-m ans = 1 s = p = a[0] for i in...
Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have a...
3
n = input() s = [] a = 0 for i in map(int, input().split()): while len(s) > 1 and min(s[-2], i)>=s[-1]: a += min(i, s[-2]) del(s[-1]) s.append(i) s.sort() print(a + sum(s[0: -2]))
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes. Input The single line of the input contains a pa...
3
m,s=map(int,input().split()) lmin=['0' for x in range(m)] lmax=['0' for x in range(m)] import sys if m==1: if s>9*m: print('-1 -1') sys.exit() else: print(str(s)+' '+str(s)) sys.exit() else: if s==0 or s>9*m: print('-1 -1') sys.exit() else: if s<=9...
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help. Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only ope...
3
n = int(input()) cs = [int(c) for c in input().split()] words = [input() for _ in range(n)] backwords = [w[::-1] for w in words] table = [[0,cs[0]] if i == 0 else [float('inf')]*2 for i in range(n)] for i in range(1,n): #print("%s -> %s" % (words[i-1], words[i])) if table[i-1][0] is not None: if words[i] >= words...
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
def chet(n): if n % 2 == 0 and n != 2: return "YES" return "NO" m = int(input()) print(chet(m))
Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100. The shop sells N kinds of cakes. Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i. Th...
3
from itertools import product N, M = map(int, input().split()) xyz = [list(map(int, input().split())) for _ in range(N)] ans = [] for lst in product([-1, 1], repeat = 3): temp = [] for x, y, z in xyz: temp.append(x * lst[0] + y * lst[1] + z * lst[2]) temp.sort(reverse=True) ans.append(sum(temp...
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
t = int(input()); x = 0; while(t != 0): x1 = input(); if "++" in x1: x = x+1; if "--" in x1: x = x-1; t = t-1; print(x);
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems. But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest ...
1
s=raw_input() k=["Danil", "Olya", "Slava", "Ann" , "Nikita"] r=[] for i in k: if i in s : r.append(s.count(i)) if(len(r)!=0 and min(r)==1 and max(r)==1 and r.count(1)==1): print "YES" else: print "NO"
You're given an integer n. For every integer i from 2 to n, assign a positive integer a_i such that the following conditions hold: * For any pair of integers (i,j), if i and j are coprime, a_i ≠ a_j. * The maximal value of all a_i should be minimized (that is, as small as possible). A pair of integers is call...
3
n = int(input()) curVal = 1 ans = [0 for x in range(n+1)] for i in range(2,n+1): if(ans[i] == 0): ans[i] = curVal for j in range(i*2, n+1, i): ans[j] = curVal curVal += 1 for q in ans[2:]: print(q, end=" ") print("")
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
3
###################################################### ############Created by Devesh Kumar################### #############devesh1102@gmail.com#################### ##########For CodeForces(Devesh1102)################# #####################2020############################# ###############################################...
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
n = int(input()) result = 0 for _ in range(n): a, b, c = [int(i) for i in input().split(' ')] if a + b + c >= 2: result += 1 print(result)
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string. For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) tw...
3
def sjs(): str1 = input() # str1 = 'nineteenineteen' n = 0 resoult = {} for i in str1: resoult[i] = str1.count(i) # print(resoult) try: for i in range(resoult['i']): if n == 0: if resoult['n'] >= 3 and resoult['i'] >= 1 and resoult['e'] >= 3 and r...
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other. Galya doesn't know the ships location. She can shoot to some cells and after each shot ...
3
n,a,b,k=[int(i) for i in input().split()] s=input() l=[] i=0 j=0 while i<len(s): if s[i]=="1": j=0 else : j+=1 if(j%b)==0: l+=[i+1] j=0 i+=1 l=l[a-1:] print(len(l)) print(*l)
You are given a special jigsaw puzzle consisting of n⋅ m identical pieces. Every piece has three tabs and one blank, as pictured below. <image> The jigsaw puzzle is considered solved if the following conditions hold: 1. The pieces are arranged into a grid with n rows and m columns. 2. For any two pieces that sh...
3
t = int(input()) for _ in range(t): n, m = map(int, input().rstrip().split()) if n == 1 or m == 1: print("YES") elif n <= 2 and m <= 2: print("YES") else: print("NO")