problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next t lines...
3
t = int(input()) for test in range(t): a,b = map(int,input().split()) if (a >= b*b and a%2 == b%2): print('YES') else: print('NO')
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
# -*- coding: utf-8 -*- """ Created on Mon May 25 12:01:08 2020 @author: Mridul Garg """ o = int(input()) for _ in range(o): s = input() n = len(s) # A = list(map(int, input().split(" "))) ans = s[0] for i in range(1, n-1, 2): ans += s[i] ans += s[-1] print(ans) ...
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:...
1
import sys from fractions import gcd from collections import Counter range = xrange input = raw_input t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) D = {} b = sorted(a) for i in range(n): D[b[i]] = i+1 dp = [0]*(n+1) for i in range(n): dp[D[a[i]]] = 1 + dp[D[a[i]]...
Today, Yasser and Adel are at the shop buying cupcakes. There are n cupcake types, arranged from 1 to n on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type i is an integer a_i. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative. Yasser, ...
3
t=int(input()) s=sum l=len def max_subarray(numbers): """Find a contiguous subarray with the largest sum.""" best_sum = float('-inf') best_start = best_end = 0 # or: None current_sum = 0 for current_end, x in enumerate(numbers): if current_sum <= 0: # Start a new sequence at th...
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have b buns, p beef patties and f chicken cutlets in your restaurant. You can sell one hamburger for ...
3
t = int(input()) for _ in range(t): b, p, f = map(int, input().split()) h, c = map(int, input().split()) if h > c: n = min(b//2, p) b -= 2*n print(h * n + c * min(b//2, f)) else: n = min(b//2, f) b -= 2*n print(c * n + h * min(b//2, p))
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,n=[int(i)for i in input().split()] p=False d=sorted([[int(i)for i in input().split()]for j in range(n)]) m=max(d,key=lambda x:x[0])[0] for x in d: if s > m:p=True;break if s > x[0]: s+=x[1] else: break print(["NO","YES"][p])
There is a robot on a coordinate plane. Initially, the robot is located at the point (0, 0). Its path is described as a string s of length n consisting of characters 'L', 'R', 'U', 'D'. Each of these characters corresponds to some move: * 'L' (left): means that the robot moves from the point (x, y) to the point (x...
3
d = {"L": (-1, 0), "R": (1, 0), "U": (0, 1), "D": (0, -1)} for _ in range(int(input())): n = int(input()) s = input() points = {(0, 0): 0} pos = [0, 0] min_loop = n + 1 for i in range(1, n + 1): pos[0] += d[s[i - 1]][0] pos[1] += d[s[i - 1]][1] if tuple(pos) in poin...
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round. For example, the following numbers are roun...
3
def main(): string = str(input()) if len(string)==1: print(1) print(string) return cnt = 0 for i in range(len(string)): if string[i]!='0': cnt+=1 print(cnt) for i in range(len(string)): if string[i]!='0': res = string[i]+('0'*(len(string)-i-1)) print(res,end=' ') print() return t = i...
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one. Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ...
3
k=int(input()) s="codeforces" a=[1]*10 pos=0 while True: check=1 for i in range(10): check*=a[i] if check>=k: break else: a[pos]+=1 if pos!=9: pos+=1 else: pos=0 ans="" for i in range(10): ans+=s[i]*a[i] print(ans)
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state. In each turn, a player must ...
3
for _ in range(int(input())): n, m = map(int, input().split()) a = list(map(lambda _: list(map(int, input().split())), range(n))) rows, cols = [True]*n, [True]*m for i in range(n): for j in range(m): if a[i][j] == 1: rows[i], cols[j] = False, False print('Vivek' if min(rows.count(True), cols...
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0. For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}. Then, she calculated an array, b_1, b_2, …, b_n: ...
3
n=int(input()) l=list(map(int,input().split())) l1=[] m=0 for i in range(n): k=l[i]+m l1.append(k) if(k>m): m=k print(*l1)
Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook. Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject. Let's consider a student the best at some...
3
"""Things to do if you are stuck:- 1.Read the problem statement again, maybe you've read something wrong. 2.See the explanation for the sample input . 3.If the solution is getting too complex in cases where no. of submissions are high ,then drop that idea because there is something simple which you are missing. 4....
You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can repl...
3
t = int(input()) while t: n = int(input()) m = 0 while n > 1: if n%2 == 0: n = n//2 m += 1 continue elif n%3 == 0: n = (2*n)//3 m += 1 continue elif n%5 == 0: n = (4*n)//5 m += 1 e...
You are given an array a consisting of n positive integers. Initially, you have an integer x = 0. During one move, you can do one of the following two operations: 1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1). 2. Just increase x by 1 (x := x + 1). ...
3
test_case = int(input()) for _ in range(test_case): n, k = map(int, input().split()) ar = list(map(int, input().split())) # print(type(ar)) # print(n, k, ar) mp = {} for i in ar: calc = i % k if calc: calc = k - calc mp.setdefault(calc, 0) mp[...
Tanya has n candies numbered from 1 to n. The i-th candy has the weight a_i. She plans to eat exactly n-1 candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day. Your task is to find the number of such candies i (let's call these candies goo...
1
n=input() arr=map(int,raw_input().split()) odd=[0] even=[0] for i in range(n): if i%2==0: odd.append(arr[i]+odd[-1]) else: even.append(arr[i]+even[-1]) ctr=0 for i in range(1,n+1): if i%2==0: o=odd[(i)/2]+even[-1]-even[i/2] e=even[(i-1)/2]+odd[-1]-odd[i/2] else: o...
AtCoDeer the deer has found two positive integers, a and b. Determine whether the concatenation of a and b in this order is a square number. Constraints * 1 ≤ a,b ≤ 100 * a and b are integers. Input Input is given from Standard Input in the following format: a b Output If the concatenation of a and b in this o...
3
a, b = input().split() n = int(a+b) print("Yes" if int(n**.5)**2 == n else "No")
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist. Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day cons...
3
n,m,z = map(int,input().split()) a= max(n,m) b= min(n,m) n= a m = b count = 0 while a<=z: if a%b==0: count+=1 a+=n else: a+=n print(count)
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that <image>...
3
elem = int(input()) ar = [] for i in input().split(' '): ar.append(int(i)) s = sum(ar) res = {} if s % 3 != 0: print(0) else: res[int(s / 3)] = [] res[int(2 * s / 3)] = [] count = 0 ret = 0 for i in range(len(ar) - 1): count = count + ar[i] if count == s / 3: res[...
Write a program which reads an integer and prints sum of its digits. Input The input consists of multiple datasets. For each dataset, an integer x is given in a line. The number of digits in x does not exceed 1000. The input ends with a line including single zero. Your program should not process for this terminal ...
3
while True: a = input() if a == '0': break print(sum(map(int,*a.split())))
Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market! In the morning, there are n opportunities to buy shares. The i-th of them allows to buy as many shares as you want, each at the price o...
3
n, m, r = map(int, input().split()) buy_price = min(map(int, input().split())) sell_price = max(map(int, input().split())) print(max(r, r % buy_price + r // buy_price * sell_price))
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the...
3
for case in range(int(input())):a,b,c=sorted([int(i) for i in input().split()]);a=(a+1 if a!=c else a );c=(c-1 if a!=c else c);print(2*(c-a))
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the gr...
3
t = int(input()) for _ in range(t): n, k = map(int, input().split()) ans = [[0] * n for i in range(n)] cnt = 0 for i in range(n): for j in range(n): if cnt == k: break ans[j][(i + j) % n] = 1 cnt += 1 if k % n == 0: print(...
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1'). In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do ...
3
class Case: def __init__(self, size, moves, string): self.size = size self.moves = moves self.string = string SPACE = ' ' ZERO = '0' ONE = '1' def get_case(): line_elements = input().split(SPACE) size = int(line_elements[0]) moves = int(line_elements[1]) string = list(inp...
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences. Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the...
3
def main(): N = int(input()) A = tuple(map(int, input().split())) a = sorted(A) if a[0] < 0 and a[-1] < 0: ans = 0 - sum(a) elif a[0] < 0: b = [i for i in a if i >= 0] c = [i for i in a if i < 0] ans = sum(b) - sum(c) else: ans = sum(a) print(ans) ma...
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
my_input = input().split('+') print('+'.join(sorted(my_input)))
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2). You are given a sequence a consisting of n integers. All these integers are distinct, each value from 1 to n appears in the sequence exactly once. You are making a sequen...
3
n_len = int(input()) n = list(map(int, input().split())) start = 0 end = n_len - 1 ans = [-1] direction = [] while (ans[len(ans)-1] < n[start] or ans[len(ans)-1] < n[end]): last_item = ans[len(ans) - 1] s = n[start] e = n[end] if s == e: if last_item < s: ans.append(s) start += 1 directi...
Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from t...
3
n = int(input()) total = 0 mx = 0 a = list(map(int, input().split())) for i in a: mx = max(mx, i) total += i total *= 2 total += n total /= n print(int((max(total,mx))))
Takahashi had a pair of two positive integers not exceeding N, (a,b), which he has forgotten. He remembers that the remainder of a divided by b was greater than or equal to K. Find the number of possible pairs that he may have had. Constraints * 1 \leq N \leq 10^5 * 0 \leq K \leq N-1 * All input values are integers. ...
3
def main(): n,k = map(int,input().split()) ans = 0 for b in range(k+1,n+1): ans += ((n//b)*max(0,b-k)+max(0,(n%b)-k+1)) if k == 0: ans -= n print(ans) main()
As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon. Elections are coming. You know the number of voters and the number of parties — n and m respectively. For each vote...
3
import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) n, m = mints() A = [0]*n h = [0]*m for i in range(n): a, b = mints() A[i] = (b, a-1) h[a-1] += 1 A.sort() r = 1e100 for k in range(1, n+1): b = h[::] w = ...
A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two r...
1
n,m=map(int,raw_input().split()) pro=[] for g in xrange(m): a,b=map(int,raw_input().split()) pro.append(a) pro.append(b) a=set(range(1,n+1)) b=list(a-set(pro)) x=b[0] print n-1 l=range(1,n+1) l.remove(x) for g in l: print x,g
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()) l=[int(x) for x in input().split()] l2=l.copy() num=len(l2) l.sort() ma=l[-1] mi=l[0] a=l2.index(ma) l3=[] for i in range(num): l3.append(l2[-1-i]) i=l3.index(mi) if i+a<num: print(i+a) else: print(i+a-1)
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements. Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed. Input The first line contains a single integer n (1 ≤ n ≤ ...
3
n=int(input()) l=list(map(int,input().split())) for i in range(n-1): if l[i] in l[i+1:]: l[i]=0 while(0 in l): l.remove(0) print(len(l)) print(*l,sep=" ")
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. T...
3
kD,kABC=1,0 n=int(input()) for i in range(n): kD,kABC=kABC*3%1000000007,(kABC*2+kD)%1000000007 print(kD)
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
n, m, a = [int(x) for x in raw_input().split()] n = (n // a) + (0 if n % a == 0 else 1) m = (m // a) + (0 if m % a == 0 else 1) print(n * m)
Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it. Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time...
1
def get_ints(): return map(int, raw_input().strip().split(' ')) n, m = get_ints() a = get_ints() b = get_ints() u = min(b) ans = max(max(a), min(a) * 2) if ans < u: print ans else: print -1
[Sakuzyo - Imprinting](https://www.youtube.com/watch?v=55Ca6av1kAY) A.R.C. Markland-N is a tall building with n floors numbered from 1 to n. Between each two adjacent floors in the building, there is a staircase connecting them. It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location...
3
# cook your dish here for t in range(int(input())): n,s,k=list(map(int,input().split())) a=list(map(int,input().split())) dic={} for i in a: dic[i]=True if s not in a: print(0) else: d1,d2=0,0 status1,status2=False,False for i in range(s-1,0,-1): ...
"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 ...
1
n, k = map(int, raw_input().split()) vec = map(int, raw_input().split()) kth = vec[k - 1] advancers = filter(lambda x: x > 0 and x >= kth, vec) print len(advancers)
Boboniu gives you * r red balls, * g green balls, * b blue balls, * w white balls. He allows you to do the following operation as many times as you want: * Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the b...
3
def ch(r,g,b,w): c=0 if r%2: c+=1 if g%2: c+=1 if b%2: c+=1 if w%2: c+=1 return c for i in range(int(input())): r,g,b,w = map(int, input().split()) co = ch(r,g,b,w) if co>1: m = 0 for i in range(min([r,g,b])): if m==10: print('NO'); break r-=1...
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());answer=0 for i in range(n): a,b,c=map(int,input().split()) if a+b+c>1: answer+=1 print(answer)
In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express. In the plan developed by the president Takahashi, the trains will run as follows: * A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds. * In the first t_1 seconds, a train must ru...
3
N = int(input()) T = list(map(lambda x:int(x)*2,input().split())) V = list(map(lambda x:int(x)*2,input().split())) sumt = sum(T) maxv = [min(i, sumt-i) for i in range(sumt+1)] ct = 0 for t,v in zip(T,V): for i in range(ct,ct+t+1): maxv[i] = min(maxv[i], v) ct += t for i in range(sumt): maxv[i+1] ...
Two integer sequences existed initially — one of them was strictly increasing, and the other one — strictly decreasing. Strictly increasing sequence is a sequence of integers [x_1 < x_2 < ... < x_k]. And strictly decreasing sequence is a sequence of integers [y_1 > y_2 > ... > y_l]. Note that the empty sequence and th...
3
n = int(input()) a = list(map(int, input().split())) a.sort() x = [] y = [] s = 0 flag = True for i in range(1, n): if a[i] == a[i-1]: s += 1 else: s = 0 if s > 1: flag = False break im = True for i in a: if im: x.append(i) im = False else: y.a...
Alice has a lovely piece of cloth. It has the shape of a square with a side of length a centimeters. Bob also wants such piece of cloth. He would prefer a square with a side of length b centimeters (where b < a). Alice wanted to make Bob happy, so she cut the needed square out of the corner of her piece and gave it to ...
1
t = int(input()) import random def miller_rabin(n, k): # Implementation uses the Miller-Rabin Primality Test # The optimal number of rounds for this test is 40 # See http://stackoverflow.com/questions/6325576/how-many-iterations-of-rabin-miller-should-i-use-for-cryptographic-safe-primes # for justific...
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
a = int(input()) b = list(map(int, input().split())) c = 0 d = {1: 0, 2: 0, 3: 0} s = 0 for i in b: if i == 1 and d[3] > 0: d[3] -= 1 c += 1 elif i == 2 and d[2] > 0: d[2] -= 1 c += 1 elif i == 3 and d[1] > 0: d[1] -= 1 c += 1 elif i == 4: c += 1 ...
There are n houses in a row. They are numbered from 1 to n in order from left to right. Initially you are in the house 1. You have to perform k moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current h...
3
l = input().split(" ") n,k,s = int(l[0]),int(l[1]),int(l[2]) if s > k*(n-1) or s<k: print("NO") else: print("YES") res = [] current = 1 if n == 2: for i in range(k): if i%2 == 0: res.append(2) else: res.append(1) for i in res: print(i,end=" ") else: num = int((s-k)/(n-2)) rem = (s-k)%(n...
Continuing the trend, this year too we present a 'Mystery' for you to solve! You will be given two numbers: a and b; and you have to output a single integer. See the sample test cases for hints. Input: The first line of the input will contain an integer t : the number of test cases. Each of the next t lines contain ...
1
t=input() while t: t-=1 a,b=map(int,raw_input().split()) print a%b
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 × 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures. Yo...
3
t = int(input()) for t_ in range(t): n = int(input()) a = list(map(int, input().split())) odd, even = 0, 0 for i in a: if i % 2 == 1: odd += 1 else: even += 1 if odd > 0 and even > 0: print("NO") else: print("YES")
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
if __name__ == "__main__": t = int(input()) for _ in range(t): x = input() if len(x) <= 10: print(x) else: print(x[0]+str(len(x)-2)+x[-1])
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ...
3
def solve(): n = input() nums = input() list1 = list(map(int, nums.split(" "))) list1.sort() for x in range(1,int(n) + 1): if (x != list1[x-1]): print(x) return print(int(n) + 1) solve()
Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny. He has a special interest to create difficult problems for others to solve. This time, with many 1 × 1 × 1 toy bricks, he builds up a 3-dimensional object. We can describe ...
3
N, M, H = map(int, input().split()) FV = list(map(int, input().split())) LV = list(map(int, input().split())) TV = [] for n in range(N): row = list(map(int, input().split())) TV.append(row) for r in range(N): for c in range(M): if TV[r][c] == 1: TV[r][c] = min(FV[c], LV[r]) for ...
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...
1
def readval(typ=int): return typ( raw_input() ) def readvals(typ=int): return map( typ, raw_input().split() ) def testcase(): n = readval() places = readval(str) sf, fs = 0, 0 for i in xrange(n-1): if places[i]=='S' and places[i+1]=='F': sf += 1 elif places[i]=='F' and places...
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
from sys import stdin, stdout int_in = lambda: int(stdin.readline()) arr_in = lambda: [int(x) for x in stdin.readline().split()] mat_in = lambda rows: [arr_in() for y in range(rows)] str_in = lambda: stdin.readline().strip() out = lambda o: stdout.write("{}\n".format(o)) arr_out = lambda o: out(" ".join(map(str, o))) ...
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
a,b = map(int,input().split()) i = 0 while(i<b): if(a%10==0): a/=10 else: a-=1 i+=1 print(int(a))
Find the sum of weights of edges of the Minimum Spanning Tree for a given weighted undirected graph G = (V, E). Constraints * 1 ≤ |V| ≤ 10,000 * 0 ≤ |E| ≤ 100,000 * 0 ≤ wi ≤ 10,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-...
3
v,e = map(int, input().split()) adj = [list(map(int, input().split())) for i in range(e)] adj.sort(key = lambda x:x[2]) group = [[i] for i in range(v)] key = [i for i in range(v)] sum = 0 for i,j,k in adj: if key[i] != key[j]: h = key[j] group[key[i]] += group[h] sum += k for t in gr...
There is a card game called "Durak", which means "Fool" in Russian. The game is quite popular in the countries that used to form USSR. The problem does not state all the game's rules explicitly — you can find them later yourselves if you want. To play durak you need a pack of 36 cards. Each card has a suit ("S", "H", ...
3
md = {"6":1,"7":2, "8":3, "9":4, "T":5, "J":6, "Q":7, "K":8,"A":9}; c = input(); a,b = input().split(); ans = False; if a[1]==b[1]: if md.get(a[0])>md.get(b[0]): ans=True; elif a[1]==c: ans=True; print(['NO','YES'][ans]);
Arpa is researching the Mexican wave. There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0. * At time 1, the first spectator stands. * At time 2, the second spectator stands. * ... * At time k, the k-th spectator stands. * At time k + 1, the (k + 1)-th specta...
3
n,k,t=map(int,input().split()) if t<=k: print(t) elif t>k and t<=n: print(k) elif t>n: t=t-n print(k-t)
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
import sys a = input() p = 0 i=1 while i < len(a): if p == 6: print('YES') i = len(a) sys.exit() else: if int(a[i]) == int(a[i-1]): p = p + 1 else: p = 0 i = i + 1 if p == 6: print('YES') else: print('NO')
Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones b...
3
s = list(input()) c = 0 for i in range(len(s)-1): if s[i] != s[i+1]: c += 1 print(c)
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
n = int(input()) As = list(map(int, input().split())) ans = 1 record = 1 prev_a = As[0] for a in As[1:]: if a >= prev_a: ans += 1 if ans > record: record = ans else: ans = 1 prev_a = a print(record)
One day Vasya came up to the blackboard and wrote out n distinct integers from 1 to n in some order in a circle. Then he drew arcs to join the pairs of integers (a, b) (a ≠ b), that are either each other's immediate neighbors in the circle, or there is number c, such that a and с are immediate neighbors, and b and c ar...
1
import sys n = input() e = [[] for _ in xrange(n)] for i in xrange(2 * n): a, b = map(int, raw_input().split()) e[a - 1].append(b - 1) e[b - 1].append(a - 1) for i in xrange(n): if len(e[i]) < 4: print -1 sys.exit(0) if n <= 5: print ' '.join(map(str, range(1, n + 1))) sys...
You start with the number 0 and you want to reach the number N. You can change the number, paying a certain amount of coins, with the following operations: * Multiply the number by 2, paying A coins. * Multiply the number by 3, paying B coins. * Multiply the number by 5, paying C coins. * Increase or decrease the num...
3
from collections import deque from collections import defaultdict import math t = int(input()) def solve(n): if dist[n] != float('inf'): return dist[n] if n == 0: return 0 if n == 1: return d ans = float('inf') for x,cost in ([5,c],[3,b],[2,a]): e = 0 if n%x: ...
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...
3
s1 = str(input()) s2 = str(input()) if s1.lower()==s2.lower(): print(0) elif s1.lower()<s2.lower(): print(-1) elif s1.lower()>s2.lower(): print(1)
Given are three integers N, K, and S. Find a sequence A_1, A_2, ..., A_N of N integers between 1 and 10^9 (inclusive) that satisfies the condition below. We can prove that, under the conditions in Constraints, such a sequence always exists. * There are exactly K pairs (l, r) of integers such that 1 \leq l \leq r \leq...
3
N, K, S = map(int, input().split()) l = [S]*K+[(S+1)%(10**9)]*(N-K) print(' '.join(map(str, l)))
Vasya has two arrays A and B of lengths n and m, respectively. He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, ...
3
n = int(input()) A = [int(i) for i in input().split()] m = int(input()) B = [int(i) for i in input().split()] res = 0 indA = 0 indB = 0 flag = False while indA < len(A) and indB < len(B): if(A[indA] == B[indB]): indA+=1 indB+=1 res+=1 else: if(A[indA]<B[indB]): ...
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other. You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts). If two...
3
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) A = a[0] flag = False for i in range(n): if a[i] != A: flag = True break if flag: print("YES") f = True B = -1 idx = 0 for i in range(1...
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
3
n, t = map(int,input().split()) s = [i for i in input()] #print(s) while(t): i=1 while(i<n): #print(i,i-1) if(s[i]=="G" and s[i-1]=="B"): s[i] = "B" s[i-1] = "G" i+=1 i+=1 t-=1 print("".join(s))
"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him. The sequence of n integers is calle...
3
n=int(input()) p=[int(x) for x in input().split()] s=0 p=set(p) for i in p: if 1<=i<=n: s+=1 print(n-s)
A positive integer is called composite if it can be represented as a product of two positive integers, both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. The following numbers aren't: 1, 2, 3, 17, 97. Alice is given a sequence of n composite numbers a_1,a_2,…,a_n. She wants to choos...
3
a=int(input()) for _ in range(a): b=int(input()) c=[int(i) for i in input().split()] d=[2,3,5,7,11,13,17,19,23,29,31] e=[] ans=[] for i in c: for j in d: if i%j==0: if not j in e: ans.append(str(len(e)+1)) e.append(j) ...
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl...
3
s = list(map(int,input().split())) m = list(map(int,input().split())) a = s[0] b = s[1] m.sort() e = [] for i in range(b - a + 1): k = m[i + a - 1] - m[i] e.append(k) print(min(e))
In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0. You are given a sequence h=\\{h_1,h_2,h_3,......\\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation: * Specify integers...
3
input() h = [0] h.extend([int(i) for i in input().split()]) ans = 0 for i in range(len(h)-1): ans += max(h[i+1] - h[i], 0) print(ans)
There are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: * Choose m such that 1 ≤ m ≤ 1000 * Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart ...
3
from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import...
Jack is working on his jumping skills recently. Currently he's located at point zero of the number line. He would like to get to the point x. In order to train, he has decided that he'll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or righ...
3
import sys import math import itertools import functools import collections import operator def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(map(int, input().split())) def lcm(a, b): return abs(a * b) // math.gcd(a, b) def wr(arr): return ' '.join(map(str, arr)) def revn(...
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost ...
1
import sys from copy import deepcopy from heapq import nsmallest def readints(): return map(int, sys.stdin.readline().split()) new_a = [] def cost(a, k): global new_a if not new_a: new_a = [0] * len(a) if k == 0: return 0 for i in xrange(len(new_a)): new_a[i] = a[i] + k * ...
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick. He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substr...
3
n = int(input()) if n == 1 : print('a') exit() elif n == 2 : print('aa') exit() elif n == 3 : print('bba') exit() elif n % 4 == 0 : print('aabb' * (n // 4)) exit() else: s1 = ('aabb' * (n // 4)) x = n % 4 s2 ='' if x >= 2 : for i in range(x//2): 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'...
3
import re import math data = input() n, m, a = re.split(' ', data) n = int(n) m = int(m) a = int(a) num = math.ceil(n/a)*math.ceil(m/a) print(num)
Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won. Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long inte...
1
st=str(raw_input()) a,b=map(int,raw_input().split()) cs=[] val=0 x=0 for i in st: v=int(i) x=(x*10+v)%a cs.append(x) back=[] x=0 z=1 for j in range(len(st)-1,0,-1): i=st[j] v=int(i) x=(z*v+x)%b back.append(x) z=(z*10)%b #print cs,back for i in range(0,len(st)-1): #print i,cs[i],back[...
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
def f(): x = input() print(x,end="") print(x[::-1]) f()
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams. After practice competition, participant number i got a score of ai. Team s...
3
import sys import math import itertools import functools import collections import operator def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(map(int, input().split())) def lcm(a, b): return abs(a * b) // math.gcd(a, b) def wr(arr): return ' '.join(map(str, arr)) def revn(...
Takahashi lives in another world. There are slimes (creatures) of 10000 colors in this world. Let us call these colors Color 1, 2, ..., 10000. Takahashi has N slimes, and they are standing in a row from left to right. The color of the i-th slime from the left is a_i. If two slimes of the same color are adjacent, they ...
3
N = int(input()) A = list(map(int, input().split())) from itertools import groupby ans = 0 for k, g in groupby(A): ans += len(list(g))//2 print(ans)
Euler's phi function for a positive integer N is usually denoted as φ(N) and defined as the number of positive integers less than or equal to N that are coprime with N. Let's call a positive integer N a super number if N can be divided by φ(N) without a remainder. e.g. 2 is a super number (since 2 mod φ(2) = 0), whi...
1
def calc(n): k=2 ans=0 while k<=n: ans+=1 q=k*3 while q<=n: ans+=1 q*=3 k*=2 return ans t=int(raw_input()) for z in range(t): a,b=map(int,raw_input().split()) mainans=0 x=calc(b) y=calc(a-1) #print x,y if 1>=a and 1<=b: ...
Input The input contains a single integer a (1 ≤ a ≤ 30). Output Output a single integer. Example Input 3 Output 27
3
a=[4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438, 454, 483, 517, 526, 535, 562, 576, 588, 627, 634, 636, 645, 648, 654, 663, 666, 690, 706, 728, 729, 762, 778, 825, 852, 861, 895, 913, 915, 922, 958, 985] b=int(input()) print (a[b-1])
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are ...
3
def solve(n, a): if n <= 2: return 0 d = [v - u for u, v in zip(a, a[1:])] max_d = max(d) min_d = min(d) if max_d - min_d > 4: return -1 min_cnt = -1 for d in range(min_d, max_d + 1): for d0 in range(-1, 2): y = a[0] + d0 valid = True cnt = 0 if d0 == 0 else 1 for x in a[1:]: dx = abs(y ...
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better ...
3
t = int(input()) for __ in range(t): a, b = input().split() a = [c for c in a] c_idx = [-1]*26 for i, c in enumerate(a): c_ord = ord(c) - ord('A') c_idx[c_ord] = max(i, c_idx[c_ord]) allowed = True for i, c in enumerate(a): c_ord = ord(c) - ord('A') if not allowe...
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i...
1
#!/usr/bin/python from sys import stdin import math def divergentSeries(n): return (n*(n+1))/2 flowerCount = stdin.readline() flowers = stdin.readline().split(' ') min = 1000000000 mins = 0 max = 0 maxes = 0 for i in range(0, int(flowerCount)): if int(flowers[i]) < min: min = int(flowers[i]) mins = 1 elif in...
You are given two strings s and t, both consisting of exactly k lowercase Latin letters, s is lexicographically less than t. Let's consider list of all strings consisting of exactly k lowercase Latin letters, lexicographically not less than s and not greater than t (including s and t) in lexicographical order. For exa...
3
from sys import stdin, stdout, setrecursionlimit input = stdin.readline import string characters = string.ascii_lowercase # digits = string.digits # setrecursionlimit(int(1e6)) # dir = [-1,0,1,0,-1] # moves = 'NESW' inf = float('inf') from functools import cmp_to_key from collections import defaultdict as dd from colle...
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
year=int(input()) while True: year+=1 y=str(year) if(len(set(y))==4): print(y) break
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t. You can perform the following operation on s any number of times to achieve it — * Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1.....
3
def num(c): return ord(c) - 97 import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n = int(input()) s1 = input().strip() s2 = input().strip() char1 = [0] * 26 char2 = [0] * 26 for c in s1: char1[num(c)] += 1 for c in s2: char2[num(c)] += 1 if ...
Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation. We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on t...
1
n = int(raw_input()) a = map(int, raw_input().split()) m = int(raw_input()) b = map(int, raw_input().split()) ans, t= 0, dict() for z in b: for y in a: if not z%y: t[z/y]= t[z/y]+1 if z/y in t else 1 print t[sorted(t.keys())[-1]]
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It'...
3
n, m, a = input().split() n = int(n) m = int(m) a = int(a) ntotal = 0 mtotal = 0 if n % a != 0: k = n // a + 1 ntotal += k else: ntotal = ntotal + n // a if m % a != 0: z = m // a + 1 mtotal += z else: mtotal = mtotal + m // a print(ntotal * mtotal)
You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice. The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists e...
3
def read_data(): n, m = map(int, input().split()) maze = [[False] * (m + 2)] for i in range(n): maze.append([False] + [c == '.' for c in input().rstrip()] + [False]) maze.append([False] * (m + 2)) r1, c1 = map(int, input().split()) r2, c2 = map(int, input().split()) return n, m, maze...
Santa has to send presents to the kids. He has a large stack of n presents, numbered from 1 to n; the topmost present has number a_1, the next present is a_2, and so on; the bottom present has number a_n. All numbers are distinct. Santa has a list of m distinct presents he has to send: b_1, b_2, ..., b_m. He will send...
1
t = input() for _ in range(t): n,m = map(int,raw_input().split(" ")) ai = map(int,raw_input().split(" ")) bi = map(int,raw_input().split(" ")) dic = [0]*(n+1) for i in range(n): dic[ai[i]] = i ans = 0 maxv = -1 for i in range(m): if dic[bi[i]] > maxv: ans += 2...
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
1
a = int(input()) b = int(input()) c = int(input()) print max(a+b+c,(a+b)*c,a*b*c,a*(b+c),a+b*c)
Bizon the Champion is called the Champion for a reason. Bizon the Champion has recently got a present — a new glass cupboard with n shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has a1 first prize cups, a2 second prize cups an...
3
# import os a1, a2, a3 = map(int, input().split()) b1, b2, b3 = map(int, input().split()) n = int(input()) # we need shelf_a = (a1+a2+a3)//5 if (a1+a2+a3)%5==0 else (a1+a2+a3)//5+1 shelf_b = (b1+b2+b3)//10 if (b1+b2+b3)%10==0 else (b1+b2+b3)//10+1 if shelf_a + shelf_b <= n: print('YES') else: print('NO') ...
We just discovered a new data structure in our research group: a suffix three! It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in. It's super simple, 100% accurate, and doesn't involve advanced machine learni...
3
n=int(input()) while(n>0): a=input() b=[] for i in a: b.append(i) if(b[-1]=='o'): print('FILIPINO') elif(b[-1]=='u'): print('JAPANESE') elif(b[-1]=='a'): print('KOREAN') n=n-1
Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence. When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time,...
3
a, b = input().split() a = int(a); b = int(b) def gcd(a, b): if a < b: return gcd(b, a) elif not a%b: return b return gcd(b, a%b) lcm = a*b//gcd(a, b) if a > b: d_count = lcm//a m_count = lcm//b - 1 if m_count > d_count: print("Masha") elif m_count == d_count: print("Equal") else: print("Dasha") e...
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
s = input() l = [s[i] for i in range(len(s)) if s[i] != "+"] l.sort() new_s = "+".join(l) print(new_s)
You are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y? Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime...
3
# Contest: Educational Codeforces Round 74 (Rated for Div. 2) (https://codeforces.com/contest/1238) # Problem: A: Prime Subtraction (https://codeforces.com/contest/1238/problem/A) def rint(): return int(input()) def rints(): return list(map(int, input().split())) t = rint() for _ in range(t): x, y = ri...
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
3
n = int(input()) s = input() maxlen = 0 curlen = 0 state = 'x' for c in s: if state == 'x' and c != 'x': maxlen += max(0, curlen - 2) curlen = 0 elif c == 'x': curlen += 1 state = c if state == 'x': maxlen += max(0, curlen - 2) print(maxlen)
You are playing a game and your goal is to maximize your expected gain. At the beginning of the game, a pawn is put, uniformly at random, at a position p\in\\{1,2,\dots, N\\}. The N positions are arranged on a circle (so that 1 is between N and 2). The game consists of turns. At each turn you can either end the game, ...
3
from bisect import bisect_right def det(p1, p2, p3): area = (p2[0] - p1[0])*(p3[1] - p1[1]) - (p2[1] - p1[1])*(p3[0] - p1[0]) return area > 0 def convex_hull(pts): pts = sorted(pts) n = len(pts) extsize = 0 extpts = [] for i in range(n): while extsize > 1: if det(extp...
In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so ...
3
def dfs(start, end): visited = list() stack = [i_list[start]] while stack: cur = stack.pop() if cur not in visited: visited.append(cur) if i_list.index(cur) == end: return True for i in i_list: if i[0] < cur[0] < i[1] or i[0...
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all. Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the max...
3
t = int(input()) for _ in range(t): n,k = list(map(int,input().split())) x = n//k y = x*k n = n - (y) if n >= 1: if n <= k//2: print(y+n) else: print((k//2)+(y)) else: print(y)