problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time. Help Yaroslav. Input The first line contains integer n (1 ≤ n ≤ 100) — the numb...
3
# # Author: eloyhz # Date: Sep/04/2020 # if __name__ == '__main__': n = int(input()) a = [int(x) for x in input().split()] c = [0] * 1001 for x in a: c[x] += 1 if n > 1 and max(c) > round(n / 2): print('NO') else: print('YES')
There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation). Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after...
3
# -*- coding: utf-8 -*- import sys from collections import Counter def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for...
You are given a sequence with N integers: A = \\{ A_1, A_2, \cdots, A_N \\}. For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied: * If A_i and A_j (i < j) are painted with the same color, A_i < A_j. Find the minimum number of col...
3
N = int(input()) A = [int(input()) for i in range(N)] from bisect import * h = [] for a in A: x = bisect_right(h, -a) if len(h) <= x: h.append(-a) else: h[x] = -a result = len(h) print(result)
A little girl loves problems on bitwise operations very much. Here's one of them. You are given two integers l and r. Let's consider the values of <image> for all pairs of integers a and b (l ≤ a ≤ b ≤ r). Your task is to find the maximum value among all considered ones. Expression <image> means applying bitwise excl...
3
l,r = [int(i) for i in input().split()] bitafter=-1; for i in range(60,-1,-1): if(l&(1<<i)!=r&(1<<i)): bitafter = i break res = 0 while(bitafter>=0): res+=1<<bitafter bitafter-=1 print(res)
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The ...
3
n,k=map(int,input().split()) m=[int(x) for x in input().split()] s=0 for i in range (0,n): if m[i]+k<=5: s+=1 print(int(s/3))
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
input() a = list(map(int, input().split(' '))) a = list(map(str, sorted(a))) print(' '.join(a))
Given N integers A_1, ..., A_N, compute A_1 \times ... \times A_N. However, if the result exceeds 10^{18}, print `-1` instead. Constraints * 2 \leq N \leq 10^5 * 0 \leq A_i \leq 10^{18} * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 ... A_N Output P...
3
N=int(input()) m=10**18 A=sorted(list(map(int,input().split()))) ans=1 for a in A: ans*=a if ans>m: print('-1') exit(0) print(ans)
Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the gro...
3
n, k = map(int, input().split() ) a = sorted(list(map(int, input().split() ) ) ) r = -1 for i in range(len(a)-1, -1, -1): if k % a[i] == 0: r = k // a[i] break print(r)
In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively. Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k. ...
3
lst=[int(input()) for i in range(6)] print('Yay!' if lst[4]-lst[0]<=lst[5] else ':(')
In the Ancient Kingdom of Snuke, there was a pyramid to strengthen the authority of Takahashi, the president of AtCoder Inc. The pyramid had center coordinates (C_X, C_Y) and height H. The altitude of coordinates (X, Y) is max(H - |X - C_X| - |Y - C_Y|, 0). Aoki, an explorer, conducted a survey to identify the center ...
3
N = int(input()) List = [[int(i) for i in input().split()] for _ in range(N)] for xt, yt, ht in List: if ht > 0: break for px in range(0, 101): for py in range(0, 101): H = ht + abs(px - xt) + abs(py - yt) if len(list(filter(lambda x: x[2] != max(H - abs(px - x[0]) - abs(py - x[1]), 0), ...
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....
1
s=list(raw_input()) r=list(raw_input()) s.reverse() if s==r: print 'YES' else : print 'NO'
You are given one integer number n. Find three distinct integers a, b, c such that 2 ≤ a, b, c and a ⋅ b ⋅ c = n or say that it is impossible to do it. If there are several answers, you can print any. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100)...
3
import sys ip = lambda : sys.stdin.readline().rstrip() for _ in range(int(ip())): n=int(ip()) ans=[] for i in range(2,int(n**0.5)+1): if n%i==0: v=n//i for j in range(2,int(v**0.5)+1): if v%j==0: st=set([i,j,v//j]) if le...
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years. There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ...
3
n,m = map(int,input().split()) s = input().split() t = input().split() q = int(input()) year_list = [] answer = '' for item in range(q): year_list.append(int(input())) s_index = (year_list[item] % n) - 1 t_index = (year_list[item] % m) - 1 answer = answer + s[int(s_index)] + t[int(t_index)] + '\n' pri...
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:...
3
I=lambda:list(map(int,input().split())) def lis(arr): n = len(arr) lis = [1]*n for i in range (1 , n): for j in range(0 , i): if arr[i]==arr[j]+1 and lis[i]< lis[j] + 1 : lis[i] = lis[j]+1 maximum = 0 for i in range(n): maximum = max(maximum ,lis[i...
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
inp=input() lis=list(i for i in str(inp)) print(lis[0].upper(),end='') for i in range(1,len(lis),1): print(lis[i],end='')
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at l...
3
import sys input=sys.stdin.readline n,m=map(int,input().split()) g=[[] for i in range(n)] deg=[0]*n for i in range(m): x,y=map(int,input().split()) x-=1;y-=1; g[x].append(y) g[y].append(x) deg[x]+=1;deg[y]+=1 vis=[False]*n pos=0 for i in range(n): if deg[pos]<deg[i]:pos=i st=[pos] vis[pos]=True ...
We have a grid with H rows and W columns, where all the squares are initially white. You will perform some number of painting operations on the grid. In one operation, you can do one of the following two actions: * Choose one row, then paint all the squares in that row black. * Choose one column, then paint all the s...
3
H = int(input()) W = int(input()) N = int(input()) import math print(math.ceil(N/max(H,W)))
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games. He came up with the following game. The player has a positive integer n. Initially the value of n equals to v and the player is able to do the following operatio...
3
n=int(input()) if(n!=2): print("1") else: print("2")
You are given a string S consisting of lowercase English letters. Determine whether all the characters in S are different. Constraints * 2 ≤ |S| ≤ 26, where |S| denotes the length of S. * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output If all ...
1
S = sorted(list(raw_input())) for i in xrange(len(S) - 1): if S[i] == S[i + 1]: print "no" exit() print "yes"
This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hed...
3
import sys def dfs(v): global g, links, used, tail, val used[v] = True maxv = 1 for u in g[v]: if not used[u]: # maxv = max(maxv, dfs(u) + 1) - было used вместо not used в условии dfs(u) maxv = max(maxv, tail[u] + 1) val[v] = links[v] * maxv tail[v]...
The only king stands on the standard chess board. You are given his position in format "cd", where c is the column from 'a' to 'h' and d is the row from '1' to '8'. Find the number of moves permitted for the king. Check the king's moves here https://en.wikipedia.org/wiki/King_(chess). <image> King moves from the posi...
3
pos_king= input() col= pos_king[0] fil= int(pos_king[1]) moves=0 if fil==8 or fil==1: if col=="a" or col=="h": moves=3 else: moves=5 elif 1<fil<8: if col=="a" or col=="h": moves=5 else: moves=8 print(moves)
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
#Codeforce 988B n = int(raw_input()) dic={} for i in range(n): m=int(raw_input()) B=map(int, raw_input().split()) sx=sum(B) B1=[sx-B[k] for k in range(m)] for k in range(m): if B1[k] not in dic: dic[B1[k]]=[i,k] else: if i !=dic[B1[k]][0]: p...
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
n=int(input()) hate='I hate' love='I love' ans='' for i in range(1,n+1): if(i%2==1): ans+=hate else: ans+=love if(i<=n-1): ans+=' that ' print(ans+' it')
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have b buns, p beef patties and f chicken cutlets in your restaurant. You can sell one hamburger for ...
3
t=int(input()) for i in range(t): a,b,c=map(int,input().split()) d,e=map(int,input().split()) co=0 if d>e: ans=min(b,a//2) co+=ans*d a-=ans*2 ans=min(c,a//2) co+=ans*e print(co) else: ans=min(c,a//2) co+=ans*e a-=ans*2 a...
"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
ns,pos=[int(i) for i in input().split()] stum=list(map(int,input().split())) min1=stum[pos-1] c=0 for i in stum: if i>0 and i>=min1: c+=1 print(c)
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
r = [None] * int(input()) n = [int(x) for x in input().split(' ')] for i in range(len(n)): r[n[i]-1]= i+1 s = '' for i in r: s += ' '+str(i) print(s[1:])
You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤...
3
for i in range(int(input())): n=int(input()) l=list(map(int,input().split())) c=0 i1=-1 i2=-1 f=0 for i in range(n): if l[i]%2==0: print(1) print(i+1) f=1 break if i1==-1: i1=i+1 continue i2=i+1 ...
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ...
3
def Buy_a_Shovel(k, r): i = 1 for i in range(1, 20000): if (i*k)%10 == 0 or (i*k - r) % 10 == 0: break return i k, r =map(int, input().split()) print(Buy_a_Shovel(k, r))
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
3
from collections import Counter if __name__ == "__main__": # take number as string num = input() digitMap = Counter(num) count = digitMap['4']+digitMap['7'] if count == 4 or count == 7: print("YES") else: print("NO")
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length k have the same sum. A subarray of an array is any sequence of consecutive elements. Phoenix currently has an array a of length n. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautifu...
3
# from sys import stdin # input = stdin.buffer.readline for _ in range(int(input())): n, k = map(int, input().split()) *a, = map(int, input().split()) s = list(set(a)) if len(s) > k: print(-1) else: s = s + [1] * (k - len(s)) print(k * 100) print(*s * 100)
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char...
3
t=int(input()) while t: t=t-1 s=input() a1=len(s) o=s.count('1') z=s.count('0') if z==0 or o==0: print("NET") else: a=min(z,o) if a%2==1: print("DA") else: print("NET")
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it? The book contains a single string of characters "a", "...
3
import sys for line in sys.stdin: line = line[:-1] ans = ['a']*(len(line)//4) for i in range(len(line)//4): if line[2*i] in {line[-2*i-1], line[-2*i-2]}: ans[i] = line[2*i] else: ans[i] = line[2*i+1] if len(line)%2 ==1 or len(line)%4 == 2: print("".join(a...
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 _ in range(t): n, k = map(int, input().rstrip().split(" ")) n, k = min(n,k), max(n,k) if k in range(n,2*n): print((n+k)//3) else: print(n)
You have A 500-yen coins, B 100-yen coins and C 50-yen coins (yen is the currency of Japan). In how many ways can we select some of these coins so that they are X yen in total? Coins of the same kind cannot be distinguished. Two ways to select coins are distinguished when, for some kind of coin, the numbers of that co...
3
A, B, C, X = (int(input()) for i in range(4)) print(sum(500 * a + 100 * b + 50 * c == X for a in range(A + 1) for b in range(B + 1) for c in range(C + 1)))
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers. Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ...
3
print("0 0", int(input()))
Little X has met the following problem recently. Let's define f(x) as the sum of digits in decimal representation of number x (for example, f(1234) = 1 + 2 + 3 + 4). You are to calculate <image> Of course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the foll...
3
n = int(input()) r = 45*18*10**17; l = n-r%n r = l +10**18-1 print(l," ",r)
Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. Y...
3
#------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w')...
There is a right triangle ABC with ∠ABC=90°. Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC. It is guaranteed that the area of the triangle ABC is an integer. Constraints * 1 \leq |AB|,|BC|,|CA| \leq 100 * All values in input are integers. * The area of the triangl...
1
L = raw_input() L = L.split() for i, val in enumerate(L): L[i] = int(val) L.sort() S = int(L[0] * L[1] / 2) print(S)
Alice and Bob are decorating a Christmas Tree. Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments. In Bob's opinion, a Christmas Tree will be beautiful if: * the number of blue ornaments used is greater b...
3
y, b, r = input().split() y, b, r = int(y), int(b), int(r) if b >= y + 1 and r >= y + 2: x = y + y + 1 + y + 2 elif y >= b - 1 and r >= b + 1: x = b + b - 1 + b + 1 elif y >= r - 2 and b >= r - 1: x = r + r - 1 + r - 2 print(x)
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this su...
3
# n,m=[int(x)for x in input().split()] # a=[x=='.'for x in input()]+[0] # k=sum([a[i] and a[i+1]for i in range(n)]) # for i in range(m): # x,c=input().split() # x,c=int(x)-1,c=='.' # k-=(a[x]-c)*(a[x-1]+a[x+1]) # a[x]=c # print(k) # n, m = map(int, input().split()) s = [c != '.' for c in input()]+[T...
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
q,w,e=0,0,0 for i in range(int(input())): a,b,c=map(int,input().split()) q+=a w+=b e+=c if q==w==e==0: print('YES') else: print('NO')
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero. An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≤ i ≤ n - 1) the equality i mod 2 = a[i] m...
3
from sys import stdin t = int(stdin.readline()) for _ in range(t): n = int(stdin.readline()) a = list(map(int, stdin.readline().rstrip().split(" "))) evenCount = 0 oddCount = 0 for i in range(len(a)): if i % 2 == 0 and a[i] % 2 != 0: evenCount += 1 if i % 2 != 0 and a[i...
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
from collections import Counter n=int(input()) s=input() d=Counter(s) flag=0 for i in d.values(): if i!=n and i%n!=0: print("-1") flag=1 break if flag==0: res='' for i in d.keys(): res+=i*(s.count(i)//n) print(res*n)
Let f_{x} = c^{2x-6} ⋅ f_{x-1} ⋅ f_{x-2} ⋅ f_{x-3} for x ≥ 4. You have given integers n, f_{1}, f_{2}, f_{3}, and c. Find f_{n} mod (10^{9}+7). Input The only line contains five integers n, f_{1}, f_{2}, f_{3}, and c (4 ≤ n ≤ 10^{18}, 1 ≤ f_{1}, f_{2}, f_{3}, c ≤ 10^{9}). Output Print f_{n} mod (10^{9} + 7). Exam...
3
N, f1, f2, f3, x = map(int, input().split()) def mmult(A, B): global mod n, m, l = len(A), len(B), len(B[0]) ret = [[0]*l for _ in range(n)] for i in range(n): for j in range(m): for k in range(l): ret[i][k] = (ret[i][k]+A[i][j]*B[j][k])%mod return ret def mpow(A,...
The Fair Nut found a string s. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences p_1, p_2, …, p_k, such that: 1. For each i (1 ≤ i ≤ k), s_{p_i} = 'a'. 2. For each i (1 ≤ i < k), there is such j that p_i < j < p_{i + 1} and s...
3
s=input() s+='b' ss=[] last=0 for i in s: if i=='a': last+=1 elif i=='b' and last!=0: ss.append(last) last=0 M=1000000007 ans=1 for i in ss: ans*=(i+1) ans%=M print(ans-1)
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state. In each turn, a player must ...
3
t = int(input()) for _ in range(t): n, m = map(int, input().split()) row, col = set(), set() # mat = [list(map(int, input().split())) for i in range(n)] for i in range(n): a = list(map(int, input().split())) for j in range(m): if a[j] == 1: row.add(i) col.add(j) res = min(n-len(row), m-len(col)) ...
You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined <image>. You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1. Output the minimum poss...
3
n, k1, k2 = input().split() a1 = input().split() a2 = input().split() res = [] for i in range(len(a1)): res.append(int(a1[i])-int(a2[i])) res = [abs(i) for i in res] k = int(k1) + int(k2) k = int(k) n = int(n) if sum(res) < int(k): if (k - sum(res)) % 2: print('1') else: print('0') elif sum(...
It's now the season of TAKOYAKI FESTIVAL! This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i. As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points. There are \frac{N...
3
n = int(input()) d = [int(i) for i in input().split()] print(sum(d[i]*d[j] for i in range(n) for j in range(i+1,n)))
A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on fo...
3
l, d, v, g, r = map(int, input().split()) t = d/v ft = t%(g+r) if ft >= g: t += r-(ft-g) t += (l-d)/v print(t)
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the...
3
x = int(input()) for i in range(x): x, y, z = map(int, input().split()) print((x + y + z)//2)
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way: qwertyuiop asdfghjkl; zxcvbnm,./ Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move...
3
s1="qwertyuiop" s2="asdfghjkl;" s3="zxcvbnm,./" d = input() x = list(input()) c_out="" if d=="R": i=0 while i<len(x): if x[i] in s1:s=s1 elif x[i] in s2:s=s2 else:s=s3 #print(s) c_out+=s[s.index(x[i])-1] i+=1 else: i=0 while i<len(x): if x[i] in s...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
1
a,b=map(int,raw_input().split()) c=map(int,raw_input().split()) d=0 for i in range(a): if c[i]>=c[b-1] and c[i]: d+=1 print d
Kurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper. Help Kurt find the maximum possible product of digits among all integers from 1 to n. Input The only input line contains the integer n (1 ≤ n ≤ 2⋅10^9). Output Print the...
3
import sys sys.setrecursionlimit(2000) from collections import Counter from functools import reduce # sys.stdin.readline() #from random import seed #from random import randint # #def validate(): # for i in range(100): # seed(i) # n = randint(1, 10000) # val1 = brute_force(n) # val2 = solu...
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a...
3
a= int(input()) for k in range(a): b= input() c= b[0] for k in range((len(b)- 2) // 2): c += b[(k * 2) + 1] print(c+ b[-1])
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
n = int(input()) x = [int(x) for x in input().split()] a, b = map(int, input().split()) result = x[a-1:b-1] print(sum(result))
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
n=int(input()) sum=kol=0; for i in range(n): a,b,c=map(int, input().split()) sum=a+b+c if sum>1: kol+=1 sum=0 print(kol)
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd. You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n...
3
from math import cos, pi, sin s = [0] * 201 for k in range(6, 401, 4): k //= 2 d = pi / k / 2 x = sin(d / 2) / sin(d) s[k] = (sum(cos(i * d) for i in range(k)) * 2 - 1) * x for _ in range(int(input())): k = int(input()) print(s[k])
There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples. Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows: * Move: ...
3
N, T = map(int, input().split()) a = [int(i) for i in input().split()] b = [a[0]] m = b[0] for i in range(1,N): if m > a[i]: m = a[i] b.append(m) c = [a[i] - b[i] for i in range(N)] print(c.count(max(c)))
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...
1
t=int(raw_input()) for _ in range(t): l=list(map(int,raw_input().split())) m=l[0] n=l[1] mat=[list(str(raw_input())) for i in range(m)] # print mat count=0 for i in range(m): for j in range(n): # print i,j if mat[i][j]=="D": if i+1==m: ...
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way: qwertyuiop asdfghjkl; zxcvbnm,./ Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move...
3
kb = ['qwertyuiop', 'asdfghjkl;', 'zxcvbnm,./'] d = input() s = '' for c in input(): for i in range(3): for j in range(len(kb[i])): if kb[i][j] == c: s += kb[i][j - 1] if d == 'R' else kb[i][j + 1] print(s)
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. You have a sequence of integers a1, a2, ..., an. In on...
1
n=int(input()) arr=list(map(int,raw_input().split())) def solve(arr,n): arr=sorted(arr) count=0 for i in range(len(arr)): count+=abs(arr[i]-(i+1)) return count print(solve(arr,n))
There is a circular pond with a perimeter of K meters, and N houses around them. The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond. When traveling between these houses, you can only go around the pond. Find the minimum distance that needs to ...
3
k,n=map(int,input().split()) a=list(map(int,input().split())) l=[a[0]+(k-a[-1])] for i in range(1,len(a)-1): l.append(a[i+1]-a[i]) print(k-max(l))
A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are n...
3
T=int(input()) for i in range(0,T): s=input() if(len(s)==1): print('Yes') else: temp=0 pos=[0]*26 for j in range(0,len(s)): pos[ord(s[j])-97]=pos[ord(s[j])-97]+1 for j in range(0,len(pos)): if(pos[j]>1): temp=1 ...
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy. Input The only line contains three integers n, a and ...
1
n,a,b = map(int, raw_input().split()) cnt = 0 for i in xrange(a, n): if n-i-1 <= b: cnt += 1 print cnt
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
3
def solution(): n, st = input(), input() res = 0 i = 3 while i <= len(st): if st[i-3:i] == "xxx": res += 1 i += 1 print(res) if __name__ == "__main__": solution()
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not. There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc...
3
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) d=[a[0]] for i in range(1,len(a)): if a[i] not in d: d.append(a[i]) print(*d)
In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters. In Taknese, the plural form of a noun is spelled based on the following rules: * If a noun's singular form does not end with `s`, append `s` to the end of the singular form. * If a noun's singular form ends with `s`...
3
S=input() print(S+('es' if S[-1]=='s' else 's'))
Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them. The park consists of n squares connected with (n - 1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored...
3
import bisect import collections import copy import functools import heapq import itertools import math import random import re import sys import time import string from typing import List, Mapping sys.setrecursionlimit(999999) cs = [0,1]+[0]*(10**6) n = int(input()) g = collections.defaultdict(list) for _ in range(n...
CODE FESTIVAL 2016 is going to be held. For the occasion, Mr. Takahashi decided to make a signboard. He intended to write `CODEFESTIVAL2016` on it, but he mistakenly wrote a different string S. Fortunately, the string he wrote was the correct length. So Mr. Takahashi decided to perform an operation that replaces a ce...
3
a="CODEFESTIVAL2016" s=input() ans=0 for i in range(len(s)): if a[i]!=s[i]: ans+=1 print(ans)
Vasya is reading a e-book. The file of the book consists of n pages, numbered from 1 to n. The screen is currently displaying the contents of page x, and Vasya wants to read the page y. There are two buttons on the book which allow Vasya to scroll d pages forwards or backwards (but he cannot scroll outside the book). F...
3
from math import ceil for _ in range(int(input())): n,x,y,d=map(int,input().split()) f=0 cand=[] if (y-x)%d==0: cand.append((y-x)//d) f=1 if (y-1)%d==0: cand.append(ceil((x-1)/d)+ceil((y-1)/d)) f=1 if (n-y)%d==0: cand.append(ceil((n-x)/d)+ceil((n-y)/d)...
You are given two polynomials: * P(x) = a0·xn + a1·xn - 1 + ... + an - 1·x + an and * Q(x) = b0·xm + b1·xm - 1 + ... + bm - 1·x + bm. Calculate limit <image>. Input The first line contains two space-separated integers n and m (0 ≤ n, m ≤ 100) — degrees of polynomials P(x) and Q(x) correspondingly. The seco...
3
import math import queue from itertools import permutations n,m=map(int,input().split()) a=[int(cost) for cost in input().split()] b=[int(cost) for cost in input().split()] n1=n a1=a[0] m1=m b1=b[0] if n1<m1: print("0/1") elif n1>m1: if (a1>0 and b1>0) or (a1<0 and b1<0): print("Infinity"...
You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59. You are given a time in format HH:MM that is currently displayed on the broken ...
1
tipo = raw_input() h = raw_input() if int(h[3]) > 5: h = h[:3] + '0' + h[4] if tipo == '12': if int(h[:2]) > 12 or h[:2] == '00': if h[1] != '0': h = '0' + h[1:] else: h = '10' + h[2:] if tipo == '24': if int(h[:2]) > 23: h = '0' + h[1:] print(h)
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ...
3
k, r = map(int, input().split()) for i in range(1, 11): if i * k % 10 == r or i * k % 10 == 0: print(i) break
Yesterday Chef had a great party and doesn't remember the way he celebreated it. But he found a strange paper in his kitchen containing n digits (lets give them indices from 1 to n and name them a1, a2 ... aN). Chef remembers that he played such game: On each step he choose an index x from 1 to n. For all indices ...
1
def adigit(digit_list): result = [] for digit in xrange(10): result.append([[0,0]]) if digit < digit_list[0]: result[-1][0][1] = -(digit-digit_list[0]) elif digit > digit_list[0]: result[-1][0][0] = digit - digit_list[0] for integer in digit_list[1::]: for digit in xrange(10): B1...
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: * Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. * Each time Applema...
3
n = int(input()) table = [int(x) for x in input().split(' ')] table.sort() count = 0 for k, v in enumerate(table, start=2): count += k * v count -= table[n - 1] print(count)
Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place. You know the rules of comparing the results of two give...
1
import sys def readints() : l = sys.stdin.readline() return map(int, l.split(' ')) def readstring() : l = sys.stdin.readline()[:-1] return l def readint() : l = sys.stdin.readline() return int(l) def clearchars(s, chars) : for c in chars : s = s.replace(c, '') return s def g...
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
a,b=map(int,input().split()) for i in range(b): if a%10>0: a-=1 else: a//=10 print(a)
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
n=int(input()) a=list(map(int,input().split())) a.sort(reverse=True) s = sum(a) k=0 for i in range(0,n): k+=a[i] if k>s/2: break print(i+1)
You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S. Notes Constraints * Elements in S is sorted in ascending order * n ≤ 100000 * q ≤ 50000 * 0 ≤ an element in S ≤ 109 * 0 ≤ an element in T ≤ 109 ...
3
# AOJ ALDS1_4_B Binary Search # Python3 2018.7.3 bal4u import sys from sys import stdin input = stdin.readline n = int(input()) s = set(map(int, input().split())) q = int(input()) t = set(map(int, input().split())) print(len(s & t))
La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each. Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes. Constraints * N is an integer between 1 and 10...
3
print("Yes" if [4*x+7*y for x in range(26) for y in range(16) ].count(int(input())) else "No")
Polycarp found under the Christmas tree an array a of n elements and instructions for playing with it: * At first, choose index i (1 ≤ i ≤ n) — starting position in the array. Put the chip at the index i (on the value a_i). * While i ≤ n, add a_i to your score and move the chip a_i positions to the right (i.e. r...
3
def sum(arr): s=0 for i in arr: s=s+i return s t=int(input()) for i in range(t): n=int(input()) arr=list(map(int,input().split())) mm=0 score=[0 for j in range(n)] for k in range(n): j=n-k-1 if arr[j]+j>=n: score[j]=arr[j] else : sc...
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
n = int(input()) n /= 5 s = n if n % 1 != 0: s += 1 print(int(s))
Kolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string. Then Borya came and said that the new string contained a tandem repeat of length l as a substring. How large could l be? See notes for definition of a tandem repeat. I...
1
def isok(s, q): i = 0 while i + 2 * q <= len(s): j = 0 while j < q and (s[i + j + q] == "?" or s[i + j] == s[i + j + q]): j += 1 if j == q: return True i += 1 return False s, k = raw_input(), int(raw_input()) s += "?" * k for i in range(len(s) // 2, -1, -1): ...
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea...
3
n = int(input()) p = list(map(int, input().split())) v = sum(p) c = 100 * n print(v/c * 100)
ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not n...
1
def an(arr): cnt = 0 st = "" for i in xrange(len(arr)): if (arr[i] > 1): return "-1" if (arr[i] == 0): st += chr(i + 65) else: cnt +=1 return st def rep(sub, st): ind = 0 for i in xrange(len(sub)): if (sub[i] == '?'): ...
There is a cave. The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside. It is dark in th...
3
from collections import deque n,m = map(int,input().split()) ab=[[] for _ in range(n+1)] for _ in range(m): a,b=map(int,input().split()) ab[a].append(b) ab[b].append(a) ans=[0]*(n+1) ans[1]=1 que=deque() que.append(1) while que: x=que.popleft() for i in ab[x]: if ans[i]==0: ans[...
Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al...
3
def ii(): return int(input()) def ss(): return [x for x in input()] def si(): return [int(x) for x in input().split()] def mi(): return map(int, input().split()) a1, a2, b1, b2 = mi() if a1 == b1: if a1 + abs(a2 - b2) <= 1000: print(a1 + abs(a2 - b2), a2, a1 + abs(a2 - b2), b2) elif a1 ...
Vasya came up with his own weather forecasting method. He knows the information about the average air temperature for each of the last n days. Assume that the average air temperature for each day is integral. Vasya believes that if the average temperatures over the last n days form an arithmetic progression, where the...
3
n=int(input()) l=list(map(int,input().split())) f=0 d=l[1]-l[0] if n>2: for i in range(n-1): if l[i+1]-l[i]!=d: f=1 break if f: print(l[-1]) else: print(l[-1]+d)
Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place. While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level: 1) The boss has t...
1
N, Max, Reg = map (int, raw_input ().split ()) Param = [map (int, raw_input ().split ()) for _ in xrange (N)] HP, time, History = Max, 0, [] while True: scroll = None HP = min (Max, HP + Reg) if HP <= 0: break for Pos, [Pow, Dmg] in enumerate (Param): if Dmg and (float (HP) / Max) * 10...
You are given an array of n integers a_1, a_2, ..., a_n, and a set b of k distinct integers from 1 to n. In one operation, you may choose two integers i and x (1 ≤ i ≤ n, x can be any integer) and assign a_i := x. This operation can be done only if i does not belong to the set b. Calculate the minimum number of opera...
3
import bisect INF = 0x3f3f3f3f3f3f3f3f pa, pb = map(int, input().split()) m = [-INF] + [ mi - i for i, mi in enumerate(map(int, input().split())) ] + [INF] n = [0] + (list(map(int, input().split())) if pb else list()) + [pa+1] temp = 0 for j in range(pb+1): k = n[j] q = n[j+1] if m[q] < m[k]: print...
Given a positive integer m, we say that a sequence x_1, x_2, ..., x_n of positive integers is m-cute if for every index i such that 2 ≤ i ≤ n it holds that x_i = x_{i - 1} + x_{i - 2} + ... + x_1 + r_i for some positive integer r_i satisfying 1 ≤ r_i ≤ m. You will be given q queries consisting of three positive intege...
3
def solve(): a, b, m = (int(x) for x in input().split()) if a == b: print(1, a) return curr = a curr_const = 1 steps_nr = 0 while b - curr > curr_const * m: curr *= 2 curr_const *= 2 steps_nr += 1 if b - curr < curr_const: print(-1) ret...
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
######### ## ## ## #### ##### ## # ## # ## # # # # # # # # # # # # # # # # # # # # # # # ### # # # # # # # # # # # # # ##### # # # # ### # # # # # # # # ##### # # # # # # # # # # # # # # # # # # #########...
Akash has lots of assignments to submit in his college. In one of the assignment he is given a string S of length N consisting of lowercase letters (a - z) only. Akash has to answer Q queries and for every query, he is given L, R and K. For each query he has to find the lexicographically Kth smallest character in subs...
1
size, queries = map(int, raw_input().split()) string ,size = raw_input(), size +1 string = '0' +string #prefix Computation prefix = [ [0]*26 for i in xrange(size)] for j in xrange(1,size): diff = ord(string[j]) - ord('a') for val in xrange(26): if val == diff: prefix[j][val] = prefix[j-1][val] + 1 else: p...
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes. The main school of the capital is located in (s_x, ...
3
from sys import stdin input = stdin.readline n, sx, sy = map(int, input().split()) neighbors = [(sx+1, sy), (sx, sy+1), (sx-1, sy), (sx, sy-1)] scores = [0,0,0,0] for i in range(n): x,y = map(int, input().split()) for i, (px,py) in enumerate(neighbors): if min(sx,x) <= px <= max(sx,x) and min(sy,y) <= ...
We have N bricks arranged in a row from left to right. The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it. Among them, you can break at most N-1 bricks of your choice. Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of t...
3
n = int(input()) xs = [int(x) for x in input().split()] c = 0 y = 1 for x in xs: if x == y: y += 1 else: c += 1 print(-1 if c == n else c)
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=int(input()) a=input().split() for i in range(n): a[i]=int(a[i]) a.sort() for x in range(n): print(a[x],end=" ")
Roy has a matrix of size NxN. Rows and Columns are numbered from 0 to N-1. j^th column of i^th row contains i xor j. In other words, Matrix[i][j] = i ^ j where 0 ≤ i,j < N. ( ^ is a bitwise operation used in C/C++ for xor, please use appropriate symbol if you're using any other language) Your task is to find the...
1
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' def get_count(N): """ max1 = N-1 j = 0 for i in range(0,N): xor = (N-1)^i if xor > max1: max1 = xor j = i """ tmp=n x=0 while tmp!=0: tmp = tmp>>1 x = x+1 x=x-1...
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2). You want to construct the array a of length n such that: * The first n/2 elements of a are even (divisible by 2); * the second n/2 elements of a are odd (not divisible by 2); * all elements of a are distinct and positi...
3
from sys import stdin, exit input = stdin.readline def i(): return input() def ii(): return int(input()) def iis(): return map(int, input().split()) def liis(): return list(map(int, input().split())) def print_array(a): print(" ".join(map(str, a))) t = ii() for _ in range(t): n, k = iis() a = liis() counter = {} ...
As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where...
3
def m_pow(x, y, m): if y == 0: return 1 if (y & 1): return m_pow(x, y - 1, m) * x % m else: t = m_pow(x, y >> 1, m) return t * t % m # (p, k) = map(int, input().split()) used = [0] * p if k == 0: print(m_pow(p, p - 1, 1000000007)) else: c = 1 if k == 1 else 0 for ...
Alice is playing with some stones. Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones. Each time she can do one of two operations: 1. take one stone from the first heap and two stones from the second heap (...
3
t=int(input()) for q in range(t): a,b,c=map(int,input().split()) ans=0 x=min(b,c//2) ans+=3*x b-=x y=min(a,b//2) ans+=3*y print(ans)