problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Bob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume. There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrea...
3
for _ in range(int(input())): a,b=map(int,input().split()) ans=abs(a-b) n=ans//5 m=(ans-5*n)//2 if ans-5*n-2*m!=0: print(n+m+1) else: print(n+m)
One warm and sunny day king Copa decided to visit the shooting gallery, located at the Central Park, and try to win the main prize — big pink plush panda. The king is not good at shooting, so he invited you to help him. The shooting gallery is an infinite vertical plane with Cartesian coordinate system on it. The targ...
3
########################################################## from collections import Counter def nCk(n, k): res = 1 for i in range(1, k + 1): res = res * (n - i + 1) // i return res import math inf=10**20 n=int(input()) c=[] dp=[0]*(n+1) for i in range(n): x,y, t,p = map(float, input().split()) ...
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...
1
""" Satwik_Tiwari ;) . 16 june , 2020 - Tuesday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IO...
We have N+1 integers: 10^{100}, 10^{100}+1, ..., 10^{100}+N. We will choose K or more of these integers. Find the number of possible values of the sum of the chosen numbers, modulo (10^9+7). Constraints * 1 \leq N \leq 2\times 10^5 * 1 \leq K \leq N+1 * All values in input are integers. Input Input is given from S...
3
nk=input("").split(" ") n=int(nk[0]) k=int(nk[1]) s=0 for i in range(k,n+2): s+=(n-i+1)*i+1 print(int(s%(10**9+7)))
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
3
n = int(input()) s = input() x_sum = 0 x_counter = 0 for i in range(n): if s[i] == 'x': x_counter += 1 elif x_counter > 0: x_sum += max(0, x_counter - 2) x_counter = 0 x_sum += max(0, x_counter - 2) print(x_sum)
We have a grid of H rows and W columns of squares. The color of the square at the i-th row from the top and the j-th column from the left (1 \leq i \leq H, 1 \leq j \leq W) is given to you as a character c_{i,j}: the square is white if c_{i,j} is `.`, and black if c_{i,j} is `#`. Consider doing the following operation...
3
h, w, k = map(int, input().split()) c = [input() for _ in range(h)] ans = 0 for h_p in range(2 ** h): for w_p in range(2 ** w): cnt = 0 for i in range(h): for j in range(w): if (h_p >> i) & 1 and (w_p >> j) & 1 and c[i][j] == '#': cnt += 1 if c...
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
1
n, t = map(int, raw_input().split()) q = raw_input() while t > 0: qq = "" i = 0 while i < len(q)-1: if q[i] == 'B' and q[i+1] == 'G': qq += "GB" i += 2 else: qq += q[i] i += 1 if i < len(q): qq += q[i] q = qq t -= 1 print q
You are given a grid with n rows and m columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number k > 0 written on it, then exactly k of its neighboring cells have a number greater than 0 written on them. Note that if the...
3
def sosedi(x,y,n,m): s = 4 if x == 0: s -= 1 if x == n - 1: s -= 1 if y == 0: s -= 1 if y == m - 1: s -= 1 return s def solve(): n, m = map(int,input().split()) lst = [list(map(int,input().split())) for i in range(n)] for x in range(n): for y ...
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path. You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times. Solve...
3
a , b = map(int , input().split()) two = three = five = seven = 0 if b - a > 0: print(2) else: print(a)
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game. Tzuyu gave Sana two integers a and b and a really important quest. In order to complete the quest, Sana has to output the smallest possible value of (a ⊕ x) + (b ⊕ x) for any given x, where ⊕ denotes the [bitwise XOR operation](http...
3
t = int(input()) for i in range(t): a,b = [int(i) for i in input().split()] print(a^0 + b^0)
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task. You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the fol...
3
def manacher(S): # 最長回文 O(n) # R[i] := i 文字目を中心とする最長の回文の半径(自身を含む) # 偶数長の回文を検出するには "a$b$a$a$b" のようにダミーを挟む # 検証: https://atcoder.jp/contests/wupc2019/submissions/8665857 i, j, n = 0, 0, len(S) R = [0]*n while i < n: while i-j >= 0 and i+j < n and S[i-j] == S[i+j]: j += 1 ...
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add...
3
n=list(input()); if '+' in n: t=n.index('+'); elif '-' in n: t=n.index('-'); e=n.index('='); f=t; s=e-1-t; a=len(n)-2-s-f; if '+' in n: if (f+s==a): for i in n: print(i,end="") elif (a-f-s==2): n=["|"]+n[0:len(n)-1]; for i in n: print(i,end="") elif(s+...
Alice has a lovely piece of cloth. It has the shape of a square with a side of length a centimeters. Bob also wants such piece of cloth. He would prefer a square with a side of length b centimeters (where b < a). Alice wanted to make Bob happy, so she cut the needed square out of the corner of her piece and gave it to ...
3
def check_final(a, b): re = (a-b)<=1 and check_prime(a+b) if re: return 'YES' else: return 'NO' def check_prime(x): if x < 2: return True elif x!=2 and x%2==0: return False else: return all(x % i for i in range(3, int(x**0.5)+1)) q = int(input()) answ...
You are given a picture consisting of n rows and m columns. Rows are numbered from 1 to n from the top to the bottom, columns are numbered from 1 to m from the left to the right. Each cell is painted either black or white. You think that this picture is not interesting enough. You consider a picture to be interesting...
3
t = int(input()) for i in range(0, t): pic = [] n, m = map(int, input().split()) for j in range(0, n): pic.append(input()) minRow = [0] minSqaresR = 5000000 for j in range(0, n): squares = pic[j].count('.') if squares < minSqaresR: minSqaresR = squares minRow = [j] elif squares == minSqaresR: m...
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not. Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro...
3
a=input() b=''.join(reversed(a)) print(a+b)
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems. Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to cele...
3
n = int(input()) + 1 if n == 1: print (0) elif n%2: print (n) else: print (n//2)
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: * An 'L' indicates he should move one unit left. * An 'R' indicates he should move one unit right. * A 'U' indicates he should move one unit up. * A 'D' indicates he shoul...
3
S = input() u = 0 d = 0 r = 0 l = 0 for s in S: if s == 'U': u += 1 elif s == 'D': d += 1 elif s == 'R': r += 1 elif s == 'L': l += 1 if len(S) % 2 != 0: print(-1) exit() ans = 0 ans += (abs(u - d)) // 2 ans += (abs(r - l)) // 2 if abs(u - d) % 2 != 0: ans += ...
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
3
n = int(input()) lvl = set(list(map(int, input().split()))[1:]) lvl = lvl | set(list(map(int, input().split()))[1:]) check = set([i+1 for i in range(n)]) print("I become the guy.") if lvl==check else print("Oh, my keyboard!")
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic che...
3
from string import ascii_lowercase, ascii_uppercase a = input() print('Correct' if len(a) >= 5 and any(x in a for x in ascii_lowercase) and any(x in a for x in ascii_uppercase) and any(x in a for x in '0123456789') else 'Too weak')
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
a=list(map(int,input().split())) if a[0]==0: print(0) else: for i in range(1,10): if ((i*a[0])-a[1])%10==0 or (i*a[0])%10==0: print(i) break
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house. Karlsson's gaze immediately fell on n wooden ...
1
import sys def getline(): return sys.stdin.readline() def getint(): return int(sys.stdin.readline()) def getints(): return [int(num) for num in getlist()] def getlist(): return sys.stdin.readline().strip().split() n = input() a,b = 0,0 for i in xrange(n): c, d = [int(num) for num in raw_input()...
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
3
n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) a.remove(a[0]) b.remove(b[0]) c=set(a+b) if(len(c)==n): print("I become the guy.") else: print("Oh, my keyboard!")
You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can repl...
3
q=int(input()) while q>0: n=int(input()) a=0 while n>1: if n%5==0: n=(4*n)//5 a=a+1 elif n%3==0: n=(2*n)//3 a=a+1 elif n%2==0: n=(n//2) a=a+1 else: ...
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
a=input() if(ord(a[0])>=97 and ord(a[0])<=122): b=a[0].upper() else: b=a[0] b+=a[1:] print(b)
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It'...
3
li=[int(num) for num in input().split()] n=li[0] m=li[1] a=li[2] u=n/a if n%a!=0: u=int(u) u=u+1 s=m/a if m%a!=0: s=int(s) s=s+1 r=u*s r=int(r) print(r)
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It'...
1
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys def get_num(n, m, a): if n % a == 0: x = n/a else: x = n/a+1 if m % a == 0: y = m/a else: y = m/a+1 return x*y if __name__ == "__main__": str = sys.stdin.readline().strip().split() n = int(str[0]) ...
One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo th...
3
n = int(input()) t = input() l = len(t) m = int(input()) q = {c: [] for c in 'abcdefghijklmnopqrstuvwxyz'} for j, c in enumerate(t): q[c].append(j) q = {c: [i + j for i in range(0, n * l, l) for j in q[c]] for c in q} t = n * list(t) for i in range(m): j, c = input().split() t[q[c].pop(int(j) -...
You are given a board of size n × n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move...
3
t=int(input()) def func1(): n=float(input()) su=0 for i in range(int((n+1)/2)): su+=i**2 su*=8 return(su) for i in range(1,t+1): print(func1())
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not. You are given current year in Berland. Your task is to find how long...
3
a=input() if len(a)==1: print(1) else: p=1 for j in range(1,len(a)): s=str(9-int(a[j]))+'0'*(len(a)-1-j) p+=int(s) print(p)
We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}. Print the number of elements p_i (1 < i < n) that satisfy the following condition: * p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}. Constraints * All values in input are integers. * 3 \leq n \leq 20 * p...
3
n=int(input()) a=list(map(int,input().split())) c=0 for i in range(1,n-1): l=a[i-1:i+2] if a[i]!=max(l) and a[i]!=min(l): c+=1 print(c)
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
def checker(array) -> int: a = array[0] b = array[1] c = array[2] if array.count(1) == 1 and array.index(1) == 0: print((a + b) * c) elif array.count(1) == 1 and array.index(1) == 2: print(a * (b + c)) elif array.count(1) == 1 and array.index(1) == 1: if (a + b) < (b + c)...
There are b boys and g girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and n participants have accepted the invitation. The organizers do not know how many boys and girls are among them. Organizers are preparing red badges for girls and blue ones for boys. Vasya ...
3
'''input 5 6 3 ''' [b, g, n] = [int(input()) for _ in range(3)] print(min(g,n)-(n-min(b,n))+1)
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet. For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name. The second ambiguity is about the Berland s...
3
n = int(input()) l = [] for i in range(n): l.append(list(str(input()))) for i in range(n): for j in range(len(l[i])): if (l[i])[j] == 'u': (l[i])[j] = 'oo' for i in range(n): j = 0 count = 1 while (count != 0): count = 0 for j in range(len(l[i]) - 1): ...
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
#nechet -m, chet -f n=input().split() a=set() c=0 for i in n: a.update(i) for i in a: c+=1 if c%2==0: print('CHAT WITH HER!') else: print('IGNORE HIM!')
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
n =int(input()) count=0 while n>0: if n%10 in [7,4]: count+=1 n//=10 if count>7: count+=1 break if count in [7,4]: print('YES') else: print('NO')
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. <image> The description of the first test case. Since sometimes it's impossible to find such point ...
3
import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) t,=I() for _ in range(t): n,k=I() an=0 if k>n: an=k-n else: an=1 if k%2!=n%2 else 0 print(an)
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y...
3
from collections import Counter s = input() c = Counter(s) cur_char = 'z' for ch in s: while c[cur_char] == 0: cur_char = chr(ord(cur_char) - 1) if ch == cur_char: print(cur_char, end='') c[ch] -= 1
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-di...
3
n = input() k = 0 while len(n) > 1: n = str(sum(map(int, n))) k += 1 print(k)
In some game by Playrix it takes t minutes for an oven to bake k carrot cakes, all cakes are ready at the same moment t minutes after they started baking. Arkady needs at least n cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can bui...
3
import math inputes = list(map(int,input().split())) rownd = math.ceil(inputes[0]/inputes[2]) if rownd == 1: if inputes[1] <= inputes[3] or inputes[1] >= inputes[3] : print('NO') elif rownd > 1: time1 = rownd*inputes[1] time2 = inputes[1]+inputes[3] if time1 > time2: print("YES") ...
n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one ...
3
import sys foo = [int(x) for x in sys.stdin.readline().strip().split(" ")] #print(foo) n, k = foo inp = [int(x) for x in sys.stdin.readline().strip().split(" ")] people = [x for x in range(0, n)] leader = 0 for a in inp: removed_idx = (leader + a) % len(people) print(people[removed_idx] + 1) del people[removed...
Polycarp has an array a consisting of n integers. He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its...
3
n = int(input()) A = list(map(int,input().split())) A.sort() o=[];e=[] for i in range(n): if(A[i]%2): o.append(A[i]) else: e.append(A[i]) if(abs(len(o)-len(e))<2): print(0) else: if(len(o)>len(e)): a = len(o)-len(e)-1;sum = 0 for i in range(a): sum+=o[i] ...
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequenc...
3
from math import log2 c = 0 n = int(input()) a = list(map(int, input().split())) for i in range(n - 1): c += a[i] j = 2 ** int(log2(n - i-1)) + i a[j] += a[i] print(c)
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
n=int(input()) l=list(map(int,input().split())) pro=[] ma=[] pe=[] for i in range(1,n+1): x=l[i-1] if x==1: pro.append(i) if x==2: ma.append(i) if x==3: pe.append(i) mi=min(len(pro),len(ma),len(pe)) print(mi) for i in range(mi): print(pro[i],ma[i],pe[i])
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears. These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh...
3
#question 1st Ichihime and Triangle --> test = int(input()) def solve(): n = list(map(int, input().split())) result = [n[1],n[2],n[2]] print(*result) for x in range(test): solve()
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value ∑_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut...
3
import sys input = sys.stdin.buffer.readline def print(val): sys.stdout.write(str(val) + '\n') for _ in range(int(input().strip())): n,m = map(int,input().split()) if n == 1: print(0) elif n == 2: print(m) else: print(2*m)
Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain. Initially, snowball is at height h and it has weight w. Each second the following sequence of events happens: snowball's weights increases by i,...
3
l = list(map(int,input().split())) s1 = list(map(int,input().split())) s2 = list(map(int,input().split())) w,h = l[0],l[1] u1,h1 = s1[0],s1[1] u2,h2 = s2[0],s2[1] while(h>0): w+=h if(h==h1): w-=u1 if(w<0): w=0 if(h==h2): w-=u2 if(w<0): w=0 h-=1 print(w)
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
n=int(input()) l=list(map(int, input().split())) ce=[] co=[] for i in l: if i&1==0: ce.append(i) else: co.append(i) if len(ce)==1: print(l.index(ce[0])+1) if len(co)==1: print(l.index(co[0])+1)
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves. We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m...
1
n = int(raw_input()) boy = map(int,raw_input().split()) boy.sort() m = int(raw_input()) girl = map(int,raw_input().split()) girl.sort() ans = 0 i = 0 j = 0 while i < n and j < m: if boy[i] - girl[j] in range(-1,2): ans = ans + 1 i = i + 1 j = j + 1 elif boy[i] > girl[j]: j = j + ...
Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on. When a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if i-th garland is switched on during x-th secon...
3
import os import sys from io import BytesIO, IOBase import math from queue import Queue import collections import itertools import bisect import heapq # sys.setrecursionlimit(100000) # ^^^TAKE CARE FOR MEMORY LIMIT^^^ import random def main(): pass BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 de...
A group of people played a game. All players had distinct scores, which are positive integers. Takahashi knows N facts on the players' scores. The i-th fact is as follows: the A_i-th highest score among the players is B_i. Find the maximum possible number of players in the game. Constraints * 1 \leq N \leq 10^5 * 1...
3
N = int(input()) L = [] for i in range(N): l,r = map(int,input().split()) L.append((l,r)) L.sort() print(L[-1][1]+L[-1][0])
Petya loves computer games. Finally a game that he's been waiting for so long came out! The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is...
3
import sys import math n, k = map(int, input().split()) a = list(map(int, input().split())) ans = 0; rems = [] for i in range(n): ans += a[i] // 10 rem = a[i] % 10 if rem != 0: rems.append(10 - rem) a[i] += 10 - rem rems.sort() for i in range(len(rems)): if k >= rems[i]: ans...
Let f(x) be the sum of digits of a decimal number x. Find the smallest non-negative integer x such that f(x) + f(x + 1) + ... + f(x + k) = n. Input The first line contains one integer t (1 ≤ t ≤ 150) — the number of test cases. Each test case consists of one line containing two integers n and k (1 ≤ n ≤ 150, 0 ≤ k ...
3
import io import os from math import gcd # See: https://codeforces.com/blog/entry/79277?#comment-650324 def f(x): # Sum of digits of x return sum(int(d) for d in str(x)) def getParams(d, K): # Given starting ones place of x and K, return sum of ones place in the K+1 terms and how many of them will over...
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
a=input() d=int(a[0] == 'a' or a[0] == 'h') + int(a[1] == '1' or a[1] == '8') if d == 0 : print(8) elif d == 1 : print(5) else : print(3)
A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring. You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Res...
3
import sys n = int(input()) a=[] for i in range(n): a.append([j for j in input()]) b=[] for i in range(n): b.append({}) for j in a[i]: if j in b[i]: print('NO') sys.exit() b[i][j]=1 c=[-1 for i in range(26)] d=[-1 for i in range(26)] e=[0 for i in range(26)] for word in a: l=ord(word[0])-97 e[l]=1 for...
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
word=input() low=up=0 for i in range(1,27): up+= word.count(chr(i+64)) low+= word.count(chr(i+96)) if up>low: print(word.upper()) else: print(word.lower())
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()) arr = [] string =[] count = 0 for i in range(n): arr.append(str(input())) for j in range(len(arr)): s = arr[j] if s.count(str(1))>=2: count +=1 print(count)
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i. Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if ...
3
test = int(input()) while test : n = int(input()) arr = list(map(int,input().split())) res = 0 mn = arr[-1] for i in range (n - 1, -1, -1): if arr[i] > mn : res += 1 else : mn = arr[i] print (res) test -= 1 # for _ in[0]*int(input()): # input();m=1e7;r=0 # for x in[*map(int,input().split())][...
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string s = s_1 s_2 ... s_{n} of length n where each letter is either R, S or P. While initializing, the bot is choosing a starting index pos (1 ≤ pos ≤ n), and then it can play any numbe...
3
for _ in range(int(input())): s = input() n = len(s) r = s.count('R') p = s.count('P') si = s.count('S') m = max(r, p, si) if(r==m): print('P'*(n)) elif(p==m): print('S'*(n)) else: print('R'*(n))
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change). In a prototype progr...
3
for _ in range(int(input())): a, b, n = map(int, input().split()) ctr = 0 while(a <= n and b <= n): # print(a, b) if a < b: a = a + b ctr += 1 continue else: b = a + b ctr += 1 continue print(ctr)
There are K pieces of cakes. Mr. Takahashi would like to eat one cake per day, taking K days to eat them all. There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i. Eating the same type of cake two days in a row would be no fun, so Mr. Takahashi would like to decide the order for eating ...
3
K, T = [int(_) for _ in input().split()] A = [int(_) for _ in input().split()] print(max(2 * max(A) - sum(A) - 1, 0))
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf...
3
# # Author: eloyhz # Date: Sep/11/2020 # # # # if __name__ == '__main__': n = int(input()) encoded = input() prefix = True decoded = '' start = 0 if n % 2 == 1: decoded = encoded[0] start = 1 for i in range(start, n): if prefix: decoded = encoded[i] + de...
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars. Each player can double his bid any number of times and triple his bid any number of ...
3
n = int(input()) input_list = list(map(int,input().split())) for i in range(n): x = input_list[i] while x%2==0: x = x//2 while x%3==0: x = x//3 input_list[i] = x if(input_list.count(input_list[0]) == n): print("Yes") else: print("No")
You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements? Input The first line contains an integer n (1 ≤ n ≤ 1000), where 2n is the number of elements in the array a. The second line contains 2n space-separat...
3
n = int(input()) d = [int(i) for i in input().split()] a = set(d ) if len(a)>1: print(' '.join([str(i) for i in sorted(d)])) else: print(-1)
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the...
3
n = int(input()) a = [int(i) for i in input().split()] a.sort() same = 1 while same < 3 and a[2 - same] == a[2]: same += 1 cnt = 1 i = 3 if same == 1: while i < n and a[i] == a[2]: cnt += 1 i += 1 if same == 2: while i < n and a[i] == a[2]: cnt += same same += 1 i +=...
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
n, k = [int(x) for x in input().split()] for _ in range(k): if n % 10 == 0: n /= 10 else: n -= 1 print(int(n))
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b. Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ...
3
t = 1 #t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) d = {} e = {} for i, k in enumerate(a): d[k] = i for i, k in enumerate(b): e[k] = i l =[] for i in a: k = d[i] - e[i] if k<0: k+=n #print(k, d[i], e[i]) l.append...
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
number = input() number = int(number) for i in range(number): Ebarat = input() a = len(Ebarat) if a<=10: print(Ebarat) else: print(Ebarat[0],end="") print(a-2,end="") print(Ebarat[a-1])
Consider sequences \\{A_1,...,A_N\\} of length N consisting of integers between 1 and K (inclusive). There are K^N such sequences. Find the sum of \gcd(A_1, ..., A_N) over all of them. Since this sum can be enormous, print the value modulo (10^9+7). Here \gcd(A_1, ..., A_N) denotes the greatest common divisor of A_1...
3
mod = 10 ** 9 + 7 N, K = map(int, input().split()) A = [0] + [pow(K // x, N, mod) for x in range(1, K + 1)] for x in reversed(range(1, K + 1)): for i in range(2, K // x + 1): A[x] -= A[i * x] print(sum(i * a for i, a in enumerate(A)) % mod)
Write a program which judges wheather given length of three side form a right triangle. Print "YES" if the given sides (integers) form a right triangle, "NO" if not so. Constraints * 1 ≤ length of the side ≤ 1,000 * N ≤ 1,000 Input Input consists of several data sets. In the first line, the number of data set, N is...
3
N=int(input()) a=[0,0,0] for i in range(N): a[0],a[1],a[2] = map(int, input().split()) a.sort() if a[0]**2+a[1]**2 == a[2]**2: print("YES") else: print("NO")
In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states: In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the sq...
3
from math import sqrt n = int(input()) a = 1 b = 1 count = 0 for a in range(1, n+1): # print('') for b in range(a, n+1): # print(a, b) c = sqrt(a**2 + b**2) cint = int(c) if c==cint and c<=n: count += 1 print(count)
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin...
3
m,n=map(int,input().split(" ")) k=(m+1)//2 if n<=k: print(2*n-1) else: print(2*(n-k))
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not. You are given current year in Berland. Your task is to find how long...
3
n = input() print(((int(n[0]) + 1) * 10 ** (len(n) - 1)) - int(n))
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
import bisect def solve(a,s): if sum(s)==b: return "YES" else: return "NO" pass t = int(input()) ans = [] for i in range(t): #n = int(input()) arr = [int(x) for x in input().split()] a = arr[0] b = arr[1] s = [int(x) for x in input().split()] #grid = [] #for j i...
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k ≥ 0. The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied: * The length of s is 1, and it consists of the character c (i.e. s_1=c); * The lengt...
3
def pizda(x,y,z): if len(s[x:y])<=1: if ord(s[x:y])!=z: return(1) else: return(0) else: a = s[x:(x+y)// 2] b = s[(x+y) // 2:y] a1 = 0 b1 = 0 for i in range(len(a)): if ord(a[i]) != z: a1 += 1 ...
You are given an integer number n. The following algorithm is applied to it: 1. if n = 0, then end algorithm; 2. find the smallest prime divisor d of n; 3. subtract d from n and go to step 1. Determine the number of subtrations the algorithm will make. Input The only line contains a single integer n (2 ≤...
3
# @author Nayara Souza # UFCG - Universidade Federal de Campina Grande # AA - Basico n = int(input()) count = 0 i = 2 if n % 2 == 0: print(n//2) else: x = 0 while i * i <= n: if n % i == 0: x = ((n - i) // 2) + 1 break i += 1 if x == 0: print(1) els...
Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: * for the array [0, 0, 1, 0, 2] MEX equals to 3 because numbers 0, 1 and 2 are presented in the array and 3 is the minimum non-negative integer not presented in the array; * for the array [1, 2, 3, 4] MEX eq...
3
import os from io import BytesIO, IOBase import sys from collections import defaultdict, deque, Counter from bisect import * from math import sqrt, pi, ceil, log, inf,gcd from itertools import permutations from copy import deepcopy from heapq import * from sys import setrecursionlimit def main(): q, x = map(int, in...
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
3
k=input() l=input() ans='' for i in range (0,len(k)): if(k[i]!=l[i]): ans=ans+'1' else: ans=ans+'0' print(ans)
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve...
3
n, m = [int(x) for x in input().split()] days = 0 while (n > 0): days += 1 n -= 1 if days % m == 0: n += 1 print(days)
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
x = int(input()) if x==2 or x%2!=0: print('NO') else: print('YES')
Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example, * f(599) = 6: 599 + 1 = 600 → 60 → 6; * f(7) = 8: 7 + 1 = 8; * f(9) = 1: 9 + 1 = 10 → 1; * f(10099) = 101: 10099 + 1 = 10100 → 1010 → 101. ...
3
def f(x): x+=1 while(x%10==0): x//=10 return(x) a=list() n=int(input()) while(n not in a): a.append(n) n=f(n) print(len(a))
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken. CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly th...
3
n = int(input()) for i in range(n): t = int(input()) if t % 3 == 0: print('YES') elif t % 3 == 1: if t >= 7: print('YES') else: print('NO') else: if t >= 14: print('YES') else: print('NO')
You need to find if a number can be expressed as sum of two perfect powers. That is, given x find if there exists non negative integers a, b, m, n such that a^m + b^n = x. Input First line of the input contains number of test cases T. It is followed by T lines, each line contains a sinle number x. Output For each te...
1
a=[] for i in range(2,1000): for j in range(2,21): p=i**j if(p>1000000): break a.append(p) a.append(1) x=input(); for i in range(1,x+1): y=input() f=0 d=0 for f in range(0,len(a)): if y-a[f] in a: print "Yes" d=2 break...
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks. Determine whether the Cossack can reward all participants, giving each of them at leas...
3
n,m,k = [int(c) for c in input().split()] if (n <= m and n <= k): print("Yes") else: print("No")
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ...
1
n = input() l = {} for i in range(n): name = raw_input() if name in l: print('YES') else: print('NO') l[name] = '1'
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
x=int(input()) o=0 for _ in range(x): y=list(map(int,input().split())) c=y.count(1) if c>=2: o+=1 print(o)
There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights. <image> Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1] Polycarpus has bought a posh piano...
1
n, k = map(int, raw_input().split()) s = [0]*(n+2) a = map(int, raw_input().split()) res = 10**10 pres = 0 for i in xrange(1, n + 1, 1): s[i] = s[i-1] + a[i-1] for i in xrange(k, n + 1, 1): tmp = s[i] - s[i-k] if tmp < res: res = tmp pres = i - k + 1 print pres
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
def abc(s): if(len(s)>10): r=len(s)-2 return (s[0]+str(r)+s[-1]) return s t=int(input()) for i in range(t): x=input() print(abc(x))
During one of the space missions, humans have found an evidence of previous life at one of the planets. They were lucky enough to find a book with birth and death years of each individual that had been living at this planet. What's interesting is that these years are in the range (1, 10^9)! Therefore, the planet was na...
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.writabl...
"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him. The sequence of n integers is calle...
1
'''input 5 5 3 3 3 1 ''' from collections import Counter n = input() arr = map(int,raw_input().split()) c = Counter(arr) ans = 0 for i in c: if i >= 1 and i <= n: ans += (c[i]-1) else: ans += (c[i]) print ans
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations. You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers. Input The first line of the input con...
3
import math s1=input() s2=input() s3=input() s4=input() dx=int(s1.split(" ")[0]) bx=int(s1.split(" ")[1]) dy=int(s3.split(" ")[0]) by=int(s3.split(" ")[1]) x=0 y=0 for i in range(0,dx): x=x+int(s2.split(" ")[i])*(bx**(dx-1-i)) for i in range(0,dy): y=y+int(s4.split(" ")[i])*(by**(dy-1-i)) if x<y: print("<")...
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
length=int(input()); word=input(); word=word.upper() temp=0 for each in range(65, 91): each=chr(each) if(each not in word): temp+=1 if(temp>0): print("NO") else: print("YES")
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not. A substring s[l … r] (1 ≤ l ≤ r ≤ |s|) of a string s = s_{1}s_{2} … s_{|s|} is the string s_...
1
import itertools import sys ans = 0 def c(s): s_len_half = len(s) / 2 s_len = len(s) for j in range(s_len_half, 0, -1): if s[j-1] == s[s_len-j]: j -= 1 continue else: return False return True s = raw_input() if len(set(s)) == 1: print 0 sys.exit() for i in range(len(s)-1, -1, -1): temp = list(ite...
Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 peo...
3
n,a,b=map(int,input().split(' ')) l=list(map(int,input().split(' '))) l.sort() print(max(sum(l[-a:])/a + sum(l[-a-b:-a])/b,sum(l[-b:])/b + sum(l[-a-b:-b])/a))
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
3
events=int(input()) e=[int(i) for i in input().split()] police=0 c=0 for i in e: if i>0: police+=i else: if police!=0: police-=1 else: c+=1 print(c)
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
3
n=int(input()) print((n%100)//20+(n%20)//10+(n%10)//5+(n%5)+(n//100))
Niwango-kun is an employee of Dwango Co., Ltd. One day, he is asked to generate a thumbnail from a video a user submitted. To generate a thumbnail, he needs to select a frame of the video according to the following procedure: * Get an integer N and N integers a_0, a_1, ..., a_{N-1} as inputs. N denotes the number of t...
1
import sys from collections import deque import copy def get_read_func(fileobject): if fileobject == None : return raw_input else: return fileobject.readline def main(): if len(sys.argv) > 1: f = open(sys.argv[1]) else: f = None read_func = get_read_func(f); in...
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
import math a, b = [int(x) for x in input().split()] while a != 0 and b != 0: x = int(math.log(a, 2)) y = int(math.log(b, 2)) if x != y: break a = a & (~(1 << x)) b = b & (~(1 << y)) if a == 0 and b == 0: print(0) else: if b > a: a, b = b, a x = int(math.log(a, 2)) + 1...
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ...
3
# Author : -pratyay- import sys inp=sys.stdin.buffer.readline inar=lambda: list(map(int,inp().split())) inin=lambda: int(inp()) inst=lambda: inp().decode().strip() wrt=sys.stdout.write pr=lambda *args,end='\n': wrt(' '.join([str(x) for x in args])+end) enum=enumerate inf=float('inf') cdiv=lambda x,y: (-(-x//y)) # Am I ...
You are given a string s consisting only of lowercase Latin letters. You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it. Let's call a string good if it is not a palindrome. Palindrome is...
3
from collections import Counter t = int(input()) for i in range(t): a = input() c = Counter(a) if len(c) == 1: print(-1) else: if a != a[::-1]: print(a) else: l = len(a) print(a[:l//2]+a[l//2+1:]+a[l//2] if l % 2 else a[:l//2-1]+a[l//2+1:]+a[l/...
There are N rabbits, numbered 1 through N. The i-th (1≤i≤N) rabbit likes rabbit a_i. Note that no rabbit can like itself, that is, a_i≠i. For a pair of rabbits i and j (i<j), we call the pair (i,j) a friendly pair if the following condition is met. * Rabbit i likes rabbit j and rabbit j likes rabbit i. Calculate ...
3
N=int(input()) *A,=map(int, input().split()) A=[-1]+A ans=0 for i in range(1,N+1): j=A[i] if j>i and A[j]==i: ans+=1 print(ans)