problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) β
maxDigit(a_{n}).$$$
Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes.
Your task is calculate a_{K} for given a_{1} and K.
Input
The ... | 3 | t = int(input())
for _ in range(t):
a, k = [int(x) for x in input().split()]
plus = -1
k -= 1
while (k > 0 and plus != 0):
mi = 100; ma = 0
for item in str(a):
mi = min(mi, int(item))
ma = max(ma, int(item))
plus = mi * ma
a += plus
k -= 1
... |
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third ro... | 3 | n=int(input())
a=[0 for i in range(26)]
s=input().strip()
ans=0
for i in range(n-1):
a[ord(s[2*i])-97]+=1
if a[ord(s[2*i+1])-65]>0:
a[ord(s[2*i+1])-65]-=1
else:
ans+=1
print(ans) |
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 | L=list(input())
L=list(map(int,L))
count = 0
if len(L)<7:
print("NO")
else :
co = True
for i in range(len(L)-6):
sum_l = sum(L[i:i+7])
if((sum_l==0 or sum_l == 7 ) and co):
print("YES")
co=False
if co:
print("NO")
|
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() and not(s.islower()):
s=s.lower()
else:
fl=s[0]
rest=s[1:]
if fl.islower() and (rest=='' or rest.isupper()):
s=fl.upper()+rest.lower()
print (s)
|
There are n pillars aligned in a row and numbered from 1 to n.
Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i.
You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met:
... | 3 | n=int(input())
l=input().split()
li=[int(i) for i in l]
copy=list(li)
copy.sort()
start=0
end=n-1
poss=1
for i in range(n):
if(li[start]==copy[i]):
start+=1
continue
if(li[end]==copy[i]):
end-=1
continue
poss=0
break
if(poss):
print("yes")
else:
print("no")
|
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:
You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k ope... | 3 | t=int(input())
for i in range(t):
n,k=map(int,input().split())
a=list(map(int,input().split()))
maxi=max(a)
mini=min(a)
if(k==0):
print(*a)
else:
if(k%2==0):
a=[i-mini for i in a]
print(*a)
else:
a=[maxi-i for i in a]
print(... |
You are given a special jigsaw puzzle consisting of nβ
m identical pieces. Every piece has three tabs and one blank, as pictured below.
<image>
The jigsaw puzzle is considered solved if the following conditions hold:
1. The pieces are arranged into a grid with n rows and m columns.
2. For any two pieces that sh... | 3 | t = int(input())
for i in range(t):
a, b = list(map(int, input().split()))
if 1 in [a, b]:
print("YES")
elif max(a, b) <= 2:
print("YES")
else:
print("NO") |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 3 | n = int(input())
print(sum(int(i) for i in input().split())/n) |
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ... | 3 | n = int(input())
s = set()
for _ in range(n):
ip = input()
if ip in s:
print("YES")
else:
s.add(ip)
print("NO") |
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | alf = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
ALF = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
a = input()
b = a[0]
if alf.count(b) == 1:
... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | # http://codeforces.com/problemset/problem/339/A
line = input()
line_sorted = "+".join(sorted(line.replace("+", "")))
print(line_sorted) |
You have array a1, a2, ..., an. Segment [l, r] (1 β€ l β€ r β€ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 β€ i β€ r).
Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]).
Your task is to find a ... | 3 | def main():
n = int(input())
seq = [int(c) for c in input().split()]
cnt = ans = 0
for i in range(n):
if cnt < 2:
cnt += 1
else:
if seq[i] == seq[i-1] + seq[i-2]:
cnt += 1
else:
cnt = 2
ans = max(ans, cnt)
... |
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.
You are given a jacket with n buttons. Determine if it is fasten... | 1 | n = int(raw_input())
b = map(int, raw_input().split())
c = b.count(1)
print "YES" if (n == 1 and c == 1) or (n > 1 and c == n - 1) else "NO"
|
Archith loves to play with number series. Archith asked his girlfriend to a date. But she was busy in solving the homework on triangular series which stated that find the least number which has higher divisors than n in a triangular series. His girlfriend made a condition that if he solves this assignment for her she w... | 1 | T=input('')
cnt=0
def no_of_divisors(t):
count=0
for i in range(1, t + 1):
if t % i == 0:
count+=1
return count
while T>cnt:
N=input('')
t_d={}
for i in range(1000000):
t=(i*(i+1)/2)
t_d[t]=no_of_divisors(t)
if t_d[t]>N:
print t
break
T-=1 |
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ... | 3 | l=list(map(int,input().split()))
l.sort()
if (l[1]+l[2]+l[0])>(l[0]*2+l[1]*2):
print(l[0]*2+l[1]*2)
else:
print(l[1]+l[2]+l[0]) |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | s = input()
t = 'hello'
i1 = 0
i2 = 0
while i1<len(t) and i2 < len(s) :
i1+=s[i2]==t[i1]
i2+=1
print('YES' if i1==len(t) else 'NO')
|
You are given a string S of length N consisting of lowercase English letters. We will cut this string at one position into two strings X and Y. Here, we would like to maximize the number of different letters contained in both X and Y. Find the largest possible number of different letters contained in both X and Y when ... | 3 | n,s=int(input()),input()
mx=-1
for i in range(n):
mx=max(mx,len(set(s[:i])&set(s[i:])))
print(mx) |
Recently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list.
For ex... | 1 | n=int(raw_input())
l=map(int,raw_input().split())
x=max(l)
l.remove(x)
for i in range(1,x/2+1):
if x%i==0:
l.remove(i)
print x, max(l) |
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimu... | 1 | from math import *
PI = 3.1415926535898
n = input()
ans = 0
while n > 0:
if n % 2 != 0:
ans += 1
n /= 2
print ans
|
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process.
Given an input array, what i... | 3 | def mp():
return map(int, input().split())
def f(a):
if sorted(a) == a:
return len(a)
return max(f(a[:len(a) // 2]), f(a[len(a) // 2:]))
n = int(input())
a = list(mp())
print(f(a)) |
You are given an array of integers a_1,a_2,β¦,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t).
Input
The input consists of multiple test cases. The first line contains an integer t (1β€ tβ€ 2 β
10^4) β the number of test cases. The description of the test cases ... | 3 | def prod(A,B):
prod=1
for i in A:
prod*=i
for j in B:
prod*=j
return prod
def answer(n,A):
A.sort()
maxi=-10**20
for i in range(6):
p=prod(A[:i],A[n-5+i:])
maxi=max(maxi,p)
return maxi
t=int(input())
for i in range(t)... |
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | a = int(input())
b = int(input())
c = int(input())
l = [0]*6
for i in range(6):
if i==0:
l[i]+=a+(b*c)
elif i==1:
l[i]+=a+b+c
elif i==2:
l[i]+=(a*b)+c
elif i==3:
l[i]+=(a+b)*c
elif i==4:
l[i]+=a*(b+c)
else:
l[i]+=a*b*c
print(max(l)) |
Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.
Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.
Let's consider a student the best at some... | 3 |
n,m=map(int,input().split())
l=[]
k=[]
for i in range(n):
l.append(list(input()))
for i in range(m):
a=[]
for j in range(n):
a.append(int(l[j][i]))
for p in range(len(a)):
if(max(a)==a[p]):
if(p not in k):
k.append(p)
if(len(k)==n):
break
print(len(k))
|
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now sh... | 3 | def IntInput(): return int(input())
def M_IntInput(): return map(int,input().split())
def M_StrInput(): return map(int,input().split())
def IntArrayInput(): return list(map(int,input().split()))
def modInverse(p,a,m): return ((p%m)*pow(a%m,m-2,m))%m
# -----------------------Anshul Raj------------------------ #
for _ ... |
There are N integers, A_1, A_2, ..., A_N, written on a blackboard.
We will repeat the following operation N-1 times so that we have only one integer on the blackboard.
* Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.
Find the maximum possible value of the... | 1 | #!/usr/bin/env python
from collections import deque
import itertools as ite
import sys
import math
sys.setrecursionlimit(1000000)
INF = 10 ** 18
MOD = 10 ** 9 + 7
N = input()
A = map(int, raw_input().split())
pos1 = pos2 = 0
flag1 = flag2 = False
for i in range(N):
if A[i] > 0:
flag1 = True
pos1 = i
elif A[i... |
A holiday weekend is coming up,
and Hotel Bytelandia needs to find out if it has enough rooms to accommodate all potential guests.
A number of guests have made reservations.
Each reservation consists of an arrival time, and a departure time.
The hotel management has hired you to calculate the maximum number of guests t... | 1 | t = int(raw_input())
while t:
t -= 1
n = int(raw_input())
arr = [int(x) for x in raw_input().split(" ")]
dep = [int(x) for x in raw_input().split(" ")]
maxcurr = 0
for i in range(n):
x = arr[i]
curr = 1
for j in range(n):
if i == j:
continue
if dep[j] > arr[i] and arr[j] <= arr[i]:
curr += 1
... |
Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.
There are ex... | 3 | n=int(input())
l=input().split()
s="".join(l)
a=s.rfind("0")
b=s.rfind("1")
print(min(a,b)+1) |
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the... | 3 | n=int(input())
l=list(map(int,input().split()))
a,b,f=0,0,0
for x in range(n):
if l[x]==25:a+=1
elif l[x]==50:
b+=1
if a==0:f=1;break
else:a-=1
else:
if b>0 and a>0:
b-=1
a-=1
elif a>2:a-=3
else:f=1;break
print(["YES","NO"][f==1]) |
Snuke has a string S consisting of three kinds of letters: `a`, `b` and `c`.
He has a phobia for palindromes, and wants to permute the characters in S so that S will not contain a palindrome of length 2 or more as a substring. Determine whether this is possible.
Constraints
* 1 \leq |S| \leq 10^5
* S consists of `a`... | 3 | S=input()
d = [0]*3
for i in range(len(S)):
d[ord(S[i])-97]+=1
if max(d)-min(d)<=1:
print("YES")
else:
print("NO") |
Write a program which computes the digit number of sum of two integers a and b.
Constraints
* 0 β€ a, b β€ 1,000,000
* The number of datasets β€ 200
Input
There are several test cases. Each test case consists of two non-negative integers a and b which are separeted by a space in a line. The input terminates with EOF.
... | 3 | import sys
for line in sys.stdin:
l = line.replace('\n', '')
a, b = l.split()
a = int(a)
b = int(b)
print(len(str(a+b))) |
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are r... | 3 | n,k=map(int,input().split())
s=input()
l=0
a=0
x=(n-k)//2
for i in range(n):
if s[i]=='(' and a+1>n//2-x:
a+=1
l+=1
elif s[i]=='(':
a+=1
print(s[i],end='')
elif s[i]==')' and l>0:
l-=1
elif s[i]==')':
print(s[i],end='') |
You are given two strings s and t. Both strings have length n and consist of lowercase Latin letters. The characters in the strings are numbered from 1 to n.
You can successively perform the following move any number of times (possibly, zero):
* swap any two adjacent (neighboring) characters of s (i.e. for any i = ... | 3 | #23
n=int(input())
s=list(input())
t=list(input())
for i in set(s):
if s.count(i)!=t.count(i):
exit(print(-1))
b=[]
k=0
while len(t)>0:
l=s.index(t[0])
for i in range(l,0,-1):
s[i],s[i-1]=s[i-1],s[i]
b.append(i+k)
k+=1
del t[0];del s[0]
print(len(b))
print(*b) |
You are given two strings of equal length s and t consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.
... | 3 | n = int(input())
for i in range(n):
a = input()
b = input()
f = 1
for el1 in a:
if f:
for el2 in b:
if el1 == el2:
print('YEs')
f = 0
break
if f:
print('NO') |
Just to remind, girls in Arpa's land are really nice.
Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if... | 3 | R = lambda: map(int, input().split())
n, m, w = R()
ws = [0] + list(R())
bs = [0] + list(R())
g = [[] for x in range(n + 1)]
for i in range(m):
x, y = R()
g[x].append(y)
g[y].append(x)
cs = [0] * (n + 1)
cnt = 1
for i in range(1, n + 1):
if not cs[i]:
cs[i] = cnt
q = []
q.append(... |
When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside β not tangerines, but blossoms instead.
"What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone."
"But these blends are at their best, aren't they?" ... | 3 | #m = input()
#n = list(map(int,m.split(' ')))
#arr = input()
#l = list(map(int,arr.split(' ')))
#print(n,l)
#print(type(l))
#input()
#print((set(input().split()) - {'0'}))
#a = {9,1,6,1,9,7,5,5,7,9,1}
#print(a)
s= str(input())
arr = ['A','B','C']
l = len(s)
x = []
for i in range(l):
if s[i] == '.' :
x.appe... |
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the dista... | 3 | n=int(input())
s=input()
m=10**17
l=list(map(int,input().split()))
for i in range(n-1):
if s[i]!=s[i+1]:
if s[i+1]!='R':
m=min(m,(l[i+1]-l[i])//2)
if (m==10**17):
m=-1
print(m)
|
There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.
On this sequence, Snuke can perform the following operation:
* Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.... | 3 | # C
n,k=map(int,input().split())
print((n+k-3)//(k-1)) |
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro... | 3 | num=input()
ll=len(num)
for x in range(ll-1,-1,-1):
num+=num[x]
print(num) |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Let p be any permutation of length ... | 3 | t=int(input())
for _ in range(t):
n=int(input())
c=[]
c1=[]
l=list(map(int,input().split()))
l.reverse()
print(*l)
|
Count the pairs of length-N sequences consisting of integers between 1 and M (inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N... | 3 | def main():
mod = 10**9+7
fact = [1, 1]
for i in range(2, 5*(10**5)+1):
fact.append(fact[-1]*i % mod)
def nPr(n, r, mod=10**9+7):
return pow(fact[n-r], mod-2, mod)*fact[n] % mod
n, m = map(int, input().split())
if m == 1:
print(0)
return
ans = nPr(m, n)
i... |
As you know, there is a furious battle going on between Marut and Devil. They are fighting with strings. Marut's strings are denoted by M and Devil's strings are denoted by D. Both of them are throwing strings on each other in order to get points. Their strings collide in air and one occurrence of some character in one... | 1 | score=list()
score+=raw_input().split(' ')
for i in range(0,len(score)) :
score[i]=int(score[i])
q=int(raw_input())
devil,marut=int(0),int(0)
while q :
q-=1
m=raw_input()
d=raw_input()
mcnt=[0]*26
dcnt=[0]*26
for i in m :
mcnt[ord(i)-ord('a')]+=1
for i in d :
dcnt[ord(i)-ord('a')]+=1
for i... |
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor x, Egor on the floor y (not on the same floor with Masha).
The house has a staircase and an elevator. If Masha u... | 3 | x, y, z, t1, t2, t3 = map(int, input().split())
lift = abs(x - z) * t2 + 2 *t3 + abs(y - x) * t2 + t3
steps = abs(y - x) * t1
if lift <= steps:
print ("YES")
else:
print ("NO")
|
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | m,n=map(int,input().split())
if n%2==0:
print((n//2)*m)
else:
print((n//2)*m + m//2) |
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
Input
The first line contains t... | 3 | na, nb = map(int, input().split())
k, m = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
maxa = A[k - 1]
minb = B[-m]
# print(maxa, minb)
if maxa < minb:
print("YES")
else:
print("NO")
|
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 | import math
n,m,a=map(int,input().split(' '))
p=math.ceil(n/a)
q=math.ceil(m/a)
print(p*q) |
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan consider... | 1 |
# target Expert
# Author : raj1307 - Raj Singh
# Date : 18.07.19
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): re... |
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment 0 and turn power off at moment M. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, ... | 1 | # -*- coding: utf-8 -*-
[n, m] = map(int, raw_input().split(' '))
a = map(int, raw_input().split(' '))
c = [0]
for i in a:
c.append(i)
c.append(m)
n += 2
d = [[0, 0] for i in xrange(0, n)]
i = 0
for i in xrange(0, n):
if i>0 and i+1<n:
d[i][0] = d[i-1][1] + c[i+1] - c[i] # θ’«εζ°οΌεΆζ°
if i==0:
d... |
We just discovered a new data structure in our research group: a suffix three!
It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.
It's super simple, 100% accurate, and doesn't involve advanced machine learni... | 3 | t=int(input())
A=[str(input()) for i in range(t)]
for i in range(t):
s=A[i][::-1]
if s.find('op')==0: print('FILIPINO')
if s.find('used')==0 or s.find('usam')==0: print('JAPANESE')
if s.find('adinm')==0: print('KOREAN')
|
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coor... | 3 | import sys
input = sys.stdin.readline
N=int(input())
P=[list(map(int,input().split())) for i in range(N)]
ANS=[1<<60]*(N+1)
ANS[-1]=0
DP1=[20000]*N
S=0
for i in range(N):
x,y,p=P[i]
DP1[i]=min(abs(x),abs(y))
S+=DP1[i]*p
ANS[0]=S
def dfs(DP,now,used):
for next_town in range(now,N):
x,y,p=P[ne... |
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with he... | 3 | import math
def main():
n, d = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
if d!=5 and d!=0:
a = list(filter(lambda x: x%5!=0 ,a))
if d&1:
a = list(filter(lambda x: x%2, a))
n = len(a)
dp = [[-1e6 for _ in range(10)] for _ in range(n + 1)]
pat... |
Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have?
Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are conside... | 3 | import math
n,k=(map(int,input().strip().split()))
if n>=k:
a=math.ceil(k/2)-1
elif n*2<=k:
a=0
else :
if k%2==0:
k+=1
a=math.floor((2*n-k)/2)+1
print(int(a)) |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | a, b = [int(x) for x in input().split()]
i = 0
while i < b:
if a % 10 == 0:
a = a // 10
else:
a -= 1
i += 1
print(a)
|
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 |
n=input("")
a=["a","e","i","o","u","A","I","E","O","U","Y","y"]
for i in list(n):
for y in list(a):
if i==y:
n=n.replace(i,"")
r = ["." + suit for suit in n]
p=''.join(r)
print(p.lower())
|
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x.
As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it.
It's guaranteed that the solution always exists. If ther... | 3 | for i in range(int(input())):
n = int(input())
print(n - 1, 1) |
Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.
His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words.
<image>
He ate coffee mi... | 1 | single = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
tens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
ones = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
def solve(n):
if(len(... |
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 len(s) == 1:
if s.islower():
print(s.upper())
else:
print(s.lower())
elif s[0].islower() and s[1:].isupper():
print(s[0].upper() + s[1:].lower())
elif s.isupper():
print(s.lower())
else:
print(s)
|
Kenkoooo is planning a trip in Republic of Snuke. In this country, there are n cities and m trains running. The cities are numbered 1 through n, and the i-th train connects City u_i and v_i bidirectionally. Any city can be reached from any city by changing trains.
Two currencies are used in the country: yen and snuuk.... | 3 | import sys
input = sys.stdin.readline
n,m,s,t = map(int,input().split())
links_e = [[] for _ in range(n+1)]
links_s = [[] for _ in range(n+1)]
for _ in range(m):
u,v,a,b = map(int, input().split())
links_e[u].append((a,v))
links_e[v].append((a,u))
links_s[u].append((b,v))
links_s[v].append((b,u))... |
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ... | 3 | n=int(input())
a=set()
for i in range(n):
s=input()
if s in a:
print('yes')
else:
a.add(s)
print('no')
|
A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).
Killjoy's account is already infected and has a rating equal to x. Its rating is constant. There are n accounts except hers, number... | 3 | t=int(input())
n=[]
x=[]
a=[]
for i in range(t):
ni,xi=map(int,input().split())
k=list(map(int,input().split()))
n.append(ni)
x.append(xi)
a.append(k)
def fun(n,x,a):
su=0
flag=1
nom=0
for i in range(n):
su+=(a[i]-x)
if a[i]!=x:
flag=0
if a[i]==x:
nom=1
if flag:
return 0
else:
if nom==1:
r... |
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what i... | 3 | def Gen_lucky(n,s):
if(len(s)==n):
L.append(int(s))
return
Gen_lucky(n,s+"4")
Gen_lucky(n,s+"7")
return
l,r=map(int,input().split())
L=[]
for i in range(1,11):
Gen_lucky(i,"")
L.sort()
ind1=0
for i in range(len(L)):
if(L[i]>=l):
ind1=i
break
ind2=0
for i... |
There is an apple tree that bears apples of N colors. The N colors of these apples are numbered 1 to N, and there are a_i apples of Color i.
You and Lunlun the dachshund alternately perform the following operation (starting from you):
* Choose one or more apples from the tree and eat them. Here, the apples chosen at ... | 3 | print("second" if all(i % 2 == 0 for i in map(
int, open(0).read().split()[1:])) else "first") |
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can b... | 3 | n = int(input())
s = input()
res = 0
for i in s:
if i == "-" and res != 0:
res -= 1
elif i == "+":
res += 1
print(res)
|
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix s... | 3 | input()
lis1=[int(i) for i in input().split()]
lis2=[int(j) for j in input().split()]
lis3=[int(k) for k in input().split()]
print(sum(lis1)-sum(lis2),sum(lis2)-sum(lis3)) |
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wan... | 3 | n=int(input())
l=list(map(int,input().split()))
s=sum(l)
cnt=0
for i in l:
k=s-i
if(k%2==0):
cnt+=1
print(cnt)
|
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 | def dfs(graph, start=0):
n = len(graph)
dp = [0] * n
visited, finished = [False] * n, [False] * n
stack = [start]
while stack:
start = stack[-1]
# push unvisited children into stack
if not visited[start]:
visited[start] = True
for child in graph[sta... |
You are given a string s consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode:
res = 0
for init = 0 to inf
cur = init
ok = true
for i = 1 to |s|
res = res + 1
... | 3 | t=int(input())
for _ in range(t):
s=input()
total=0
prefix_s=[]
for i in s:
if i =='-':
total-=1
prefix_s.append(total)
else:
total+=1
prefix_s.append(total)
minimum=min(0,min(prefix_s))
maximum_number=abs(minimum)
total=0
... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | import math
input = input("")
melon = False
for x in range(0,100,2):
if math.fabs(int(input) - x) % 2 == 0 and int(input) > 2:
melon = True
if melon == True:
print("YES")
else:
print("NO")
|
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i Γ 1 (that is, the width is 1 and the height is a_i).
Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will... | 3 | from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
#import math
#import time
#import random # randome is not available at Codeforces
def I():
return int(input())
def MI():
... |
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture:
<image>
Petr ... | 1 | DAYS_OF_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
md = raw_input()
[m, d] = map(int, md.split())
days = DAYS_OF_MONTH[m]
week1 = (7-d+1)
left = days - week1
lastwk = left % 7
print 1 + left/7 + 1 if lastwk > 0 else 1 + left/7 |
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 | g=int(input())
g+=1
while len(set(str(g)))!=4:
g+=1
print(g) |
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. It... | 3 | def khoshans(n):
if n==0:
return 'no'
m=0
f='yes'
while n!=0:
y=n%10
n=n//10
if y!=4 and y!=7:
f='no'
return f
def tedad(n):
t=0
while n!=0:
n=n//10
t=t+1
return t
c=int(input())
n=int(input())
a=n
t=tedad(n)
m=0
s=0
for i in ra... |
The only difference between easy and hard versions is constraints.
The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, ..., a_n (1 β€ a_i β€ k), where a_i is the show, the episode of which will be shown in i-th day.
The... | 3 | t = int(input())
for i in range(t):
n, k, d = map(int, input().split())
a = list(map(int, input().split()))
check = [0] * k
count = 0
for j in range(d):
check[a[j] - 1] += 1
if check[a[j] - 1] == 1:
count += 1
ans = count
j = 0
for q in range(d, n):
ch... |
Chef Monocarp has just put n dishes into an oven. He knows that the i-th dish has its optimal cooking time equal to t_i minutes.
At any positive integer minute T Monocarp can put no more than one dish out of the oven. If the i-th dish is put out at some minute T, then its unpleasant value is |T - t_i| β the absolute d... | 3 | from math import inf
dp = [[0 for i in range(402)] for j in range(202)]
for _ in range(int(input())):
n = int(input())
arr = [int(x) for x in input().split()]
arr.sort()
arr.insert(0,0)
for idx in range(1,n+1):
dp[idx][0] = inf
for time in range(1,(2*n) + 1):
dp[idx][time... |
You are given a sequence of integers a_1, a_2, ..., a_n. You need to paint elements in colors, so that:
* If we consider any color, all elements of this color must be divisible by the minimal element of this color.
* The number of used colors must be minimized.
For example, it's fine to paint elements [40, 1... | 1 | import sys,os,math
from collections import Counter, defaultdict
import bisect
from sys import stdin, stdout
from itertools import repeat
# sys.stdin = open('input')
# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())
def main():
n = map(int, raw_inpu... |
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 | s=input()
s=list(s)
a=['a','e','i','o','u','y']
sr=""
for i in range(len(s)):
if s[i].lower() not in a:
sr+='.'
sr+=s[i].lower()
print("".join(sr))
|
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())
ans = [[int(i) for i in input().split()] for j in range (n)]
a = 0
an = []
for i in range(n):
an.append(ans[i][0] + ans[i][1] + ans[i][2])
for j in range(n):
if (an[j] >= 2):
a += 1
print(a)
|
Lee is going to fashionably decorate his house for a party, using some regular convex polygons...
Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis a... | 3 | ll = lambda: list(map(int, input().split()))
st= lambda: input()
v = lambda: map(int, input().split())
ii = lambda: int(input())
for _ in range(ii()):
n=ii()
if(n%4!=0):
print("NO")
else:
print("YES")
|
You are given a string s, consisting of n lowercase Latin letters.
A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not.
The length of the substring is the number of letters in it.
Let's call some string of length n diverse if and o... | 3 | n=int(input())
s=input()
x=0
for i in range(0,n-1):
if (s[i]!=s[i+1]):
print("YES")
x=1
print(s[i]+s[i+1])
break
if(x==0):
print("NO")
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}.
Anton can perform the following sequence of operations any number of ti... | 3 | t = int(input())
while(t):
t = t - 1
n = int(input())
a = [int(s) for s in input().split()]
b = [int(s) for s in input().split()]
minus = []
plus = []
zero = []
if a[0] == 1:
plus.append(1)
else:
plus.append(0)
if a[0] == -1:
minus.append(1)
els... |
Ilya plays a card game by the following rules.
A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom co... | 3 | n, t = int(input()), []
for i in range(n):
a, b = map(int, input().split())
t.append([b - 1, a])
t.sort(reverse = True)
k, s = 1, 0
for i, j in t:
k += i
s += j
if k < 1: break
print(s) |
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student... | 3 | n = int(input())
a = input()
c1 = 0
c2 = 0
i = 0
ans = 0
while i < len(a):
if a[i] == '(':
c1 += 1
if a[i] == ')':
c2 += 1
if c1 == c2:
c1 = 0
c2 = 0
elif c2 > c1:
cc1 = 0
cc2 = 1
j = i + 1
while j < len(a):
if a[j] == '(':
... |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | def main():
[k, n, w] = [int(_) for _ in input().split()]
must_have = k * w * (w + 1) // 2
must_borrow = max(must_have - n, 0)
print(must_borrow)
if __name__ == '__main__':
main()
|
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 | #-------------------------------------------------------------------------------
#http://codeforces.com/problemset/problem/71/A
#-------------------------------------------------------------------------------
def main():
n = int(input())
a = []
for i in range(n):
inp = input()
if len(inp)<1... |
Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.
We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on t... | 3 | n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
d = {}
for i in a:
for j in b:
if j%i == 0:
cur = j//i
if cur in d:
d[cur] += 1
else:
d[cur] = 1
l = sorted(d.items(), key = lambda x... |
Given is a number sequence A of length N.
Find the number of integers i \left(1 \leq i \leq N\right) with the following property:
* For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i.
Constraints
* All values in input are integers.
* 1 \leq N \leq 2 \times 10^5
* 1 \leq A_... | 3 | n = int(input())
a = sorted(list(map(int, input().split())))
x = max(a)
dp = [0] * x
for ai in a:
i = 1
while i * ai <= x:
dp[i * ai - 1] += 1
i += 1
ans = 0
for ai in a:
if dp[ai-1] <= 1:
ans += 1
print(ans) |
Little Jhool was was the most intelligent kid of his school. But he did NOT like his class teacher, his school, and the way he was taught things in school. Well, he was a rebel, to say the least. Like most of us, he hated being punished by his teacher - specially, when the punishment was to sit beside someone of the o... | 1 | #!python2
if __name__ == "__main__":
T = int(raw_input().strip())
for t in xrange(T):
N = int(raw_input().strip())
temp = map(int, raw_input().split())
B = temp[0]
G = temp[1]
opp = min(G, B)
com = opp - 1 + max(G, B) - opp
if com > opp:
print "Little Jhool wins!"
else:
print "The ... |
Mr. Infinity has a string S consisting of digits from `1` to `9`. Each time the date changes, this string changes as follows:
* Each occurrence of `2` in S is replaced with `22`. Similarly, each `3` becomes `333`, `4` becomes `4444`, `5` becomes `55555`, `6` becomes `666666`, `7` becomes `7777777`, `8` becomes `888888... | 3 | s, k = input(), int(input())
for i in range(k):
if s[i] != '1':
print(s[i])
exit()
print(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 | def list_input(): return list(map(int, input().split()))
def multiple_input(): return map(int, input().split())
n = int(input())
a = list_input()
d = {1: 0, 2: 0, 3: 0, 4: 0}
for i in a:
d[i] += 1
count = 0
while d[1] > 0:
while d[1] - 1 >= 0 and d[3] > 0:
d[1] -= 1
d[3] -= 1
count +... |
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | lst = [int(x) for x in input().split()]
m = lst[0]
n = lst[1]
overall = 0
print((m*n) // 2) |
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 | m, n = 0, 0
for a in range(5):
l = input()
if '1' in l:
m = a+1
n = l.index('1')//2 + 1
break
print(abs(3 - m) + abs(3 - n))
|
Today at the lesson of mathematics, Petya learns about the digital root.
The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-d... | 1 | import sys
def digital_root(x):
if 0 <= x and x <= 9:
return x
return digital_root(sum([int(d) for d in str(x)]))
n = int(sys.stdin.readline().strip())
for q_i in range(n):
k, x = map(int, sys.stdin.readline().strip().split(" "))
t = x + 9 * (k - 1)
sys.stdout.write("%d\n" % t)
|
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 | n=input()
n=str(int(n)+1)
while(1):
if(not(n[0]==n[1])):
if(n[1]!=n[2] and n[2]!=n[0]):
if(n[3]!=n[0] and n[3]!=n[1] and n[3]!=n[2]):
print(n)
break
n=str(int(n)+1)
|
Amugae has a hotel consisting of 10 rooms. The rooms are numbered from 0 to 9 from left to right.
The hotel has two entrances β one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similar... | 3 | n=int(input())
s=input()
emp=[0]*10
for i in range(len(s)):
if s[i]=="L":
for j in range(len(emp)):
if emp[j]==0:
emp[j]=1
break
elif s[i]=="R":
for j in range(len(emp)):
if emp[len(emp)-j-1]==0:
emp[len(emp)-j-1]=1
... |
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 | import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict
# available on Google, not available on Codeforces
# import numpy as np
# import scipy
def solve(arr, brr): # fix inputs here
console("----- solving ------")
arr = [int(x) for x in arr]
brr =... |
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change).
In a prototype progr... | 3 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 19:37:41 2020
@author: Mongia Bros
"""
for _ in range(int(input())):
a,b,n = list(map(int,input().split()))
if a>b:
a,b = b,a #making a always larger
c=0
k=0
while a<=n and b<=n:
a = a+b
c = c+1
if a>n:
... |
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.
We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ... | 3 | n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
s1 = 0
s2 = 0
for i in range(n):
s1|=a[i]
s2|=b[i]
print(s1+s2)
|
Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
A sequence a is a subsegment of a... | 3 | n, m = map( int, input().split() )
fac = [1]
for i in range( 1, n + 1 ):
fac.append( ( fac[ -1 ] * i ) % m )
ans = 0
for i in range( 1, n + 1 ):
ans += ( (n - i + 1) * fac[ i ] * fac[ n - i + 1 ] ) % m
ans %= m
print( ans )
|
You have an integer variable x. Initially, x=0.
Some person gave you a string S of length N, and using the string you performed the following operation N times. In the i-th operation, you incremented the value of x by 1 if S_i=`I`, and decremented the value of x by 1 if S_i=`D`.
Find the maximum value taken by x duri... | 3 | n=int(input())
s=input()
x=0
ans=0
for i in s:
if i=="I":
x+=1
else:
x-=1
ans=max(ans,x)
print(ans) |
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the resul... | 3 | index = {
'A': 0,
'B': 0,
'C': 0,
}
for _ in range(3):
i = input()
if i[1] == '>':
index[i[0]] += 1
index[i[2]] -= 1
else:
index[i[0]] -= 1
index[i[2]] += 1
ans = [0, 0, 0]
for key, value in index.items():
if value == -2 and ans[0] == 0:
... |
You are given string S and T consisting of lowercase English letters.
Determine if S equals T after rotation.
That is, determine if S equals T after the following operation is performed some number of times:
Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.
Here, |X| denotes the len... | 1 | import sys
s = raw_input()
t = raw_input()
l = len(s)
for i in range(l):
if s[i:] + s[:i] == t:
print 'Yes'
sys.exit()
print 'No' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.