problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manag... | 3 | n=int(input())
t = [[] for i in range(n+1)]
for i in range(1,n+1):
a = int(input())
if a == -1:
t[0].append(i)
else:
t[a].append(i)
ans = 0
r = t[0]
while r:
r=[i for j in r for i in t[j]]
ans += 1
print(ans) |
There are two infinite sources of water:
* hot water of temperature h;
* cold water of temperature c (c < h).
You perform the following procedure of alternating moves:
1. take one cup of the hot water and pour it into an infinitely deep barrel;
2. take one cup of the cold water and pour it into an infin... | 3 | import math
def getValue(num, data):
[hot, cold, t] = data
more = math.ceil(num)
less = math.floor(num)
f = (hot * more + cold * (more - 1)) / (2 * more - 1)
s = (hot * less + cold * (less - 1)) / (2 * less - 1)
if (abs(f - t) < abs(s - t) or (more - num) * 10 == 5): return more
else: ... |
Mishka got an integer array a of length n as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
* Replace each occurre... | 3 | # JAI SHREE RAM
import math; from collections import *
import sys; from functools import reduce
# sys.setrecursionlimit(10**6)
def get_ints(): return map(int, input().strip().split())
def get_list(): return list(get_ints())
def get_string(): return list(input().strip().split())
def printxsp(*... |
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.
A young hacker Vasya disassembled the program and foun... | 3 | def read():
inputs = input().strip()
return list(map(int, inputs.split()))
n = input()
x = n[0] + n[2] + n[4] + n[3] + n[1]
p = int(x)**5 % 100000
print(str(p // 10000) + str(p % 10000 // 1000) + str(p % 1000 // 100) + str(p % 100 // 10) + str(p % 10))
|
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | for i in range(int(input())):
a,b = list(map(int,input().split()))
if a<=b:
print(b-a)
elif a%b==0:
print(0)
else:
print(b - (a%b)) |
Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.
Lyft has become so popular so that it is now used by all m taxi drivers in the city, who every day transport the rest of the city residents β n riders.
Each resident (including taxi drivers) of Palo... | 3 | from math import inf
n, m = list(map(int, input().split()))
x = list(map(int, input().split()))
t = list(map(int, input().split()))
riders = []
drivers = [-inf]
for i in range(len(x)):
if t[i] == 1:
drivers.append(x[i])
else:
riders.append(x[i])
drivers.append(inf)
result = [0] * m
cur = 1... |
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.
Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 Γ 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will ... | 3 | n = int(input())
paint = [int(c) for c in input().split()]
_min = min(paint)
dist = cur = 0
for i in range(2 * n - 1):
if paint[i % n] > _min:
cur += 1
else:
dist = max(dist, cur)
cur = 0
ans = _min * n + dist
print(ans)
|
There are n friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.
For each friend the value f_i is known: it is either f_i = 0 if the i-th friend doesn't know whom he wants to give the gift to or... | 3 | n=int(input())
a=[*map(int,input().split())]
b=[-1]*n
r=range(n)
for i in r:
if a[i]:b[a[i]-1]=i
s={i for i in r if b[i]<0}
t=[i for i in s if a[i]<1]
if len(t)>1:
for i,j in zip(t,t[1:]+[t[0]]):a[i]=j+1;s-={i}
for i in(*t,*r):
if a[i]<1:
j=s.pop()
if j==i:j=s.pop();s|={i}
a[i]=j+1
print(*a) |
Santa Claus has n candies, he dreams to give them as gifts to children.
What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has.
Input
The only line contains positive integ... | 1 | n=input()
a=[]
cur=1
while True:
if(cur+cur+1>n):
a.append(n)
break
a.append(cur)
n-=cur
cur+=1
ans=len(a)
print ans
for i in range(0,ans):
print a[i], |
Find \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}.
Here \gcd(a,b,c) denotes the greatest common divisor of a, b, and c.
Constraints
* 1 \leq K \leq 200
* K is an integer.
Input
Input is given from Standard Input in the following format:
K
Output
Print the value of \displaystyle{\sum_{... | 3 | K=int(input())
from math import gcd
c=0
for i in range(1,K+1):
for j in range (1,K+1):
for k in range (1,K+1):
c=c+gcd(gcd(i,j),k)
print(c) |
To improve the boomerang throwing skills of the animals, Zookeeper has set up an n Γ n grid with some targets, where each row and each column has at most 2 targets each. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to n from left to right.
For each column, Zookeeper will t... | 3 | import sys
import math
from collections import defaultdict,Counter
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
# sys.stdout=open("CP3/output.txt",'w')
# sys.stdin=open("CP3/input.txt",'r')
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
... |
Valera has got n domino pieces in a row. Each piece consists of two halves β the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do t... | 1 | if __name__ == '__main__':
n = int(raw_input())
D = [[int(num) for num in raw_input().split()] for _ in range(n)]
x_sum = y_sum = 0
even_odd = False
for x, y in D:
x_sum += x
y_sum += y
if x % 2 == 1 and y % 2 == 0 or x % 2 == 0 and y % 2 == 1:
even_odd = True
... |
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr... | 3 | al = list(map(int,input().split()))
wp = 7-max(al)
ll = [None,'1/6','1/3','1/2','2/3','5/6','1/1']
print(ll[wp])
|
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ... | 3 | n = input()
if '0' in n:
n = n.replace('0', '', 1)
else:
n = n[:-1]
print(n) |
We have N bricks arranged in a row from left to right.
The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it.
Among them, you can break at most N-1 bricks of your choice.
Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of t... | 3 | n = int(input())
l = list(map(int, input().split()))
j = 1
for i in l:
if i==j: j+=1
if j==1:print(-1)
else:print(n-j+1) |
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th... | 3 |
1^4 * 2^3 * 3^2 * 2^2
2^5 * 3^2 * 1
# 4 1234 = 1!*3!*2!*4! 332222
# aaxa reorder(aaxa) <= n <= 2222222
# 2! = 2
# 3! = 3 * 2! = 3!
# 4! = 3! * 2! * 2!
# 5! = 5!
# 6! = 3! * 5!
# 7! = 7!
# 8! = 2! * 2! * 2! * 7!
# 9! = 3! * 3! * 2! * 7!
def get_facts_memo():
memo = {}
memo["2"] = [0,0,0,1]
memo["3"] = [... |
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and... | 1 | N = raw_input()
a = raw_input()
vals = a.split(' ')
paths = []
for val in vals:
if val == '0':
paths.append('0')
elif val == '1' and paths and paths[-1] == '1':
paths.append('0')
elif val == '1':
paths.append('1')
elif val == '2' and paths and paths[-1] == '2':
paths.a... |
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | 3 | n=int(input())
s1=""
for i in range(n):
s=input()
for j in range(0,len(s)+1,2):
if len(s)==2:
print(s)
break
elif j>=len(s):
print(s[j-1],end="")
else:
print(s[j],end="")
print()
|
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 | n,t=list(map(int,input().split()))
l=list(map(int,input().split()))
s=0
i=0
j=0
m=0
c=0
while j<n:
if i==0:
while s<=t and j<n:
s=s+l[j]
if s>t:
s=s-l[j]
i=i+1
break
else:
j=j+1
c=c+1
else... |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | a,b=input().split()
a=int(a)
b=int(b)
i=1
while(True):
a=a*3
b=b*2
if(a<=b):
i+=1
else:
print(i)
break
|
You are given the set of vectors on the plane, each of them starting at the origin. Your task is to find a pair of vectors with the minimal non-oriented angle between them.
Non-oriented angle is non-negative value, minimal between clockwise and counterclockwise direction angles. Non-oriented angle is always between 0 ... | 3 | from math import atan2
s = lambda a, b: a[0] * b[0] + a[1] * b[1]
v = lambda a, b: a[0] * b[1] - a[1] * b[0]
p = []
for i in range(int(input())):
x, y = map(int, input().split())
p.append((atan2(x, y), (x, y), i + 1))
p.sort()
d = [(s(a, b), abs(v(a, b)), i, j) for (x, a, i), (y, b, j) in zip(p, p... |
Takahashi and Aoki will have a battle using their monsters.
The health and strength of Takahashi's monster are A and B, respectively, and those of Aoki's monster are C and D, respectively.
The two monsters will take turns attacking, in the order Takahashi's, Aoki's, Takahashi's, Aoki's, ... Here, an attack decreases ... | 3 | A,B,C,D = map(int,input().split())
print('Yes' if (B+C-1)//B <= (A+D-1)//D else 'No') |
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 | def main():
input_str_1 = input()
input_str_2 = input()
res = []
for x, y in zip(input_str_1, input_str_2):
if x == y:
res.append('0')
else:
res.append('1')
print(''.join(res))
if __name__ == '__main__':
main()
|
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.
Artem wants to paint an n Γ m board. Each cell of the board should be colored in white or black.
Lets B be the number of black cells that have at least one white neighbor adja... | 3 | t = int(input())
for x in range(t):
n, m = map(int, input().split())
print('W' + ('\n'.join(['B' * m] * n))[1:])
|
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 | #t=int(input())
import math
t=int(input())
while t:
n=int(input())
j=n
cnt=0
oo=0
oe=0
ee=0
while j:
s=input()
l=len(s)
o,z=0,0
for i in range(l):
if s[i]=='1':
o+=1
else:
z+=1
if l%2==0:
... |
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 β€ i, j β€ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 | for _ in range(int(input())):
n, k = map(int,input().split())
a = [(int(i),1) for i in input().split()]
b = [(int(i),0) for i in input().split()]
c = sorted(a+b,key=lambda x:x[0],reverse=True)
l = []
cnt = 0
for i,j in c:
if len(l)==n:
break
if j==0:
c... |
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer n, you can perform the following operations zero or more times:
* mul x: multiplies n by x (where x is an arbitrary positive integer).
* sqrt: replaces n with β... | 3 | n = int(input())
i = 2
s = {}
if n == 1:
print(1, 0)
exit()
while n > 1:
if n% i == 0:
if i in s:
s[i] += 1
else:
s[i] = 1
n //= i
else:
i += 1
ans = 0
maxp2 = max([s[i] for i in s])
k = 1
while k < maxp2:
k <<= 1
ans += 1
if len(list(filter(lambda x: x < k, [s[i] for i in s]))) > 0:
ans += 1
ans1... |
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ... | 3 | l = list(map(int,input().split()))
a = l[0]
b = l[1]
n = l[2]
def gcd(x,y):
l = []
for i in range(1,min(x,y)+1):
if x % i == 0 and y % i == 0 :
l.append(i)
return max(l)
x = gcd(a,n)
y = gcd(b,n)
i = 1
while x <= n or y <= n :
if i % 2 == 0 :
n -= gcd(b,n)
else :
... |
There are N slimes standing on a number line. The i-th slime from the left is at position x_i.
It is guaruanteed that 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}.
Niwango will perform N-1 operations. The i-th operation consists of the following procedures:
* Choose an integer k between 1 and N-i (inclusive) with equ... | 3 | n=int(input())
a=list(map(int,input().split()))
mod=10**9+7
m=1
for i in range(2,n):m=m*i%mod
ans=0
x=m
for i in range(n):
ans=(ans+x*(a[i]-a[i-1]))%mod
x=(x+m*pow(i+1,mod-2,mod))%mod
print(ans) |
One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages.
Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Som... | 3 | # -*- coding: utf-8 -*-
"""
Created on Fri May 22 13:59:32 2020
@author: dell
"""
n=int(input())
l=[x for x in map(int,input().split())]
li=l[:]
k=0
pages=0
while pages<n:
pages+=li[k%7]
k+=1
k=k%7
print(7 if k==0 else k) |
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 | from math import *
n = int(input())
def cp(m):
for i in range(2,int(sqrt(m))+1):
if (m % i == 0):
return False
return True
def sp(m):
for i in range(2,int(sqrt(m))+1):
if (m % i == 0 and cp(i)):
return i
return 0
def lala(m):
if (m % 2 == 0): return int(m/2... |
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 β€ hh < 24 and 0 β€ mm < 60. We use 24-hour time format!
Your task is to find the number of minutes before the New Year. You know that New Year comes when the... | 3 | n=int(input())
for i in range(n):
h,m=map(int,input().split())
print((24-h-1)*60+60-m) |
n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students.
You can change each student's score as long as the following conditions are satisfied:
* All scores are integers ... | 3 |
def maxSelfGrade(n,m,arr):
if sum(arr)>=m:
return m
else:
return sum(arr)
t=int(input())
for i in range(t):
n,m=map(int,input().split())
arr=list(map(int,input().split()))
print(maxSelfGrade(n,m,arr)) |
You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | a = []
for i in range(5):
a.append(input().split())
for i in range(5):
if a[i].count('1')==1:
k=i
h=a[i].index('1')
break
print(abs(2-k)+abs(2-h)) |
There are n students who have taken part in an olympiad. Now it's time to award the students.
Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and ce... | 3 | n , k =map(int, input().split())
half = n//2
x= half//(k+1)
non_winners= n- x - (x*k)
print(x , x*k , non_winners) |
Vasya has a multiset s consisting of n integer numbers. Vasya calls some number x nice if it appears in the multiset exactly once. For example, multiset \{1, 1, 2, 3, 3, 3, 4\} contains nice numbers 2 and 4.
Vasya wants to split multiset s into two multisets a and b (one of which may be empty) in such a way that the q... | 3 | a=int(input())
ans=[0 for i in range(101)]
z=list(map(int,input().split()))
for i in range(len(z)):
ans[z[i]]+=1
if(ans.count(1)%2==1):
s=''
if(len(z)-ans.count(1)-2*ans.count(2)==0):
print('NO')
else:
print('YES')
flag=0
tra=0
for i in range(len(ans)):
... |
Ziota found a video game called "Monster Invaders".
Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns.
For the sake of simplicity, we only consider two different types of monsters and three different types of guns.
Namely, the two types of monsters are:
*... | 3 |
from sys import stdin
n,r1,r2,r3,d = map(int,stdin.readline().split())
a = list(map(int,stdin.readline().split()))
dp = [0,float("inf")]
for i in range(1,n+1):
na = a[i-1]
ndp = [float("inf"),float("inf")]
c1 = r1*na+r3
c2 = min(r1*(na+2) , r2+r1)
if i != n:
ndp[0] = min( dp[0]+c1 , dp[... |
Β«One dragon. Two dragon. Three dragonΒ», β the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | 3 | s = []
k = int(input())
l = int(input())
m = int(input())
d = int(input())
n = int(input())
i = 0
a = [i for i in range(1, n + 1)]
for i in range(n):
if a[i] % k == 0:
s.append(a[i])
if a[i] % l == 0:
s.append(a[i])
if a[i] % m == 0:
s.append(a[i])
if a[i] % d == 0:
s.... |
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 | def r(t=int):
return list(map(t, input().split()))
def ri(t=int):
return t(input())
def cd(it):
ret_val = dict()
for v in it:
ret_val[v] = ret_val.get(v, 0) + 1
return ret_val
for _ in range(ri()):
n, m = r()
if n == 1:
ans = 0
elif n == 2:
ans = m
else:... |
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character ... | 3 | #!/usr/bin/env python3
def main():
w = input()
words = set()
for i in range(len(w)):
words.add(w[i:] + w[:i])
return len(words)
if __name__ == '__main__':
print(main())
|
In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.
Note that in this problem you do not have to minimize the number of sw... | 3 | n=int(input())
a=list(map(int,input().split()))
b=sorted(a)
x=[]
y=[]
j=0
for i in range(n):
if a[i]!=b[i] :
#print(b[i])
c=a.index(b[i])
j+=1
a[c],a[i]=a[i],a[c]
#a[i]=10**10
x.append(i)
y.append(c)
a[i]=10**10
print(j)
for i in range(j):
print(x[i],y... |
There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:
* Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.
What is the largest possible sum of the integers written on the blackboard after... | 3 | li = list(map(int,input().split()))
n=int(input())
print(max(li)*(2**n-1)+sum(li)) |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | yr=int(input())
for i in range(yr+1,100000) :
i=str(i)
if i[0]!=i[1] and i[1]!=i[2] and i[2]!=i[3] and i[0]!=i[3] and i[0]!=i[2] and i[3]!=i[1] :
print(i)
break
|
Given is a positive integer N.
Find the number of pairs (A, B) of positive integers not greater than N that satisfy the following condition:
* When A and B are written in base ten without leading zeros, the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.
Con... | 3 | N = int(input())
Cij = [0] * 100
for i in range(1, N + 1):
Cij[int(str(i)[0] + str(i)[-1])] += 1
count = 0
for i in range(10):
for j in range(10):
count += Cij[i * 10 + j] * Cij[j * 10 + i]
print(count) |
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game Β«Call of Soldiers 3Β».
The game has (m + 1) players and n types of soldiers in total. Players Β«Call of Soldiers 3Β» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each ... | 3 | n,m,k = [int(x) for x in input().split()]
player = []
fri = 0
for i in range(m+1):
player.append(int(input()))
f = player[m]
for i in range(m):
t = bin(f^player[i])
d = 0
for a in t:
if a == '1':
d += 1
if d <= k:
fri += 1
print(fri)
|
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. ... | 3 | def main():
n = int(input())
numbers = [int(_) for _ in input().split()]
numbers.sort()
try:
print(next(numbers[i] for i in range(1, n) if numbers[i] > numbers[0]))
except StopIteration:
print('NO')
if __name__ == '__main__':
main()
|
The length of the longest common prefix of two strings s = s_1 s_2 β¦ s_n and t = t_1 t_2 β¦ t_m is defined as the maximum integer k (0 β€ k β€ min(n,m)) such that s_1 s_2 β¦ s_k equals t_1 t_2 β¦ t_k.
Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}.
For each i (1 β€ i β€ n) she calculated a_i β the length of ... | 3 | #_________________ Mukul Mohan Varshney _______________#
#Template
import sys
import os
import math
import copy
from math import gcd
from bisect import bisect
from io import BytesIO, IOBase
from math import sqrt,floor,factorial,gcd,log,ceil
from collections import deque,Counter,defaultdict
from itertools import permu... |
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of... | 3 | n,s=[int(x) for x in input().split(' ')]
d,ans={},0
for i in range(n-1):
a,b=[int(x) for x in input().split(' ')]
if a in d.keys():
d[a]+=1
else:
d[a]=1
if b in d.keys():
d[b]+=1
else:
d[b]=1
for v in d.values():
if v==1:
ans+=1
print(2*s/ans) |
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q... | 3 | str = input().split()
ice_cream = int(str[1])
disappointed_kids = 0
for i in range(int(str[0])):
new_str = input().split()
if new_str[0] == "+":
ice_cream = ice_cream + int(new_str[1])
if new_str[0] == "-":
if (ice_cream - int(new_str[1]))>= 0:
ice_cream = ice_cream - int(new_str[1])
else:
dis... |
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages ... | 3 | import fractions
import math
n=int(input())
#a,b=map(int,input().split(' '))
#n=list(map(int,input().split(' ')))
t=list(map(int,input().split(' ')))
a=set(t)
print(n+1-len(a))
|
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 β€ k β€ n) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then pri... | 1 | n,k = [int(x) for x in raw_input().split(' ')]
a = [int(x) for x in raw_input().split(' ')]
b = []
c = []
for i in range(len(a)):
if a[i] not in b:
b.append(a[i])
c.append(i)
if(len(b) >= k):
print "YES"
for i in range(k):
print c[i]+1,
else:
print "NO"
|
Karan's mathematics professor has given him a lots of homework. Since he is busy preparing for September Easy Challenge, he needs your help.
Given two numbers, find the sum of prime numbers between them, both inclusive.
Input:
The first line contains the number of test cases T. Each test case contains two space sep... | 1 | def prime_gen(ma):
c=range(3, ma+1, 2)
i=0
while c[i]<(ma+1)**0.5:
j=i+1
while j<len(c):
if c[j] % c[i] == 0: del c[j]
j+=1
i+=1
return [2]+c
tc = int(raw_input())
max = 0
queries = []
for i in range(tc):
l,r = map(int,raw_input().split())
queries.append( (l,r))
if r>max:
max=r
pr... |
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... | 1 | # force903A
_set = set();
a = 0;
while 3*a <= 100:
b = 0;
while 3*a+7*b <= 100:
_set.add(3*a+7*b);
b+=1;
a+=1;
n = input();
for i in range(0, n):
x = input();
if x in _set:
print "YES";
else:
print "NO";
|
Given an integer x, find 2 integers a and b such that:
* 1 β€ a,b β€ x
* b divides a (a is divisible by b).
* a β
b>x.
* a/b<x.
Input
The only line contains the integer x (1 β€ x β€ 100).
Output
You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in... | 3 | n = int(input())
if n <= 1:
print(-1)
else:
if n%2==0:
print(n, 2)
else:
print(n-1, 2) |
Dr .: Peter, do you know "Yes, I have a number"?
Peter: I used to do it on TV the other day. You remember something by the number of characters in each word contained in a sentence. "Yes, I have a number", so it means "the number 3.14" and is a keyword for remembering pi.
Dr .: Peter, that's not the case. This should... | 3 | # coding: utf-8
# Your code here!
while True:
n=input()
if n=="END OF INPUT":
break
a=list(n)
count=0
for i in range(len(a)):
if a[i]!=' ':
count+=1
else:
print(count,end="")
count=0
print(count)
|
Nauuo is a girl who loves writing comments.
One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes.
It's known that there were x persons who would upvote, y persons who would downvote, and there were also another z persons who would vote, but you don't know whether they woul... | 3 | from sys import stdin
def input():
return stdin.readline()
x,y,z=map(int,input().split())
if z!=0 and min(x,y)+z>=max(x,y):
print("?")
else:
if x==y:
print(0)
elif x>y:
print("+")
else:
print("-")
|
You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | import math
def beautifulmatrix(l):
r,c = 0,0
for i in range(0,5):
for j in range(0,5):
if l[i][j] == 1:
r,c = i,j
break
return int(math.fabs(r-2)+math.fabs(c-2))
m = []
for x in range(5):
k = list(map(int,input().split()))
m.append(k)
print(beauti... |
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 | k2,k3,k5,k6=map(int,input().strip().split(' '))
x=min(k2,k5,k6)
s=256*x
k2-=x
x=min(k2,k3)
s+=(x*32)
print(s) |
Tonio has a keyboard with only two letters, "V" and "K".
One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximu... | 3 | #!/usr/bin/env python3
S = list(input())
a = 0 # No swap
b = 0 # With swap
x = 0 # No swap
y = 0 # With swap
for i in range(1, len(S)):
n = x
m = y
if S[i - 1] == 'V' and S[i] == 'V':
# Keep S[i] = V
x = x
# Swap S[i] = V to K
y = max(y, a + 1)
elif S[i - 1] == 'K... |
Little X and Little Z are good friends. They always chat online. But both of them have schedules.
Little Z has fixed schedule. He always online at any moment of time between a1 and b1, between a2 and b2, ..., between ap and bp (all borders inclusive). But the schedule of Little X is quite strange, it depends on the ti... | 3 | p,q,l,r=map(int,input().split())
n=[]
m=[]
for i in range(p):
n.append(list(map(int,input().split())))
for i in range(q):
m.append(list(map(int,input().split())))
ans=0
z=0
for i in range(l,r+1):
c=False
for j in range(q):
x=m[j][0]+i
y=m[j][1]+i
for k in range(p):
... |
You have a sequence a with n elements 1, 2, 3, ..., k - 1, k, k - 1, k - 2, ..., k - (n - k) (k β€ n < 2k).
Let's call as inversion in a a pair of indices i < j such that a[i] > a[j].
Suppose, you have some permutation p of size k and you build a sequence b of size n in the following manner: b[i] = p[a[i]].
Your goal... | 3 | import sys
import math
inf = float('inf')
# input = sys.stdin.readline
def lcm(a,b):
return int((a/math.gcd(a,b))*b)
"""
n = int(input())
n,k = map(int,input().split())
arr = list(map(int,input().split()))
"""
for _ in range(int(input())):
n,k=map(int,input().split())
perm = [0]*k
diff = (n-k)+1
if... |
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the... | 3 | import bisect
n, k, A, B = map(int, input().split())
X = sorted([int(a)-1 for a in input().split()])
def calc(l, r):
def cnt(a, b):
return bisect.bisect_left(X, b) - bisect.bisect_left(X, a)
c = cnt(l, r)
if c == 0:
ret = A
elif r-l == 1:
ret = B * c
else:
m = ... |
Snuke has a calculator. It has a display and two buttons.
Initially, the display shows an integer x. Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:
* Button A: When pressed, the value on the display is incremented by 1.
* Button ... | 3 | x,y = map(int,input().split(" "))
def a(x,y):
if y < x:
return float('inf')
else:
return y - x
print(min([a(x,y),a(-x,y)+1,a(x,-y)+1,a(-x,-y)+2])) |
An African crossword is a rectangular table n Γ m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.
To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a lette... | 3 | w,h = map(int,input().split())
l = []
fi = []
for x in range(w):
fi.append(input())
for y in range(w):
c = fi[y]
for x in list(c):
if c.count(x) > 1:
c = c.replace(x, '#')
l.append(c)
t = []
for y in range(h):
tem = ''
for x in range(w):
tem += fi[x][y]
t.append... |
Pushok the dog has been chasing Imp for a few hours already.
<image>
Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of strin... | 1 | import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
def cmp(x,y):
if x[1]*y[0] > x[0]*y[1]:
return 1
e... |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 1 | import sys
a = []
for x in raw_input().split():
a.append(int(x))
n = a[0]
height = a[1]
b = []
for x in raw_input().split():
b.append(int(x))
counter = 0
for i in range(0, n):
counter += 1;
if(b[i] > height):
counter += 1;
print (counter)
|
Given a permutation p of length n, find its subsequence s_1, s_2, β¦, s_k of length at least 2 such that:
* |s_1-s_2|+|s_2-s_3|+β¦+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2.
* Among all such subsequences, choose the one whose length, k, is as small as possible.
If mul... | 3 | T = int(input())
for _ in range(T):
N = int(input())
P = list(map(int,input().split()))
if N==2:
print(2)
print(*P)
continue
ans = [P[0]]
for a,b,c in zip(P,P[1:],P[2:]):
if (a < b and b > c) or (a > b and b < c):
ans.append(b)
ans.append(P[-1])
pr... |
The girl Taylor has a beautiful calendar for the year y. In the calendar all days are given with their days of week: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.
The calendar is so beautiful that she wants to know what is the next year after y when the calendar will be exactly the same. Help Tayl... | 1 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 13 20:31:34 2016
@author: Dell_
"""
import sys
if False:
input = open('calendar.txt', 'r')
else:
input = sys.stdin
y = int(input.readline().strip())
def ifLeap(y):
if y%4 != 0:
Leap = False
elif y%4 == 0 and y%100 != 0:
Leap = True
e... |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k β [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | from math import *
from copy import *
from string import * # alpha = ascii_lowercase
from random import *
from sys import stdin
from sys import maxsize
from operator import * # d = sorted(d.items(), key=itemgetter(1))
from itertools import *
from collections import Counter # d = dict(Counter(l))
import math
def... |
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the... | 3 | n=int(input())
l=list(map(int,input().split()))
d=[]
for i in range(n):
c=1
for j in l:
if(j>l[i]):
c=c+1
d.append(c)
print(*d)
|
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each prob... | 3 | import math
n=int(input())
a=[int(x) for x in input().split(" ")]
b=[int(x) for x in input().split(" ")]
ca,cb=0,0
for i in range(n):
if a[i]==1 and b[i]==0:
ca+=1
if a[i]==0 and b[i]==1:
cb+=1
if ca==0:
print("-1")
elif(cb<ca):
print("1")
else:
print(int(math.ceil((cb+1)/ca)))
|
Masha has n types of tiles of size 2 Γ 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.
Masha decides to construct the square of size m Γ m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ... | 3 | import sys
import math
import collections
import operator as op
from collections import deque
from math import gcd, inf, sqrt, pi, cos, sin, ceil, log2
from bisect import bisect_right, bisect_left
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
from functools import reduce
from sys import ... |
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 | friends = int(input())
gifts = list(map(int, input().split()))
receive = ['_' for i in range(friends)]
for i, receiver in enumerate(gifts):
receive[receiver - 1] = str(i + 1)
print(' '.join(receive))
|
You wrote down all integers from 0 to 10^n - 1, padding them with leading zeroes so their lengths are exactly n. For example, if n = 3 then you wrote out 000, 001, ..., 998, 999.
A block in an integer x is a consecutive segment of equal digits that cannot be extended to the left or to the right.
For example, in the i... | 1 | mod = 998244353
n = input()
a = [0] * n
b = [0] * n
c = [0] * n
a[0] = 10
p10 = 10 # = 10 ^ 1
add = 10 # = 1 * 10 ^ 1
for i in xrange(1, n):
p10 *= 10
if p10 >= mod: p10 %= mod
add = 10 * add + p10
if add >= mod: add %= mod
c[i] = c[i - 1] + a[i - 1]
if c[i] >= mod: c[i] -= mod
b... |
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her cand... | 3 | n, k = map(int, input().split())
arr = list(map(int, input().split()))
count = 0
rem = 0
for a in arr:
if a >= 8:
k -= 8
rem += a - 8
else:
if a + rem >= 8:
k -= 8
rem += a - 8
else:
k -= a + rem
rem = 0
count += 1
if k <=... |
Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values p_i β the index of the router to which the i-th router was connected... | 3 | n = int(input()) #2e5
pl = list(map(int,input().split())) #p2εΌε§
ll = [n]
while ll[-1]>1:
ll.append(pl[ll[-1]-2])
ll.reverse()
print(*ll)
|
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes... | 3 | a , b , c , d = list(map(int , input().split()))
r = max(3*a // 10 , a-(a*c//250))
s = max(3*b // 10 , b-(b*d//250))
if r > s:
print("Misha")
else:
if r < s:
print("Vasya")
else:
print("Tie")
|
Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. I... | 3 | def partition(A, p, r):
x = A[r]
i = p - 1
for j in range(p, r):
if A[j] <= x:
i += 1
A[i], A[j] = A[j], A[i]
A[i + 1], A[r] = A[r], A[i + 1]
return i + 1
n = int(input())
A = list(map(int, input().split()))
q = partition(A, 0, n - 1)
print(*A[:q], f"[{A[q]}]", *A... |
Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 β€ m β€ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
... | 3 | n = int(input())
s = input()
S = list(s)
a = 1
while a*(a+1)/2 <= n:
b = int(a*(a+1)/2)
print(S[b-1], end="")
a = a+1
|
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty β a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge).
M... | 3 | R=lambda:list(map(int,input().split()))
n,k=R()
a=sorted(R())
b=0
for i in a:
while i>k+k:
k+=k
b+=1
k=max(k,i)
print(b)
|
Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.
The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up. These buttons are numbered 1 through N. When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It ... | 3 | n, *A = map(int, open(0).read().split())
x = 0
for i in range(n):
A[x], x = 0, A[x]-1
if x == -1:
print(x)
exit()
if x == 1:
print(i+1)
exit() |
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.
Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of sever... | 3 | n,k=map(int,input().split())
lis=list(map(int,input().split()))
c=0
for x in lis:
if x<0:
c+=1
if c==n:
for i in range(n):
if k==0:
break
k-=1
lis[i]=-lis[i]
if k%2==1:
lis[n-1]=-(lis[n-1])
elif c==0:
if k%2==1:
lis[0]=-lis[0]
else:
i=0
... |
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 | k=1
m,n,a=map(int,input().split())
if(n>a):
k=k*((n+a-1)//a)
if(m>a):
k=k*((m+a-1)//a)
print(int(k)) |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | n,m=map(int,input().split())
count=0
while not m<n:
n=n*3
m=m*2
count+=1
print(count) |
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 β€ k β€ r, and set k days as the number of days in a week.
Alice is going to paint some n... | 3 |
import sys
import math
from math import *
from collections import defaultdict
import os
import sys
from io import BytesIO, IOBase
from collections import deque
def main():
res = 0
a,b = list(map(int ,input().split()))
if a<= 1:
print(1)
return
if a<= b:
b = a-1
res = 1
print(res+((1+b)*(b))//2)
for ... |
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 | s = input()
if s.isupper():
print(s.lower())
elif len(s) == 1: # double equal sign to equalize
print(s.capitalize())
elif s.islower():
print(s)
elif s[0].islower():
if s[1:len(s)].isupper(): #Mind the colon of the string slice and observe has been used
print(s.capitalize())
eli... |
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | 3 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 16 14:07:57 2019
@author: felip
"""
A, B, C, D = [ int(d) for d in input().split(' ') ]
k=4
p=3
o=2
i=1
if A==B==C==D:
g=k-i
# print(g)
elif A==B==C!=D or A==B==D!=C or B==C==D!=A or (A==B and C==D) or (A==C and B==D) or (A==D and B==C):
g=k-o
# print(t)... |
Constraints
* 1 β€ |V| β€ 100
* 0 β€ |E| β€ 9900
* -2 Γ 107 β€ di β€ 2 Γ 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named wi... | 3 | V,E = list(map(int,input().split()))
STD = [list(map(int,input().split())) for _ in range(E)]
D = [[float('inf')]*V for _ in range(V)]
for i in range(V):
D[i][i] = 0
for std in STD:
D[std[0]][std[1]] = std[2]
for k in range(V):
for i in range(V):
for j in range(V):
D[i][j] = min(D[i]... |
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(''))
for i in range(0,n):
word = input('')
temp = list(word)
l = len(temp)
if l<= 10: print(word)
else: print(str(temp[0]) + str(l-2) + str(temp[l-1])) |
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 β€ si β€ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 3 | # input list, sorted in reverse order
notused = input()
groupList = list(sorted(input().split(), reverse=True))
# convert elements to int (starts with string)
groupList = [ int(i) for i in groupList ]
"""
groupList = []
for i in range(10000):
groupList.append(1)
"""
ones = groupList.count(1)
twos = groupList.... |
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).
You are given a sequence a consisting of n integers. All these integers are distinct, each value from 1 to n appears in the sequence exactly once.
You are making a sequen... | 3 |
n = int(input())
a = list(map(int, input().split()))
ll = [0] * n
rr = [0] * n
l = 0
r = 0
while l < n:
if l >= r:
r = l + 1
while r < n and a[r] > a[r - 1]:
r += 1
ll[l] = r - l
l += 1
l = n - 1
r = n - 1
while r >= 0:
if r <= l:
l = r - 1
while ... |
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.
In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh... | 3 | t = int(input())
while t:
n, a, b, c, d = map(int, input().split())
twl, twu = c-d, c+d
sum = (a-b)*n
sum_limit = (a+b)*n
while True:
if sum>=twl and sum<=twu and sum<=sum_limit:
print("YES")
break
elif sum<twl:
sum+=1
else:
pri... |
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())
while (t):
a,b = list(map(int,input().split()))
a = bin(a)[2:]
b = bin(b)[2:]
if (len(a) < len(b)):
a,b = b,a
while (len(b) < len(a)):
b = '0' + b
x = 0
for i in range(len(a)):
x = x * 2 + (a[i] == '1' and b[i] == '1')
print((int(a,2)^x) + (int(b,2)^x))
t -= 1
|
You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i.
For every i (1 β€ i β€ n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly... | 3 | import sys
import math
import bisect
def main():
for _ in range(int(input())):
a = input()
b = input()
c = input()
n = len(a)
ans = True
for i in range(n):
if a[i] == c[i] or b[i] == c[i]:
pass
else:
ans = False... |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k β [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | import sys
t = int(sys.stdin.readline().strip())
for i in range(t):
a, b = map(int, sys.stdin.readline().strip().split())
if (a == b):
sys.stdout.write("0\n")
elif (b < a):
if ((a-b)%2==0):
sys.stdout.write("1\n")
else:
sys.stdout.write("2\n")
else:
if ((b-a)%2==0):
sys.stdout.write("2\n")
e... |
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first... | 3 | a,b=map(int,input().split())
c=input()
if a==1 and b>0:
print(0)
elif b==0:
print(c)
else:
r=''
for i in range(a):
if i==0:
if c[i]!='1':
b-=1
r+='1'
else:
if c[i]!='0':
b-=1
r+='0'
if b==0:
break
r+=c[i+1:]
print(r) |
Masha has n types of tiles of size 2 Γ 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.
Masha decides to construct the square of size m Γ m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ... | 3 | for _ in range(int(input())):
n,m=map(int,input().split())
flag=False
for i in range(n):
a,b=map(int,input().split())
c,d=map(int,input().split())
if b==c:
flag=True
if m%2!=0:
print("NO")
else:
if (flag):
print("YES")
... |
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())
for i in range(a):
b = input()
if (len(b) > 10):
print("{}{}{}".format(b[0], str(len(b) - 2), b[len(b) - 1]))
else:
print(b)
|
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:
... | 3 | num = int(input())
final = [num]
for i in range(1,num):
#final.append(" ")
final.append(i)
for i in range(0,len(final)):
final[i] = str(final[i])
fstring = ' '.join(final)
print(fstring) |
Another Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced β their sum is equal to 0.
Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means... | 3 | def main():
n = int(input())
arr = []
neg = []
pos = []
for i in range(n):
a = int(input())
if a%2 != 0:
if a < 0:
neg.append(i)
else:
pos.append(i)
arr.append(a//2)
total = sum(arr)
#print(total)
while tot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.