problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Snuke signed up for a new website which holds programming competitions. He worried that he might forget his password, and he took notes of it. Since directly recording his password would cause him trouble if stolen, he took two notes: one contains the characters at the odd-numbered positions, and the other contains the... | 3 | o = input()
e = input()
print(''.join([a + b for a, b in zip(o, e)]) + (o[-1] * (len(o + e) % 2)))
|
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For e... | 1 | s = list(raw_input())
um = 0
dois = 0
zero = 0
for k in s:
if k == "1":
um += 1
elif k == "2":
dois += 1
else:
zero += 1
if zero == 0 or dois == 0:
print "".join(sorted(s))
else:
ar = ["0"] * len(s)
atual = 0
for i in xrange(len(s)-1, -1, -1):
if s[i] == "2":
ar[i+atual] = "2"
if s[i] ... |
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 | x=int(input())
t=list(map(int,input().split()))
E=set()
E=set(t)
f=len(E)
t=list(E)
if (f==1):
print("NO")
else:
t.sort()
print(t[1]) |
The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0... | 3 |
n, k = map(int, input().split())
ids = [int(x) for x in input().split()]
tela = []
for id in ids:
if not id in tela:
tela.insert(0, id)
if len(tela)>k:
tela.pop()
print(len(tela))
print(*tela)
|
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^5) β the number of test cases.
The next t lines... | 3 | for _ in range(int(input())):
n,k=[int(n) for n in input().split()]
if (n%2==0 and k%2==1) or (n%2==1 and k%2==0):
print("NO")
elif n>=k*k:
print("YES")
else:
print("NO") |
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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 29 23:26:57 2020
@author: gohlifang
"""
s = list(input()) #sum needs to count
t = list(filter(("+").__ne__,s))
sum = "+".join(sorted(t))
print(sum) |
This is an easier version of the problem. In this version n β€ 1000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company ... | 3 | import sys
import math
from collections import defaultdict
from collections import deque
from itertools import combinations
from itertools import permutations
input = lambda : sys.stdin.readline().rstrip()
read = lambda : list(map(int, input().split()))
go = lambda : 1/0
def write(*args, sep="\n"):
for i in args:
... |
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.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 1 | N=input()
print["NO","YES"][any([N%i==0 for i in [4,7,44,47,74,77,444,447,474,477,744,747,774,777]])] |
You are given two arrays of integers a_1,β¦,a_n and b_1,β¦,b_m.
Your task is to find a non-empty array c_1,β¦,c_k that is a subsequence of a_1,β¦,a_n, and also a subsequence of b_1,β¦,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f... | 3 | def ans():
set_a = set(a)
set_b = set(b)
if set_a & set_b:
print("YES")
f = list(set_a & set_b)
print(1, f[0])
else:
print("NO")
t = int(input())
for i in range(t):
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input(... |
You are given a prime number p, n integers a_1, a_2, β¦, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 β€ i < j β€ n) for which (a_i + a_j)(a_i^2 + a_j^2) β‘ k mod p.
Input
The first line contains integers n, p, k (2 β€ n β€ 3 β
10^5, 2 β€ p β€ 10^9, 0 β€ k β€ p-1). p is guaranteed to be prime.
The se... | 3 | n, p, k = map(int, input().split())
a = list(map(int, input().split()))
a = [(i ** 4 - i * k) % p for i in a]
c = {i: 0 for i in a}
for i in a:
c[i] += 1
s = 0
for i in c:
i = c[i]
s += (i * (i - 1)) // 2
print(s)
|
You are given a permutation p_1,p_2,...,p_N consisting of 1,2,..,N. You can perform the following operation any number of times (possibly zero):
Operation: Swap two adjacent elements in the permutation.
You want to have p_i β i for all 1β€iβ€N. Find the minimum required number of operations to achieve this.
Constraint... | 3 | n,*l=map(int,open(0).read().split())
b=c=0
for i,p in enumerate(l):
if b: b=0
elif i==p-1: c+=1; b=1
print(c) |
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 | p=[i for i in input().split()]
for i in range(len(p)):
p[i]=int(p[i])
print((p[0]*p[1])//2)
|
You're given an array a of n integers, such that a_1 + a_2 + β
β
β
+ a_n = 0.
In one operation, you can choose two different indices i and j (1 β€ i, j β€ n), decrement a_i by one and increment a_j by one. If i < j this operation is free, otherwise it costs one coin.
How many coins do you have to spend in order to make a... | 3 | for _ in range(int(input())):
n = int(input())
a = [*map(int,input().split())]
first_pos = 0
for i in range(n):
if(a[i]>0):
first_pos = i
break
i = first_pos+1
ans = abs(sum(a[0:first_pos]))
dec = a[i-1]
while(i<n-1):
a[i]+=dec
dec = a[i]
... |
A few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. Ever since, she tried to avoid contact with others, for fear that this secret might be noticed.
To get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long t... | 3 | n,k=map(int,input().split())
l=list(map(int,input().split()))
l1=list(map(int,input().split()))
if k>=2 :
print('Yes')
exit()
for i in range(n-1) :
if l[i]>=l[i+1] and l[i+1]!=0 :
print('Yes')
exit()
l[l.index(0)]=l1[0]
if l!=sorted(l) :
print('Yes')
exit()
print('No')
|
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve... | 3 | l,r=map(int,input().split())
if(l==r):
print(l)
else:
print(2) |
One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one... | 1 | n= int(raw_input())
arr = map(int, raw_input().split(' '))
#print n
#print arr
if sum(arr) != 0:
print "YES"
print "1"
print "1 " + str(len(arr))
else:
found = -1
for i in xrange(len(arr) - 1):
leftarr = arr[0:i+1]
rightarr = arr[i+1:]
#print leftarr, rightarr
if sum(leftarr) != 0 and sum(righ... |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 1 | from math import *
x = int(raw_input())
print int(ceil(x/5.)) |
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one ... | 3 | def sum_pow(n):
mem = [1]
for i in range(8):
mem.append((n * mem[i]))
return mem
mem ,pre= sum_pow(2),0
for i in input():
asc, sum, c= ord(i), 0, 7
while (asc != 0):
sum += (asc % 2) * mem[c]
asc //= 2
c -= 1
print((pre - sum) % 256)
pre = sum
|
Input
The input is given from standard input in the following format.
> $H \ W$ $a_{1, 1} \ a_{1, 2} \ \cdots \ a_{1, W}$ $a_{2, 1} \ a_{2, 2} \ \cdots \ a_{2, W}$ $\vdots \ \ \ \ \ \ \ \ \ \ \vdots \ \ \ \ \ \ \ \ \ \ \vdots$ $a_{H, 1} \ a_{H, 2} \ \cdots \ a_{H, W}$
Output
* Print the maximum number of souvenirs... | 3 | H,W = map(int,input().split())
src = [list(map(int,input().split())) for i in range(H)]
dp = [[[0 for ex in range(W)] for sx in range(W)] for xy in range(H+W-1)]
dp[0][0][0] = src[0][0]
for xy in range(H+W-2):
n = min(xy+1,H,W,H+W-xy-1)
sx0 = max(0,xy-H+1)
for sx in range(sx0, sx0+n):
for ex in ran... |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | s=str(input())
countup=0
countdown=0
for i in s:
if i.isupper():
countup=countup+1
else:
countdown=countdown+1
if countup>countdown:
print(s.upper())
elif(countup<countdown):
print(s.lower())
else:
print(s.lower())
|
Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.
They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.
Let th... | 3 | n=int(input())
a=list(map(int,input().split()))
x=sum(a)
y=0
l=[]
for i in range(n-1):
y+=a[i]
l.append(abs(x-2*y))
print(min(l)) |
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be ... | 3 | n=int(input())
a=list(map(int,input().split()))
t=n
for i in range(n):
a[abs(a[i])-1]=-1*(a[abs(a[i])-1])
if(abs(a[i])==t):
print(t,end=" ")
t=t-1
for j in range(t-1,-1,-1):
if(a[j]<0):
print(t,end=" ")
t=t-1
else:
p... |
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 | def solve():
a,b = list(map(int, input().split()))
diff = abs(b-a)
if diff==0:
print(0)
else:
if diff%10==0:
ans = int(diff/10)
print(ans)
else:
ans = int(diff/10) + 1
print(ans)
return
if __n... |
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one.
Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ... | 3 | def find_ten_root(n):
i=0
while i**10 < n :
i+=1
return(i)
n=int(input())
k=find_ten_root(n)
ans=[k]*10
adad=k**10
p=0
while adad>n :
if adad*(ans[p]-1)/ans[p] >=n :
adad=adad*((ans[p]-1)/ans[p])
ans[p]-=1
p=(p+1)%10
else:
break
a='codeforces'
p=0
answer=... |
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 | for ttt in range(int(input())):
# n, m = map(int, input().split())
n = int(input())
# n, x = map(int, input().split())
a = list(map(int, input().split()))
x = [a[0]]
for i in range(1, n - 1):
if a[i - 1] <= a[i] and a[i + 1] >= a[i] or a[i - 1] >= a[i] and a[i + 1] <= a[i]:
continue
x.append(a[i])
x.append(... |
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.
Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ... | 3 | def binSearch(a, x):
l = -1
r = len(a)
while l < r - 1:
m = (r + l) // 2
if a[m] < x:
l = m
else:
r = m
return r
a = [0] * 47
a[1] = 1
a[2] = 1
for i in range(3, 47):
a[i] = a[i-1]+a[i-2]
n = int(input())
i = binSearch(a, n)
if (n == 0):
print(0, ... |
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'... | 3 | def dragons(lst, k):
summa = 0
i = 0
while i < len(lst):
if lst[i][0] < k:
k += lst[i][1]
else:
return "NO"
i += 1
return "YES"
s, n = [int(i) for i in input().split()]
a = list()
for i in range(n):
x, y = [int(j) for j in input().split()]
a.appe... |
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.
It turned out that among Pasha's friends there are exactly n boys and exactly n... | 3 | n, w = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
ans = 0
if(a[0]*2 > a[n]):
ans = ((a[n]/2)*n) + a[n]*n
else:
ans = (a[0]*n) + (a[0]*2*n)
print(w if ans>w else ans)
|
The development of algae in a pond is as follows.
Let the total weight of the algae at the beginning of the year i be x_i gram. For iβ₯2000, the following formula holds:
* x_{i+1} = rx_i - D
You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.
Constraints
* 2 β€ r β€ 5
* 1 β€ D... | 3 | r, D, x = map(int, input().split())
for i in range(0, 10):
x = r*x -D
print(x) |
We guessed some integer number x. You are given a list of almost all its divisors. Almost all means that there are all divisors except 1 and x in the list.
Your task is to find the minimum possible integer x that can be the guessed number, or say that the input data is contradictory and it is impossible to find such n... | 3 | Q = int(input())
def decompose(x):
ans = {}
cx = x
d = 2
while d * d <= cx:
t = 0
while x % d == 0:
t += 1
x = x // d
if t > 0:
ans[d] = t
d += 1
if x > 1:
ans[x] = 1
return ans
def fastpow(x, p):
if p == 0:
return 1
ans = fastpow(x, p // 2)
ans *= ans
if ... |
Alex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three.
So they play with each other according to following rules:
... | 1 | n=input()
l=[]
for i in range(n):
l.append(input())
spec=3
p=0
for i in range(n):
if l[i] == spec:
print "NO"
p=1
break
if (l[i]==1 and spec ==2) or (l[i]==2 and spec==1):
spec =3
continue
if (l[i]==2 and spec ==3) or (l[i]==3 and spec==2):
spec = 1
... |
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 |
k, n, w = [int(i) for i in input().split()]
totalprice = 0
for i in range(1, w + 1):
totalprice += i * k
if totalprice < n:
print(0)
else:
print(totalprice - n) |
There is an array with n elements a1, a2, ..., an and the number x.
In one operation you can select some i (1 β€ i β€ n) and replace element ai with ai & x, where & denotes the [bitwise and](https://en.wikipedia.org/wiki/Bitwise_operation#AND) operation.
You want the array to have at least two equal elements after appl... | 3 | n, x = map(int, input().split())
a = list(map(int, input().split()))
b = [0 for i in range(100005)]
vis = [0 for j in range(100005)]
flag = 0
tt = 0
for k in a:
b[k] += 1
if b[k] > 1:
flag = 1
break
if flag:
print(0)
else:
for k in a:
t = k & x
if b[t] and k != t:
... |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i β j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| β€ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
a.sort()
ok = True
for i in range(1, len(a)):
if a[i]-a[i-1]>1:
ok = False
print("YES") if ok else print("NO") |
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 3 | def solve(str1):
lang = "HQ9"
code = []
for i in str1:
if(i in lang):
code.append(i)
if(len(code) == 0):
return 'NO'
else:
return 'YES'
str1 = input()
print(solve(str1)) |
You are given a string S of length N and another string T of length M. These strings consist of lowercase English letters.
A string X is called a good string when the following conditions are all met:
* Let L be the length of X. L is divisible by both N and M.
* Concatenating the 1-st, (\frac{L}{N}+1)-th, (2 \times \... | 3 | import math
n, m = map(int, input().split())
s = input()
t = input()
gcd = math.gcd(n, m)
N = n // gcd
M = m // gcd
ans = n * m // gcd
for i in range(gcd):
if s[i*N] != t[i*M] :
ans = -1
break
print(ans) |
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e... | 1 | def get_amazing_perfs(scores):
mn = scores[0]
mx = scores[0]
amzing = 0
for i in scores[1:]:
if i < mn:
mn = i
amzing += 1
elif i > mx:
mx = i
amzing += 1
return amzing
if __name__ == '__main__':
n = int(raw_input())
scores = ... |
Alyona has recently bought a miniature fridge that can be represented as a matrix with h rows and 2 columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but ... | 3 | n, h = [int(x) for x in input().split(" ")]
a = [int(x) for x in input().split(" ")]
m = n
for i in range(0, n):
nok = False
b = a[0:i+1]
b.sort()
if i % 2 != 0:
s = 0
for j in range(1, i+1, 2):
if s+b[j] > h:
nok = True
break
else... |
Natasha's favourite numbers are n and 1, and Sasha's favourite numbers are m and -1. One day Natasha and Sasha met and wrote down every possible array of length n+m such that some n of its elements are equal to 1 and another m elements are equal to -1. For each such array they counted its maximal prefix sum, probably a... | 3 | P = 998244853
N, M = map(int, input().split())
fa = [1]
for i in range(4040):
fa.append(fa[-1]*(i+1)%P)
fainv = [pow(fa[-1], P-2, P)]
for i in range(4040)[::-1]:
fainv.append(fainv[-1]*(i+1)%P)
fainv = fainv[::-1]
def C(a, b):
return fa[a]*fainv[a-b]*fainv[b]%P
def calc(i):
return C(N+M, M) if N-M >... |
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not.
There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc... | 3 | for _ in range(int(input())):
n=int(input())
lis=list(map(int,input().split()))
ans=[]
for i in range(2*n):
if lis[i] not in ans :
ans.append(lis[i])
print(*ans)
|
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 | import math
n=int(input())
def f(n):
x=2
while(x*x<=n):
if(n%x==0):
return(x)
x+=1
return(n)
cnt=0
while(n%2!=0):
n-=f(n)
cnt+=1
print(int(cnt+n/2)) |
Write a program which prints multiplication tables in the following format:
1x1=1
1x2=2
.
.
9x8=72
9x9=81
Input
No input.
Output
1x1=1
1x2=2
.
.
9x8=72
9x9=81
Example
Input
Output | 3 | for n in range(1, 10):
for m in range(1, 10):
print(str(n) + "x" + str(m) + "=" + str(n*m)) |
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t.
Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim... | 3 | n = list(map(int,list(input())))
for i in range(len(n)):
n[i]=min(n[i],9-n[i])
if n[0]==0:
n[0]=9
print(*n,sep="")
|
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 3 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 13:18:48 2020
@author: θ΅΅ζ³½ε
"""
(n,k)=[int(x) for x in input().split()]
score=[int(x) for x in input().split()]
last=score[k-1]
count=0
for i in range(n):
if score[i]>=last and score[i]>0:
count+=1
else:
count=count
print(count) |
Nuske has a grid with N rows and M columns of squares. The rows are numbered 1 through N from top to bottom, and the columns are numbered 1 through M from left to right. Each square in the grid is painted in either blue or white. If S_{i,j} is 1, the square at the i-th row and j-th column is blue; if S_{i,j} is 0, the ... | 3 | import sys
n, m, q = map(int, input().split())
dp1 = [[0] * (m + 1) for _ in range(n + 1)]
dpv = [[0] * (m + 1) for _ in range(n + 1)]
dph = [[0] * (m + 1) for _ in range(n + 1)]
prev_s = '0' * m
for i in range(n):
s = input()
for j in range(m):
is1 = s[j] == '1'
additional = 0
if is... |
You are given an integer x of n digits a_1, a_2, β¦, a_n, which make up its decimal notation in order from left to right.
Also, you are given a positive integer k < n.
Let's call integer b_1, b_2, β¦, b_m beautiful if b_i = b_{i+k} for each i, such that 1 β€ i β€ m - k.
You need to find the smallest beautiful integer y,... | 3 | # import sys
# input = sys.stdin.readline
n, k = map(int, input().split())
x = input()
a = [int(d) for d in x]
b = [0] * n
for i in range(k):
for j in range(i, n, k):
b[j] = a[i]
ok = True
for i in range(n):
if b[i] > a[i]:
ok = True
break
elif b[i] == a[i]:
pass
else:
... |
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.
The valid sizes of T-shirts are either "M" or from 0 to 3 "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.
Ther... | 3 | n = int(input())
d =[]
for i in range(n):
d.append(input())
e =[]
for i in range(n):
e.append(input())
f=e.copy()
for i in range(0,len(f)):
if f[i] in d and f[i] in e:
d.remove(f[i])
e.remove(f[i])
print(len(d)) |
You are given an array a of n integers.
You want to make all elements of a equal to zero by doing the following operation exactly three times:
* Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different).
It can... | 3 | n = int(input())
a = list(map(int, input().split()))
if n == 1:
print(1,1)
print(-1*a[0])
print(1,1)
print(0)
print(1,1)
print(0)
else:
print(2,n)
for i in range(1,n):
if a[i]%n != 0:
val1 = a[i]%n
val = (n-1)*val1
print(val,end=' ')
... |
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.
Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.
Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone... | 3 | s = [1,11,111,1111,2,22,222,2222,3,33,333,3333,4,44,444,4444,5,55,555,5555,6,66,666,6666,7,77,777,7777,8,88,888,8888,9,99,999,9999]
t = int(input())
for _ in range(0,t):
x = int(input())
ans = 0
for i in s:
if i == x:
ans += len(str(i))
break
else:
ans +=... |
The sequence of m integers is called the permutation if it contains all integers from 1 to m exactly once. The number m is called the length of the permutation.
Dreamoon has two permutations p_1 and p_2 of non-zero lengths l_1 and l_2.
Now Dreamoon concatenates these two permutations into another sequence a of length... | 3 | import heapq
t=int(input())
for _ in range(t):
n=int(input())
a=list(map(int,input().split()))
q=[]
s=set()
memo=[0]*n
ret=[]
for i in range(n):
heapq.heappush(q,-a[i])
cmax=heapq.heappop(q)
heapq.heappush(q,cmax)
s.add(a[i])
if len(s)==i+1 and -c... |
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number a, the second player wrote number b. How many ways ... | 3 |
n , m =map(int , input().split())
c1= 0
c2 = 0
w = 0
for i in range(1,7):
if abs(n-i)<abs(m-i):
c1+=1
elif abs(n-i)>abs(m-i):
c2+=1
else :
w+=1
print("{} {} {}".format(c1,w,c2)) |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 3 | n=int(input())
l=[int(x) for x in input().split()]
a=sorted(l,reverse=True)
s0=sum(a)
b=[]
for i in range (n):
b.append(a[i])
s=sum(b)
if s<=(s0/2):
i+=1
else:
break
print(i+1)
|
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it eit... | 3 | import sys;input=sys.stdin.readline
T, = map(int, input().split())
for tt in range(T):
N, M = map(int, input().split())
X = []
for _ in range(N):
X.append(list(map(int, input().split())))
d = [0] * (N+M-1)
d2 = [0] * (N+M-1)
for i in range(N):
for j in range(M):
d[i+j... |
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to... | 3 | n = int(input())
if 10 < n <= 21:
print(4 if n != 20 and n != 21 else (4*4-1 if n == 20 else 4))
else:
print(0) |
Suppose you have two polynomials <image> and <image>. Then polynomial <image> can be uniquely represented in the following way:
<image>
This can be done using [long division](https://en.wikipedia.org/wiki/Polynomial_long_division). Here, <image> denotes the degree of polynomial P(x). <image> is called the remainder o... | 1 | import sys
import random
import functools
import re
import itertools
import math
import copy
import bisect
import Queue
from collections import Counter
sys.setrecursionlimit(1000000)
def debug(*_):
for x in _:
print >> sys.stderr, x,
print >> sys.stderr
if __name__ == "__main__":
n = int(sys.std... |
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | 3 | n1=input()
n2=input()
n3=input()
if(sorted(n1+n2)==sorted(n3)):
print("YES")
else:
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 | for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
flag = True
minus_one = False
plus_one = False
for j in range(n):
if j == 0:
if a[j] != b[j]:
print("NO")
flag = False
... |
There is a directed graph with N vertices and M edges. The i-th edge (1β€iβ€M) points from vertex a_i to vertex b_i, and has a weight c_i. We will play the following single-player game using this graph and a piece.
Initially, the piece is placed at vertex 1, and the score of the player is set to 0. The player can move t... | 3 | N, M = map(int, input().split())
edge = []
for i in range(M):
a, b, c = map(int, input().split())
edge.append([a, b, c*-1])
d = [float('inf')] * (N+1)
d[1] = 0
for i in range(1, N+1):
for e in edge:
if (d[e[0]] != float('inf')) & (d[e[1]] > d[e[0]] + e[2]):
d[e[1]] = d[e[0]] + e[2]
... |
Tsumugi brought n delicious sweets to the Light Music Club. They are numbered from 1 to n, where the i-th sweet has a sugar concentration described by an integer a_i.
Yui loves sweets, but she can eat at most m sweets each day for health reasons.
Days are 1-indexed (numbered 1, 2, 3, β¦). Eating the sweet i at the d-t... | 3 | n, m = map(int, input().split())
a = sorted(list(map(int, input().split())))
s = 0
for i in range(len(a)):
if i < m:
s += a[i]
print(s, end=' ')
continue
a[i] += a[i-m]
s += a[i]
print(s, end=' ')
print() |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | n = int(input())
l = list(map(int, input().split()))
val = l[0]
current = 1
ma = 1
for i in range(1, n):
if l[i] >= val:
current += 1
val = l[i]
else:
ma = max(ma, current)
current = 1
val = l[i]
print(max(ma, current))
|
The German University in Cairo (GUC) dorm houses are numbered from 1 to n. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).
For each house, the... | 1 | #!/usr/bin/python
n , p = map(int , raw_input().split())
From = {}
To = {}
def Input():
for i in range(p):
a , b , d = raw_input().split()
To[a] = (b , int(d))
From[b] = a
#def calu(s):
# global Min
# print(s, Min)
# if not To.has_key(s):
# print(s , Min)
# return (s , Min)
# v = To[s]
# Min = min(Min ,... |
Darshak (Dark) likes to get fruits from trees a lot,he always like to eat those natural fruits directly from the tree.
Today he has an infinite full binary tree (each node has exactly two child's) with special properties.
Dark's tree has the following special properties :
Each node of the tree has a value of goodness.... | 1 | from math import *
L=[2,3,5,7]
def prime_check(num):
if(num==1):
return 0
if(num in L):
return 1
elif(num<=1 or num%2==0 or num%3==0 or num%5==0 or num%7==0):
return 0
for i in xrange(11,int(sqrt(num))+1,4):
if(num%i==0):
return 0
i+=2
if(num%i==0):
return 0
L.append(num)
return 1
... |
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters.
<image>
Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested th... | 1 | n=input()
f=[1,1]
i=2
while True:
t=f[i-1]+f[i-2]
if t>1000:
break
f.append(t)
i+=1
ans=list('o'*n)
for i in range(1,n+1):
if i in f:
ans[i-1]='O'
print ''.join(map(str,ans)) |
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1... | 1 | t = int(raw_input())
for k in xrange(t):
n = int(raw_input())
ar = map(int, raw_input().split())
mini = 56488964895
freq = {}
if n == 1:
print -1
continue
i = 0
j = 1
at = 2
freq[ar[i]] = 1
while j < n and j - i >= 1:
if not ar[j] in freq:
freq[ar[j]] = 0
freq[ar[j]] += 1
#print mini
... |
Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order. From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized. If there are multiple pairs that maximize the value, any of them is accepted.
Constraints
* 2 ... | 3 | n = int(input())
a = list(map(int, input().split()))
a_i = max(a)
a.sort(key=lambda x: abs(a_i/2-x))
if a[0] == a_i:
print(a_i, a[1])
else:
print(a_i, a[0])
|
Recently, Norge found a string s = s_1 s_2 β¦ s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them!
A substring of s is a non-empty string x = s[a β¦ b] = s_{a} s_{a + 1} β¦ s_{b} (1 β€ a β€ b β€ n). For e... | 3 | import operator as op
from functools import reduce
def nCr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom
entrada = input().split(" ")
palavra = input()
keyboard = input().split(" ")
n = int(entrada[0])
k = int(ent... |
We have N pieces of ropes, numbered 1 through N. The length of piece i is a_i.
At first, for each i (1β€iβ€N-1), piece i and piece i+1 are tied at the ends, forming one long rope with N-1 knots. Snuke will try to untie all of the knots by performing the following operation repeatedly:
* Choose a (connected) rope with a... | 3 | N,L = map(int,input().split())
A = list(map(int,input().split()))
A.insert(0,0)
cmax = 0
ind = -1
for i in range(1,N):
if A[i]+A[i+1]>cmax:
cmax = A[i]+A[i+1]
ind = i
if cmax>=L:
print("Possible")
for i in range(1,ind):
print(i)
for i in range(N-1,ind-1,-1):
print(i)
else... |
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get th... | 1 | fact = (1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800)
head = True
head_char = False
chars = [False] * 10
head_q = False
question = 0
for c in raw_input():
if c.isalpha() and not chars[ord(c) - ord('A')]:
if head:
head_char = True
chars[ord(c) - ord('A')] = True
if c == '?'... |
Alice and Bob play a game. There is a paper strip which is divided into n + 1 cells numbered from left to right starting from 0. There is a chip placed in the n-th cell (the last one).
Players take turns, Alice is first. Each player during his or her turn has to move the chip 1, 2 or k cells to the left (so, if the ch... | 3 | T = int(input())
A = "Alice"
B = "Bob"
for _ in range(T):
n, k = map(int,input().split())
if(n==0):
print(B)
elif(k%3!=0):
print(B) if(n%3==0) else print(A)
else:
if(n%(k+1)%3==0 and n%(k+1)!=k):
print(B)
else:
print(A)
|
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 β€ x β€ a) coins of value n and y (0 β€ y β€ b) coins of value 1, then the total value of taken coins will be S.
You have to answer q independent test cases.
Input
The... | 3 | for i in range(int(input())):
a, b, n, s = map(int,input().split())
m = s//n
if m >= a:
v = n*a + b
else:
v = m*n + b
if v >= s:
print('YES')
else:
print('NO') |
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks.
<image>
There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the ... | 3 | import sys
n=int(sys.stdin.readline())
d=list(map(int,sys.stdin.readline().split()))
s=[[] for g in d]
mxpt=[-2e9,-2e9]
mxcnt=[0,0]
for i in d:
if i>mxpt[0]:
mxpt[1]=mxpt[0]
mxcnt[1]=mxcnt[0]
mxpt[0]=i
mxcnt[0]=1
elif i==mxpt[0]:
mxcnt[0]+=1
elif i>mxpt[1]:
mxpt[1]=i
mxcnt[1]=1
else: mxcnt[1]+=(i==mxp... |
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi... | 3 | n, m = map(int, input().split())
a = list(map(int, input().split()))
s = (n - 1) * 2
#print(s)
#print(m, sum(a), s*5)
v = m - sum(a) - (s*5)
if(v == 0):
print(s)
elif(v/5 > 0):
print(s + int(v / 5))
else:
print(-1)
|
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.
But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than n. Can you help me to find th... | 1 | def cmmdc(a, b):
if b == 0: return a
return cmmdc(b, a%b)
def cmmmc(x, y):
return int((x*y)/cmmdc(x,y))
def maxim(a, b):
if a>b: return a
return b
def main():
n = int(raw_input())
"""
if n%2==0:
if n%3==0:
sol = cmmmc( n-1, cmmmc(n, n-2) )
sol = maxim... |
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible.
There are n manholes in the room which are situated on one line, but, unfortunately, all the manholes are clo... | 3 | def ans(n, k):
if(n == 2):
return(6)
return(min(k - 1, n - k) + 6 + 3 *(n - 2))
if __name__ == '__main__':
nk = list(map(int, input().strip().split()))
print(ans(nk[0], nk[1])) |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | s = input()
if(len(set(s))%2!=0):
print("IGNORE HIM!")
else:
print("CHAT WITH HER!") |
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.
Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of o... | 3 | s=input()
t=input()
print(max(len(s),len(t)) if(s!=t) else -1) |
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m... | 3 |
def cap(a, b):
if a == b:
print(0)
return
if b > a:
a, b = b, a
if a % b != 0:
print(-1)
return
count = 0
k = a // b
while k > 1:
if k % 8 == 0:
k //= 8
count += 1
continue
elif k % 4 == 0:
k... |
The main street of Berland is a straight line with n houses built along it (n is an even number). The houses are located at both sides of the street. The houses with odd numbers are at one side of the street and are numbered from 1 to n - 1 in the order from the beginning of the street to the end (in the picture: from ... | 3 | n,a=[int(x) for x in input().split()]
if a&1:
print(a//2+1)
else:
print((n-a)//2+1) |
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
Input
The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.
Output
Print "YES" (without the quot... | 3 | s=str(input())
aba,ab,ba,skip=0,0,0,0
n=len(s)
for i in range(n):
if i<skip:
continue
if i+2<n and ((s[i]=="B" and s[i+1]=="A" and s[i+2]=="B") or (s[i]=="A" and s[i+1]=="B" and s[i+2]=="A")):
aba+=1
skip=i+3
elif i+1<n and s[i]=="A" and s[i+1]=="B":
ab+=1
skip=i+2
... |
Write a program which finds the greatest common divisor of two natural numbers a and b
Hint
You can use the following observation:
For integers x and y, if x β₯ y, then gcd(x, y) = gcd(y, x%y)
Constrants
1 β€ a, b β€ 109
Input
a and b are given in a line sparated by a single space.
Output
Output the greatest comm... | 1 | # -*- coding: utf-8 -*-
def converter(a, b):
larger = max(a, b)
smaller = min(a, b)
if smaller == 0:
return larger
else:
return converter(smaller, larger % smaller)
def main():
a, b = [int(x) for x in raw_input().strip().split(' ')]
print converter(a, b)
if __name_... |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner β Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | n= input()
s= input()
n=int(n)
def solution(n,s):
a = 0;
b = 0;
for i in range(len(s)):
if (s[i]=='A'):
a+=1
else:
b+=1
if a>b:
return "Anton"
elif a<b:
return "Danik"
else:
return "Friendship"
print (solution(n,s)) |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | a=int(input(""))
c=a%2
if a>=4 and c==0:
print("YES")
else:
print("NO")
|
You have an initially empty cauldron, and you want to brew a potion in it. The potion consists of two ingredients: magic essence and water. The potion you want to brew should contain exactly k\ \% magic essence and (100 - k)\ \% water.
In one step, you can pour either one liter of magic essence or one liter of water i... | 3 | from math import ceil, gcd
from collections import Counter
for ttt in range(int(input())):
n=int(input())
ess=n
wat=100-n
hh=gcd(ess,wat)
print(wat//hh+ess//hh) |
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 β€ a, b β€ 103), separated by a single space.
Output
Output ... | 1 | import sys
import re
s = raw_input()
g = re.match("([0-9-]+) ([0-9-]+)", s)
a = int(g.group(1))
b = int(g.group(2))
sys.stdout.write(str(a+b)) |
There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the trou... | 3 | def fact(k):
res = 1
for i in range(1, k+1):
res *= i
return res
def Cnk(n, k):
return fact(n) // (fact(k) * fact(n-k))
n, m, t = map(int, input().split(' '))
minN = 4
minM = 1
total = 0
N = minN
while N + minM <= t:
M = t - N
if N <= n and M <= m:
total += Cnk(n, N) * Cnk(m... |
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 | # cook your dish here
import math
t = int(input())
while t:
a,b = map(int,input().split())
moves = math.ceil((abs(a-b))/10)
print(moves)
t-=1 |
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())
mat=[]
ans="NO"
for i in range(n):
a11,a12=map(int,input().split())
a21,a22=map(int,input().split())
mat.append([a11,a12,a21,a22])
if a12==a21 and m%2==0:
ans="YES"
print(ans)
|
You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset.
Both the given array and required subset may contain equal values.
Input
The first line contains a single integer t (1 β€ t β€... | 3 | t=int(input())
def fun(n,a):
flag=0
for i in range(n):
for j in range(i+1,n+1):
s=a[i:j]
if sum(s)%2==0:
print(j-i)
ss=[k+1 for k in range(i,j)]
# print(ss)
print(*ss,sep=" ")
flag+=1... |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 1 |
n=input()
print max(n,-int(-n/10),-int(-n/100*10+-n%10)) |
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example:
* 10010 and 01111 are similar (they have the same character in position 4);
* 10... | 3 | for _ in range(int(input())):
n = int(input())
s = input()
if(s.count('0'*n) >= 1): print ("0"*n)
else: print("1"*n) |
Imp likes his plush toy a lot.
<image>
Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies.
Initially, Imp has only on... | 1 | x,y = map(int,raw_input().split())
me = y-1
if(y == 0):
print "No"
elif(y == 1):
if(x == 0):
print "Yes"
else:
print "No"
elif(x < me):
print "No"
else:
left = x-me
if(left == 0):
print "Yes"
else:
if(left%2 == 0):
print "Yes"
else:
... |
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ... | 3 | n=int(input())
i1=input()
z_count=i1.count('0')
o_count=i1.count('1')
# while ('01','10' in i1):
# if '01' in i1:
# i1=i1.replace('01','')
# elif '10' in i1:
# i1=i1.replace('10','')
# else:
# break
print(max(z_count,o_count)-min(z_count,o_count))
# print(len(str(i1)))
|
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example:
* 10010 and 01111 are similar (they have the same character in position 4);
* 10... | 3 | from sys import stdin
def inp():
return stdin.buffer.readline().rstrip().decode('utf8')
def itg():
return int(stdin.buffer.readline())
def mpint():
return map(int, stdin.buffer.readline().split())
# ############################## import
# ############################## main
for __ in range(itg()):
... |
Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts a... | 3 | x=input()
y=input().split()
y=[int(i) for i in y]
c1=0
c2=0
for i in y:
if(i%2==0):
c1+=1
else:
c2+=1
if(sum(y)%2!=0):
print("First")
else:
if(c2!=0):
print("First")
else:
print("Second")
|
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ... | 3 | t = int(input())
while t:
t -= 1
n, k = map(int, input().split(' '))
s = input()
ones = list(filter(lambda x: s[x] == '1', range(n)))
ones.insert(0, -k-1)
ones.append(n+k)
l = len(ones)
ans = 0
for i in range(l-1):
ans += (ones[i+1] - ones[i] - k - 1) // (k + 1)
print(ans... |
You've come to your favorite store Infinitesco to buy some ice tea.
The store sells ice tea in bottles of different volumes at different costs. Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen. The store has an infinite supply... | 3 | Q, H, S, D = map(int, input().split())
N = int(input())
S = min(Q * 4, H * 2, S)
D = min(S * 2, D)
ans = (N//2) * D + (N%2) * S
print(ans) |
You are given two integers x and y. You can perform two types of operations:
1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation:
* x = 0, y = 6;
* x = 0, y = 8;
* x = -1, y = 7;
* x = 1, y = ... | 3 | t=int(input())
for hh in range(0,t):
x,y=[int(x) for x in input().split()]
a,b=[int(x) for x in input().split()]
mn=min(x,y)
mx=max(x,y)
ans1=mn*b+(mx-mn)*a
ans2=(x+y)*a
print(min(ans1,ans2)) |
You are given one integer n (n > 1).
Recall that 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 of length 5, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (... | 3 | for t in range(int(input())):
n=int(input())
if(n%2==0):
for i in range(n,0,-1):
print(i,end=" ")
else:
for i in range((n//2)+1,n+1,1):
print(i,end=" ")
for i in range(n//2,0,-1):
print(i,end=" ")
|
There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.
Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, ... | 3 | R,C,K=map(int,input().split())
m=[[0]*(C+1) for _ in range(R+1)]
for _ in range(K):
r,c,v=map(int,input().split())
m[r][c]=v
d=[[0]*4 for _ in range(R+1)]
for j in range(1,C+1):
for i in range(1,R+1):
t=m[i][j]
if t>0:
d[i][3]=max(d[i][3],d[i][2]+t)
d[i][2]=max(d[i][2],d[i][1]+t)
d[i][1]... |
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point ... | 3 | t = int(input())
while t > 0:
n,k = map(int, input().split(' '))
if n == k:
print(0)
if k > n:
print(k-n)
if k < n:
if (k % 2 == n % 2):
print(0)
else:
print(1)
t -= 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.