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 construct such a string s of length n that for each i from 1 to k there is at least one i-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minim...
3
a='abcdefghijklmnopqrstuvwxyz' for j in range(int(input())): n,k = input().split() n=int(n) k = int(k) l=n//k s='' s=s+a[0:k]*l n=n-(l*k) while n!=0: s+=a[k-1] k-=1 n-=1 print(s)
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
ip_one = input().lower() ip_two = input().lower() #print(ip_one, ip_two) if ip_one < ip_two: print(-1) elif ip_one > ip_two: print(1) elif ip_one == ip_two: print(0)
You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 ≀ l ≀ r ≀ n) with maximum arithmetic mean (1)/(r - l + 1)βˆ‘_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding). If there are many such subsegments find the longest one. Input The first line contains single integer...
3
n = int(input()) a = list(map(int, input().split())) c = max(a) ml = 0 k, z = 0, 0 u = [] for i in range(len(a)): if a[i] == c: ml+=1 if (ml >0 and a[i] != c) or i == len(a)-1: u.append(ml) ml = 0 t = max(u) print(t)
Takahashi's house has only one socket. Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets. One power strip with A sockets can extend one empty socket into A empty sockets. Find the minimum number of power strips required. Constraints * All values in inp...
3
A,B=map(int,input().split());print(-((1-B)//~-A))
Little Shino is interested in the fighting tournaments. Once she went to watch one of the tournaments. There were N fighters and i^{th} fighter will be represented by i. Each fighter has some distinct strength. Rules of the tournament are: Each fight will have 2 fighters. In a fight, fighter with more strength will w...
1
import sys lineArray = sys.stdin.readline().rstrip().split() fighters = int(lineArray[0]) queries = int(lineArray[1]) sequence = sys.stdin.readline().rstrip().split() strengthSeq = {} fighterNumber = 1 for c in sequence: strengthSeq[fighterNumber] = int(c) fighterNumber = fighterNumber + 1 result = {} ...
You are given an array a_1, a_2, …, a_n. In one operation you can choose two elements a_i and a_j (i β‰  j) and decrease each of them by one. You need to check whether it is possible to make all the elements equal to zero or not. Input The first line contains a single integer n (2 ≀ n ≀ 10^5) β€” the size of the array....
3
n = int(input()) x = input() y = x.split() z = [int(d) for d in y] m = max(z) if sum(z)%2 ==0 and sum(z) >= 2*m: print('YES') else: print('NO')
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m. Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f...
3
t = int(input()) while t != 0: n, m = map(int, input().split()) a = list(map(int, input().split()))[:n] b = list(map(int, input().split()))[:m] x = set(a) y = set(b) z = x.intersection(y) k = list(z) if len(z) == 0: print('NO') else: print('YES') print(1, k[0]...
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string. Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent ...
3
a =list(input()) n = int(input()) t = [int(i) for i in input().split()] t = sorted(t) s = len(a) k=0 for i in range(s//2): while k<n and t[k]-1 <= i: k+=1 if k%2==1: a[i],a[s-i-1] = a[s-i-1],a[i] print(''.join(a))
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful...
1
n = int(raw_input()) mod = 10 ** 9 + 7 p_n = 1 for i in range(2, n + 1): p_n *= i p_n %= mod p_2n = p_n for i in range(n + 1, 2 * n + 1): p_2n *= i p_2n %= mod p_n *= p_n p_n %= mod p_n = pow(p_n, mod - 2, mod) ans = p_2n * p_n ans %= mod print ans-n
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game... In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f...
3
for _ in range(int(input())): n=int(input()) s=input() if n%2==0: no=0 for i in range(1,n,2): if int(s[i])&1: no+=1 if no==(n//2): print(1) else: print(2) else: ne=0 for i in range(0,n,2): if int(s[i])%2==0: ne+=1 if ne==((n//2)+1): print...
Luba is surfing the Internet. She currently has n opened tabs in her browser, indexed from 1 to n from left to right. The mouse cursor is currently located at the pos-th tab. Luba needs to use the tabs with indices from l to r (inclusive) for her studies, and she wants to close all the tabs that don't belong to this se...
3
n,pos,l,r=map(int,input().split()) s=0 if abs(pos-l)<=abs(pos-r): if l>=2: s+=(1+abs(pos-l)) if r<n: s+=((r-l)+1) elif r<n: s+=(abs(pos-r)+1) else: if r<n: s+=(abs(pos-r)+1) if l>=2: s+=(abs(r-l)+1) elif l>=2: s+=(abs(pos-l)+1) prin...
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 9 08:54:05 2020 @author: apple """ n=int(input()) m=0 for i in range(0,n): a,b=map(int,input().split(' ')) if b-a>=2: m+=1 print(m)
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k. In one move, you can choose two indices i and j (1 ≀ i, j ≀ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w...
3
import sys input = lambda: sys.stdin.readline().rstrip() inp = sys.stdin.buffer.readline def I(): return list(map(int,inp().split())) from heapq import * for _ in range(I()[0]): n,k=I() a=I() b=I() for i in range(k): z1=min(a) z2=max(b) zind1=a.ind...
Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt. Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place p. Now the elimination rou...
1
p,x,y=map(int,raw_input().split()) i=0 while x-y>=50: x-=50 i-=1 while True: d=(x//50)%475 for temp in range(25): d=(d*96+42)%475 if p==d+26: i=int(round(i)) print max((2*i+1)/2,0) exit(0) if i>=0: i+=0.5 x+=50 else: i+=1 x+=50
There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i. Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob β€” from right to left. The game ends if all the candies are eaten. The process consists o...
3
t=int(input()) for _ in range(t): n=int(input()) l=list(map(int,input().split())) i=1 j=n-1 c=1 a=l[0] b=0 temp1=l[0] temp2=0 while(i<=j): if(c%2==1): while(i<=j and temp2<=temp1): temp2+=l[j] b+=l[j] j-=1 ...
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation. Given are two integers A and B. If Takahashi can calculate A \times B, print the result; if he cannot, print `-1` instead. Constraints * 1 \leq A \leq 20 * 1 \leq B ...
3
a, b = map(int, input().split()) print(a*b if (0<a<10) & (0<b<10) else -1)
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
remix=input( ) s=[] if remix[:3]!='WUB': for i in range(len(remix)-2): if remix[i:i+3]=='WUB': print(remix[:i],end=' ') break for i in range(2,len(remix)-2): for j in range(i+1,len(remix)+1): if remix[i-2:i+1]=='WUB' and remix[j:j+3]=='WUB': if i!=j-1: ...
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 # from collections import Counter # from math import ceil,log # def gcd(a, b): # if(a==0): # return b # return gcd(b%a,a) # def sieve(n): # prime=[True for i in range(n+1)] # p=2 # while(p*p<=n): # if (prime[p]==True): # for i in range(p*p,n+1,p): # prime[i]=False # p+=1 #...
You have a robot that can move along a number line. At time moment 0 it stands at point 0. You give n commands to the robot: at time t_i seconds you command the robot to go to point x_i. Whenever the robot receives a command, it starts moving towards the point x_i with the speed of 1 unit per second, and he stops when...
3
for _ in range(int(input())): n = int(input()) q = [] for i in range(n): a,b = list(map(int,input().split())) q.append( (a,i,b)) if n == 1: print(1) continue q.sort() # print(q) goFrom = 0 goFromTime = q[0][0] now = goFromTime + abs(q[0][2]) goTo =...
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups f...
3
n=int(input()); years = input().split(); arr = list(); for j in range(len(years)): arr.append(int(years[j])); min_value = min(arr); max_value = max(arr); ans = (min_value + max_value)//2; print(ans)
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cel...
1
n = input(); print 3*n*(n+1)+1
We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i. In how many ways can we choose three of the sticks with different lengths that can form a triangle? That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions: ...
3
import itertools N = int(input()) L = map(int, input().split()) C = list(itertools.combinations(L,3)) ans = 0 for a, b, c in C: if a < b + c and b < a + c and c < b + a and a != b and b != c and a != c: ans += 1 print(ans)
Carl is a beginner magician. He has a blue, b violet and c orange magic spheres. In one move he can transform two spheres of the same color into one sphere of any other color. To make a spell that has never been seen before, he needs at least x blue, y violet and z orange spheres. Can he get them (possible, in multiple...
3
l=list(map(int,input().split())) l1=list(map(int,input().split())) k=0 k1=0 k2=0 k3=0 if l[0]-l1[0]<0 : k=k+abs(l[0]-l1[0]) else : k1=k1+abs(l[0]-l1[0]) if l[1]-l1[1]<0 : k=k+abs(l[1]-l1[1]) else : k2=k2+abs(l[1]-l1[1]) if l[2]-l1[2]<0 : k=k+abs(l[2]-l1[2]) else : k3=k3+abs(l[2]-l1[2]) kil=0 kil...
Write a program which reads two integers a, b and an operator op, and then prints the value of a op b. The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part. Constraints * 0 ≀ a, b ≀ 20000 * No divisions by zero are given. Input The input c...
1
#coding:utf-8 #Simple Calculator while 1: aopb = raw_input().split() if aopb[1] == "+": print int(aopb[0]) + int(aopb[2]) elif aopb[1] == "-": print int(aopb[0]) - int(aopb[2]) elif aopb[1] == "*": print int(aopb[0]) * int(aopb[2]) elif aopb[1] == "/": print int(aopb...
The only difference between easy and hard versions is constraints. A session has begun at Beland State University. Many students are taking exams. Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following: *...
3
def find_min(ar, count, m): ans = 0 total = ar for i in range(100, 0, -1): total += count[i] * i for i in range(100, 0, -1): if total <= m: break if count[i] == 0: continue diff = total - m req = diff // i if diff % i > 0: req += 1 cur = min(req, count[...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules. A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many ...
3
""" In the name of God """ n, k = map(int, input().split()) count = 0 lst = list(map(int, input().split())) for j in range(len(lst)): if lst[j] >= lst[k-1] and lst[j] > 0: count+=1 else: break print(count)
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 i in range(t): n=int(input()) if 0<sum(int(j)%2 for j in input().split())<n: print('NO') else: print('YES')
Let's consider all integers in the range from 1 to n (inclusive). Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 ≀ a < b ≀ n. The greatest common divisor, gcd(a, b), of two positive integ...
3
def test(m): print(int(m / 2)) n = int(input()) for i in range(n): m = int(input()) test(m)
Polycarp is practicing his problem solving skill. He has a list of n problems with difficulties a_1, a_2, ..., a_n, respectively. His plan is to practice for exactly k days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip ...
3
n, k = map(int, input().strip().split()) arr = list(map(int, input().strip().split())) inds = list(range(1, n+1)) inds.sort(key=lambda x:arr[x-1], reverse=True) max_inds = inds[:k] max_inds.sort() total = sum([arr[i-1] for i in max_inds]) max_inds[-1] = n for i in range(k-1, 0, -1): max_inds[i] -= max_inds[i-1] print(...
Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to 1 meter movement in the south, north, west or east direction respectively). It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visite...
3
from collections import defaultdict for i in range(int(input())): S = input() x = 0 y = 0 Ans = 0 Dict = defaultdict(bool) for i in S: if(i=="N"): if(Dict[(x,y,x,y+1)] or Dict[(x,y+1,x,y)]): Ans += 1 else: Ans+=5 Dic...
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it. For each of next n days Vasya knows a_i β€” number of units of garbage he will produce on the i-th day. Each unit of garbage must be dis...
3
import bisect from itertools import accumulate import os import sys import math from decimal import * 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 fi...
Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula: \\[ c_{ij} = \sum_{k=1}^m a_{ik}b_{kj} \\] where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ res...
1
[n, m, l] = [int(x) for x in raw_input().split()] A = [] B = [] C = [] counter = 0 while counter < n: A.append([int(x) for x in raw_input().split()]) counter += 1 counter = 0 while counter < m: B.append([int(x) for x in raw_input().split()]) counter += 1 counter = 0 while counter < n: C.append([0...
Are you going to Scarborough Fair? Parsley, sage, rosemary and thyme. Remember me to one who lives there. He once was the true love of mine. Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there. Willem asks his friend, Grick for directions, Grick helped...
3
nn, mm = (int(x) for x in input().split(' ')) s = input() for m in range(mm): l, r, c1, c2 = input().split(' ') l, r = int(l), int(r) s_upd = s[l-1:r].replace(c1, c2) s = s[:l-1] + s_upd + s[r:] print(s)
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'. In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov...
3
def ints(): return list(map(int,input().split())) for _ in range(int(input())): n = int(input()) a = input() m = 0 c = 0 for i in range(n): if a[i]=='(': c+=1 else: c-=1 m = min(m,c) no = 0 c = 0 for i in range(n)[::-1]: if a[...
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four...
3
import sys as _sys def main(): t = int(input()) for i_t in range(t): a, b, c = _read_ints() result = find_d(a, b, c) print(result) def _read_line(): result = _sys.stdin.readline() assert result[-1] == "\n" return result[:-1] def _read_ints(): return map(int, _read_l...
Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner β€” Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a...
3
n=int(input()) s=input() a=b=0 for i in s: if i=='A': a+=1 else: b+=1 if a==b: print("Friendship") elif a>b: print("Anton") else: print("Danik")
On the way to school, Karen became fixated on the puzzle game on her phone! <image> The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0. One move consists of choosing one row or column, and adding 1 to all of the cells in that row or col...
1
def read_arr(): return [int(num) for num in raw_input().split()] n, m = read_arr() A = [read_arr() for i in range(n)] B = [[a for a in ai] for ai in A] def ans_1(): pos = True S = [] for i in xrange(n): mr = min(A[i]) for j in xrange(mr): S.append('row ' + str(i + 1)) ...
You are given a string s of length n, which consists only of the first k letters of the Latin alphabet. All letters in string s are uppercase. A subsequence of string s is a string that can be derived from s by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD...
3
import string [n, k] = [int(x) for x in input().split()] val_dict = {c: 0 for c in string.ascii_uppercase[:k]} for c in input(): val_dict[c] += 1 print(min([val_dict[key] for key in val_dict])*k)
The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they f...
1
I=lambda:map(int, raw_input().split()) n = input() a = I() ans = sum(a) for x in [x for x in xrange(1, n / 3 + 1) if not n % x]: ans = max(ans, max([sum(a[ti :: x]) for ti in xrange(x)])) print ans
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of...
3
s = input().split(' ') n = int(s[0]) m = int(s[1]) a = int(s[2]) b = int(s[3]) if b / m > a: print(a * n) else: p = 1 if n % m == 0: p = 0 f = b * ((n // m) + p) s = b * (n // m) + a * (n - m * (n // m)) print(min(f, s))
Find sum of all the numbers that are multiples of 10 and are less than or equal to a given number "N". (quotes for clarity and be careful of integer overflow) Β  Input Input will start with an integer T the count of test cases, each case will have an integer N. Β  Output Output each values, on a newline. Β  Constraints...
1
import math for _ in range(input()): n=input() s=int(math.floor(n//10)) print ((s*(s+1))/2)*10
WizKid went on a trip to Wonderland with his classmates. Now, as you know, going on trips incurs costs including hotel costs, fooding, shopping, etc. And when many people go together, usually one person pays and it is expected that the others will pay back their share. But, after a few days people lost track of who owe...
1
t=input() for i in range(t): name=[] tc=raw_input().split(' ') n=int(tc[0]) q=int(tc[1]) for j in range(n): name.append([raw_input(),0]) for k in range(q): p=raw_input() p=str(p) a=int(raw_input()) np=int(raw_input()) pp=[] for l in range(n...
This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them a...
3
import sys input = sys.stdin.readline ''' ''' n, m = map(int, input().split()) g = [[] for _ in range(n)] for _ in range(m): x, y = map(int, input().split()) g[x-1].append(y-1) g[y-1].append(x-1) def ring(n, m, g): if all(len(l) == 2 for l in g): return True else: return False ...
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
3
z=input k,n,w=map(int,z().split()) n1=k*(w*(w+1)/2) print(0 if n1<=n else int(n1-n))
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ...
3
from sys import stdin,stdout ans = [] for i in range(int(input())): s = stdin.readline() cnt, ans_tmp, j, l = 0, [], 0, len(s)-2 while j <= l-2: tmp = s[j] + s[j+1] + s[j+2] if j <= l-4 and tmp+s[j+3]+s[j+4] == 'twone': ans_tmp.append(str(j+3)) ans_tmp.append(' ') cnt += 1 j += 5 ...
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that βˆ‘_{i=1}^{n}{βˆ‘_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl...
3
t = int(input()) for _ in range(t): res = 0 n, m = map(int, input().split()) per = [int(i) for i in input().split()] for i in range(len(per)): res += per[i] / (i + 1) * (i + 1) if m == int(res): print('YES') else: print('NO')
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k...
3
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) c=-1 t=0 i=n-1 while(i>0 and a[i]<=a[i-1] ): i=i-1 while(i>0 and a[i]>=a[i-1] ): i=i-1 print(i)
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=input().split() s = [] for i in range(n): s.append(int(l[i])) d = '' for i in range(n): d+=str(s.index(i+1)+1) + ' ' print(d)
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t...
3
a=int(input()) b=input() c=input() d=0 for i in range(a): e=int(b[i]) f=int(c[i]) d+=min(abs(e-f),10-abs(e-f)) print(d)
Levko loves permutations very much. A permutation of length n is a sequence of distinct positive integers, each is at most n. Let’s assume that value gcd(a, b) shows the greatest common divisor of numbers a and b. Levko assumes that element pi of permutation p1, p2, ... , pn is good if gcd(i, pi) > 1. Levko considers ...
1
n, k = map(int, raw_input().split()) if k == n: print -1 else: if k == n - 1: a = range(1, n + 1) else: a = [n] + range(2, 2 + k) + [1] + range(2 + k, n) print ' '.join(map(str, a))
This contest is `CODEFESTIVAL`, which can be shortened to the string `CF` by deleting some characters. Mr. Takahashi, full of curiosity, wondered if he could obtain `CF` from other strings in the same way. You are given a string s consisting of uppercase English letters. Determine whether the string `CF` can be obtai...
3
s=input() if "C"not in s:print("No") elif s.find("C",0)<s.find("F",s.find("C",0)+1):print("Yes") else:print("No")
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a. Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen w...
1
R = lambda: map(int, raw_input().split()) n, m = R() if n == 1: print 1 else: if m <= n / 2: print m + 1 else: print m - 1
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant...
3
s = input() n = len(s) a = ['a', 'o', 'u', 'i', 'e'] ans = "YES" for i in range(n - 1): if s[i] != 'n' and s[i] not in a and s[i + 1] not in a: ans = 'NO' if s[n - 1] != 'n' and s[n - 1] not in a: ans = 'NO' print(ans)
Fox Ciel has a board with n rows and n columns. So, the board consists of n Γ— n cells. Each cell contains either a symbol '.', or a symbol '#'. A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks. <image> Ciel wants to draw several ...
1
#!/usr/bin/env python # -*- coding: utf-8 -*- # Jonathan Prieto - d555 # import sys # sys.stdin = open("input.txt", "r") n = int( raw_input()) t = [] w = False ast = 0 for i in range(n): s = list(raw_input()) t.append(s) if s.count('#') > 0: w = True ast = ast + s.count('#') def acep(x,y): ...
A positive integer x is called a power of two if it can be represented as x = 2^y, where y is a non-negative integer. So, the powers of two are 1, 2, 4, 8, 16, .... You are given two positive integers n and k. Your task is to represent n as the sum of exactly k powers of two. Input The only line of the input contain...
3
from math import log L = [] def power_of_2(x): return 1<< (x).bit_length() - 1 def solve(n, k): if n == k: for i in range(n): L.append(1) return True if n < k: return False return helper(n, k - power_of_2(n), k - 1) def helper(n, x, y): ## Get closest power of 2 p = power_of_2(n) ## Get differenc...
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
n=int(input()) m=input() l=[] j=0 for i in range(n): l.append(m[i]) for i in range(1,n): if l[i]==l[i-1]: j=j+1 print(j)
Two players decided to play one interesting card game. There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a...
3
for _ in range(int(input())): n,k1,k2=map(int,input().split()) a=[int(i) for i in input().split()] b=[int(i) for i in input().split()] print("YES") if max(a)>max(b) 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
#!/usr/bin/env python3 def intersects(x1, y1, x2, y2): if x1 <= x2 and y1 >= y2: return True if x2 <= x1 and x1 <= y2: return True if x2 <= y1 and y1 <= y2: return True return False t = int(input()) for _ in range(t): n, a, b, c, d = map(int, input().split()) if inter...
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ...
3
import sys input = sys.stdin.readline t=int(input()) for tests in range(t): n,k=map(int,input().split()) S=input().strip() A=[] X=0 for s in S: if s=="0": X+=1 else: A.append(X) X=0 if X!=0: A.append(X) if len(A)==1 and A[0]...
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types β€” shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick. Each tool can be sold for exactly one emerald. How many...
3
t = int(input()) for i in range(t): a,b = map(int,input().split()) if a == 0 or b == 0: print(0) elif 2*a <= b: print(a) elif 2*b <= a: print(b) else: if b > a: # b - 2*x = a - x x = b - a ans = x a = a - x if a%3 == 2: ans = ans + 1 + 2*int(a/3) else: ans = ans + 2*int(a/3) ...
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
n = int(input()) difficulty_lst = [int(k) for k in (input().split(" "))] length1 = len(difficulty_lst) is_difficult = False for i in range(0, length1): if difficulty_lst[i] == 1: is_difficult = True break if is_difficult: print("HARD") else: print("EASY")
You are given an array a of n integers and an integer s. It is guaranteed that n is odd. In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s. The median of the array with odd length is the ...
3
# your code goes here n, s = map(int, input().split()) arr = [int(x) for x in input().split()] arr.sort() ans = abs(s-arr[n//2]) arr[n//2] = s for i in range(n): if i < n//2: if arr[i] > s: ans += abs(s-arr[i]) else: if arr[i] < s: ans += abs(s-arr[i]) print(ans)
The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank. One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible. Vasya ha...
3
ranks = int(input()) array = list(map(int, input().split())) a, b = map(int, input().split()) ans = sum(array[a-1:b-1]) print(ans)
Arkady is playing Battleship. The rules of this game aren't really important. There is a field of n Γ— n cells. There should be exactly one k-decker on the field, i. e. a ship that is k cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if...
3
from sys import stdin from math import ceil n,m=map(int,stdin.readline().strip().split()) s=[list(stdin.readline().strip()) for i in range(n)] acum1=[[0 for i in range(n)] for j in range(n)] ans=-1 x=-1 y=-1 for i in range(n): for j in range(n): acum=0 acum0=0 acum1=0 acum11=0 ...
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()) max_capacity, current_capacity = -1, 0 for __ in range(n): a, b = map(int, input().split()) current_capacity -= a current_capacity += b max_capacity = max(max_capacity, current_capacity) print(max_capacity)
Takahashi the Jumbo will practice golf. His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive). If he can achieve the objective, print `OK`; if he cannot, print `NG`. Constraints * All values in input are integers. * 1 \leq A \leq B \...
3
k = int(input()) a, b = map(int, input().split()) if (a <= (b//k) * k): print("OK") else: print("NG")
Statement You need to find a string which has exactly K positions in it such that the character at that position comes alphabetically later than the character immediately after it. If there are many such strings, print the one which has the shortest length. If there is still a tie, print the string which comes the le...
1
T=input() while T: T-=1 N=input() t=N%25 N+=((N/25)) if t==0: N-=1 t+=97 s='' if t==97: t=122 while N>=0 and t>=97: s+=chr(t) t-=1 N-=1 if t==96: t=122 print s
You have a given integer n. Find the number of ways to fill all 3 Γ— n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap. <image> This picture describes when n = 4. The left one is the shape and the right one is 3 Γ— n tiles. Input The only line cont...
1
def fpow(a, b): if b == 1: return a x = fpow(a, int(b/2)) if b%2 == 0: return x*x else: return x*x*a n = int(input()) if n%2 == 1: print(0) else: print(fpow(2, n/2))
Vasya has his favourite number n. He wants to split it to some non-zero digits. It means, that he wants to choose some digits d_1, d_2, …, d_k, such that 1 ≀ d_i ≀ 9 for all i and d_1 + d_2 + … + d_k = n. Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different d...
3
t=int(input()) print(t) for i in range(t): print(1,end=" ")
Find the minimum area of a square land on which you can place two identical rectangular a Γ— b houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, * You are given two identical rectangles with side lengths a and b (1 ≀ a, b ≀ 100) β€” positive integers (you are given ...
3
if __name__ == "__main__": N = int(input()) for _ in range(N): a, b = input().split(" ") a = int(a) b = int(b) print(min(max(a, 2*b)**2, max(2*a,b)**2))
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water. You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of wa...
3
for _ in range(int(input())): n, k = map(int, input().split()) lis = list(map(int,input().split())) lis.sort() ans = lis[-1] if n == 1: print(lis[0]) i = n - 2 while k > 0 and i >= 0: ans += lis[i] i -= 1 k -= 1 print(ans)
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
3
a=input() b=input() ls=[] for i in range(len(a)): for j in range(len(b)): if i==j: if a[i]==b[j]: ls.append('0') else:ls.append('1') for i in ls: print(i,end='')
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≀ n ≀ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
3
n = int(input()) if n % 2 == 1: print((n // 2 + 1) * -1) else: print(n // 2)
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
1
for x in range(int(raw_input())): lent = int(raw_input()) arr = set(map(int, raw_input().split(" "))) print len(arr)
Connect the countless points with lines, till we reach the faraway yonder. There are n points on a coordinate plane, the i-th of which being (i, yi). Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes th...
3
n=int(input()) y=list(map(int,input().split())) if n==2: print("Yes") exit elif n==1: print("No") exit def check(a,d): for i in range(0,n): a[i]-=i*d if len(set(a))==2: return True else: return False if check(y.copy(),y[1]-y[0]): print("Yes") exit elif check(y...
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 inp(dtype=str, strip=True): s = input() res = [dtype(p) for p in s.split()] res = res[0] if len(res) == 1 and strip else res return res def problem1(): t = inp(int) for _ in range(t): a, b = inp(int) delta = abs(b - a) res = delta // 5 delta = delta % 5 ...
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn. More formally, the guys take turns giving each ot...
3
import math def solve(): s = input() tokens = s.split() a = int(tokens[0]) b = int(tokens[1]) n = int(math.sqrt(a)) approx = n*(n + 1) if approx == b: return "Equal" elif approx > b: return "Valera" return "Vladik" result = solve() if result == "Valera": print(result) else: print("Vladik")
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ...
3
a=input() l=[int(x) for x in input().split()] y=[] for e in l: y.append(l.count(e)) print(max(y))
In Berland each high school student is characterized by academic performance β€” integer value between 1 and 5. In high school 0xFF there are two groups of pupils: the group A and the group B. Each group consists of exactly n students. An academic performance of each student is known β€” integer value between 1 and 5. Th...
3
n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) ax = [0, 0, 0, 0, 0, 0] bx = [0, 0, 0, 0, 0, 0] for i in range(n): ax[a[i]] += 1 bx[b[i]] += 1 ans = 0 for i in range(6): if (ax[i] + bx[i]) % 2 == 1: ans = -1 break else: ans += abs((ax[i] -...
Do you know a story about the three musketeers? Anyway, you will learn about its origins now. Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys. There are n warriors. Richelimakieu wants to choose three ...
1
from copy import deepcopy ans = float('Inf') n,m = map(int, raw_input().split(' ')) deg = [0 for i in range(n+1)] adj = [[] for i in range(n+1)] for i in range(m): j,k = map(int, raw_input().split(' ')) adj[j].append(k) adj[k].append(j) deg[j] += 1 deg[k] += 1 for i in range(n): adj[i].sort() ...
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
3
for i in range(int(input())): n=int(input()) n1=list(map(int,input().split())) c=list(set(n1)) print(len(c))
There are times you recall a good old friend and everything you've come through together. Luckily there are social networks β€” they store all your message history making it easy to know what you argued over 10 years ago. More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to...
3
#macro intln = lambda: [int(s) for s in input().split()] floatln = lambda: [float(s) for s in input().split()] def printarr(a): s = '' for i in a: s += str(i) + ' ' print(s) #code n, k = intln() a = intln() b = [0] * n for i in range(n): a[i] -= 1 for i in range(n): b[i] += 1 if i < k: ...
A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string. You are given a string s, ...
3
a=int(input()) b=input() d={} for i in b: if i in d: d[i]+=1 else: d[i]=1 r=0 for i in d: if d[i]%a!=0: r=1 break if r==1: print(-1) else: z='' for i in d: z+=i*(d[i]//a) print(z*a)
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million...
1
k = input() l = input() res = 0 while l != 1 and not (l % k): l /= k res += 1 if l == 1: print 'YES\n' + str(res - 1) else: print 'NO'
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs). <image> Fig. 1 A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertic...
3
n = int(input()) list_tree = [[] for _ in range(n)] list_parent = [None for _ in range(n)] for _ in range(n): id, k, *C = map(int, input().split()) list_tree[int(id)].extend(C) for c in C: list_parent[int(c)] = int(id) for id in range(n): child = list_tree[id] if list_parent[id] == N...
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
3
#in the name of god #Mr_Rubik a=input() b=input() cnt=0 if len(a)!=len(b): print("NO") exit(0) for i in range (len(a)): if a[i]==b[len(a)-i-1]: cnt+=1 if cnt==len(a):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...
3
n=input() l=list(map(int,input().split(" "))) l.sort() for i in l: print(i,end=" ")
Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid. Each test case consists of an integer n and two arrays a and b, of size n. If after some (possibly zero) operations described below, array a can be transformed into array b, the ...
3
T=int(input()) X=[] for i in range (0,T): C=[] D=[] n=int(input()) A=[int(x) for x in input().split(' ')] B=[int(x) for x in input().split(' ')] for i in range (0, len(A)//2): a=[A[i], A[len(A)-1-i]] b=[B[i], B[len(A)-1-i]] a.sort() b.sort() C.append(a) ...
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
3
for i in range(int(input())): n=int(input()) arr=list(map(int,input().split())) ar1=list(dict.fromkeys(arr)) print(len(ar1))
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer. Reliable sources have informed the financier Anton of some information about the exchange rate of...
3
n=list(input()) s=n[-1] f=0 for i in range(len(n)-1): if int(n[i])%2==0 and int(n[i])<int(s): n[i],n[-1]=n[-1],n[i] f=1 print(''.join(n)) break for i in range(len(n)-2,-1,-1): if int(n[i])%2==0 and f==0: temp=n[i] n[i]=n[-1] n[-1]=temp f=1 ...
Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages. Recent actions shows a list of n different threads ordered by the time of the latest message in the thread....
3
n= int(input()) lista = input().split() cont = 0 i = n-1 if n == 1: print("0") else: while i > 0: if int(lista[i]) > int(lista[i-1]): cont += 1 i -= 1 if i == 0: cont+= 1 else: cont += 1 break print(n-cont) ...
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
n = int(input()) k = input() x = 0 for i in range(0, len(k) - 1): if k[i] == k[i + 1]: x += 1 print(x)
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i...
1
from operator import mul from fractions import Fraction def nCk(n,k): return int( reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) ) n = int(raw_input()) s = 0 a = [] for i in xrange(n): b = int(raw_input()) a.append(b) s+=b s-=1 ans = 1 for i in xrange(n): ans*=(nCk(s, a[n-1-i]-1)%1000000007) ...
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not ...
1
# your code goes here inp = raw_input(); inp1 = inp.split('P'); inp1 = [elem for elem in inp1 if len(elem)>0] inp2 = inp.split('C'); inp2 = [elem for elem in inp2 if len(elem)>0] ret = 0; for elem in inp1: ret = ret+len(elem)/5+1; if len(elem)%5==0: ret = ret-1; for elem in inp2: ret = ret+len(elem)/5+1; if len(...
The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But ...
1
n, s = map(int, raw_input().split()) v = map(int, raw_input().split()) if sum(v) >= s: m = min(v) c = 0 for x in v: c += x - m if c >= s: print m else: k = s - c h = (k / n) + (0 if k % n == 0 else 1) print m - h else: print -1
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. <image> Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in th...
1
'''input 21 1 1 1 1 0 0 0 0 0 0 0 0 0 ''' l=[int(x) for x in raw_input().split()] def score(l): s=0 #print l for i in l: if i&1==0: s+=i return s def dis(ll,ind): l=ll[:] tot=l[ind] al=tot/14 l[ind]=0 for i in range(14): l[i]+=al #print tot,ind for i in range(tot%14): l[(ind+i+1)%14]+=1 return s...
Trouble came from the overseas lands: a three-headed dragon Gorynych arrived. The dragon settled at point C and began to terrorize the residents of the surrounding villages. A brave hero decided to put an end to the dragon. He moved from point A to fight with Gorynych. The hero rode from point A along a straight road ...
3
import math def vectorLength(x1, y1, x2, y2): return math.sqrt(math.pow(x1-x2, 2) + math.pow(y1-y2, 2)) xa, ya = [int(item) for item in input().split()] xb, yb = [int(item) for item in input().split()] xc, yc = [int(item) for item in input().split()] if round(vectorLength(xa,ya, xb, yb) + vectorLength(xb,yb, xc,...
Let's call an array t dominated by value v in the next situation. At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1...
3
from math import inf t = int(input()) for i in range(t): n = int(input()) array = list(map(int, input().split())) last_seen = dict() min_length = inf for j in range(len(array)): if array[j] in last_seen: length = j - last_seen[array[j]] min_length = min(min_length, length) last_seen[array[j]] = j ...
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
a=int(input()) while True : a=a+1 a=str(a) if a.count(a[0])==1 and a.count(a[1])==1 and a.count(a[2])==1 and a.count(a[3])==1 : print(a) break a=int(a)
You are given positive integers X and Y. If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it. If it does not exist, print -1. Constraints * 1 ≀ X,Y ≀ 10^9 * X and Y are integers. Input Input is given from Standard Input in...
3
from sys import exit X, Y = map(int,input().split()) if X % Y == 0 : print(-1) else:print(X)