problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied. ZS and Chris are...
3
n = int(input()) sp = [] fl = True for i in range(n): s1, s2 = input().split('|') if fl: if 'OO' == s1: s1 = '++' fl = False elif 'OO' == s2: s2 = '++' fl = False sp.append(s1) sp.append(s2) if not fl: print('YES') for i in range(0...
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
print(len(set(list(filter(None, map( lambda x: x.strip(), input()[1:-1].split(',')))))) )
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. You want...
3
author="DarshanMohan" import sys 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 j in range(b)] for i in range(a)] d...
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()) s=input() ans=0 for i in range(0,n-1): if s[i] == s[i+1]: ans=ans+1 print(ans)
Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number ...
1
n = input() h = map(int , raw_input().split()) #pura ques to padh leta if 0 not in h: print -1 exit(0) zero = h.count(0) hm = sum(h) while hm % 9 != 0: hm -= 5 cnt = hm / 5 if cnt == 0: print 0 exit(0) print '5'*cnt + '0'*zero
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
word = input() numl = word.count('l') if numl >= 2 and 'e' in word and 'h' in word and 'o' in word: indexh = word.index('h') word = word[(indexh + 1):] if 'e' in word: indexe = word.index('e') word = word[(indexe + 1):] if 'l' in word: indexl = word.index('l') ...
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di...
3
input();l1,l2=[],[] for i,v in enumerate(map(int,input().split())): if v%2==0:l1+=[i+1] else:l2+=[i+1] print(l1[0] if len(l1)==1 else l2[0])
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ...
3
a,b = map(int,input().split()) z = sorted(map(int,input().split())) q = z[0]*2 for i in range(1,a): q= max(q,z[i]-z[i-1]) q = max(q,(b-z[-1])*2) print(q/2)
This is the harder version of the problem. In this version, 1 ≤ n ≤ 10^6 and 0 ≤ a_i ≤ 10^6. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend...
3
import math arr = [0] * 1000100 n = 0 # Calculate amount of move for prime number x def gogo(x): global n global arr cv = 0 ans = 0 for i in range(n): cv = (cv + arr[i]) % x ans += min(cv, x - cv) # print(x, i, arr[i], cv, ans) return ans def main(): global n ...
Reminder: the [median](https://en.wikipedia.org/wiki/Median) of the array [a_1, a_2, ..., a_{2k+1}] of odd number of elements is defined as follows: let [b_1, b_2, ..., b_{2k+1}] be the elements of the array in the sorted order. Then median of this array is equal to b_{k+1}. There are 2n students, the i-th student has...
3
for _ in range(int(input())): n=int(input()) abc=sorted(list(map(int, input().split()))) print(abc[n]-abc[n-1])
Input The input contains a single integer a (1 ≤ a ≤ 64). Output Output a single integer. Examples Input 2 Output 1 Input 4 Output 2 Input 27 Output 5 Input 42 Output 6
3
a=[0,1,1,1,2,1,2,1,5,2,2,1,5,1,2,1,14,1,5,1,5,2,2,1,15,2,2,5,4,1,4,1,51,1,2,1,14,1,2,2,14,1,6,1,4,2,2,1,52,2,5,1,5,1,15,2,13,2,2,1,13,1,2,4,267,1,4,1,5,1,4,1,50,1,2,3,4,1,6,1,52,15,2,1,15,1,2,1,12,1,10,1,4,2] n=int(input()) print(a[n])
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
w=str(input()).lower() if 1<=len(w)<=100: s="" for x in w: if x in 'aeiyou': s+="" else: s+= '.'+x print(s)
Dreamoon is a big fan of the Codeforces contests. One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing! Based on this, you come up with the following problem: There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi...
3
for _ in range(int(input())): a = input().split(' ') n = int(a[0]) x = int(a[1]) a = input().split(' ') for i in range(n): a[i] = int(a[i]) count = 1 while True: if count in a: count = count + 1 elif x > 0: x = x - 1 count = count +...
Boboniu gives you * r red balls, * g green balls, * b blue balls, * w white balls. He allows you to do the following operation as many times as you want: * Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the b...
3
def soln(w,r,g,b): br=(r%2!=0) bw=(w%2!=0) bg=(g%2!=0) bb=(b%2!=0) count=0 if br:count+=1 if bg:count+=1 if bb:count+=1 if bw:count+=1 if count==2: return "NO" else: if r==0 or g==0 or b==0: if count<=1: return("YES") ...
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger. But h...
3
s=int(input()) if(s>=-128 and s<=127): print("byte") elif(s>=-32768 and s<=32767): print("short") elif(s>=-2147483648 and s<=2147483647): print("int") elif(s>=-9223372036854775808 and s<=9223372036854775807): print("long") else: print("BigInteger")
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
e=input() s=input() i=0 c=0 while(i<len(s)): j=i+1 try: while(s[i]==s[j]): c=c+1 j=j+1 except: break i=j print(c)
Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon...
3
def to_list(s): return list(map(lambda x: int(x), s.split(' '))) def solve(a): return str(max(a)) n = int(input()) a = to_list(input()) print(solve(a))
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
# cook your dish here for _ in range(int(input())): n,m=map(int,input().split()) a=sum(list(map(int,input().split()))) if a==m: print("YES") else: print("NO")
You are given two integers a and b. In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves. Your task is to find the minimum number of mo...
3
t=int(input()) for i in range(t): a,b=input().split() a,b=int(a),int(b) diff =abs(a-b) if diff%10==0: print(diff//10) else: print(diff//10+1)
The length of the longest common prefix of two strings s = s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum integer k (0 ≤ k ≤ min(n,m)) such that s_1 s_2 … s_k equals t_1 t_2 … t_k. Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}. For each i (1 ≤ i ≤ n) she calculated a_i — the length of ...
3
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.wri...
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
no_st = int(input()) x = 0 for i in range(no_st): st = input() if st[1] == '+': x += 1 else: x -= 1 print(x)
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
num = int(input()) s = input() count_a = s.count('A') diff = len(s) - count_a if count_a > diff: print("Anton") elif count_a < diff: print("Danik") else: print("Friendship")
<image> This figure shows railway tracks for reshuffling cars. The rail tracks end in the bottom and the top-left rail track is used for the entrace and the top-right rail track is used for the exit. Ten cars, which have numbers from 1 to 10 respectively, use the rail tracks. We can simulate the movement (comings an...
3
import sys x=[] u=[] for line in sys.stdin.readlines(): y=int(line) if(y!=0): x.append(y) else: u.append(x.pop(-1)) for i in range(len(u)): print(u[i])
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero. For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not. Now, you ha...
3
for _ in range(int(input())): cur = int(input()) if cur < 4: print(4 - cur) else: print(cur % 2)
You are the gym teacher in the school. There are n students in the row. And there are two rivalling students among them. The first one is in position a, the second in position b. Positions are numbered from 1 to n from left to right. Since they are rivals, you want to maximize the distance between them. If students a...
3
tc = input() r = [] for i in range(0,int(tc)): n,x,a,b = input().split() r.append(min(int(n)-1,abs(int(a)-int(b))+int(x))) for x in r: print(x)
Not to be confused with [chessboard](https://en.wikipedia.org/wiki/Chessboard). <image> Input The first line of input contains a single integer N (1 ≤ N ≤ 100) — the number of cheeses you have. The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and...
3
n = int(input()) h = s = 0 for i in range(n): if input().split(' ')[1] == 'hard': h += 1 else: s += 1 if h < s: h, s = s, h i = 1 while (i ** 2 + 1) // 2 < h or i ** 2 // 2 < s: i += 1 print(i)
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property. Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=...
3
inp = [] out = [] for x in range(int(input())): s = input() for i in range(len(s)-1): if s[i] != s[i+1]: out.append((s[0] + str(1-int(s[0])))*len(s)) break if len(out) < x+1: out.append(s) for o in out: print(o)
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
text = input().lower() vol = ["a", "o", "y", "e", "u", "i"] ans = '' for i in vol: if i in text: text = text.replace(i,'') for t in text: ans = ans+'.'+t print(ans)
You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m. Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B. For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ...
3
input() A = input().split() input() B = input().split() for x in range (len(A)): A[x] = int(A[x]) for x in range(len(B)): B[x] = int(B[x]) flag = False for n in A: for m in B: if n+m not in A and n+m not in B: print(n, m) flag = True break if flag: ...
As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as <image>, where k is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers. A well-known hipster Andrew adores everything funky ...
3
n = int(input()) m = 1 arr = [] while(True): mm = (m*(m+1))//2 if mm>n: break arr.append(mm) m+=1 ll = len(arr) flag = 0 for i in range(ll): curr = arr[i] req = n-curr l = i r = ll-1 while(l<=r): mid = (l+r)//2 if arr[mid]>=req: r = mid-1 else: l = mid+1 if i<=l<ll and arr[l]==req: flag=1 b...
AtCoDeer the deer found two positive integers, a and b. Determine whether the product of a and b is even or odd. Constraints * 1 ≤ a,b ≤ 10000 * a and b are integers. Input Input is given from Standard Input in the following format: a b Output If the product is odd, print `Odd`; if it is even, print `Even`. E...
3
print(('Even','Odd')[eval(input().replace(' ','*'))%2])
George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers b. During the game, George modifies the array by using special changes. Let's mark George's current array as b1, b2, ..., b|b| (record |b| denotes the current length of the array). Then one change is a sequence...
1
s = raw_input() i,ans,n = 0,1,len(s) while i < n: j,i = i,i+1 while i<n and '0' == s[i]: i += 1 if j > i-j or (j == i-j and s[:j] >= s[j:i]): ans += 1 else: ans = 1 print ans
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
a=[] for i in range(5): a.append(list(map(int,input().split(" ")))) for i in range(5): for j in range(5): if(a[i][j]==1): v=[i,j] print(abs(abs(v[0]-2)+abs(v[1]-2)))
Your friend has recently learned about coprime numbers. A pair of numbers {a, b} is called coprime if the maximum number that divides both a and b is equal to one. Your friend often comes up with different statements. He has recently supposed that if the pair (a, b) is coprime and the pair (b, c) is coprime, then the...
3
# In this template you are not required to write code in main import sys inf = float("inf") #from collections import deque, Counter, OrderedDict,defaultdict #from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace from math import ceil,floor,log,sqrt,factorial,pow,pi,gcd #from bisect import b...
There are N people standing in a queue from west to east. Given is a string S of length N representing the directions of the people. The i-th person from the west is facing west if the i-th character of S is `L`, and east if that character of S is `R`. A person is happy if the person in front of him/her is facing the...
3
N,K = map(int,input().split()) S = list(input()) ans = 0 for x,y in zip(S,S[1:]): if x==y: ans += 1 print(min(N-1,ans+2*K))
Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations: * multiply the current number by 2 (that is, replace the number x by 2·x); * append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1). You need to help Vasil...
3
#!/usr/bin/env python3 def convert(a, b): path = [b] while b != a: if b % 2 == 0 and b > 0: b //= 2 path.append(b) elif b % 10 == 1: b //= 10 path.append(b) else: return None return reversed(path) def main(): ans = c...
Find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten. Constraints * 1 \leq N < 10^{100} * 1 \leq K \leq 3 Input Input is given from Standard Input in the following format: N K Output Print the count. Examples Input 100 1 Output 19 Inpu...
3
N=input() l=len(N) K=int(input()) dp=[[[0 for i in range(4)] for i in range(2)] for i in range(l+1)] dp[0][0][0]=1 for i in range(l): for smaller in range(2): for c in range(4): lim=9 if smaller else int(N[i]) for d in range(lim+1): if(c!=3): dp[i+...
There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams...
3
z,zz,dgraphs=input,lambda:list(map(int,z().split())),{} from string import * from collections import * from queue import * from sys import * from collections import * from math import * from heapq import * from itertools import * from bisect import * from collections import Counter as cc from math import factorial as f...
Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other. The entire universe turned into an enormous clock face with ...
1
from sys import stdin lines = stdin.readlines() temp1 = True temp2 = True liste = map(int,lines[0].split()) temp3 = True h = liste[0] m = liste[1] s = liste[2] t1 = liste[3] t2 = liste[4] m /= 5 s /= 5 c1 = min(t1,t2) c2 = max(t1,t2) temp4 = True if m == 0: m = 12 if s == 0: s = 12 for i in range(c1,c2): i...
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
import math H=int(input()) W=int(input()) N=int(input()) t=max(H,W) print(math.ceil(N/t))
AtCoDeer the deer and his friend TopCoDeer is playing a game. The game consists of N turns. In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition: (※) After each turn, (the number of times the player has played Paper)≦(the number of times the ...
3
s = input() N = len(s) p = 0 for i in range(N): if s[i] == "p": p += 1 print(N//2-p)
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
#Exspiravit n=int(input()) inp=input()+' ' s=[] s1=0 for i in range(0,n): s2=inp.find(' ',s1+1) s+=[int(inp[s1:s2])] s1=s2 r=0 e=0 e2=0 for i in s: if i==4: r+=1 elif i==3: r+=1 e+=1 for i in s: if i==2: if e2>1: e2-=2 else: r+=1 ...
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
t=int(input()) for i in range(t): n=int(input()) a=list(map(int,input().split())) even,odd=[],[] for j in range(n): if(j%2 != a[j]%2): if j%2: even.append(a[j]) else: odd.append(a[j]) print(len(even) if len(even)==len(odd) else '-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
n,k = map(int,input().split()) string = input() dictionary = {} for i in range(len(string)): if string[i] in dictionary: dictionary[string[i]] += 1 else : dictionary[string[i]] = 1 minimum = dictionary[string[0]] if len(dictionary) == k: for i in dictionary.keys(): if dictionary[i] <...
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ...
3
s = input() max = 0 calc = 0 for c in s: calc = calc + 1 if c == 'A' or c == 'E' or c == 'I' or c == 'O' or c == 'U' or c == 'Y': max = calc if calc > max else max calc = 0 calc = calc + 1 max = calc if calc > max else max print(max)
You are given $n$ integers $w_i (i = 0, 1, ..., n-1)$ to be sorted in ascending order. You can swap two integers $w_i$ and $w_j$. Each swap operation has a cost, which is the sum of the two integers $w_i + w_j$. You can perform the operations any number of times. Write a program which reports the minimal total cost to...
3
def solve(A,n,s): ans = 0 V = [False for i in range(n)] # 値が交換済みかどうか B = sorted(A) T = [None for i in range(10001)] for i in range(n): T[B[i]] = i for i in range(n): if V[i]: continue cur = i #カーソル S = 0 #サークル内の数字の総和 m = 10000 # VMAX an = 0 # サークル...
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant. Shop, where Noora is working, has a plan on the following n days. For each day sales manager...
3
n, f = map(int, input().split()) d = [] for i in range(n): d.append(list(map(int, input().split()))) d.sort(reverse=True, key=lambda x: min(2 * x[0], x[1]) - min(x[0], x[1])) res = 0 for i in range(n): if i < f: res += min(2 * d[i][0], d[i][1]) else: res += min(d[i][0], d[i][1]) print(res)
Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks. There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each. What is the minimum amount of money with which he can bu...
1
# C - Energy Drink Collector # https://atcoder.jp/contests/abc121/tasks/abc121_c import operator N, M = map(int, raw_input().split()) stores = list() for _ in range(N): stores.append( tuple(map(int, raw_input().split())) ) stores.sort(key=lambda x : x[0]) money = 0 cans_cnt = 0 for cost_i, cans_i in stores: ...
Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N. Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, repo...
3
X,N=map(int,input().split()) P=sorted(list(map(int,input().split()))) t=0 for i in range(0,102): if i not in P: if abs(X-t)>abs(X-i): t=i print(t)
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...
1
k=input() ans = 0 for i in range(k): p=raw_input().split(' ') if int(p[0]) + 2 <= int(p[1]) : ans = ans + 1 print ans
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
3
from collections import Counter n = int(input()) t = [int(i) for i in input().split()] counter = Counter(t) c = min(counter.values()) if len(counter) < 3: print(0) else: print(c) skills = [1, 2, 3] grp_by_skill = [] for s in skills: grp_by_skill.append([i + 1 for i in range(n) if t[i] == s]...
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k. During each turn Vova can choose what to do: * If the current charge of his laptop battery is strictly gre...
3
import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') ...
There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid. When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1). In how many ways can the knight reach the square (X, Y)? Find the number of ways modulo 10^9 + 7. Constraints * 1 \leq X \leq 10^6 * 1 \l...
1
MOD = 1000000007 fac = finv = inv = None def init(n): global fac, finv, inv fac = [0] * n finv = [0] * n inv = [0] * n fac[0] = fac[1] = 1 finv[0] = finv[1] = 1 inv[1] = 1 for i in xrange(2, n): fac[i] = fac[i - 1] * i % MOD inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD ...
You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that: * No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in t...
3
if __name__ == "__main__": nqueries = int(input()) outputs = [] for query in range(nqueries): nstudents = int(input()) skills = [int(k) for k in input().split()] skills.sort() twoTeams = False ind = 0 while (not twoTeams) and ind < nstudents - 1: i...
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings. An integer greater than 1 is composite, if it is not prime, i.e. if...
3
n=int(input()) for i in range(n): p=int(input()) if p in [1,2,3,5,7,11]: print(-1) elif p%4==0 or p%4==2: print(p//4) elif p%4==1 or p%4==3: print((p//4)-1)
All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of n⋅ m different seals, denoted by distinct numbers. All of them were written in an n× m table. The table is lost now. Naruto managed to remember elements of each row from left to right, and eleme...
3
import sys input = sys.stdin.readline for _ in range(int(input())): n,m = map(int, input().split()) d = {} for i in range(n): l = list(map(int, input().split())) d[l[0]] = l z = [] for i in range(m): l = list(map(int, input().split())) if l[0] in d: z = l for i in z: print(*d[i])
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
a=[] for i in range(5): b=list(map(int,input().split())) a.append(b) s1=0 s2=0 for i in range(5): for j in range(5): if a[i][j]==1: s1=i+1 s2=j+1 print((abs(3-s1))+(abs(3-s2)))
Nastia has received an array of n positive integers as a gift. She calls such an array a good that for all i (2 ≤ i ≤ n) takes place gcd(a_{i - 1}, a_{i}) = 1, where gcd(u, v) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers u and v. You can perform the op...
3
def answer(): m=min(a) for i in range(n): if(a[i]==m): ind=i break opp=[] c=1 for i in range(ind-1,-1,-1): opp.append([ind+1,i+1,m,m+c]) c+=1 c=1 for i in range(ind+1,n): opp.append([ind+1,i+1,m,m+c]) c+=1 print(len(opp...
You play a computer game. In this game, you lead a party of m heroes, and you have to clear a dungeon with n monsters. Each monster is characterized by its power a_i. Each hero is characterized by his power p_i and endurance s_i. The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero ...
3
import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" ...
A maze is composed of a grid of H \times W squares - H vertical, W horizontal. The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is `#` and a road if S_{ij} is `.`. There is a magician in (C_h,C_w). He can do the following two kinds of moves: * Move A: Walk to a ...
3
from collections import deque h, w = map(int, input().split()) ch, cw = map(int, input().split()) dh, dw = map(int, input().split()) s = [list(input()) for _ in range(h)] d = deque() d.append([ch-1, cw-1]) dist = [[float('inf')] * w for _ in range(h)] dist[ch-1][cw-1] = 0 while d: x, y = d.popleft() for i in ...
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ...
3
n=int(input()) x=[1] for i in range(0,n): x.append(x[i]+i+2) if sum(x)>n: x.remove(x[i]+i+2) break print(len(x))
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
for i in range(int(input())): s = str(input()) if len(s) > 10: print(s[0] + str(len(s)-2) + s[-1]) else: print(s)
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the po...
3
x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) k = 0 n = int(input()) for i in range(n): a, b, c = map(int, input().split()) if (a * x1 + b * y1 + c) * (a * x2 + b * y2 + c) < 0: k += 1 print(k)
There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people c...
3
n=int(input()) m=int(input()) a=[] for _ in range(n): a.append(int(input())) mx=max(a)+m mn=max(a) while(m): ind=a.index(min(a)) a[ind]+=1 m-=1 mn=max(a) print(mn,end=' ') print(mx)
One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides,...
1
import math __author__ = 'abbas' n = int(raw_input()) a = [int(x) for x in raw_input().split()] a.append(0) a.sort(reverse=True) pi = math.pi ans = 0.0 for i in range(0,n,2): ans += a[i]*a[i] - a[i+1]*a[i+1] print ans*pi
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
3
n=int(input()) x=input() x=x.lower() x=set(x) if len(x)==26: print("YES") else: print("NO")
Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_commo...
1
#import resource import sys #resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY]) #threading.Thread(target=main).start() #import threading #threading.stack_size(2**25) #sys.setrecursionlimit(10**6) #jai guru ji mod=(10**9)+7 #fact=[1] #for i in range(1,1000001): # fact.append((fact[-1]*i)...
There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones. In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who canno...
3
t = int(input()) for p in range(t): n = int(input()) ara = list(map(int, input().strip().split())) ones = flag = 0 for i in ara: if i == 1 and flag == 0: ones += 1 else: flag = 1 if flag == 1: if ones % 2 == 0: print("First") else: ...
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
s1=str(input()) l=len(s1) l2=int((l+1)/2) c1=list('-')*l2 s=0 for m in range(0,l,2): c1[s]=s1[m] s+=1 c1.sort() t='+'.join(c1) print(t)
You are given two integers x and y. You can perform two types of operations: 1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation: * x = 0, y = 6; * x = 0, y = 8; * x = -1, y = 7; * x = 1, y = ...
3
n = input() def solve(x, y, a, b): if x < 0 and y < 0 or x > 0 and y > 0: return abs(min(x, y)) * min(2*a, b) + abs(x-y)*a return a * (abs(x) + abs(y)) for i in range(int(n)): x, y = map(int, input().split(' ')) a, b = map(int, input().split(' ')) solution = solve(x, y, a, b) print(so...
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
a=int(input()) if(a%2==1 or a==2): print("NO") else: print("YES")
The cows have just learned what a primitive root is! Given a prime p, a primitive root <image> is an integer x (1 ≤ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is. Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given ...
3
n=int(input()) if(n==2): print(1) exit() n-=1 res=0 for i in range(1,n): chk=True for j in range(2,i+1): if(n%j==0 and i%j==0): chk=False if(chk): res+=1 print(res)
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print `Yes`; if it cannot, print `No`. Constraints * 1 \leq N \leq 100 * N is an int...
3
print(['No','Yes'][int(input()) in [j*i for i in range(1,10) for j in range(1,10)]])
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
import os import sys import math import heapq from decimal import * from io import BytesIO, IOBase from collections import defaultdict, deque def r(): return int(input()) def rm(): return map(int,input().split()) def rl(): return list(map(int,input().split())) for _ in range(r()): na,nb=rm() a=rl(...
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....
1
n = int(raw_input()) L = [int(x) for x in raw_input().split()] def multithreading(L): count = 0 for x in xrange(len(L) - 1, 0, -1): if L[x] > L[x - 1]: count += 1 else: break return len(L) - (count + 1) print multithreading(L)
Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i. The N players will arrive at the place one by one in some order. To ma...
3
n = int(input()) a = list(map(int, input().split())) a = a + a a.sort(reverse=True) ans = 0 for i in range(1,n): ans += a[i] print(ans)
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other cons...
3
s=input() t=input() k=0 if(len(s)!=len(t)): print('No') else: for i in range(0,len(s)): if s[i] in 'aeiou' and t[i] in 'aeiou': continue elif s[i] not in 'aeiou' and t[i] not in 'aeiou': continue else: k=1 print('No') ...
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i...
3
l=list(map(int,input().split(" "))) n=l[0] m=l[1] a=list(map(int,input().split(" "))) total=0 total=total+(a[0]-1) for i in range(0,m-1): if a[i]==a[i+1]: total=total elif a[i]<a[i+1]: total=total+(a[i+1]-a[i]) else: total=(n-a[i])+a[i+1]+total print(total)
We have N ID cards, and there are M gates. We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards. How many of the ID cards allow us to pass all the gates alone? Constraints * All values in input are integers. * 1 \leq N \leq 10^5 * 1 \leq M \leq 10^5 * ...
1
N,M=map(int ,raw_input().split()) S = 1 E = N for i in range(M): L,R=map(int ,raw_input().split()) if S<L: S=L if E>R: E=R if E<S: print(str(0)) else: print(str(E-S+1))
There are n cards numbered 1, …, n. The card i has a red digit r_i and a blue digit b_i written on it. We arrange all n cards in random order from left to right, with all permutations of 1, …, n having the same probability. We then read all red digits on the cards from left to right, and obtain an integer R. In the sa...
3
import sys import math import bisect from sys import stdin, stdout from math import gcd, floor, sqrt, log2, ceil from collections import defaultdict as dd from bisect import bisect_left as bl, bisect_right as br from bisect import insort from collections import Counter from collections import deque from heapq import he...
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0. For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}. Then, she calculated an array, b_1, b_2, …, b_n: ...
3
n=int(input()) arr=list(map(int,input().split())) max=arr[0] res=[] res.append(arr[0]) for i in range(1,n): if max<arr[i]+max: max+=arr[i] res.append(max) else: res.append(arr[i]+max) print(*res)
This is an interactive problem. Omkar has just come across a duck! The duck is walking on a grid with n rows and n columns (2 ≤ n ≤ 25) so that the grid contains a total of n^2 cells. Let's denote by (x, y) the cell in the x-th row from the top and the y-th column from the left. Right now, the duck is at the cell (1, ...
3
def read(): s = '' while not s.strip().isdigit(): s = input() return int(s) def tile(i, j): return 2 ** (i + j) if i % 2 else 0 n = read() for i in range(n): for x in [tile(i, j) for j in range(n)]: print(x, end = ' ') print('', flush = True) q = read() for qx in range(q): k = read() i = n - 1; ...
Imp likes his plush toy a lot. <image> Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies. Initially, Imp has only on...
3
a, b = map(int, input().split()) if (a - (b - 1)) > -1 and (a - (b - 1)) % 2 == 0 and b != 0 and not (b == 1 and a != 0): print("YES") else: print("NO")
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help. Artem wants to paint an n × m board. Each cell of the board should be colored in white or black. Lets B be the number of black cells that have at least one white neighbor adja...
3
t=int(input()) for i in range(t): n,m=list(map(int,input().split())) s="B"*(m-2) for i in range(n): if(n==m==2): print("WB") print("BB") break elif(n>=3): if(i<2): print("WB"+s) else: print("BB"+s) else: if(i==0): print("WW"+s) else: print("BB"+s)
This problem is actually a subproblem of problem G from the same contest. There are n candies in a candy box. The type of the i-th candy is a_i (1 ≤ a_i ≤ n). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all di...
3
#!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def main(): from collections import Counter q =...
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
def solve(a,n): d1 = {} d2 = {} for i in a: if d1.get(i) == None: d1[i] = 1 else: d2[i] = 1 arr = [] for i in d1.keys(): arr.append(i) return arr t = int(input()) for _ in range(t): n = int(input()) a = list(map(int,input().sp...
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n. He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se...
3
N=int(input()) for x in range(N): n=int(input()) import math print(math.ceil(n/2))
The three friends, Kuro, Shiro, and Katie, met up again! It's time for a party... What the cats do when they unite? Right, they have a party. Since they wanted to have as much fun as possible, they invited all their friends. Now n cats are at the party, sitting in a circle and eating soup. The rules are simple: anyone...
3
from math import * x,y = map(int,input().split()) if y == 0 or y == 1: print(1) elif x%2 == 0 and y < x//2: print(y) elif x%2 != 0 and y< ceil(x/2): print(y) else: print(x-y)
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
s = input() shello = "hello" j = 0 for i in range(len(s)): if j == 5: break elif s[i] == shello[j]: j += 1 if j == 5: print("YES") else: print("NO")
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2). He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will...
1
# -*- coding:utf-8 -*- import sys, os if __name__ == '__main__': # 读取输入的一个整数,浮点数,字符/字符串, int, float, str v = int(sys.stdin.readline().strip()) # value1 # 读取输入的一行的两个整数,浮点数,字符/字符串 for i in range(v): x1, y1, x2, y2 = list(map(int, sys.stdin.readline().strip().split(" "))) # int, float, str if x1 == x2 or y1 =...
There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1},...
3
import sys, os n = int(sys.stdin.buffer.readline()) A = [int(x) for x in sys.stdin.buffer.readline().split()] cumsum = [0.0] for a in A: cumsum.append(cumsum[-1] + a) def mean(interval): i, j = interval return (cumsum[j] - cumsum[i]) / (j - i) B = [] for i in range(n): B.append((i, i + 1)) w...
HQ9+ is a joke programming language which has only four one-character instructions: * "H" prints "Hello, World!", * "Q" prints the source code of the program itself, * "9" prints the lyrics of "99 Bottles of Beer" song, * "+" increments the value stored in the internal accumulator. Instructions "H" and "Q"...
3
S = input() if 'H' in S or 'Q' in S or '9' in S: print('YES') else: print('NO')
Print the K-th element of the following sequence of length 32: 1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51 Constraints * 1 \leq K \leq 32 * All values in input are integers. Input Input is given from Standard Input in the following format: K Output Print ...
3
s=[1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51] a=int(input()) print(s[a-1])
Given an integer x, find 2 integers a and b such that: * 1 ≤ a,b ≤ x * b divides a (a is divisible by b). * a ⋅ b>x. * a/b<x. Input The only line contains the integer x (1 ≤ x ≤ 100). Output You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in...
3
x = int(input()) resposta = list() for a in reversed(range(1, (x) + 1)): for b in range (1, x + 1): if (a%b == 0) and (a*b > x) and (a/b < x): resposta.append(a) resposta.append(b) break else: pass if len(resposta) > 1: print(resposta[0], resposta[1]) else: print(-1) ...
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections. The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Ob...
3
def C(frm, what): ans = 1 for i in range(what): ans *= frm - i ans = ans // (i + 1) return ans n = int(input()) ans = C(n, 5) * C(n, 5) * 120 print (ans)
There are K lemurs on Madagascar and Kevin has N bananas. He has to give away all his bananas to lemurs. Lemurs are happy if all of them get the same number of bananas (even if they don't get any). In one minute Kevin can do one of the following: Find one banana. Discard one banana (eat). Increase a population of ...
1
s=f=1000000 n,k=map(int,raw_input().split()) if(n%k==0): print 0 else: j=k for i in range(1000000): a=n//k b=(n//k)+1 x=b*k-n y=n-(a*k) g=min(x,y) d=k-j if((g+d)<f): f=g+d #print g,d k+=1 k=j for l in range(1000000): #print "tatti" if k<=0: break #print k a=n//k b=(n//k)+1 x=(...
We have a sequence of length N, a = (a_1, a_2, ..., a_N). Each a_i is a positive integer. Snuke's objective is to permute the element in a so that the following condition is satisfied: * For each 1 ≤ i ≤ N - 1, the product of a_i and a_{i + 1} is a multiple of 4. Determine whether Snuke can achieve his objective. ...
3
N = int(input()) a = list(map(int,input().split())) W,Q = 0,0 for i in a: if i%4 == 0: Q += 1 elif i%2 == 0: W += 1 if Q >= N//2 or Q >= (N-W)/2: print("Yes") else: print("No")
There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one. We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while pa...
3
import sys from collections import Counter input = sys.stdin.readline n = int(input()) a = dict(Counter(sorted(input().split()))) ans = 0 f = 0 for val in a: ans += min(f, a[val]) f += max(a[val] - f, 0) print(ans)
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given. Shift each character of S by N in alphabetical order (see below), and print the resulting string. We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` ...
3
n = int(input()) s = input() w_n = n % 26 print("".join([chr(65 + (ord(w) - 65 + w_n) % 26) for w in s]))
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k. Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p. Input The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime. The se...
3
n, p, k = map(int, input().split()) A = list(map(int, input().split())) step4 = {} for i in A: h = (i ** 4) - (k * i) h %= p if h not in step4: step4[h] = 0 step4[h] += 1 ans = 0 for u in step4: ans += (step4[u]) * (step4[u] - 1) // 2 print(ans)