problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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 |
scheme = input()
def football(sscheme):
dangerous = 'NO'
if '0000000' in sscheme or '1111111' in sscheme:
dangerous = 'YES'
return dangerous
print(football(scheme)) |
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 | from math import *
t=int(input())
for i in range(t):
a,b,n=map(int,input().split())
f=0
while a<=n and b<=n:
m=max(a,b)
mn=min(a,b)
if mn==a:
a+=m
else:
b+=m
f+=1
print(f) |
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | import string
s1 = input().lower()
s2 = input().lower()
if s1 < s2:
print("-1")
elif s1 == s2:
print("0")
else:
print("1") |
You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i ≥ a_{i-1} holds) and an integer k.
You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.
Let max(i) be equal to the maximum in the i-th subar... | 3 | n, k = map(int, input().split())
arr = [int(x) for x in input().split()]
diff = [arr[i] - arr[i-1] for i in range(1, n)]
diff.sort(reverse=True)
cost = sum(diff)
for i in range(k-1):
cost -= diff[i]
print(cost)
|
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter... | 3 | a = input().split()
n = int(a[0])
m = int(a[1])
walrus = 1
while m >= walrus:
m = m - walrus
walrus = walrus + 1
if walrus > n:
walrus = 1
print(m)
# 1513951319879
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 1 | n = int(input())
l1 = list()
l2 = list()
l3 = list()
for i in range(n):
a,b,c = map(int,raw_input().split(" "))
l1.append(a)
l2.append(b)
l3.append(c)
a = sum(l1)
b = sum(l2)
c = sum(l3)
if a==0 and b==0 and c==0:
print("YES")
else:
print("NO") |
"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 | def mod():
x=input().split()
y=int(x[0])
z=int(x[1])
f=input().split()
a=list(map(int,f))
a.sort(reverse=True)
counter=0
for i in range(len(a)):
if a[i]>=a[z-1] and a[i]>0:
counter+=1
print(counter)
mod() |
There are N children standing in a line from left to right. The activeness of the i-th child from the left is A_i.
You can rearrange these children just one time in any order you like.
When a child who originally occupies the x-th position from the left in the line moves to the y-th position from the left, that child... | 3 | N=int(input())
A=list(map(int,input().split()))
A=[(A[i],i) for i in range(0,N)]
A.sort(reverse=True)
dp=[[0 for i in range(0,N)] for j in range(0,N)]
for i in range(0,N-1):
a,index=A[-1]
dp[N-1][i]=a*abs(index-i)
for _ in range(1,N):
i=N-1-_
for j in range(0,i+1):
left=j
right=i-j
... |
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 ... | 3 | # cook your dish here
b=int(input())
flag=0
for i in range(1,b+1):
s=list(str(i))
fo=s.count('4')
sev=s.count('7')
if (fo+sev)==len(s):
if b%i==0:
flag=1
break
if flag==1:
print('YES')
else:
print('NO') |
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | n=int(input())
q=list(map(int,input().split()))
w=n*[0]
for i in range (n):
w[q[i]-1]=i+1
for i in w:
print(i,end=" ")
|
Valera has got n domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do t... | 1 | import sys, math
boven=[]
onder=[]
draaien=False
n=int(sys.stdin.readline())
for x in range(n):
a=[int(x) for x in sys.stdin.readline().split()]
boven.append(a[0])
onder.append(a[1])
if sum(a)%2==1:
draaien=True
if (sum(boven)+sum(onder))%2==1:
print -1
else:
if sum(boven)%2==0:
... |
Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.
First Petya puts a marble under the glass in position s. Then he performs some (pos... | 1 | r=lambda:map(int, raw_input().split())
n,s,t=r()
p=r()
i=0
a=[0]*n
b=False
while s != t:
if a[s-1]:
b=True
break
a[s-1]=1
s = p[s-1]
i+=1
print -1 if b else i |
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve... | 1 | # Vasya and Socks
data = raw_input().split()
n = int(data[0])
m = int(data[1])
socks = n
day = 1
while socks > 0:
if day % m != 0:
socks -= 1
day += 1
print day - 1
|
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 | t = int(input())
for i in range(t):
n = input()
c = 0
nums = []
n_reversed = n[::-1]
for k in range(len(n)):
if n_reversed[k] != '0':
c += 1
nums.append(n[(len(n)-k-1):])
n_list = list(n)
n_list[len(n)-k-1] = '0'
n = "".join(n_list)... |
Jamie loves sleeping. One day, he decides that he needs to wake up at exactly hh: mm. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every x minutes until hh: mm is reached, and only then he will wake up. He wants to kno... | 3 | n=int(input())
h,m = [int(i) for i in input().split()]
if h%10==7 or m%10==7 or h//10==7 or m//10==7 :
print(0)
else :
c = 0
while True:
m-=n
c+=1
if m<0:
m+=60
h-=1
if h<0 : h=23
if h%10==7 or m%10==7 or h//10==7 or m//10==7 :
... |
Takahashi has N days of summer vacation.
His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.
He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.
What is the maximum number of days Takahashi can hang out during the vacation if ... | 3 | N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
print(max(N - sum(A), -1)) |
Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market!
In the morning, there are n opportunities to buy shares. The i-th of them allows to buy as many shares as you want, each at the price o... | 3 | import sys
# sys.setrecursionlimit(10**6)
from sys import stdin, stdout
import bisect #c++ upperbound
import math
import heapq
def modinv(n,p):
return pow(n,p-2,p)
def cin():
return map(int,sin().split())
def ain(): #takes array as input
return list(map(int,sin().split... |
Bob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume.
There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrea... | 3 | from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
from fractions import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 1000010
MOD = 10**9+7
spf = [i for i in range(MAXN)]
def sieve():
for i ... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 1 | s=raw_input()
x=0
for i in range(len(s)):
if s[i]=="4" or s[i]=="7":
x+=1
if x==4 or x==7:
print "YES"
else:
print "NO" |
Alice and Bob are playing One Card Poker.
One Card Poker is a two-player game using playing cards.
Each card in this game shows an integer between `1` and `13`, inclusive.
The strength of a card is determined by the number written on it, as follows:
Weak `2` < `3` < `4` < `5` < `6` < `7` < `8` < `9` < `10` < `11` < `... | 3 | a, b = map(int, input().split())
print('Draw' if a == b else 'Alice' if (a+12) % 14 > (b+12) % 14 else 'Bob')
|
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 = 0
for i in range(n) :
a = input()
l = a.split()
temp = 0
for j in range(3):
if l[j]=='1':
temp += 1
if(temp >= 2):
ans += 1
print(ans)
|
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1... | 3 | l=input().split()
m=int(l[0])
n=int(l[1])
l=[]
for i in range(m):
lo=input().split()
li=[int(i) for i in lo]
l.append(li)
arr=[[0 for i in range(n)]for i in range(m)]
ok=0
for i in range(m):
ok+=l[i][0]
arr[i][0]=ok
for i in range(1,n):
curr=0
for j in range(m):
curr=max(curr,arr[j][... |
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations:
* eat exactly... | 3 | for _ in range(int(input())):
input()
a = list(map(int,input().split()))
b = list(map(int,input().split()))
min_a = min(a)
min_b = min(b)
moves = 0
for (a_i,b_i) in zip(a,b):
a_i -= min_a
b_i -= min_b
moves += max(a_i,b_i)
print(moves)
|
A wise king declared a new calendar. "Tomorrow shall be the first day of the calendar, that is, the day 1 of the month 1 of the year 1. Each year consists of 10 months, from month 1 through month 10, and starts from a big month. A common year shall start with a big month, followed by small months and big months one aft... | 1 | #!/usr/bin/env python
import sys
import math
import itertools as it
from collections import deque
sys.setrecursionlimit(10000000)
n = input()
for loop in range(n):
y, m, d = map(int, raw_input().split())
m_lst = [20, 19, 20, 19, 20, 19, 20, 19, 20, 19]
cnt = 0
for i in range(m - 1):
cnt += m... |
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds n is defined. I... | 3 | a=int(input())
b=[]
c=[]
m=0
n=0
for i in range(a):
k=input().split()
d=int(k[0])
e=int(k[1])
b.append(d)
c.append(e)
for i in range(a):
if b[i] > c[i]:
m+=1
elif b[i]==c[i]:
continue
else:
n+=1
if m > n:
print("Mishka")
elif m < n:
print("Chris")
else:
... |
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | 3 | a=int(input())
b=int(input())
c=int(input())
d=int(input())
e=int(input())
f=[]
if(a==1 or b==1 or c==1 or d==1):
f.append(1)
if(True):
for i in range(1,e+1):
if(a*i<=e):
f.append(a*i)
if(b*i<=e):
f.append(b*i)
if(c*i<=e):
f.append(c*i)
if(d*... |
Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.
You are given Smeke's current rating, x. Print `ABC` if Smeke will participate in ABC, and print `ARC` otherwise.
Constraints
* 1 ≦ x ≦ 3{,}000
* x i... | 1 | N = int(raw_input())
ans = "ARC"
if(N < 1200):
ans = "ABC"
print ans |
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.
Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ... | 3 | def factorial(n):
lst = [1]
p = 1
for i in range(1, n+1):
lst.append((i*lst[i-1]))
return (lst)
n=int(input())
l=[int(j) for j in input().split()]
c,cnt=0,0
k=[0]*n
l.sort()
if n%2!=0:
k[n-1]=l[n-1]
for i in range(n//2):
k[c]=l[n//2+i]
c+=1
k[c]=l[i]
c+=1
for i in range(1,n-... |
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols ... | 3 | n = int(input())
values = list(map(int,input().split()))
q = int(input())
for i in range(q):
a,b = map(int,input().split())
a = a-1
x = 0
y = 0
if a>0:
values[a-1] += b-1
x = b-1
if a<n-1:
values[a+1] += values[a]-b
y= (values[a]-b)
values[a]=0
for i in range(... |
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... | 1 | from sys import stdin, stdout
ti = lambda : stdin.readline().strip()
ma = lambda fxn, ti : map(fxn, ti.split())
ol = lambda arr : stdout.write(' '.join(str(i) for i in arr) + '\n')
os = lambda i : stdout.write(str(i) + '\n')
olws = lambda arr : stdout.write(''.join(str(i) for i in arr) + '\n')
n = int(ti())
a = ma(int... |
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()
import re
x=re.compile(r'^(.*)h(.*)e(.*)l(.*)l(.*)o(.*)$')
if x.match(s):
print("YES")
else:
print("NO")
|
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n × m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.
A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of ... | 1 | import sys
import time
str=raw_input()
ssp=str.split()
n=int(ssp[0])
m=int(ssp[1])
mx=[0,1,0,-1]
my=[1,0,-1,0]
a=[]
v=[]
i=0
j=0
k=0
for i in range(0,n):
str=raw_input()
a.append(str)
v.append([0]*m)
ans=0
for i in range(0,n):
str=a[i]
for j in range(0,m):
if str[j]=='P':
for ... |
You are given three integers A, B and C.
Determine if there exists an equilateral triangle whose sides have lengths A, B and C.
Constraints
* All values in input are integers.
* 1 \leq A,B,C \leq 100
Input
Input is given from Standard Input in the following format:
A B C
Output
If there exists an equilateral ... | 3 | x=[int(i) for i in input().split(" ")]
y="Yes" if x[0]**3==x[0]*x[1]*x[2] else "No"
print(y) |
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | n=[int(i) for i in input()]
s=[int(i) for i in input()]
print("".join(str(n[i]^s[i]) for i in range(len(n)))) |
Areas on the Cross-Section Diagram
Your task is to simulate a flood damage.
For a given cross-section diagram, reports areas of flooded sections.
<image>
Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides. For example, for the abov... | 3 | def marge_ponds(lx, area_of_pond):
global ponds
if ponds:
lp = ponds.pop()
if lp[0] > lx:
return marge_ponds(lx, area_of_pond + lp[1])
else:
ponds.append(lp)
return area_of_pond
terrains = input().strip()
x, last_x, ponds = 0, [], []
for terrain in terrains... |
You are given two arrays a and b, both of length n.
Let's define a function f(l, r) = ∑_{l ≤ i ≤ r} a_i ⋅ b_i.
Your task is to reorder the elements (choose an arbitrary order of elements) of the array b to minimize the value of ∑_{1 ≤ l ≤ r ≤ n} f(l, r). Since the answer can be very large, you have to print it modulo... | 3 | n = int(input())
a = []
b = []
s = input().split(' ')
for i in range(n):
a.append(int(s[i]))
s = input().split(' ')
for i in range(n):
b.append(int(s[i]))
l = 1
r = n
for i in range(n):
a[i] = (l * r * a[i])
l += 1
r -= 1
a.sort()
b.sort()
b.reverse()
ans = 0
mod = 998244353
for i in range(n):
ans = (ans + ... |
Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.
Tell him whether he can do so.
Input
The first line of the input contains a single integer t (1≤ t ≤... | 3 | import math
for _ in range(int(input())):
n,x = map(int,input().split())
a = list(map(int,input().split()))
if n==x:
if sum(a)%2:
print("Yes")
else:
print("No")
elif x == 1:
f = 1
for i in a:
if i%2:
... |
There was an electronic store heist last night.
All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ... | 3 | n=int (input())
a=list(map(int,input().strip().split(" ")))
mi=min(a)
ma=max(a)
print(ma-mi-len(a)+1) |
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 i in range(t):
x,y=map(int,input().split())
a,b=map(int,input().split())
if b>=2*a:
print((x+y)*a)
else:
print(min(x,y)*b+(max(x,y)-min(x,y))*a)
|
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 | #!/usr/bin/env python
a = input()
if ('H' in a) or ('Q' in a) or ('9' in a):
print("YES")
else:
print("NO")
|
Lunar New Year is approaching, and you bought a matrix with lots of "crosses".
This matrix M of size n × n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 ≤ i, j ≤ n. We define a cross appearing in the i-th row and the j-th column (1 < i... | 3 | n=int(input())
l=[]
for i in range(0,n):
p=input().rstrip()
x=list(p)
l.append(x)
if n<=2:
print(0)
else:
T=0;
for i in range(1,len(l)-1):
for j in range(1,len(l[i])-1):
if l[i][j]=='X' and l[i-1][j-1]=='X' and l[i-1][j+1]=='X' and l[i+1][j-1]=='X' and l[i+1][j+1]=='X':
... |
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | 3 | T = int (input ())
for I in range (0, T):
M = input ().split (' ')
X = int (M [0])
Y = int (M [1])
N = int (M [2])
print (int ((N - Y) // X * X + Y)) |
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment ... | 3 | fly1 = list(map(int, input().split()))
fly2 = list(map(int, input().split()))
if fly1[0] == fly2[0] or fly1[2] == fly2[2] or fly1[1] == fly2[1]:
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 | nums = input().strip().split('+')
nums = list(map(int, nums))
nums.sort()
nums = map(str, nums)
print('+'.join(nums)) |
There are n points on the plane, (x_1,y_1), (x_2,y_2), …, (x_n,y_n).
You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
I... | 3 | n=int(input())
max_=0
for i in range(n):
a,b=map(int,input().split())
max_=max(max_,a+b)
print(max_)
|
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).
A... | 3 | n = int(input())
arr = list(map(int, input().split()))
q = int(input())
check = [0]*(10**5 + 1)
sum2 = 0
sum4 = 0
for i in arr:
sum2 -= check[i] // 2
sum4 -= check[i] // 4
check[i] += 1
sum2 += check[i] // 2
sum4 += check[i] // 4
for i in range(q):
a, b = input().split()
b = int(b)
if a ... |
You are given a Young diagram.
Given diagram is a histogram with n columns of lengths a_1, a_2, …, a_n (a_1 ≥ a_2 ≥ … ≥ a_n ≥ 1).
<image> Young diagram for a=[3,2,2,2,1].
Your goal is to find the largest number of non-overlapping dominos that you can draw inside of this histogram, a domino is a 1 × 2 or 2 × 1 recta... | 3 | n=int(input())
a=map(int,input().split())
x=0
y=0
for i in a:
x+=i//2
y+=(i+1)//2
x,y=y,x
print(min(x,y)) |
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.
CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly th... | 3 | import sys
sys.version
n=int(input())
for i in range(1,n+1):
x=int(input())
ans=0
if(x%3==0 or x%7==0):
ans=1
for y in range(1,x+1):
if(x-y*3>=0 and (x-y*3)%7==0):
ans=1
if ans==1:
print("YES")
else:
print("NO")
|
You are given $n$ packages of $w_i$ kg from a belt conveyor in order ($i = 0, 1, ... n-1$). You should load all packages onto $k$ trucks which have the common maximum load $P$. Each truck can load consecutive packages (more than or equals to zero) from the belt conveyor unless the total weights of the packages in the s... | 3 | def calc_k_constP(P):
tmp_total_w = 0
tmp_k = 1
for w in w_s:
tmp_total_w += w
if tmp_total_w > P:
tmp_k += 1
tmp_total_w = w
return tmp_k
n, k = map(int, input().split(' '))
w_s = [int(input()) for i in range(n)]
max_w = max(w_s)
left, right = max_w, 10000 * ... |
Gildong's town has a train system that has 100 trains that travel from the bottom end to the top end and 100 trains that travel from the left end to the right end. The trains starting from each side are numbered from 1 to 100, respectively, and all trains have the same speed. Let's take a look at the picture below.
<i... | 1 | from __future__ import print_function, division
import sys
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
input = lambda: sys.stdin.readline().rstrip("\r\n")
from functools import reduce
def common_member(a, b):
a_set = set(a)
b_set = set(b)
s = a_set &... |
Not so long ago company R2 bought company R1 and consequently, all its developments in the field of multicore processors. Now the R2 laboratory is testing one of the R1 processors.
The testing goes in n steps, at each step the processor gets some instructions, and then its temperature is measured. The head engineer in... | 3 | if __name__ == '__main__':
cin = input
n, m, ln, rn = map(int, cin().split())
a = [int(v) for v in cin().split()]
if ln < min(a) <= max(a) < rn:
print(["Incorrect", "Correct"][n - m > 1])
else:
print(["Correct", "Incorrect"][min(a) < ln or max(a) > rn])
|
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets.
Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filt... | 3 | def main():
n, m, k = map(int, input().split())
m -= k
if m > 0:
for i, a in enumerate(sorted(map(int, input().split()), reverse=True), 1):
m -= a - 1
if m <= 0:
print(i)
break
else:
print(-1)
else:
print(0)
if... |
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number".
Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co... | 3 | n = int(input())
# nm+1 |= d
def prime(n):
if n == 1:
return False
for i in range(2,n):
if n%i == 0:
return False
return True
if prime(n) and n!=2:
print(1)
else:
for i in range(1,1000+1):
if not prime(n*i+1):
print(i)
break
|
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official language... | 3 | def fastio():
import sys
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
MOD = 10**9 + 7
I = lambda:list(... |
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from t... | 1 | def go(n):
if n<4:
return [1] if 1==n else [1,2] if 2==n else [1,1,3]
a=go(n/2)
for i in range(len(a)):
a[i]*=2
return [1]*((n+1)/2)+a
print ' '.join(map(str,go(input())))
|
Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≤ m ≤ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
... | 3 | n=int(input())
s=input();l=0;r=1;k=1
w=""
while r<=n:
#print (s[l:r][0])
w+=s[l:r][0]
k+=1
l=r
r+=k
print (w)
|
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ... | 1 | number=raw_input()
n=len(number)
new_num=''
max_num=int(number[:n-1],2)
j=len(number)-1
for i in range(1,n-1):
if number[i]=='0':
new_num=number[:i]+number[i+1:]
num=int(new_num,2)
if num>max_num:
max_num=num
break
print bin(max_num)[2:]
|
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem... | 3 | n=int(input())
s=input()
if s[0]=='S' and s[n-1]=='F':
print("Yes")
else:
print("No") |
There is a cave.
The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.
It is dark in th... | 3 | import collections
n,m=map(int, input().split())
g=[[] for _ in range(n+1)]
for i in range(m):
a,b=map(int,input().split())
g[a].append(b)
g[b].append(a)
q=collections.deque()
q.append(1)
visit=[-1]*(n+1)
visit[1] = 1
ans=[0]*(n+1)
while q:
v=q.popleft()
for i in g[v]:
if visit[i] == -1:
ans[i] = v
visit... |
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.
There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ... | 3 | n, m = map(int, input().split())
s = input().split()
t = input().split()
q = int(input())
for _ in range(q):
tmp = int(input())
print(s[(tmp+n-1)%n]+t[(tmp+m-1)%m])
|
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a ... | 3 | n,m=map(int,input().split())
B=[]
for i in range(n):
A=list(map(str,input().split()))
B.append(A)
for i in B:
if (('C' in i) or ('Y' in i) or ('M' in i)):
print("#Color")
break
else:
print("#Black&White")
|
We have a sequence of N integers: A_1, A_2, \cdots, A_N.
You can perform the following operation between 0 and K times (inclusive):
* Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element.
Compute the maximum possible pos... | 3 | N, K = map(int, input().split())
A = list(map(int, input().split()))
S = sum(A)
D = []
i = 1
while i * i <= S:
if S % i == 0:
D.append(i)
if S // i != i:
D.append(S // i)
i += 1
D = sorted(D, reverse=True)
for d in D:
mod = [a % d for a in A]
mod = sorted(mod)
s = sum(m... |
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, r... | 3 | # @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-11-04 15:07
# @url:https://codeforc.es/contest/1445/problem/D
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio
BUFSIZE = 8192
BUFSIZE = 8192
class FastI... |
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... | 1 | #Question Name --> Anton and Danik
x = input()
y = raw_input()
q = y.count('A')
w = y.count('D')
if(q>w):
print 'Anton'
elif(q<w):
print 'Danik'
else:
print 'Friendship' |
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 sys
def canBeCutEven(w: int) -> bool:
if w > 2 and (w - 2) % 2 == 0:
print('YES')
else:
print('NO')
input = sys.stdin.readline
w = int(input())
canBeCutEven(w) |
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins.
Constraints
* N is an integer between 1 and 10000 (inclusive).
* A is an integer between 0 and 1000 (inclusive).
Input
Input is given from Standard Input in the following format:
N
A
Output... | 3 | n,m=open(0)
n,m=int(n)%500,int(m)
print( "Yes" if n%500<=m else "No") |
You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.
The following definition of a... | 3 | s = input()
open = "({<["
close = ")}>]"
clopen = {']': '[', '}': '{', '>': '<', ')': '('}
ir2 = 0
ir = 0
if len(s) % 2 == 1:
print("Impossible")
exit()
else:
l = []
for i in range(len(s)):
if s[i] in open:
ir += 1
l.append(s[i])
else:
ir -= 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 | string=input()
string=set(string)
if (len(string)%2==0):
print("CHAT WITH HER!")
else :
print("IGNORE HIM!")
|
"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 | n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
ans=0
for i in range(len(a)):
if a[i]>=a[k-1] and a[i]>0:
ans+=1
print(ans)
|
Two little greedy bears have found two pieces of cheese in the forest of weight a and b grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox... | 1 | import sys
def get(num):
#print num
x1 = 0
while (num > 0 and num%2 == 0):
x1 = x1 + 1
num = num / 2
y1 = 0
while (num > 0 and num%3 == 0):
y1 = y1 + 1
num = num / 3
z1 = 0
while (num > 0 and num%5 == 0):
z1 = z1 + 1
num = num / 5
... |
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 | q = int(input())
for i in range(q):
a, b, n, S = map(int,input().split())
if a*n + b < S:
print('NO')
elif S % n > b:
print('NO')
else:
print('YES') |
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.
CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly th... | 3 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 12 18:04:15 2017
@author: ms
"""
def main():
n = int(input())
ch = []
for i in range(n):
ch.append(int(input()))
res = []
for i in range(1,101):
num = i
ok = False
while(num>=0):
if (num%7 == 0):
... |
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the ... | 3 | n,m=map(int,input().split())
a=input()
b=input()
dp=[[0 for i in range(m+1)] for j in range(n+1)]
ans=0
for i in range(1,n+1):
for j in range(1,m+1):
if a[i-1]==b[j-1]:
dp[i][j]=max(dp[i][j],dp[i-1][j-1]+2)
ans=max(ans,dp[i][j])
else:
dp[i][j]=max(dp[i-1][j], dp[i... |
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first c... | 3 | A=list(map(list,(list(input().split()))))
m=[]
p=[]
s=[]
for x,a in A:
if a=="m":
m.append(int(x))
elif a=="p":
p.append(int(x))
else:
s.append(int(x))
m.sort()
p.sort()
s.sort()
def check(x):
if len(x)==3:
if x[0]==x[1]==x[2]:
return 3
if ... |
Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers.
Vanya wants to know how many digits he will have to write down as he labels the bo... | 3 | withFile = 0
if(withFile == 1):
fin = open('input.txt', 'r')
fout = open('output.txt', 'w')
def getl():
if(withFile == 0):
return input()
else:
return fin.readline()
def printl(s):
if(withFile == 0):
print(s)
else:
fout.write(str(s))
def get_arr():
x ... |
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec... | 3 | def check(x1,y1,x2,y2):
if(x1==x2):
if(y1+y2==x1):
return "Yes"
if(x1==y2):
if(x2+y1==x1):
return "Yes"
if(y1==y2):
if(x1+x2==y1):
return "Yes"
if(y1==x2):
if(x1+y2==y1):
return "Yes"
return "No"
t=int(input())
for _ in range(t):
x1,y1=map(int,input().split())
x2,y2=map(int,input().split())
... |
Nauuo is a girl who loves writing comments.
One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes.
It's known that there were x persons who would upvote, y persons who would downvote, and there were also another z persons who would vote, but you don't know whether they woul... | 3 | x, y, z = map(int, input().split())
if x - y > z:
print('+')
elif y - x > z:
print('-')
elif z == 0:
print(0)
else:
print('?')
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | n=int(input())
list=list(map(int,input().split()))
even=0
for i in range(3):
if list[i]%2==0:
even+=1
if even<2:
even=0
else:
even=1
temp=0
for i in range(len(list)):
if even==0:
if list[i]%2==0:
temp=i
break
elif even==1:
if list[i]%2!=0:
... |
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= [int(i) for i in input().split()]
for i in range(10):
x = r*x-D
print(x)
|
One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides,... | 1 |
import math
n = int(raw_input())
rlist = [0]+[int(j) for j in raw_input().split()]
rlist.sort()
rPairs = reversed(zip(rlist[:-1], rlist[1:]))
red_area = 0
for ind, rs in enumerate(rPairs):
if ind%2:
pass
else:
red_area += rs[1]**2*math.pi - rs[0]**2*math.pi
print red_area
|
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.
You know that you have n bacteria in the Petri dish and size of the i-th bacteria is a_i. Also you know intergalactic positive integer constan... | 1 | n,k = map(int, raw_input().split(" "))
a = map(int, raw_input().split(" "))
a = sorted(a)
count = 0
same = 1
oldsame = 0
for i in range(0,n-1):
if (a[i+1] == a[i]):
same = same + 1
continue
else:
oldsame = same
same = 1
if (a[i+1] - a[i] > k):
count = count + oldsame
... |
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | n = int(input())
cap = 0
curr = 0
for i in range(n):
a, b = map(int, input().split())
curr -= a
curr += b
cap = max(cap, curr)
print(cap) |
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())
list=[]
i=n
c=1
list = [int(x) for x in input().split()]
list.sort()
m=list[len(list)-1]
j=len(list)-2
while(j>=0):
if(m<=sum(list[:j+1])):
m=m+list[j]
c=c+1
elif(m>sum(list[:j])):
break
j=j-1
print(c) |
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 | # http://codeforces.com/problemset/problem/131/A
s=input()
for i in s.split():
a=i[1:]
if not a.isupper()and a!='' :
print(s)
break
else:
print(s.swapcase())
|
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... | 1 | s = raw_input()
l = 'x'
s = l + s
m = 1
k = 1
for i in s:
if i == l:
k += 1
if k > m:
m = k
else:
l = i
k = 1
if m >= 7:
print "YES"
else:
print "NO"
|
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.
This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to... | 3 | n = int(input())
count = n
for i in range(n+n):
if count<len(str(i)):
print(str(i)[count])
break
else:
count-=len(str(i))
|
Lunar New Year is approaching, and you bought a matrix with lots of "crosses".
This matrix M of size n × n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 ≤ i, j ≤ n. We define a cross appearing in the i-th row and the j-th column (1 < i... | 3 | m = int(input())
l = []
for i in range(m):
l.append(list(input()))
ans = 0
for i in range(1, m - 1):
for k in range(1, m - 1):
if l[i][k] == 'X' and l[i - 1][k - 1] == 'X' and l[i - 1][k + 1] == 'X' and l[i + 1][k - 1] == 'X' and l[i + 1][k + 1] == 'X':
ans += 1
print(ans) |
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).
If two... | 3 | for _ in range(int(input())):
n = int(input())
arr = list(map(int,input().split()))
dic = {}
for i in range(n):
try:
if dic[arr[i]]:
dic[arr[i]].append(i+1)
except:
dic[arr[i]] = [i+1]
# print(dic)
t = [dic[i] for i in dic]
t = sorted(t,key=lambda x:len(x))
# print(t)
l = 0
if len(t)==1:
print... |
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | 3 | n = [int(input()) for _ in range(4)]
print(sum(any([not t % y for y in n]) for t in range(1, int(input()) + 1))) |
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).
For a positive integer n, we call a... | 3 | #rOkY
#FuCk
################################## kOpAl #######################################
def ans(a):
i=a
while(i>0):
print(i,end=' ')
i-=1
print()
t=int(input())
while(t>0):
a=int(input())
ans(a)
t-=1
|
Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n.
Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to som... | 3 | import sys
from collections import defaultdict
readline = sys.stdin.readline
N = int(readline())
B = list(map(int, readline().split()))
D = [i-B[i] for i in range(N)]
C = defaultdict(lambda: -1)
table = [None]*N
for i in range(N):
table[i] = C[D[i]]
C[D[i]] = i
dp = [0]*N
for i in range(N):
if t... |
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m... | 3 | n = int(input())
a = list(map(int,input().split()))
m = int(input())
b = list(map(int,input().split()))
a.sort()
b.sort()
i,j =0,0
c =0
dif =[-1,0,1]
while True:
if i>=n or j>=m:
break
if a[i]-b[j] in dif:
i += 1
j += 1
c += 1
elif a[i]>b[j]:
j += 1
else:... |
When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.
You are given N numbers X_1, X_2, ..., X_N, where N is an even number. For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..... | 3 | n=int(input())
x=list(map(int,input().split()))
xx=sorted(x)
for i in range(n):
print(xx[n//2] if x[i]<=xx[n//2-1] else xx[n//2-1]) |
For a string S consisting of the uppercase English letters `P` and `D`, let the doctoral and postdoctoral quotient of S be the total number of occurrences of `D` and `PD` in S as contiguous substrings. For example, if S = `PPDDP`, it contains two occurrences of `D` and one occurrence of `PD` as contiguous substrings, s... | 3 | pd = input()
pd = pd.replace('?', 'D')
print(pd) |
Yae joins a journey plan, in which parties will be held several times during the itinerary. She wants to participate in all of them and will carry several dresses with her. But the number of dresses she can carry with her may be smaller than that of the party opportunities. In that case, she has to wear some of her dre... | 3 |
A,B = [int(i) for i in input().split()]
ans = 0
if B % A == 0:
ans = B // A
else:
ans = B // A + 1
print(ans)
|
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a perso... | 3 | import sys
c,n=0,0
for sr in sys.stdin:
if(sr[0]=='+'):
n+=1
elif(sr[0]=='-'):
n-=1
else:
i=sr.index(':')
c+=((len(sr)-2-i)*n)
print(c)
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from ... | 3 | #
import collections, atexit, math, sys
from functools import cmp_to_key
#key=cmp_to_key(lambda x,y: 1 if x not in y else -1 )
sys.setrecursionlimit(1000000)
def getIntList():
return list(map(int, input().split()))
import bisect
try :
#raise ModuleNotFoundError
import numpy
def dprint(*args... |
A permutation of length n is an array p=[p_1,p_2,...,p_n], which contains every integer from 1 to n (inclusive) and, moreover, each number appears exactly once. For example, p=[3,1,4,2,5] is a permutation of length 5.
For a given number n (n ≥ 2), find a permutation p in which absolute difference (that is, the absolut... | 3 | import sys
def eprint(*args):
print(*args, file=sys.stderr)
zz=1
from math import *
#sys.setrecursionlimit(10**6)
if zz:
input=sys.stdin.readline
else:
sys.stdin=open('input.txt', 'r')
sys.stdout=open('all.txt','w')
t=int(input())
while t>0:
t-=1
n=int(input())
p=(n//2)*2
if n==2 or n==3:
print(-1)... |
Oz is in love with number theory, so he expects you to love it too and solve his problems. The current problem which has been given by Oz to you is in the form of an array. So, he has given you N integers i.e a1,a2,..,aN to deal with. You have to find the number of divisors of the product of all these integers.
Input... | 1 | from math import *
n = int(raw_input())
a = map(int,raw_input().split())
ans = {}
mod = 10**9+7
for v in a:
for i in xrange(2,int(sqrt(v))+1):
while (v%i==0):
if not i in ans:
ans[i]=0
ans[i]+=1
v=v/i
if v>1:
if not v in ans:
ans[v]=0;
ans[v]+=1
res = 1
for key in ans:
res*=(ans[key]+1)
print r... |
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.
Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day cons... | 1 | n, m, z = map(int, raw_input().split())
i = max(n, m)
j = min(n, m)
c = i
kills = 0
while i <= z:
if i % j == 0:
kills += 1
i += c
print kills |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.