problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a ≠ b) will indulge if:
1. gcd(a, b) = 1 or,
2. a divides b or b d... | 3 | import math
for _ in range(int(input())):
n=int(input())
for i in range(n):
print((2*n)+(i*2),end=" ")
print()
|
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... | 1 | a = int(raw_input())
b = int(raw_input())
c = int(raw_input())
s1= a + b +c
s2 = a*b + c
s3 = a + b*c
s4 = a*b*c
s5 = (a + b)*c
s6 = a*(b+c)
print max(s1,s2,s3,s4,s5,s6)
|
You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1).
For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1... | 3 | # @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-08-15 10:37
# @url:https://codeforc.es/contest/1398/problem/C
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio
BUFSIZE = 8192
BUFSIZE = 8192
class Fast... |
Snuke has N strings. The i-th string is s_i.
Let us concatenate these strings into one string after arranging them in some order. Find the maximum possible number of occurrences of `AB` in the resulting string.
Constraints
* 1 \leq N \leq 10^{4}
* 2 \leq |s_i| \leq 10
* s_i consists of uppercase English letters.
In... | 3 | N,*L = open(0).read().split()
ans = 0
a = 0
b = 0
c = 0
for s in L:
for j in range(len(s)-1):
if s[j]=='A' and s[j+1]=='B':
ans += 1
if s[-1]=='A' and s[0]=='B':
c += 1
elif s[-1]=='A':
a += 1
elif s[0]=='B':
b += 1
if c!=0:
if a+b>0:
ans += c+min(a,b)
else:
ans += c-1
else:
... |
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | 3 | for _ in range(int(input())):
N=int(input())
A=list(input())
B=list(input())
countlist=[]
countlistB=[]
count=1
for i in range(1,N):
if(A[i]!=A[i-1]):
countlist.append(count)
count=1
else:
count+=1
countlist.append(count)
countB=1
... |
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... | 1 | s=raw_input()
cu=0
cl=0
t=len(s)
for i in range(t):
if s[i].isupper()==True:
cu=cu+1
else:
cl=cl+1
if cu>cl:
print s.upper()
else:
print s.lower() |
Given are positive integers A and B.
Let us choose some number of positive common divisors of A and B.
Here, any two of the chosen divisors must be coprime.
At most, how many divisors can we choose?
Definition of common divisor
An integer d is said to be a common divisor of integers x and y when d divides both x a... | 3 | from math import gcd
A, B = map(int, input().split())
m = gcd(A, B)
#print(m)
num = int(m**0.5) #mに対する素因数分解は、int(√m)の場合を調べればよい
ans = 1
for i in range(2,num+1):
if m%i:
continue
ans += 1
while not m%i:
m /= i
if m>1:
ans+=1 #m+1が素因数の場合がある
print(ans) |
We have a board with a 2 \times N grid. Snuke covered the board with N dominoes without overlaps. Here, a domino can cover a 1 \times 2 or 2 \times 1 square.
Then, Snuke decided to paint these dominoes using three colors: red, cyan and green. Two dominoes that are adjacent by side should be painted by different colors... | 3 | n = int(input())
s = input()
t = input()
ans = 1
mod = 10**9+7
bef = True
skip = -1
for i in range(n):
if skip == i:
continue
if i == 0:
if s[i] == t[i]:
ans *= 3
else:
ans *= 6
elif bef:
ans *= 2
else:
if s[i] != t[i]:
ans *= 3
if s[i] == t[i]:
bef = True
else:
... |
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())
l=[0]*n
t=0
for i in range(n):
p=input().split(' ')
for k in range(len(p)):
if p[k]=='1':
l[i]=l[i]+1
for i in range(len(l)):
if l[i]>=2:
t=t+1
print(t)
|
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 3 | a1 , a2 , a3 , a4 = input().split()
a1 , a2 , a3 , a4 = int(a1) , int(a2) , int(a3) , int(a4)
s = input()
sum = 0
for i in s:
i = int(i)
if i == 1:
sum+=a1
elif i == 2:
sum+=a2
elif i == 3:
sum+=a3
else:sum+=a4
print(sum) |
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 | def main():
number = input()
ans = 0
for digit in number:
if digit in ['4', '7']:
ans += 1
if ans in [4, 7]:
print("YES")
else:
print("NO")
if __name__ == "__main__":
main() |
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | t = int(input())
for _ in range(t):
arr = list(map(int, input().split()))
maxm = max(arr)
minm = min(arr)
if arr.count(maxm) < 2:
print('NO')
else:
print('YES')
print(minm, minm, maxm) |
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.... | 1 | a=int(raw_input())
c=0
while(a!=0):
b=raw_input()
b=b.split()
if b.count('1')>1:
c=c+1
a=a-1
print c
|
Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'.
Constraints
* 1 ≤ H ≤ 300
* 1 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero)... | 3 | while True:
h, w = map(int, input().split())
if h==w==0:
break
for _ in range(h):
print('#'*w)
print()
|
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | for tc in range(int(input())):
lis = [int(i) for i in input().split()]
lis.sort()
if lis[1] == lis[2]:
print("YES")
print(lis[0], lis[0], lis[1])
else:
print("NO") |
Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one.
In school, where Noora is studying, teachers are putting down marks to the online class register, wh... | 3 | n,k = map(int,input().split())
arr = list(map(int,input().split()))
avg = 0
count = 0
i = 0
while(True):
avg = sum(arr)/(n+i)
avg = avg + 0.5
avg = str(avg)
x = avg.find(".")
avg = avg[:x]
avg = int(avg)
i+=1
if avg == k:
break
if avg!=k:
arr.append(k)
count+=... |
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 | k = int(input())
for i in range(k):
n= int(input())
two=three=five=0
while n%2==0:
n=n//2
two+=1
while n%3==0:
n=n//3
three+=1
while n%5==0:
n=n//5
five+=1
if n!=1:
print(-1)
else:
print(two+three*2+five*3)
|
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 ... | 3 | input()
a=input().split()
b=c=0
for i in a:
if i=='5':b+=1
else:c+=1
if c==0:print(-1)
elif b<9:print(0)
else:print('5'*((b//9)*9)+'0'*c) |
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 | a,b,c,d=map(int,input().split())
e=max(a,b,c,d)
if e==a:
print(a-b,a-c,a-d)
elif e==b:
print(b-a,b-c,b-d)
elif e==c:
print(c-b,c-a,c-d)
elif e==d:
print(d-b,d-c,d-a) |
Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.
Consider two infinite sets of numbers. The first set consists of odd positive numbers (1, 3, 5, 7, …), and the second set consists of even posi... | 3 | import getpass
import sys
if getpass.getuser() != 'frohenk':
filename = 'half'
# sys.stdin = open('input.txt')
# sys.stdout = open('output.txt', 'w')
else:
sys.stdin = open('input.txt')
# sys.stdin.close()
import math
import string
import re
import math
import random
from decimal import Decimal, g... |
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them.
For example, if the... | 3 | t=int(input())
for i in range(t):
a=input()
a='0'+a
ki=-1
c=[]
for k in range(len(a)):
if a[k] == '0':
if k-1>=0 and a[k-1]=='0':
continue
else:
c.append(0)
ki+=1
else:
c[ki]+=1
c.sort(reverse=Tru... |
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surfac... | 1 | #!/usr/bin/env python
from sys import stdin, stderr
def main():
H, L = map(int, stdin.readline().split())
A = (H*H - L*L)/(-2.0*H)
print('%.10f' % A)
return 0
if __name__ == '__main__': main()
|
After lessons Nastya decided to read a book. The book contains n chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.
Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number k as the fi... | 3 | n = int(input())
a = []
for i in range(n):
l = list(input().split())
q = [int(i) for i in l]
a.append(q)
k = int(input())
for j in range(n):
if a[j][0] <= k <= a[j][1]:
print(n - j)
break |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | num_coor, list_a= int(input("")), []
x = y = z = 0
dic = dict()
for num in range(num_coor):
dic[f"{num}"] = list(map(int, input("").split()))
for attr in range(len(dic.keys())):
x += dic[f"{attr}"][0]
for attr in range(len(dic.keys())):
y += dic[f"{attr}"][1]
for attr in range(len(dic.keys())):
z += dic... |
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6.
Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task!
Each digit c... | 3 | a,b,c,d=map(int,input().split())
# 2 3 5 6
y=min(a,c,d)
print(min(b,a-y)*32+y*256)
|
A palindrome is a string t which reads the same backward as forward (formally, t[i] = t[|t| + 1 - i] for all i ∈ [1, |t|]). Here |t| denotes the length of a string t. For example, the strings 010, 1001 and 0 are palindromes.
You have n binary strings s_1, s_2, ..., s_n (each s_i consists of zeroes and/or ones). You ca... | 3 | for i in range(int(input())):
n=int(input())
b,g,o=0,0,0
for i in range(n):
s=input()
if len(s)%2: o+=1
if s.count('0')%2==0: g+=1
else: b+=1
if o==0 and b%2: n-=1
print(n)
|
You are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates.
You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:
* Move the chip i by 2 to the left or 2 to the right for free (i.e. replace... | 3 | n=int(input())
arr=list(map(int, input().split()))
l=[0]*101
for i in arr:
l[i%100]+=1
s1, s2=0,0
for i in range(len(l)):
if i%2:
s1+=l[i]
else:
s2+=l[i]
print(min(s1, s2))
|
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills).
So, about the teams. Firstly, these two teams should have the s... | 3 | t = int(input())
for _ in range(t):
n = int(input())
l = list(map(int,input().split()))
s1,s2 = set(), set()
d = dict()
for i in l:
if i in d:
d[i] += 1
else:
d[i] = 1
nd = sorted(d.items(), key = lambda x: {x[1],x[0]})
for i in range(len(nd)):
... |
Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:
* on Mondays, Thursdays and Sundays he eats fish food;
* on Tuesdays and Saturdays he eats rabbit stew;
* on other days of week he eats chicken stake.
Polycarp plans to go on a trip and already pa... | 3 | l=list(map(int,input().rstrip().split()))
g=min(l[0]//3,l[2]//2,l[1]//2)
l[0]-=3*g
l[1]-=2*g
l[2]-=2*g
ans=7*g
p=[0,1,2,0,2,1,0]
maxi=0
#print(ans)
for i in range(7):
l1=[]
l1=l1+l
loval=0
for j in range(7):
if l1[p[(i+j)%7]]>0:
l1[p[(i+j)%7]]-=1
loval+=1
... |
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());l=[int(i) for i in input().split()]
print(l[0],end="")
x=l[0]
for i in range(1,n):
print(" ",x+l[i],end="")
if x+l[i]>x:
x=l[i]+x |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | s=input()
n=len(s)
j=0
x=0
for i in range(1,n):
if s[i-1]==s[i]:
x=x+1
else:
x=0
if x==6:
j=1
if j==1:
print('YES')
else:
print('NO') |
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi... | 1 | n=input()
if n%2==0:
x=n/2
print x
#li=[]
s=''
for i in range(1,x+1):
s=s+' '+'2'
# li=li+['2']
# delimiter=' '
# s=delimiter.join(li)
print s[1:]
else:
x=n/2
print x
s=''
#li=[]
for i in range(1,x):
s=s+' '+'2'
# li=li+[... |
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.
Input
The first and the single line contains three space-separated integers — the areas of the parallelepi... | 3 | a,b,c = input().split()
a=int(a)
b=int(b)
c=int(c)
m=max(a,b,c)
for i in range(1,m+1):
if(a%i==0 and b%i==0):
x=a//i
y=b//i
if(x*y==c):
print(4*(x+y+i))
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | #if all letters of a word are uppercase -> consider that a word has been typed with the Caps lock key
#if all letters of a word except the first one are uppercase -> consider that a word has been typed with the Caps lock key
#word="AB"
word=input()
#if the first letter of the word is lower-case when all other letter... |
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their h... | 3 | N = int(input())
R = input().split()
r = [int(i) for i in R]
M = max(r)
m = min(r)
i = 0
for i in range(len(r)):
if r[i] == M:
s = i
del r[i]
break
r.reverse()
r.append(M)
q = 0
for q in range(len(r)):
if r[q] == m:
d = q
break
print(s+d) |
Entrance Examination
The International Competitive Programming College (ICPC) is famous for its research on competitive programming. Applicants to the college are required to take its entrance examination.
The successful applicants of the examination are chosen as follows.
* The score of any successful applicant is ... | 3 | while True:
m, n_min, n_max = map(int, input().split())
if m == 0 and n_min == 0 and n_max == 0:
break
P = [int(input()) for _ in range(m)]
ans = [0, 0]
for i in range(n_min, n_max+1):
# print("i: {}, P[i-1]: {}, P[i]: {}".format(i, P[i-1], P[i]))
ans[0] = max(P[i - 1] - P[i]... |
Arpa is taking a geometry exam. Here is the last problem of the exam.
You are given three points a, b, c.
Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c.... | 3 | ax, ay, bx, by, cx, cy = map(int, input().split())
a = (bx - ax, by - ay)
da = a[0] ** 2 + a[1] ** 2
b = (cx - ax, cy - ay)
db = b[0] ** 2 + b[1] ** 2
c = (cx - bx, cy - by)
dc = c[0] ** 2 + c[1] ** 2
if ((cx - ax) * (by - ay) == (cy - ay) * (bx - ax)) or da != dc:
print("No")
else:
print("Yes")
|
A and B are preparing themselves for programming contests.
An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solvi... | 3 |
a,b=map(int,input().split())
big=max(a,b)
small=min(a,b)
if big>=2*small :
print(small)
else:
print((big+small)//3)
|
Two players decided to play one interesting card game.
There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a... | 3 | t = int(input())
for i in range(t):
n, k, p = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
if max(a) > max(b):
print('YES')
else:
print('NO')
|
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 | import sys
data = sys.stdin.read().splitlines()
string = data[0].lower()
vowels = set(['a', 'o', 'y', 'e', 'u', 'i'])
novowels = [x for x in string if x not in vowels]
print('.' + '.'.join(novowels))
|
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the pl... | 3 | x = input()
map_ = {}
for ele in x:
if ele in map_:
map_[ele] +=1
else:
map_[ele] = 1
c = 0
for ele in map_:
if map_[ele]%2!=0:
c+=1
if c<=1:
print("First")
else:
if c%2 == 0:
print("Second")
else:
print("First") |
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.
The slogan of the company consists of n characters, so the decorators hung a lar... | 3 | n,k=map(int,input().split())
s=input()
# print(s[2:3])
if k>n//2:
s=s[::-1]
for i in range(n-k):
print("RIGHT")
print("PRINT",s[0:1])
for i in range(1,n):
print("LEFT")
print("PRINT",s[i:i+1])
elif k==1:
print("PRINT",s[0:1])
for i in range(1,n):
print("RIGHT")
print("PRINT",s[i:i+1])
else:
for i in ra... |
zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.
zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this tas... | 3 | st = input()
x = 'abcd'
elem = st[0]
for i in range(1, len(st)):
if st[i] == elem[i - 1]:
j = 0
while x[j] == elem[i - 1] or (i + 1 < len(st) and x[j] == st[i + 1]):
j += 1
elem += x[j]
else:
elem += st[i]
print(elem) |
As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of ... | 3 | from collections import OrderedDict
n,m = map(int,input().split())
t=n
md1 = OrderedDict()
while(n):
s = input().split()
md1[s[1]] = s[0]
n-=1
while(m):
s1 = input().split()
s3 = s1[1][:-1]
keys = md1.keys()
#print(s3)
#print(keys)
if(s3 in keys):
#print("YES")
print(... |
Ayush and Ashish play a game on an unrooted tree consisting of n nodes numbered 1 to n. Players make the following move in turns:
* Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to 1.
A tree... | 3 | from sys import stdin
from math import sqrt,gcd
from collections import deque
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
lcm=lambda x,y:(x*y)//gcd(x,y)
hg=lambda x,y:((y+x-1)//x)*x
for _ in range(I()):
n,x=R()
v=[[] for i in range(n+1)]
for i in range(n... |
You are given an integer sequence 1, 2, ..., n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is minimum possible.
The value |x| is the absolute value of x and sum(S) is the sum of elements of the set S.
Input
The first line of the input ... | 3 | import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy
sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in s... |
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
* At least one participant should get a dip... | 3 | input()
a = list(map(int, input().split()))
print(len(set(a)) - 1 if 0 in a else len(set(a)))
# HaPpY NoWrUz 1398
# UBCF
# CodeForcesian
# ashegham
|
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536...
Your task is to print the k-th digit of this sequence.
Input
The first and only lin... | 3 | k=int(input())
i=0
r=1
while(k>=r):
r+=9*(i+1)*10**i
i+=1
r=r-(9*i*10**(i-1))
ans=str(((k-r)//i)+10**(i-1))[(k-r)%i]
print(ans) |
You are given a text of single-space separated words, consisting of small and capital Latin letters.
Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.
Calculate the volume of the given text.
Input
The first line contains one integer number n ... | 1 | import sys
if __name__ == '__main__':
numOfCharacters = int(sys.stdin.readline())
words = []
while (numOfCharacters > 0):
lineOfWords = sys.stdin.readline()
words = [x for x in lineOfWords.split()]
numOfCharacters = numOfCharacters - len(lineOfWords)
maxV = 0;
for word ... |
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r... | 3 | t = int(input())
for _ in range(t) :
n = int(input())
bookshelf = list(map(int, input().split()))
if sum(bookshelf) == 1 :
print(0)
else :
start = -1
end = -1
onecount = bookshelf.count(1)
tempcount = 0
answer = 0
for i in range... |
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the re... | 3 | n = input()
z = 0
tuplas = list()
for i in range(int(n)):
x = input()
x = x.split(" ")
t = [x[0], x[1]]
a = 0
if i == 0:
tuplas.append(t)
continue
for tup in tuplas:
if x[0] == tup[1]:
tup[1] = x[1]
a = 1
break
if a == 0:
tu... |
Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1, 2, ..., n} is such function <image>, that for any <image> the formula g(g(x)) = g(x) holds.
Let's denote as f(k)(x) the function f applied k times to the value x. More formally, f(1)(x) = f(x), f(k)(x) = f(f(k - 1)(x))... | 3 | from math import gcd
n = int(input())
f = list(map(int,input().split()))
vis = [0 for i in range(n)]
cyc = [False for i in range(n)]
dp = [0 for i in range(n)]
def dfs(u):
if vis[u] == 2:
return -1
if vis[u] == 0:
vis[u] = 1
ret = dfs(f[u])
vis[u] = 2
return ret
if v... |
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | n = int(input())
p = list(map(int, input().split()))
pcop = p
for i in range(len(pcop)):
print(p.index(i + 1) + 1)
|
You are given a sequence of integers of length n and integer number k. You should print any integer number x in the range of [1; 10^9] (i.e. 1 ≤ x ≤ 10^9) such that exactly k elements of given sequence are less than or equal to x.
Note that the sequence can contain equal elements.
If there is no such x, print "-1" (w... | 3 | n,k = map(int,input().split())
lst = list(map(int,input().split()))
lst.sort()
if k == n:
print(lst[-1])
elif k==0:
t = lst[0]-1
print(-1 if t<1 else t)
elif lst[k-1] == lst[k]:
print(-1)
else:
print(lst[k-1]) |
One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile:
<image> By the pieces lay a large square wooden board. The board is divided into n^2 cells arranged into n ... | 3 | n=int(input())
f=[['#']*(n+2)]
a=f+[[*('#'+input()+'#')]for _ in range(n)]+f*2
for i in range(1,n+1):
for j in range(1,n+1):
if a[i][j]=='.':
for k,l in (1,-1),(1,0),(1,1),(2,0):
if a[i+k][j+l]<'.':print('NO');exit()
a[i+k][j+l]='#'
print('YES') |
Vasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars.
Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles.
I... | 3 | n=int(input())
a=int(input())
b=int(input())
bigger = max(a,b)
smaller = min(a,b)
if (a==b) and (n%a != 0):
print('NO')
exit()
for i in range(n//bigger+1):
if (n-bigger*i)%smaller==0:
print('YES')
Ber_Cola=i
Bars_bar=(n-bigger*i)//smaller
if (b > a): Ber_Cola, Bars_bar = B... |
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
a1, a2, ..., an → an, a1, a2, ..., an - 1.
Help Twi... | 3 | a=int(input())
s=[int(i) for i in input().split()]
i=0
c=0
if sorted(s)==s:
print(0)
else:
if s[-1]>s[0]:
print(-1)
else:
while(s[i+1]>=s[i]):
i+=1
for j in range(i+1,len(s)-1):
if s[j+1]<s[j]:
break
else:
c+=1
... |
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:
* f(0) = a;
* f(1) = b;
* f(n) = f(n-1) ⊕ f(n-2) when n > 1, where ⊕ de... | 3 | t=int(input())
for i in range(t):
a,b,n=map(int,input().split())
k=0
x=[a,b]
k=x[0]^x[1]
x.append(k)
if (n%3==0):
print(x[0])
elif (n%3==1):
print(x[1])
else:
print(x[2])
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | a=int(input())
b=[]
for i in range(a):
c=input()
if(len(c)>10):
d=[]
d.append(c[0])
d.append(str(len(c)-2))
d.append(c[len(c)-1])
b.append("".join(d))
else:
b.append(c)
for i in b:
print(i) |
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 | s1=input()
s2=input()
l1=len(s1)
x=int(s1,2)
y=int(s2,2)
z=x^y
res=bin(z).replace("0b","")
l2=len(res)
print("0"*(l1-l2)+res) |
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.
The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each... | 3 | n,m=map(int,input().split())
d=[0]*(n+1)
for i in range(m):
inp=list(map(int,input().split()))
s=inp.index(max(inp))
d[s+1]+=1
print(d.index(max(d)))
|
There is a right triangle ABC with ∠ABC=90°.
Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC.
It is guaranteed that the area of the triangle ABC is an integer.
Constraints
* 1 \leq |AB|,|BC|,|CA| \leq 100
* All values in input are integers.
* The area of the triangl... | 3 | a, b, c = map(int,input().split())
print("%d"%(a*b/2))
|
Valera has 2·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap.
Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube fr... | 1 | n=input()
A=map(int, raw_input().split())
from collections import defaultdict as D
d=D(list)
for i,e in enumerate(A):
d[e]+=[i]
c=[0,0]
j=1
r=[]
R=[]
for i in range(10,100):
if len(d[i])==1:
r+=[(d[i][0],j)]
c[j-1]+=1
j = 3-j
if len(d[i])>1:
r+=[(d[i][0],1)]
r+=[(... |
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the ... | 3 | from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import... |
How many ways are there to choose two distinct positive integers totaling N, disregarding the order?
Constraints
* 1 \leq N \leq 10^6
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer.
Examples
Input
4
Output
1
Input
999999
Output
499999 | 3 | N = int(input())
if N == 1:
print(0)
else:
print((N+1)//2-1) |
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f... | 3 | #in the name of god
#Mr_Rubik
#codeforces,problemset
n1,n2,k1,k2=map(int,input().split())
if n2<n1:print('First')
else:print('Second')
|
A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count.
The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is h... | 1 | n = input()
i = 2
for k in range(n-1):
print i,
i = (i + k + 1) % n + 1
|
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 | m,s=list(map(int,input().split()))
l=list(map(int,input().split()))
res=l[0]-1
for i in range(1,s):
if l[i]<l[i-1]:
res+=m-l[i-1]+(l[i]-1)+1
else:
res+=l[i]-l[i-1]
print(res)
|
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | v=int(input())
s=list(map(int,input().split()))
x=[]
c=s[0]
count=0
for i in s:
if i>=c:
count+=1
c=i
else:
c=i
count=1
x.append(count)
print(max(x)) |
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6.
Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task!
Each digit c... | 3 | p,q,r,s=map(int,input().split())
Sum=min(p,r,s)
print(256*Sum+32*min(p-Sum,q))
|
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())
a = list(map(int, input().split()))
odd = 0
even = 0
for i in range(0,len(a)):
if a[i] % 2 == 0:
even+=1
c = i
else:
odd+=1
d = i
print(d+1 if odd<even else c+1) |
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them.
Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1.
Input
T... | 1 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/584/A
Solution: The strategy that I follow is to make the 10s multiple of t which has n digits. Generating a 10s multiple
of t is easy, use t and then put zeroes. But since we need to have a bound of the number of digits in it, we
first calcu... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | n=int(input())
c=0
for i in range(0,n):
x,y=input().split()
x,y=int(x),int(y)
if y-x>=2: c+=1
print(c) |
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 | first = input()
second = input()
result = ""
for i in range(len(first)):
if first[i] == second[i]:
result += "0"
else:
result += "1"
print(result) |
Polycarp has invited n friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side.
Each friend is characterized by two values h_i (their height) and w_i (their width). On the photo the i-th friend will occupy a rectangle h_i ... | 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... |
When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.
You, the smartwatch, has found N routes to his home.
If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.
Find the smallest cost of a route that takes not l... | 3 | n,t=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n)]
l=[x[0] for x in l if x[1]<=t]
print(min(l) if len(l)>0 else 'TLE')
|
Toad Ivan has m pairs of integers, each integer is between 1 and n, inclusive. The pairs are (a_1, b_1), (a_2, b_2), …, (a_m, b_m).
He asks you to check if there exist two integers x and y (1 ≤ x < y ≤ n) such that in each given pair at least one integer is equal to x or y.
Input
The first line contains two space-s... | 3 | from sys import stdin
n, m = map(int, stdin.readline().split())
edges = []
for i in range(m):
a, b = map(int, stdin.readline().split())
edges.append((a,b))
pin = edges[0][0]
pinn = edges[0][1]
fedges = list(filter(lambda x: pin not in x, edges))
fedgess = list(filter(lambda x: pinn not in x, edges))
if len(fe... |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 01:07:09 2020
@author: RACHIT
"""
def check(l:list)->str:
l.sort()
x=True
for i in range(1,len(l)):
x=x and l[i]-l[i-1]<=1
if x:
return "YES"
return "NO"
if __name__=="__main__":
t=int(input())
while(t>0):
n=int(in... |
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 | for _ in range(int(input())):
n,m=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n)]
f=1
for i in range(n):
for j in range(m):
if (i==0 or i==n-1) and (j==0 or j==m-1):
if l[i][j]>2:
f=0
break
... |
Jzzhu has invented a kind of sequences, they meet the following property:
<image>
You are given x and y, please calculate fn modulo 1000000007 (109 + 7).
Input
The first line contains two integers x and y (|x|, |y| ≤ 109). The second line contains a single integer n (1 ≤ n ≤ 2·109).
Output
Output a single integer... | 3 | from collections import deque, Counter, OrderedDict
from heapq import nsmallest, nlargest
from math import ceil,floor,log,log2,sqrt,gcd,factorial,pow,pi
from bisect import bisect_left,bisect_right
def binNumber(n,size=4):
return bin(n)[2:].zfill(size)
def iar():
return list(map(int,input().split()))
def ini(... |
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card.
Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≤ x ≤ s, buy food that costs exactly x burles and obtain ⌊x/10⌋ burles as a cashback (in other words, Mishka ... | 3 |
def solve():
n=int(input())
sum1=0
while(1):
if(n<10):
print(sum1+n)
return
x=n//10
sum1+=x*10
n=n-(x*10)+x
for _ in range(int(input())):
solve() |
Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a m... | 1 | from collections import defaultdict, Counter
n, m = tuple( [int(t) for t in raw_input().split() ] )
D_F, D_K = defaultdict(list), defaultdict(list)
for i in range(n):
c, d = tuple( [int(t) for t in raw_input().split() ] )
D_F[d].append(c)
for j in range(m):
c, d = tuple( [int(t) for t in raw_input().split() ] )
... |
Petya and Vasya are competing with each other in a new interesting game as they always do.
At the beginning of the game Petya has to come up with an array of N positive integers. Sum of all elements in his array should be equal to S. Then Petya has to select an integer K such that 0 ≤ K ≤ S.
In order to win, Vasya ha... | 3 | import sys
import math
import heapq
import collections
def inputnum():
return(int(input()))
def inputnums():
return(map(int,input().split()))
def inputlist():
return(list(map(int,input().split())))
def inputstring():
return([x for x in input()])
n, s = inputnums()
if s < 2*n:
print ("NO")
else:
... |
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into s to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" a... | 3 | def pal(a):
ctr = 0
while ctr < len(a)/2:
if a[ctr] != a[len(a)-ctr-1]:
return False
ctr+=1
return True
a = input()
alp = []
p = 'NA'
if not len(a) > 10 or len(a) < 1:
if a.islower():
for char in a:
if not char in alp:
alp.append(char)
... |
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be n players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately.
Organizers are stil... | 1 | n = int(raw_input())
a = [0, 1]
while a[-1] <= n-1:
a.append(a[-1] + a[-2] + 1)
print len(a) - 2
|
You are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once.
A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) character... | 3 | t = int(input())
for x in range(t):
p = [-1, -1, -1]
s = input()
n = len(s)
if (s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0):
n = 0
for i in range(len(s)):
p[int(s[i]) - 1] = i
if (p[0] != -1 and p[1] != -1 and p[2] != -1):
n = min(n, max(p[0], p[1... |
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec... | 3 | t = int(input())
for i in range(t):
# print(i + 1, "------")
a1, b1 = map(int, input().split())
a2, b2 = map(int, input().split())
# print(a1, b1, a2, b2)
c = 0
if a1 == a2:
if b1 + b2 == a1:
c +=1
if b1 == a2:
if a1 + b2 == b1:
c +=1
if a1 == b2:
if a2 + b1 == a1:
c +=1
if b1 == b2:
if a1 + ... |
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the... | 3 | n=int(input())
matrix=[[j for j in input()] for i in range(n)]
def check_diagonal(matrix,n):
t=1
d_element=matrix[0][0]
for i in range(n):
if matrix[i][i]!=d_element or matrix[i][n-i-1]!=d_element:
t=0
if t!=1:
return False
return True
def rest_element(matrix,n):
r_e... |
Let's consider equation:
x2 + s(x)·x - n = 0,
where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.
You are given an integer n, find the smallest positive integer root of equation x, or else determine that there are no such roots.
Input
A sing... | 3 | def sum_of_digits(nr):
s = 0
while nr > 0:
s += nr % 10
nr //= 10
return s
def main():
n = int(input())
solutions = []
for s in range(154):
delta = (s ** 2 + 4 * n) ** 0.5
x = (-s + delta)/2
if int(x) != x:
continue
x = int(x)
... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | n = int(input())
words = []
for i in range(n):
word = input()
if len(word) <= 10:
words.append(word)
continue
a = len(word) - 2
s = [str(word[0]) + str(a) + str(word[len(word) - 1])]
words += s
for w in words:
print(w)
|
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | 3 | from sys import *
input = stdin.readline
for _ in range(int(input())):
n = int(input())
a1 = input()
b1 = input()
a = []
for i in a1:
a.append(i)
b = []
for i in b1:
b.append(i)
a.pop()
b.pop()
ans = []
for i in range(n-1,-1,-1):
... |
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 3 | cal = list(map(int, input().split()))
s = input()
f = 0
for i in range(0,len(s)):
if s[i] == str(1):
f += cal[0]
elif s[i] == str(2):
f += cal[1]
elif s[i] == str(3):
f += cal[2]
else:
f += cal[3]
print(f)
|
Lunar New Year is approaching, and you bought a matrix with lots of "crosses".
This matrix M of size n × n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 ≤ i, j ≤ n. We define a cross appearing in the i-th row and the j-th column (1 < i... | 3 | n = int(input())
s = []
for i in range(n):
ip = input()
s.append(ip)
count = 0
for i in range(1,n-1):
for j in range(1,n-1):
if s[i][j] == 'X' and s[i-1][j-1] == 'X' and s[i-1][j+1] == 'X' and s[i+1][j-1] == 'X' and s[i+1][j+1] == 'X':
count +=1
print(count) |
A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and... | 3 | n,m = map(int,input().split())
a = set(map(int,input().split()))
b = set(map(int,input().split()))
i = sorted(a&b)
u = sorted(a|b)
print(len(i),len(u))
for x in i:
print(x)
for x in u:
print(x)
|
You went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock.
You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 ≤ x_i ≤ a_i), then for all 1 ≤ j < i at ... | 3 | x = int(input())
s = str(input()).split()
for i in range(x):
s[i] = int(s[i])
s = s[::-1]
sumi = s[0]
for i in range(1, x):
if s[i-1] > s[i]:
sumi += s[i]
else:
if s[i-1]-1 > 0:
sumi += s[i-1]-1
s[i] = s[i-1]-1
else:
break
print(sumi) |
There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.
Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.
Recently, they learned the operation called xor (exclusive OR).
What is xor?
For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\... | 3 | n=int(input())
a=[int(j)for j in input().split()]
x=0
for i in a:x^=i
print(*[x^i for i in a]) |
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 ≤ n ≤ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | 3 | x = int(input())
y=0
if x%2 == 0:
y = int(x/2)
else:
y = int(-(x+1)/2)
print(y) |
Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya... | 3 | a=[0]
j=0
x,y=map(int,input().split())
for i in range(y):
if input().find('0')!=-1:
a[j]+=1
else:
a.append(0)
j+=1
print(max(a)) |
There are n monsters standing in a row numbered from 1 to n. The i-th monster has h_i health points (hp). You have your attack power equal to a hp and your opponent has his attack power equal to b hp.
You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it... | 3 | n, a, b, k = map(int, input().split())
h = list(map(int, input().split()))
c = 0
for i in range(n):
h[i] = h[i]%(a+b)
if(h[i]==0):
h[i] = (a+b)
h.sort()
for i in range(n):
if(h[i]<=a):
c+=1
continue
cnt = h[i]//a
if(h[i]%a!=0):
cnt+=1
cnt -=1
#print(cnt, k, c)
if(k>=cnt):
c+=1
k -= (cnt)
print(c) |
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | 3 | for _ in range(int(input())):
n = int(input())
a = input()
b = input()
a+= '0'
b+= '0'
l1 , l2 = [],[]
for i in range(1,n+1) :
if a[i] != a[i-1] : l1.append(i)
if b[i] != b[i-1] : l2.append(i)
l2.reverse()
l3 = l1+l2
print(len(l3),sep=" ",end=" ")
for i ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.