problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Bob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume. There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrea...
3
def main(): for _ in range(int(input())): a, b = map(int, input().split()) a = abs(a - b) print(a // 5 + (a % 5 + 1) // 2) if __name__ == '__main__': main()
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
s = input().split(' ') for i in range(len(s)): s[i] = int(s[i]) for i in s: if i < max(s): print(max(s) - i,end=' ')
The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds. The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of c problems, the winners of the round are the first n people in the rating list. Eac...
1
c,d = [int(x) for x in raw_input().split()] n,m = [int(x) for x in raw_input().split()] k = int(raw_input()) ans = 0 total = n*m - k; total = 0 if (total < 0) else total fac = total/n ans = min(fac*c + (total - fac*n)*d,(fac+1)*c) ans = min(ans,total*d) print ans
Ivan has n songs on his phone. The size of the i-th song is a_i bytes. Ivan also has a flash drive which can hold at most m bytes in total. Initially, his flash drive is empty. Ivan wants to copy all n songs to the flash drive. He can compress the songs. If he compresses the i-th song, the size of the i-th song reduce...
3
import operator n,m=map(int,input().split()) a1=[] a2=[] for i in range(0,n): a,b=map(int,input().split()) a1.append(a) a2.append(b) d={} need=sum(a1) diff=need-m c=0 for i in range(0,n): d[i]=a1[i]-a2[i] sorted_d = sorted(d.items(), key=operator.itemgetter(1), reverse=True) for i in sorted_d: if d...
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm × b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting t...
3
a, b = sorted(map(int, input().split())) A, B = a, b ships = 0 while 0 < a < b: ships += b // a a, b = sorted([b % a, a]) print(ships)
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder). Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that. You have to answer t independent test cases. Input The fi...
3
t=int(input()) while(t): c=0 n=int(input()) if(n==1): print("0") else: while(n%3==0): if(n%6==0): c+=1 n/=6 else: c+=2 n/=3 if(n==1): print(c) else: print("-1") t-=1
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
a = int(input()) b = int(input()) c = int(input()) s1 = a * b * c s2 = (a + b) * c s3 = a * (b + c) s4 = a + b + c print(max([s1, s2, s3, s4]))
You have three piles of candies: red, green and blue candies: * the first pile contains only red candies and there are r candies in it, * the second pile contains only green candies and there are g candies in it, * the third pile contains only blue candies and there are b candies in it. Each day Tanya eats...
3
t = int(input()) for _ in range(t): r,g,b = sorted(map(int, input().split())) #print(r,g,b) #print(maxnum, mednum, minnum) if r + g > b: ans = sum([r, g, b]) // 2 else: ans = r + g print(ans)
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ...
3
a = int(input()) bm = a%4 if bm == 0: print(1, 'A') elif bm == 1: print(0, 'A') elif bm == 2: print(1, 'B') elif bm == 3: print(2, 'A')
Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once. The i-th dish (1 \leq i \leq N) he ate was Dish A_i. When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points. Additionally, when he eats Dish i+1 just after eating Dish i (1 \...
3
n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) c=list(map(int,input().split())) s,f=0,-1 for x in a: s+=b[x-1] if x-f==1: s+=c[f-1] f=x print(s)
You are given k sequences of integers. The length of the i-th sequence equals to n_i. You have to choose exactly two sequences i and j (i ≠ j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the...
1
k=int(raw_input()) arr=[] arrx=[] for i in range(k): n=int(raw_input()) arr1=list(map(int,raw_input().split())) arrx.append(arr1) arr.append(n) dict1={} flag=0 i=0 dict2={} while(i<k and flag==0): k1=sum(arrx[i]) for j in range(arr[i]): try: if(dict1[k1-arrx[i][j]]!=i+1): flag=1 print("YES") prin...
A company has N members, who are assigned ID numbers 1, ..., N. Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number. When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X. You are given the information ...
3
N=int(input()) A=list(map(int,input().split())) AA=[0]*N for j in A: AA[j-1]+=1 for i in AA: print(i)
Consider a conveyor belt represented using a grid consisting of n rows and m columns. The cell in the i-th row from the top and the j-th column from the left is labelled (i,j). Every cell, except (n,m), has a direction R (Right) or D (Down) assigned to it. If the cell (i,j) is assigned direction R, any luggage kept o...
3
def solve(arr,r,c): change = 0 for i in range(r): if arr[i][-1] == 'R': change += 1 elif i == r-1: change += arr[i].count('D') print(change) for _ in range(int(input())): r,c = list(map(int,input().split())) arr = [] for i in range(r): s = str(inp...
Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers 1, 5, 10 and 50 respectively. The use of other roman digits is not allowed. Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as...
3
def ceildiv(a, b): return -(-a // b) def test_ceildiv(): assert ceildiv(6, 3) == 2 assert ceildiv(7, 3) == 3 assert ceildiv(5, 3) == 2 def brute_force(n, m): """Count numbers in range [0; m] equal to 4a + 9b + 49c ...for some non-negative a, b and c such that (a + b + c) <= n """ nu...
N people are arranged in a row from left to right. You are given a string S of length N consisting of `0` and `1`, and a positive integer K. The i-th person from the left is standing on feet if the i-th character of S is `0`, and standing on hands if that character is `1`. You will give the following direction at mo...
3
n,k=map(int,input().split()) s=list(input()) j=0 ans=0 cnt=0 for i in range(n): if s[i]=="0": if i==0 or s[i-1]=="1": cnt+=1 if cnt>k: while s[j]=="1": j+=1 while s[j]=="0": j+=1 cnt-=1 ans=max(ans,i-j+1) print(ans)
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
line = input() count = 0 pre = None for i in line: if i == pre: count += 1 if count == 7: print("YES") exit() else: pre = i count = 1 print("NO")
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ...
1
n = int(input()) st = list(raw_input()) print abs(st.count('0') - st.count('1'))
Areas on the Cross-Section Diagram Your task is to simulate a flood damage. For a given cross-section diagram, reports areas of flooded sections. <image> Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides. For example, for the abov...
3
s=input() s1=[] s2=[] ans=[] a=0 a1=0 for i in range(len(s)): if s[i]=="\\": s1.append(i) elif s[i]=="/" and s1: i2=s1[-1] a1=i-i2 a+=a1 while s2 and s2[-1][0]>i2: a1+=s2[-1][1] s2.pop() s2.append([i2,a1]) s1.pop() n=len(s2) for j...
Today is August 24, one of the five Product Days in a year. A date m-d (m is the month, d is the date) is called a Product Day when d is a two-digit number, and all of the following conditions are satisfied (here d_{10} is the tens digit of the day and d_1 is the ones digit of the day): * d_1 \geq 2 * d_{10} \geq 2 *...
3
m,d = map(int,input().split()) ans = 0 for i in range(1,m+1): for j in range(1,d+1): if j%10 >= 2 and j//10 >= 2 and (j%10) * (j//10) ==i: ans += 1 print(ans)
Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times — at i-th step (0-indexed) you can: * either choose position pos (1 ≤ pos ≤ n) and increase v_{pos} by k^i; * or not choose any posit...
3
t = int(input()) for _ in range(t): n,k = map(int, input().split()) l = list(map(int,input().split())) count = [0 for i in range(60)] for num in l: j = 0; while num: count[j]+=num%k j+=1; num = num//k for i in count: if i>1: print("NO") break else: print("YES")
Ivan has n songs on his phone. The size of the i-th song is a_i bytes. Ivan also has a flash drive which can hold at most m bytes in total. Initially, his flash drive is empty. Ivan wants to copy all n songs to the flash drive. He can compress the songs. If he compresses the i-th song, the size of the i-th song reduce...
1
from sys import stdin lines = stdin.readlines() n,m = map(int,lines[0].split()) n2 = n summ = 0 liste = [] for i in range(1,n+1): a = int(lines[i].split()[0]) a2 = int(lines[i].split()[1]) summ += a liste.append(a-a2) c = summ-m flag = True if c<=0: print 0 flag = False liste = sorted(liste) ...
Bob programmed a robot to navigate through a 2d maze. The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'. There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single ex...
3
n, m = map(int, input().split()) a = [['0'] * (m + 2)] for i in range(n): a.append(['0'] + list(input()) + ['0']) a.append(['0'] * (m + 2)) s = input() x, y = -1, -1 for i in range(1, n + 1): for j in range(1, m + 1): if a[i][j] == 'S': x, y = i, j k = 0 for u in range(4): for d in range...
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property. Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=...
3
T=int(input()) while T>0: T-=1 t=input() l=2*len(t) s=[0]*l for i in range(1,len(s),2): s[i]=1 a='' count=[0,0] for i in t: count[int(i)]+=1 if count[0]==0: a='1'*len(t) elif count[1]==0: a='0'*len(t) else: for i in s: a+=st...
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
a=eval(input()) for i in range(a): exec("word%s=input()"%i) for i in range(a): exec("length=len(word%s)"%i) if length<=10: exec("print(word%s)"%i) else: num=str(length-2) exec("print(str(word%s[0]+num+word%s[-1]))"%(i,i))
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem...
3
n = int(input()) ans = int((n//3)*2) print(ans+1 if n%3 else ans)
There are n pillars aligned in a row and numbered from 1 to n. Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i. You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met: ...
3
k = int(input()) m = 0 s = list(map(int, input().split())) for i in range(k): if(s[i]>s[m]): m = i ans = "YES" for i in range(m-1): if(s[i]>s[i+1]): ans = "NO" for i in range(m,k-1): if(s[i]<s[i+1]): ans = "NO" print(ans)
When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead. "What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone." "But these blends are at their best, aren't they?" ...
1
s = raw_input() for i in xrange(len(s)-2): a = set() a.update(set([s[i],s[i+1],s[i+2]])) if a==set(['A','B','C']): print 'Yes' exit(0) print 'No'
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
3
n = list(map(int,input().split())) n.sort() count=0 x=len(n) for i in range(x-1): if n[i]==n[i+1]: count+=1 print(count)
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil"). However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum ti...
3
numCidades = int(input()) cidadesDesejadas = input() cidadesDesejadas = cidadesDesejadas.split() flag = True menor = 0 igual = 0 indice = 0 for i in range(numCidades): if(flag == True): menor = cidadesDesejadas[i] flag = False else: if(int(cidadesDesejadas[i]) < int(menor)): menor = cidadesDesejadas[i] ig...
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S. You have to answer q independent test cases. Input The...
3
temp = 0 q = int(input()) for i in range(q): a, b, n, S = map(int,input().split()) if(S % n <= b and a * n + b >= S): print('YES') else: print('NO')
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
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ n = eval(input()) for i in range(n): x = input() t = len(x) if t>10: print(x[0]+str(t-2)+x[-1]) else: 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()) for _ in range(N): s=input() l=len(s) if(l>10): num=l-2 #print(num) ans=s[0]+str(num)+s[-1] print(ans) else: print(s)
You have a string s consisting of n characters. Each character is either 0 or 1. You can perform operations on the string. Each operation consists of two steps: 1. select an integer i from 1 to the length of the string s, then delete the character s_i (the string length gets reduced by 1, the indices of characters ...
3
import sys import math from functools import reduce import bisect def getN(): return int(input()) def getNM(): return map(int, input().split()) def getList(): return list(map(int, input().split())) def input(): return sys.stdin.readline().rstrip() def index(a, x): i = bisect.bisect_left(a,...
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample. Limak will repeat the following operation till everything is destroyed. Block is called internal if i...
3
x = int(input()) y = list(map(int, input().split(' '))) y[0] = 1 y[x-1] = 1 z = y[:] for i in range(1, x): z[i] = min(z[i], z[i-1] + 1) w = y[:] for i in range(x-2, -1, -1): w[i] = min(w[i], w[i+1]+1) ans = 0 for i in range(x): ans = max(ans, min(z[i], w[i])) print(ans)
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts. Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str...
3
# region fastio import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.w...
You have two integers l and r. Find an integer x which satisfies the conditions below: * l ≤ x ≤ r. * All digits of x are different. If there are multiple answers, print any of them. Input The first line contains two integers l and r (1 ≤ l ≤ r ≤ 10^{5}). Output If an answer exists, print any of them. Oth...
3
kk = str(input()) arr = kk.split() lower = int(arr[0]) higher = int(arr[1]) flag = 0 for i in range(lower, higher + 1): strs = str(i) dicts = {} inner = 0 for j in strs: if j not in dicts: dicts[j] = 1 else: inner = 1 break if inner == 0:...
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()) l = list(map(int,input().split())) length = 1 maxi = 0 c = 0 for i in range(n - 1): if l[i] <= l[i+1]: c = 1 length += 1 if length > maxi: maxi = length else: length = 1 if n == 1 or c == 0: print(1) else: print(maxi)
Problem statement Modulo is very good at drawing trees. Over the years, Modulo has drawn a picture of a tree with $ N $ vertices. The vertices of this tree are numbered from $ 1 $ to $ N $, and the vertices $ a_i $ and $ b_i $$ (1 \ leq i \ leq N-1) $ are directly connected by edges. All vertices are not yet painted....
3
import sys from collections import deque readline = sys.stdin.readline def parorder(Edge, p): N = len(Edge) par = [0]*N par[p] = -1 stack = [p] order = [] visited = set([p]) ast = stack.append apo = order.append while stack: vn = stack.pop() apo(vn) for vf in...
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz). The picture showing the correct sudoku solution: <image> Blocks are bordered with bold black color. Your task is to change at most 9 elements of this field (i.e. choose s...
3
t=int(input()) for k in range(0,t): a=[] for i in range(0,9): p=input() p=list(p) a.append(p) a[0][0]=a[0][1] a[1][3]=a[1][2] a[2][6]=a[2][5] a[3][1]=a[3][2] a[4][4]=a[4][3] a[5][8]=a[5][7] a[6][2]=a[6][1] a[7][5]=a[7][4] a[8][7]=a[8][6] for i in r...
Welcome to PC Koshien, players. This year marks the 10th anniversary of Computer Koshien, but the number of questions and the total score will vary from year to year. Scores are set for each question according to the difficulty level. When the number of questions is 10 and the score of each question is given, create a ...
3
i=0 sum=0 while i<10: s=int(input()) sum+=s i+=1 print(sum)
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way ...
3
if __name__ == "__main__": n_bars = int(input()) bars = map(int, input().split()) counts = {} for b in bars: if b not in counts: counts[b] = 1 else: counts[b] += 1 print("{} {}".format(max(list(counts.values())), len(counts)))
Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of ...
3
import math n, a, b = map(int, input().split()) x = [int(i) for i in input().split()] ans = [0] * n for i, w in enumerate(x): r = (w * a) // b ans[i] = w - math.ceil(r * b / a) if ans[i] < 0: ans[i] = 0 print(' '.join(str(i) for i in ans))
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. It...
3
def is_lucky(n: str) -> bool: return n.count("4") + n.count("7") == len(n) def sumar_digitos(num: str) -> (int, int): n = len(num) prim_mitad = num[0:n//2] seg_mitad = num[n//2:] return sum(map(lambda x: int(x), prim_mitad)), sum(map(lambda x: int(x), seg_mitad)) def is_lucky_ticket(num: str) -> bool: a, ...
The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line. The Two-dimensional kingdom has a regular army of n people. Each soldier registered himse...
3
def main(): n, m, x, y = map(int, input().split()) aa = list(map(int, input().split())) it, res, b, f = iter(enumerate(map(int, input().split()), 1)), [], -x, ' '.join try: for i, a in enumerate(aa, 1): while b < a - x: j, b = next(it) if b <= a + y: ...
Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the e...
3
import math import itertools import collections def getdict(n): d = {} if type(n) is list: for i in n: if i in d: d[i] += 1 else: d[i] = 1 else: for i in range(n): t = ii() if t in d: d[t] += 1 ...
Try guessing the statement from this picture: <image> You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a ⋅ b = d. Input The first line contains t (1 ≤ t ≤ 10^3) — the number of test cases. Each test case contains one integer d (0 ≤ d ≤ 10^3). ...
3
import math t=int(input()) D=[int(input()) for i in range(t)] for d in D: if 1<=d<=3: print("N") elif d==0: print("Y",0,0) else: MIN=math.sqrt(d) MAX=d while True: a=(MIN+MAX)/2 b=d-a if abs(a+b-a*b)<=10**(-9): b...
Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can. But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend...
3
a=list(map(int,input().split())) b=list(map(int,input().split())) s=0 t=0 for i in range(0,a[0]): s+=86400-b[i] t+=1 if s>=a[1]: break print(t)
You are given a string s consisting only of lowercase Latin letters. You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it. Let's call a string good if it is not a palindrome. Palindrome is...
3
# import sys # sys.stdin = open("test.in","r") # sys.stdout = open("test.out","w") n=int(input()) for i in range(n): a=list(input()) b=a.count(a[0]) a.sort() if b==len(a): print('-1') else: print("".join(a))
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
x=int(input()) d=5 k=0 while x!=0: k=k+x//d x=x%d d=d-1 print(k)
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()) num = money // 100 + (money % 100) // 20 + (money % 100 % 20) // 10 + (money % 100 % 20 % 10) // 5 + (money % 100 % 20 % 10 % 5) // 1 print(num)
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars. There are...
3
import math i=lambda:map(int,input().split()) n,k=i() g=k for a in i():g=math.gcd(g,a) print(k//g) print(*range(0,k,g))
You are given an integer array of length n. You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to [x, x + 1, ..., x + k - 1] for some value x and length k. Subsequence ...
3
n = input() n = int(n) s = input() a = s.split() for i in range(n): a[i] = int(a[i]) dp = [] pre = [] pos = {} ans, p = 0, 0 w = [] for i in range(n): pos[a[i]] = i if (a[i] - 1) in pos.keys(): dp.append(dp[pos[a[i] - 1]] + 1) pre.append(pos[a[i] - 1]) else: dp.append(1) ...
An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4]. Polycarp invented a really cool p...
3
#Bhargey Mehta (Sophomore) #DA-IICT, Gandhinagar import sys, math, queue sys.setrecursionlimit(1000000) #sys.stdin = open("input.txt", "r") n = int(input()) q = list(map(int, input().split())) p = [0] for i in range(n-1): p.append(p[-1]+q[i]) off = n-max(p) for i in range(n): p[i] += off v = {i for i in range(1, n+1)...
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ...
3
input() n = input() print(abs(len(n) - 2 * n.count('1')))
A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert a grams of sand into b grams of lead, the second one allows you to convert c grams of lead into d grams of gold a...
3
import sys a, b, c, d, e, f = [float(x) for x in (sys.stdin.readline()).split()] if(c == 0 and d != 0): print("Ron") elif(d == 0): print("Hermione") else: if(a == 0 and b != 0): print("Ron") elif(b == 0): print("Hermione") else: if(e == 0 and f != 0): print("Ron...
There is a grid with H horizontal rows and W vertical columns. Let (i, j) denote the square at the i-th row from the top and the j-th column from the left. For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an empty square; if a...
3
h,w=map(int,input().split()) a=[input()for _ in range(h)] dp=[[0]*w for _ in range(h)] dp[0][0]=1 for i in range(h): for j in range(w): if i>0 and a[i-1][j]!='#': dp[i][j]+=dp[i-1][j] if j>0 and a[i][j-1]!='#': dp[i][j]+=dp[i][j-1] dp[i][j]=dp[i][j]%(10**9+7) print(dp...
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q...
1
n,d=map(int,raw_input().split()) ans=0 while n: n-=1 s,x=map(str,raw_input().split()) if s=='+': d+=int(x) else: x=int(x) if d>=x: d-=x else: ans+=1 print d,ans
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
s = str(input()) print('' + s[0].upper() + s[1:])
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not. You are given current year in Berland. Your task is to find how long...
3
Input=lambda:map(int,input().split()) n = int(input()) p = len(str(n)) a = n // pow(10,p-1) + 1 a*=(pow(10,p-1)) print(a-n)
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
# your code goes here n=str(input()) c=[] for i in range(len(n)): if( (ord(n[i])>=65 and ord(n[i])<=90) or (ord(n[i])>=97 and ord(n[i])<=122)): c.append(n[i]) ans=set(c) print(len(ans))
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
1
a, b, c, d = raw_input().split() a = int(a) b = int(b) c = int(c) d = int(d) if a == b and b == c and c == d: print(3) elif a == b and b == c or a == b and b == d or a == c and c == d or b == c and c == d: print(2) elif a != b and a != c and a != d and b != c and b != d and c != d: print(0) elif a == b and...
You wrote down all integers from 0 to 10^n - 1, padding them with leading zeroes so their lengths are exactly n. For example, if n = 3 then you wrote out 000, 001, ..., 998, 999. A block in an integer x is a consecutive segment of equal digits that cannot be extended to the left or to the right. For example, in the i...
3
n = int(input()) steps = [] st = 1 mod = 998244353 for i in range(n + 1): steps.append(st) st *= 10 st %= mod for i in range(1, n + 1): mid = (n - i - 1) * 10 * 9 * 9 * (steps[n - i - 2]) if n - i < 2: mid = 0 mid %= mod borders = 2 * 10 * 9 * steps[n - i - 1] if n == i: ...
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...
1
import sys n,m = map(int,raw_input().strip().split()) arr = map(int,raw_input().strip().split()) arr = sorted(arr) ans = sys.maxint for i in range(m-n+1): ans = min(ans,arr[i+n-1]-arr[i]) print ans
The map of Berland is a rectangle of the size n × m, which consists of cells of size 1 × 1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that...
3
import sys sys.setrecursionlimit(10**6) def lakes(n,m,matrix, k): def checkBorder(u,v): if u >= 0 and u < m and v >= 0 and v < n: return True return False visited = [[False for _ in range(m)] for _ in range(n)] size = [] startt = [] dx = [-1,1,0,0] dy = [0,0,1,-1] is_open = False s = 0...
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
s= input() # 512 4 l = s.split() n = int(l[0]) k = int(l[1]) while k>=1: if n%10==0: n = n//10 else: n = n-1 k=k-1 print(n)
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
1
n=int(raw_input()) a=[0]*26 y=raw_input().lower() for i in y: a[ord(i)-97]=1 if list(set(a))==[1]: print "YES" else: print "NO"
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling...
1
import sys import os inp = sys.stdin out = sys.stdout def main(): run() def run(): #TODO put your code here test = raw_input() array = map(int, raw_input().split()) array.sort() for num in array: print(num) main() sys.exit(0)
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper. To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ...
3
#!/usr/bin/env python3 # codeforces little elephant and bits import sys a = sys.stdin.readline().strip() totals = {} # key = index of digit cut out, value = base 10 val of cut string max_seen = 0 max_str = a[1:] for i in range(len(a)): if a[i] == '0': cut = a[:i] + a[i + 1:] max_str = cut break # b = int(c...
Arpa is taking a geometry exam. Here is the last problem of the exam. You are given three points a, b, c. Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c....
3
import sys import math import itertools import collections 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(n): return str(n)[::-1] def dd():...
In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b. Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b suc...
3
for _ in range(int(input())): n = int(input()) # a = map(int, input().split()) # l1 = list(map(int, input().split())) # l2 = list(map(int, input().split())) res = [] flag = True if n%2 == 0: res.append(n//2) res.append(n//2) print(*res) else: lim = int(n**(0.5)) + 1 for i in range(2,lim): if n%i ==...
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
w = int(input()) if w == 2: print("NO") elif(w%2!=0): print("NO") else: print("YES")
You are given three sequences: a_1, a_2, …, a_n; b_1, b_2, …, b_n; c_1, c_2, …, c_n. For each i, a_i ≠ b_i, a_i ≠ c_i, b_i ≠ c_i. Find a sequence p_1, p_2, …, p_n, that satisfy the following conditions: * p_i ∈ \\{a_i, b_i, c_i\} * p_i ≠ p_{(i mod n) + 1}. In other words, for each element, you need to choose ...
3
""" Problem Statement: https://codeforces.com/problemset/problem/1408/A Author: striker """ def generate_required_sequence(n: int, sequence1: list, sequence2: list, sequence3: list) -> str: resultant_sequence = list() for index, v in enumerate(zip(sequence1, sequence2, sequence3)): if not index: ...
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
s=input() s1=s.upper() print(s1[0]+s[1:])
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from...
3
t = int(input()) for _ in range(t): n, x = map(int, input().split()) if (n <= 2): print(1) continue print(((n-2+(x-1))//x)+1)
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment ...
3
#n, k = map(int, input().split(" ")) # read multiple integers into different variables #L = [int(x) for x in input().split()] # read multiple integers into a list #print(' '.join(map(str, L))) # print multiple integers in one line x1, y1, z1 = map(int, input().split(" ")) # read mul...
Alice and Bob play 5-in-a-row game. They have a playing field of size 10 × 10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts. In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins imm...
3
a=[] f=False for i in range(10): s=input() a.append(s) if s.find('XXXX.')!=-1 or s.find('XXX.X')!=-1 or s.find('XX.XX')!=-1 or s.find('X.XXX')!=-1 or s.find('.XXXX')!=-1: f=True for i in range(10): s='' for j in range(10): s+=a[j][i] if s.find('XXXX.')!=-1 or s.find('XXX.X')!=-1 ...
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
from itertools import groupby s=input() l=[] for key,group in groupby(s): l.append([len(list(group)),int(key)]) l.sort(reverse=True) if l[0][0]>=7: print("YES") else: print("NO")
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished. In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh...
3
import sys, random from bisect import bisect_left, bisect_right input = sys.stdin.readline def main(): inf = 10 ** 20 t = int(input()) # t, a, b = map(int, input().split()) for _ in range(1, t+1): # print("Case #{}: ".format(_), end = '') n, a, b, c, d = map(int, input().sp...
You have an array a_1, a_2, ..., a_n where a_i = i. In one step, you can choose two indices x and y (x ≠ y) and set a_x = \left⌈ (a_x)/(a_y) \right⌉ (ceiling function). Your goal is to make array a consist of n - 1 ones and 1 two in no more than n + 5 steps. Note that you don't have to minimize the number of steps. ...
3
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase from math import sqrt,ceil def main(): for _ in range(int(input())): n = int(input()) x = n ls = [x] while x > 2: x = ceil(sqrt(x)) ls.append(x) ...
n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students. You can change each student's score as long as the following conditions are satisfied: * All scores are integers ...
3
t=int(input()) for i in range(t): n,m=map(int,input().split()) li=[int(num) for num in input().split(" ",n-1)] k=sum(li)-li[0] l=m+k print(min(m,sum(li)))
There is a function f(x), which is initially a constant function f(x) = 0. We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows: * An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x). ...
1
# -*- coding: utf-8 -*- import sys from heapq import heappush, heappop, heapify N=input() hq1=[] #中央値より小さい値を入れるヒープキュー hq2=[] #中央値より大きい値を入れるヒープキュー fx=0 #f(x)の最小値 for _ in range(N): q=map(int, sys.stdin.readline().split()) if q[0]==1: q_type=q[0] a=q[1] b=q[2] heappush(hq...
You are given the array a consisting of n positive (greater than zero) integers. In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a...
3
t = int(input()) for i in range(t): n = int(input()) Case = False ar = list(sorted(map(int, input().rstrip().split(" ")))) Case = "YES" for i in range(n-1): if abs(ar[i]-ar[i+1]) > 1: Case = "NO" break print(Case)
Given is a string S. Replace every character in S with `x` and print the result. Constraints * S is a string consisting of lowercase English letters. * The length of S is between 1 and 100 (inclusive). Input Input is given from Standard Input in the following format: S Output Replace every character in S with ...
3
N = len(str(input())) print("x"*N)
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal. Hopefully, you've met a very handsome wandering trader who has two trade offers: * exchange 1 stick for x sticks (you lose 1 stick and gain x sticks...
3
import sys def onemore(n, m): if n%m: return 1 else: return 0 T=int(sys.stdin.readline()) for _ in range(T): x, y, k = map(int, sys.stdin.readline().split()) print((k*y+k-1)//(x-1)+ onemore((k*y+k-1), x-1)+ k)
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin. The world can be represented by the first quadrant of a plane and the wall is built along the identity line (...
3
n = int(input()) directions = input() x = 0 y = 0 count = 0 kingdom = 0 prev_kingdom = 0 for i in directions: if i == 'R': x += 1 elif i == 'U': y += 1 if (y > 0 and x < y) or (x < 0 and y > x) or (x == 0 and y > 0) or (y == 0 and x < 0): kingdom = 1 if prev_kingdom == 2: ...
A and B are preparing themselves for programming contests. To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger. For each chess piece we know its weight: * the queen's weight is 9, * the rook's weight is 5, * the ...
1
def A(): total = 0 d = {} d['Q'] = 9 d['R'] = 5 d['B'] = 3 d['N'] = 3 d['P'] = 1 d['K'] = 0 d['.'] = 0 d['q'] = -9 d['r'] = -5 d['b'] = -3 d['n'] = -3 d['p'] = -1 d['k'] = 0 for i in range(8): s = raw_input() for i in s: total ...
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans. New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two ch...
3
N = [int(i) for i in input().split()] n = N[0] a = N[1] b = N[2] if n > a*b : print (-1) else : dem = [int (i) for i in range (1,n+1,2)] resp = [int (i) for i in range (2,n+1,2)] i = 0 res = [] l_r = len(resp) i_r = 0 l_d = len(dem) i_d = 0 k = 0 for i in range(a) : if k == 0 : k = 1 else : k =...
Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm. .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# Note that the top left corner should be drawn by '#'. Constraints * 1 ≤ H ≤ 300 * 1...
1
while 1: H, W = map(int, raw_input().split()) if H == W == 0: break for i in range(H): if i % 2 == 0: if W % 2 == 0: print "#." * (W/2) else: print "#." * (W/2) + "#" else: if W % 2 == 0: print ".#" * (W/2) else: print ".#" * (W/2) + "." print ""
Consider the following process. You have a binary string (a string where each character is either 0 or 1) w of length n and an integer x. You build a new binary string s consisting of n characters. The i-th character of s is chosen as follows: * if the character w_{i-x} exists and is equal to 1, then s_i is 1 (forma...
3
import sys # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') import math import collections from sys import stdin,stdout,setrecursionlimit import bisect as bs setrecursionlimit(2**20) M = 10**9+7 T = int(stdin.readline()) # T = 1 for _ in range(T): # n = int(stdin.readline()) ...
AtCoder Mart sells 1000000 of each of the six items below: * Riceballs, priced at 100 yen (the currency of Japan) each * Sandwiches, priced at 101 yen each * Cookies, priced at 102 yen each * Cakes, priced at 103 yen each * Candies, priced at 104 yen each * Computers, priced at 105 yen each Takahashi wants to buy s...
3
X=int(input()) A=X // 100 B=X % 100 if B <= A *5: print(1) else: print(0)
Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square. A square of size n × n is called prime if ...
3
simple = [727, 719, 709, 701, 691, 683, 677, 673, 661, 659, 653, 647, 643, 641, 631, 619, 617, 613, 607, 601, 599, 593, 587, 577, 571, 569, 563, 557, 547, 541, 523, 521, 509, 503, 499, 491, 487, 479, 467, 463, 461, 457, 449, 443, 439, 433, 431, 421, 419, 409, 401, 397, 389, 383, 379, 373, 367, 359, 353, 349, 347, 337, ...
Vasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded. For example, if n = 4722 answer is 4720. If n = 5 Vasya can round it to 0 or to 10. Both ways are correct. For given n find out to which integer will Vasy...
3
n = int(input()) s = str(n) if int(s[-1]) == 0: print(n) exit() if int(s[-1])<= 5: n -= int(s[-1]) else: n += abs(10 - int(s[-1])) print(n)
Raccoon is fighting with a monster. The health of the monster is H. Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health. Raccoon wins when the monster's health becomes 0 or below. If Raccoon can win without using...
3
h,n=map(int,input().split()) a=[int(i) for i in input().split()] print("Yes" if h<=sum(a) else "No")
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()) L=list(map(int,input().split())) for i in range(n): print(L.index(i+1)+1,end=" ") print()
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
n = int(input()) s = 0 capacity = 0 for i in range(n): info = input() ex, en = info.split() ex = int(ex) en = int(en) s += en - ex if s > capacity: capacity = s print(capacity)
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k. During each turn Vova can choose what to do: * If the current charge of his laptop battery is strictly gre...
3
t = int(input()) for T in range(t): k, n, a, b = [int(x) for x in input().split()] n1 = n jp, p = 0, 0 c = 0 if k <= n * b: print("-1") else: if k > n * a: print(n) else: lb = -1 ub = n + 1 mid = 0 while(ub > lb ...
You are given n integers a_1, a_2, ..., a_n, where n is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold: 1. At least (n - 1)/(2) of the adjacent differences a_{i + 1} - a_i for i = 1, 2, ..., n - 1 are grea...
3
import sys input=sys.stdin.readline t=int(input()) for ii in range(t): n=int(input()) a=[int(i) for i in input().split() if i!='\n'] for i in range(n): if i&1: if a[i]>0: a[i]=-a[i] else: if a[i]<0: a[i]=-a[i] ...
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: * Employee A is the immediate manag...
3
mod = 1000000007 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) ls = lambda : list(input()) n=ii() nodes=[ii()-1 for i in range(n)] mx=1 for i in range(n): x=nodes[i] c=1 while x!=-2...
Polycarpus has got n candies and m friends (n ≥ m). He wants to make a New Year present with candies to each friend. Polycarpus is planning to present all candies and he wants to do this in the fairest (that is, most equal) manner. He wants to choose such ai, where ai is the number of candies in the i-th friend's prese...
3
n, m = map(int, input().split()) q = n//m r = n % m a = [q] * m for i in range(r): a[i] += 1 for i in range(m): print(a[i], end=' ')
Amugae has a hotel consisting of 10 rooms. The rooms are numbered from 0 to 9 from left to right. The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similar...
3
#r = open('inp.txt', 'r') s = input() s = input() #r.close() rooms = [0 for i in range(10)] for i in s: if i == "L": for n in range(10): if rooms[n] == 0: rooms[n] = 1 break elif i == "R": for n in range(1, 11): if rooms[-n] == 0: rooms[-n] = 1 break else: rooms[int(i)] = 0 #o = ope...