problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or ... | 3 | ta = input()
ha = [x for x in input().split()]
yes = False
for i in ha:
if i[0] == ta[0] or i[1] == ta[1]:
yes = True
break
if yes: print("YES")
else: print("NO") |
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | 3 | t = int(input())
for i in range (t):
num = input().split(' ')
n = int(num[0])
x = int(num[1])
if n <= 2:
print(1)
else:
if((n-2) % x) != 0:
sp = 1
else:
sp = 0
print(int((n-2) / x) + sp + 1) |
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 1 | import sys, math
str = sys.stdin.readline().split()
n = int(str[0])
m = int(str[1])
a = float(str[2])
x = math.ceil(n/a)
y = math.ceil(m/a)
print int(x*y) |
Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes ... | 3 | import math
from decimal import *
getcontext().prec=30
x=input()
m=int(input())
ans=[0]*1010
def dfs(curr,bal):
if curr>m:
return 1
for i in range(bal+1,11):
if ans[curr-1]!=i and x[i-1]=='1':
ans[curr]=i
if dfs(curr+1,i-bal)==1:
return 1
return 0
if d... |
Polycarp has created his own training plan to prepare for the programming contests. He will train for n days, all days are numbered from 1 to n, beginning from the first.
On the i-th day Polycarp will necessarily solve a_i problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first... | 3 | #from fractions import Fraction
from collections import defaultdict
from math import*
import os
import sys
from io import BytesIO, IOBase
from heapq import nlargest
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
... |
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | s=input()
t=input()
a=s[::-1]
if(a==t):
print("YES")
else:
print("NO")
|
Problem description
You will be given a zero-indexed array A. You need to rearrange its elements in such a way that the following conditions are satisfied:
A[i] ≤ A[i+1] if i is even.
A[i] ≥ A[i+1] if i is odd.
In other words the following inequality should hold: A[0] ≤ A[1] ≥ A[2] ≤ A[3] ≥ A[4], and so on. Operation... | 1 | import sys
T=input()
while T:
N=input()
A=sorted([int(i) for i in raw_input().split()])
if N >= 3:
A[1],A[2]=A[2],A[1]
i=3
while (i+1)<N:
A[i],A[i+1]=A[i+1],A[i]
i=i+2
for i in A:
sys.stdout.write(str(i))
sys.stdout.write(' ')
print
T-=1 |
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, ... | 3 | a = int(input())
b = int(input())
c = int(input())
ans = 0
while a > 0 and b > 1 and c > 3:
a -= 1
b -= 2
c -= 4
ans += 7
print(ans) |
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong lo... | 3 | def main():
n,m = map(int, input().split())
pal = ''
ws = []
p_pal = []
for _ in range(n):
w = input()
ws.append(w)
if isPal(w):
if not pal:
pal += w
co... |
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 | nickname = str(input()).lower()
mylist = list(dict.fromkeys(nickname))
if (int(len(mylist)))%2==0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
|
On her way to programming school tiger Dasha faced her first test — a huge staircase!
<image>
The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — th... | 3 | a,b = input().split()
a,b = int(a),int(b)
if abs(a-b)>1 or (a ==0 and b ==0):
print('NO')
else:
print('YES') |
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at le... | 3 | n = int(input())
if n % 3 == 0:
m = n // 3
for i in range(m):
print('.' * (3 * i) + 'abb' + '.' * (n - 3 - 3 * i))
print('.' * (3 * i) + 'a.a' + '.' * (n - 3 - 3 * i))
print('.' * (3 * i) + 'bba' + '.' * (n - 3 - 3 * i))
elif n % 4 == 0:
m = n // 4
for i in range(m):
pri... |
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substr... | 3 | n = int(input())
for i in range(n):
print("aabb"[i%4], end='')
|
The princess is going to escape the dragon's cave, and she needs to plan it carefully.
The princess runs at vp miles per hour, and the dragon flies at vd miles per hour. The dragon will discover the escape after t hours and will chase the princess immediately. Looks like there's no chance to success, but the princess ... | 1 | vp = input()
vd = input()
t = input()
f = input()
c = input()
if vp >= vd:
print 0
else:
dd = 0
dp = t * vp
b = 0
while True:
if dp * vd - dd * vp >= c * (vd - vp):
break
else:
dd = dp = (dp * vd - dd * vp) / float(vd - vp)
dp += dd / vd * vp... |
You are given n numbers a_1, a_2, …, a_n. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors?
For example, for the array [1, 4, 5, 6, 7, 8], the arrangement on the left is valid, while arrangement on the right is not, as 5≥ 4 + 1 and 8> 1 + 6.
<im... | 3 | n = int(input())
x = list(map(int, input().split()))
x.sort()
if(x[-1] < x[-2]+x[-3]):
print("YES")
print(*x[:-2], x[-1], x[-2])
else:
print("NO") |
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy.
But his plan failed. The reason for this w... | 3 | import string
import math
s = int(input())
t = 0
for i in range(1,1024):
if (int(bin(i)[2:]) <= s):
t += 1
print(t) |
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 | s1 = input()
s2 = input()
s3 = input()
dict1 = {}
dict2 = {}
elements1 = set()
elements2 = set()
for i in s1:
if i not in elements1:
elements1.add(i)
dict1[i] = 1
else:
dict1[i] += 1
for i in s2:
if i not in elements1:
elements1.add(i)
dict1[i] = 1
else:
... |
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... | 3 | a=input()
ans=a.replace('1','')+'2'
t=ans.find('2')
print(ans[:t]+'1'*a.count('1')+ans[t:-1]) |
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 ⋅ n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from ... | 3 | input();c,d=0,0
for i,j in zip(map(int,input().split()),map(int,input().split())):c,d=max(c,d+i),max(d,c+j)
print(max(c,d)) |
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n ... | 3 | from collections import defaultdict
MyDict = defaultdict(list)
input()
X = list(map(int, input().split()))
for i in range(len(X)):
MyDict[X[i]].append(i)
for i in sorted(MyDict.keys()):
if len(MyDict[i]) > 1:
Temp = sorted(MyDict[i])
print(min(Temp[j] - Temp[j - 1] for j in range(1, len(Temp)))... |
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 | for t in range(int(input())):
n = int(input())
x = list(map(int, input().split()))
flag = 0
for i in range(n):
if x[i]%2 == 0:
print(1)
print(i+1)
flag = 1
break
if flag == 0:
if n == 1:
print(-1)
else:
print(2)
print(1, 2)
|
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 | #python33
def program():
a=list(input())
b=list(input())
c=list(input())
c.sort()
a+=b
a.sort()
if(a==c):
print('YES')
else:
print('NO')
program()
|
You are given a sequence of integers of length n and integer number k. You should print any integer number x in the range of [1; 10^9] (i.e. 1 ≤ x ≤ 10^9) such that exactly k elements of given sequence are less than or equal to x.
Note that the sequence can contain equal elements.
If there is no such x, print "-1" (w... | 3 | # import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
t = 1
# t = int(input())
while t:
t -= 1
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
# s = input()
a.sort()
if k == 0:
ans = a[0]-1
else:
ans = a[k... |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | # https://codeforces.com/problemset/problem/977/A
if __name__ == "__main__":
n, k = map(int, input().split())
for i in range(k):
if n % 10 == 0:
n = n // 10
else:
n = n - 1
print(n)
|
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | 3 | for _ in range(int(input())):
n=int(input())
if((n//2)%2!=0):
print("NO")
else:
print("YES")
temp=0
for i in range(2,n+1,2):
print(i,end=" ")
temp+=i
for i in range(1,n-1,2):
print(i,end=" ")
temp-=i
print(temp)
... |
Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i. He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A. In how many ways can he make his selection?
Constraints
* 1 \leq N \leq 50
* 1 \leq A \leq 50
* 1 \leq x_... | 3 | n,a=map(int,input().split())
X=list(map(int,input().split()))
dp=[[[0]*(sum(X)+1) for _ in range(n+1)] for _ in range(n+1)]
dp[0][0][0]=1
for i in range(1,n+1): #x_1,x_2...x_n
for k in range(i): #k枚数選ぶ
for s in range(sum(X)+1): #合計
if dp[i-1][k][s]:
dp[i][k+1][s+X[i-1]]+=dp[i-1][k][s] #1枚選択肢が増え... |
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 | count = int(input())
input_data = []
sure = 0
while count > 0:
input_data.append(input())
count -= 1
for i in input_data:
if i.count("1") >= 2:
sure += 1
print(sure)
|
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ... | 3 | for _ in range (int(input())):
l = input()
g = list()
for i in range(len(l)):
try:
if (l[i:i+3] == 'two'):
try:
if (l[i:i+5] == 'twone'):
g.append(str(i+2+1))
continue
except:
... |
Apart from Nian, there is a daemon named Sui, which terrifies children and causes them to become sick. Parents give their children money wrapped in red packets and put them under the pillow, so that when Sui tries to approach them, it will be driven away by the fairies inside.
Big Banban is hesitating over the amount ... | 3 | k = int(input())
if k > 36 or k < 0:
print(-1)
else:
while k > 0:
if 2 <= k:
print(8, end='')
k = k - 2
else:
print(4)
k = k-1
|
[Sakuzyo - Imprinting](https://www.youtube.com/watch?v=55Ca6av1kAY)
A.R.C. Markland-N is a tall building with n floors numbered from 1 to n. Between each two adjacent floors in the building, there is a staircase connecting them.
It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location... | 3 | for x in range(int(input())):
n,s,k = list(map(int,input().split()))
h=list(map(int,input().split()))
i=0
while max(s-i,1) in h and min(s+i,n) in h:
i+=1
print(i) |
The only difference between easy and hard versions is constraints.
There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the p_i-th kid (in case of i = p_i the kid will give his book to himself). It is guaranteed that all values of p_i are distinct integers ... | 3 | from math import *
from sys import *
from heapq import *
from collections import defaultdict
from itertools import permutations
import os, sys
from io import IOBase, BytesIO
M=10**9+7
def graph_as_tree_1_root():
n=int(input())
dict=defaultdict(list)
for _ in range(n-1):
x,y=list(map(int,input().sp... |
Pasha has many hamsters and he makes them work out. Today, n hamsters (n is even) came to work out. The hamsters lined up and each hamster either sat down or stood up.
For another exercise, Pasha needs exactly <image> hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster e... | 1 | n=input()
S=raw_input()
x=S.count("x")
X=S.count("X")
f,s="xX" if x>X else "Xx"
m=abs(len(S)/2 - x)
print m
print S.replace(f,s,m) |
There are n products in the shop. The price of the i-th product is a_i. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.
In fact, the owner of the shop can change the price of some product i in such a way that the difference between the old price of this ... | 3 | q=int(input())
while q:
q-=1
n,k=input().split()
n=int(n)
k=int(k)
a=[]
a=input().split()
b=[0]*len(a)
for i in range(len(a)):
b[i]=int(a[i])+k
mn=min(b)
mx=max(b)
if mx-mn<=2*k:
print(mn)
else:
print("-1") |
There are n shovels in Polycarp's shop. The i-th shovel costs i burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs.
Visitors are more likely to buy a pair of shovels if their total cost ends with severa... | 3 | import bisect
def list_output(s):
print(' '.join(map(str, s)))
def list_input(s='int'):
if s == 'int':
return list(map(int, input().split()))
elif s == 'float':
return list(map(float, input().split()))
return list(map(str, input().split()))
n = int(input())
seq = str(n)
l ... |
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≤ i ≤ n) and do a_i := a_i + 1.
If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T... | 3 | t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
numz = len([x for x in a if x == 0])
if sum(a) == 0 and numz == 0:
print("1")
elif sum(a) != 0 and numz == 0:
print ("0")
elif numz == -sum(a):
print (numz+1)
else:
prin... |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | a='I hate it'
b=input()
for i in range(int(b)-1):
if i%2==0:
a=a.replace('it','that I love it')
else:
a=a.replace('it','that I hate it')
a.replace
print(a) |
You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.
<image>
An example of a trapezoid
Find the area of this trapezoid.
Constraints
* 1≦a≦100
* 1≦b≦100
* 1≦h≦100
* All input values are integers.
* h is even.
Input
The input is given from Standard Input i... | 3 | A=int(input())
B=int(input())
H=int(input())
print(int((A+B)/2*H)) |
There are n children numbered from 1 to n in a kindergarten. Kindergarten teacher gave a_i (1 ≤ a_i ≤ n) candies to the i-th child. Children were seated in a row in order from 1 to n from left to right and started eating candies.
While the i-th child was eating candies, he calculated two numbers l_i and r_i — the num... | 3 | import math
from decimal import Decimal
import heapq
def na():
n = int(input())
b = [int(x) for x in input().split()]
return n,b
def nab():
n = int(input())
b = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
return n,b,c
def dv():
n, m = map(int, input().split())
return n,m
... |
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
qwertyuiop
asdfghjkl;
zxcvbnm,./
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move... | 3 | def keyboard(d, s):
k = "qwertyuiopasdfghjkl;zxcvbnm,./"
if d == 'L':
shift = 1
else:
shift = -1
r = ""
for i in range(len(s)):
r += k[k.index(s[i]) + shift]
return r
d = input().strip()
s = input().strip()
print(keyboard(d, s)) |
Gildong has a square board consisting of n rows and n columns of square cells, each consisting of a single digit (from 0 to 9). The cell at the j-th column of the i-th row can be represented as (i, j), and the length of the side of each cell is 1. Gildong likes big things, so for each digit d, he wants to find a triang... | 3 | import math
inf = 5000
def get_point_ranges(table):
points_ranges = {d: {'min_row': inf, 'max_row': 0, 'min_col': inf, 'max_col': 0} for d in range(10)}
for i in range(len(table)):
for j, d in enumerate(table[i]):
points_ranges[d]['min_row'] = min(points_ranges[d]['min_row'], i)
... |
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so... | 3 | g = {}
for i in range(-100, 20001):
g[i] = []
for i in range(1, 10001):
if 2*i<=10000:
g[i] = [i-1, 2*i]
else:
g[i] = [i-1]
a, b = list(map(int, input().split(' ')))
visited = [False] * 20005
dist = [100000] * 20005
x = [a]
dist[a] = 0
while x:
a = x.pop()
if not visited[a]:
... |
Ilya lives in a beautiful city of Chordalsk.
There are n houses on the street Ilya lives, they are numerated from 1 to n from left to right; the distance between every two neighboring houses is equal to 1 unit. The neighboring houses are 1 and 2, 2 and 3, ..., n-1 and n. The houses n and 1 are not neighboring.
The ho... | 3 | import sys, os
def init():
if 'local' in os.environ :
sys.stdin = open('./input.txt', 'r')
def solve():
n = int(input())
a = [ int(x) for x in input().split()]
res = 0
for i in range(n):
if a[i] != a[-1]:
res = max(res, n-1-i)
break
for i in reversed(... |
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())
x=[int(x) for x in input().split()]
a=[0]*n
a[-1]=x[-1]
for j in range(len(x)-2,-1,-1):
a[j]=x[j]+a[j+1]
print(max(a))
|
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 | a = str(input())
b = str(input())
for i in range(len(a)):
if(a[i]!=b[i]):
print(1,end='')
else:
print(0,end='') |
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 | #!/bin/env python3
a = [int(i) for i in input().split()]
m = a[0]
n = a[1]
print(int(n*m/2))
|
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and... | 3 | n = int(input())
seq = input().split(" ")
c = [0] * 100001
dp = [0] * 100001
for i in range(n):
aux = int(seq[i])
c[aux] += 1
dp[1] = c[1]
for i in range(2, 100001):
dp[i] = max(dp[i - 1], dp[i - 2] + i * c[i])
print(dp[100000])
|
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane... | 3 |
def judge():
for i in range(4):
if a[i][3] == 0:
continue
left = (i + 3) % 4
right = (i + 1) % 4
mid = (i + 2) % 4
if a[i][0] or a[i][1] or a[i][2] or a[left][2] or a[mid][1] or a[right][0]:
return True
return False
while True:
try:
... |
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 | """
Nome: Stefano Lopes Chiavegatto
RA: 1777224
"""
days = int(input())
money = input()
list_money = money.split(" ")
list_money = [int(i) for i in list_money]
seg = 1
maxseg = 1
i = 1
while i < len(list_money):
if list_money[i] >= list_money[i - 1]:
seg = seg + 1
else:
seg = 1
if seg > maxseg:
maxseg = seg
... |
You are given an array s consisting of n integers.
You have to find any array t of length k such that you can cut out maximum number of copies of array t from array s.
Cutting out the copy of t means that for each element t_i of array t you have to find t_i in s and remove it from s. If for some t_i you cannot find s... | 3 | [n, k] = [int(x) for x in input().split(' ')]
s = list(sorted([int(x) for x in input().split(' ')]))
table = []
for i in range(n):
if i == 0:
table.append([s[i],1])
elif s[i] == s[i-1]:
table[len(table)-1][1] += 1
else:
table.append([s[i],1])
def can(length):
totalLength = 0
... |
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... | 1 | paginas = int(raw_input())
algarismos = 0
if paginas < 10:
algarismos = paginas
elif paginas < 100:
algarismos = 2*(paginas + 1) - 11
elif paginas < 1000:
algarismos = 3*(paginas + 1) - 111
elif paginas < 10000:
algarismos = 4*(paginas + 1) - 1111
elif paginas < 100000:
algarismos = 5*(paginas + 1) - 11111
elif p... |
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police offi... | 3 | n=int(input())
m=list(map(int,input().split()))
q=0
ans=0
for i in m:
q+=i
if q<0:
ans+=1
q=0
print(ans)
|
Little Monk is an extremely miser person. He hates spending money on things, be it for his own good or bad. But this time his friends have caught up with him, and are demanding a huge birthday treat. But, Monk is... well, Monk.
He figured out that there is no way for him to save himself and his money now. So, he deci... | 1 | def rec(prob, start, path, lim):
if(start in list(path)):
return len(path)
path.add(start)
if(len(path)==lim):
return len(path)
for i in list(prob[start-1]):
rec(prob, i, path, lim)
return len(path)
frnds, rels = raw_input().split(" ")
rels=int(rels)
frnds=int(frnds)
inv=[]
for i in range(1,frnds+1):
in... |
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter — its complexity. The complexity of the i-th chore equals hi.
As Petya is older, he wants to take the chores with complexity larger... | 3 | nab=list(map(int,input().strip().split()))
n=nab[0]
a=nab[1]
b=nab[2]
chores=list(map(int,input().strip().split()))
chores.sort(reverse=True)
d=a
while(d>0):
prev=chores[0]
chores.pop(0)
d=d-1
#print(chores)
for i in chores:
if(prev==i):
print('0')
break
else:
c=len(chores)
... |
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams.
You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ... | 3 | n = int(input())
s = input()
grams = set()
for i in range(n - 1):
grams.add(s[i:i+2])
total = 0
val = None
for gram in grams:
c = 0
for i in range(n-1):
if s[i:i+2] == gram:
c += 1
if c > total:
total = c
val = gram
print(val)
|
Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y').
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle ... | 3 | from math import sqrt
r,x1,y1,x2,y2 = input().split()
r,x1,y1,x2,y2 = map(int,[r,x1,y1,x2,y2])
d = sqrt((x1-x2)**2+(y1-y2)**2)
if d/(2*r) == int(d/(2*r)):
s = int(d/(2*r))
print(s)
else:
s = int(d/(2*r))
print(s+1) |
T is playing a game with his friend, HL.
There are n piles of stones, the i-th pile initially has a_i stones.
T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in th... | 3 | def main():
t : int = int(input())
for _ in range(t):
n : int = int(input())
T : [int] = list(map(int, input().split(' ')))
mx : int = max(T)
sm : int = sum(T)
if 2*mx > sm:
print('T')
elif sm&1 == 1:
print('T')
else:
print('HL')
main()
|
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 | word = input()
lowerCase = 0
upperCase = 0
for i in word:
if i.islower():
lowerCase += 1
if i.isupper():
upperCase += 1
if upperCase > lowerCase:
print(word.upper())
else:
print(word.lower()) |
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya h... | 3 | from sys import stdin
n,h,k = map(int, stdin.readline().rstrip().split())
l = [int(x) for x in stdin.readline().rstrip().split()]
total = 0
remain = 0
tot_potato = 0
smashed = 0
i = 0
for i in range(len(l)):
if(tot_potato+l[i]<=h):
tot_potato+=l[i]
else:
tot_potato=l[i]
total+=1
... |
You are given a chess board with n rows and n columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.
A knight is a chess piece that can attack a piece in cell (x_2, y_2) from the cell (x_1, y_1) if one of the following conditions is met:
* |x_... | 3 | def horses(n):
lst = list()
for i in range(n):
s = ''
if i % 2 == 0:
for j in range(n):
if j % 2 == 0:
s += 'W'
else:
s += 'B'
else:
for j in range(n):
if j % 2 == 0:
... |
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | 1 | a,b=map(int,raw_input().split())
for i in range(1,a+1):
if i%2!=0:
print "#"*b
elif i%4==0:
print "#"+"."*(b-1)
else:
print "."*(b-1)+"#"
|
— This is not playing but duty as allies of justice, Nii-chan!
— Not allies but justice itself, Onii-chan!
With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters — Karen and Tsukihi — is heading for somewhere they've never reached — water-surrounded islands!
There are three... | 1 | a,b,c=map(int,raw_input().split())
M=998244353
def C(x, y):
z,t=0, 1
for i in range(min(x,y)+1):
z=(z+t)%M
t=t*(x-i)*(y-i)*pow(i+1,M-2,M)%M
return z
print C(a,b)*C(a,c)*C(b,c)%M |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | def somatorio(cost, nbananas):
return (float(cost) * nbananas * (nbananas + 1)) / 2
values = [int(x) for x in input().split()];
banana_cost = values[0]
money = values[1]
nbananas = values[2]
res = somatorio(banana_cost, nbananas)
res = res - money
if res < 0:
res = 0
print(int(res))
|
Unary is a minimalistic Brainfuck dialect in which programs are written using only one token.
Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm... | 1 | s=raw_input()
ans=''
for i in s:
if i=='>':
ans+='1000'
elif i=='<':
ans+='1001'
elif i=='+':
ans+='1010'
elif i=='-':
ans+='1011'
elif i=='.':
ans+='1100'
elif i==',':
ans+='1101'
elif i=='[':
ans+='1110'
elif i==']':
ans+=... |
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge).
M... | 3 | n,k=map(int,input().split())
ans=0
for i in sorted(map(int,input().split())):
while i>2*k:
ans+=1
k*=2
k=max(k,i)
print(ans) |
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.
According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the requ... | 3 | from array import array
n, i = int(input())+1, 1
ar = array('l',(0 for _ in range(n)))
for num in map(int,input().split()):
ar[num], i = i, i+1
q, c = input(), [0, 0]
for num in map(int,input().split()):
c[0] += ar[num]
c[1] += (n-ar[num])
print(*c)
|
Mislove had an array a_1, a_2, ⋅⋅⋅, a_n of n positive integers, but he has lost it. He only remembers the following facts about it:
* The number of different numbers in the array is not less than l and is not greater than r;
* For each array's element a_i either a_i = 1 or a_i is even and there is a number (a_i)/(... | 3 | z1=[]
z2=[]
n,l,r=map(int,input().split())
for x in range(l):
z1.append(1<<x)
for x in range(r):
z2.append(1<<x)
mn=sum(z1+[1]*(n-l))
mx=sum(z2+[z2[-1]]*(n-r))
print(mn,mx) |
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b.
Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ... | 3 | import math
def facts(n):
ans = []
for i in range(1, int(math.sqrt(n)+1)):
if(n%i==0):
ans.append(i)
ans.append(n//i)
ans = sorted(list(dict.fromkeys(ans)))
if(ans[-1]==n):
ans = ans[:-1]
return ans
n = int(input())
p1= list(map(int, input().split()))
p2 = ... |
Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he und... | 1 | from bisect import *
s,b=map(int,raw_input().split())
a=list(map(int,raw_input().split()))
ar=[]
for i in range(b):
d,g=map(int,raw_input().split())
ar.append((d,g))
ar.sort()
pref=[0]
for i in range(b):
pref.append(pref[-1]+ar[i][1])
for i in range(s):
x=a[i]
l=0
r=b
while l<r:
m=(l... |
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain posi... | 3 | a = int(input())
def sumar(n):
t = str(n)
suma = 0
for x in t:
suma+=int(x)
return(suma)
b =len( str(a))
m = a - 9*b
if m < 0:
m = 0
l = []
while (m < a):
if (m +sumar(m)==a):
l.append(m)
m+=1
if len(l)>0:
print(len(l))
for x in l:
print(x)
else:... |
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... | 1 | a = raw_input().lower()
b = raw_input().lower()
if a == b:
print '0'
elif sorted([a,b])[0] == a:
print '-1'
else:
print '1'
|
Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!
A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system.
There are n booking requests received by now. Each request is characterized by two numbers: ci and p... | 3 | n=int(input())
x=[]
for i in range(n):
c,p=map(int, input().split())
x+=[(p,c,i)]
k=int(input())
r=list(map(int, input().split()))
s=0
q=[]
for (v,c,a) in reversed(sorted(x)):
p=-1
u=10000
for (j,z) in enumerate(r):
if c<=z<u:
p=j
u=z
if p>-1:
r[p]=0
... |
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a n... | 1 | #import resource
import sys
#resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
#threading.Thread(target=main).start()
#import threading
#threading.stack_size(2**26)
#sys.setrecursionlimit(10**8)
mod=(10**9)+7
#fact=[1]
#for i in range(1,1000001):
# fact.append((fact[-1]*i)%mod)
#ifact=... |
Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.
Constraints
* $2 \leq n \leq 100,000$
* $0 \leq m \leq 100,000$
* $1 \leq q \leq 10,000$
Input
In the first line, two integer $n$ and $m$ are given. $n$ is the ... | 3 | # -*- coding: utf-8 -*-
from collections import deque
import sys
sys.setrecursionlimit(200000)
if __name__ == '__main__':
n, m = [int(s) for s in input().split(" ")]
M = [set() for j in range(n)]
for _ in range(m):
u, v = [int(s) for s in input().split(" ")]
M[u].add(v)
M[v].add(u... |
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla... | 1 | n = int(raw_input())
a = [raw_input().split()for i in xrange(n)]
s = {x: 0 for x in [y[0] for y in a]}
for i in a:
s[i[0]] += int(i[1])
w, m = [], max(s.values())
w = [x for x in s if s[x] == m]
if len(w) == 1:
print w[0]
quit()
s = {x: 0 for x in [y[0] for y in a]}
for i in a:
s[i[0]] += int(i[1])
... |
This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt.
To make a toast, each friend needs nl ... | 3 | n,k,l,c,d,p,nl,np=map(int,input().split())
print(int(min(c*d,p/np,k*l/nl)/n))
|
You are given a problemset consisting of n problems. The difficulty of the i-th problem is a_i. It is guaranteed that all difficulties are distinct and are given in the increasing order.
You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to as... | 3 | n = int(input())
a = list(map(int, input().split()))
i = 0
ms = 1
curr = 1
for i in range(n-1):
if (2*a[i] >= a[i+1]):
curr = curr + 1
else:
ms = max(curr, ms)
curr = 1
ms = max(curr,ms)
print(ms)
|
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.
Vasiliy plans to buy his favorite drink fo... | 3 | from sys import stdout
log = lambda *x: print(*x)
def cin(*fn, def_fn=str):
i,r = 0,[]
for c in input().split(' '):
r+=[(fn[i] if len(fn)>i else fn[0]) (c)]
i+=1
return r
N = 100005
n, = cin(int)
x = cin(int)
q, = cin(int)
freq = [0]*(N+1)
for v in x: freq[v] += 1
# build dp
dp = [0]*(N+1)
for i in range(... |
In a mystical TimeLand, a person's health and wealth is measured in terms of time(seconds) left.
Suppose a person there has 24x60x60 = 86400 seconds left, then he would live for another 1 day.
A person dies when his time left becomes 0. Some time-amount can be borrowed from other person, or time-banks.
Some time-amoun... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
import re
for i in xrange(int(raw_input())):
N,K = map(int, re.split(' *',raw_input()))
slips = [int(i) for i in re.split(' *',raw_input()) if i!='']
dp = [slip... |
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).
Consider a permutation p of length ... | 3 | # from math import factorial
MOD = 10**9 + 7
n = int(input())
out = 1
for i in range(n):
out *= (i+1)
out %= MOD
out = out - pow(2, n - 1, MOD)
print(out % MOD) |
Vova's house is an array consisting of n elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The i-th element of the array is 1 if there is a heater in the position i, otherwise the i-th element of the array is 0.
Each heater has a va... | 3 | n, r = list(map(int, input().split()))
a = list(map(int, input().split()))
a.insert(0, 0)
pos = 1
ans = 0
last = 0
while(True):
if pos > n:
break
prelast = last
for i in range(max(0, pos - r + 1), min(pos + r, n + 1)):
if a[i] == 1:
pos = i + r
last = i
if prelast == last:
ans = -1
b... |
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoy... | 3 | s=input()
count=0
for i in range(len(s)):
if(s[i]=='Q'):
for j in range(len(s[i+1:])):
if(s[i+1:][j]=='A'):
for k in range(len(s[i+j+1:])):
if(s[i+j+1:][k]=='Q'):
count+=1
print(count) |
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | t = int(input())
for _ in range(t):
nums = [int(i) for i in input().split(' ')]
nums.sort()
if nums[0] != nums[1] and nums[1] != nums[2] and nums[2] != nums[0]:
print('NO')
elif nums[0] == nums[1] and nums[1] != nums[2]:
print('NO')
elif nums[1] == nums[2]:
print('YES')
... |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | n = int(input())
x_cor, y_cor, z_cor = 0, 0, 0
while n > 0:
vector = [int(x) for x in input().split()]
x_cor += vector[0]
y_cor += vector[1]
z_cor += vector[2]
n -= 1
if x_cor == 0 and y_cor == 0 and z_cor == 0:
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 | s=input()
s=s.replace('+',"")
n=int(s)
l=[]
ans=""
for i in range(len(s)):
d=n%10
l.append(d)
n=n//10
l.sort()
for i in range(len(s)-1):
print(str(l[i])+'+',end="")
print(l[len(s)-1],end="")
|
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | input()
for i in input().split():
if i == "1":
print("HARD")
exit()
print("EASY")
|
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A1440... | 3 | u = int(input()[-1]) % 2
print(u) |
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:
... | 3 | n = int(input())
if n > 1:
print(n, 1, end=" ")
else:
print(1)
for i in range(2, n):
print(i, end=' ')
|
You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements?
Input
The first line contains an integer n (1 ≤ n ≤ 1000), where 2n is the number of elements in the array a.
The second line contains 2n space-separat... | 3 | n = int(input())
a = [int(x) for x in input().split()]
a = sorted(a)
if sum(a[:n]) != sum(a[n:]):
print(*a)
else:
print(-1) |
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the... | 3 | n=int(input())
a=list(map(int,input().split()))
b=sorted(a,key=lambda x:-x)
count=0
for i in range(len(a)):
for j in range(len(b)):
if a[i]==b[j] and count==0:
a[i]=j+1
break
for i in a:
print(i,end=" ")
|
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l ≤ a,b,c ≤ r, and then he computes the encrypted value m = n ⋅ a + b - c.
Unfortunately, an adversa... | 3 | for t in range(int(input())):
l,r,m = map(int,input().split())
dif=r-l
for i in (range(r,l-1,-1)):
mm1=m%i
mm2=i-mm1
if mm1<=dif and m>=i:
print(i,r,r-mm1)
break
elif mm2<=dif:
print(i,l,l+mm2)
break
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | a=[]
for i in range(0,int(input())):
if len(a)==0:
a=input()
a=list(map(int,a.split()))
else:
b=input()
b=list(map(int,b.split()))
for i in range(0,3):
a[i]=a[i]+b[i]
f=1
for i in range(0,3):
if a[i]!=0:
f=0
break
if f==1:
print("... |
Given a set of integers (it can contain equal elements).
You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B).
Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example:
* m... | 3 | def mex(hash_map):
for i in range(0,1000):
if(i not in hash_map):
return i
return None
t=int(input())
while t>0:
t-=1
n=int(input())
a=list(map(int,input().strip().split()))
a.sort()
used={}
used2={}
for i in a:
if i in used:
used2... |
Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.
The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing N... | 3 | import os
import sys
from io import BytesIO, IOBase
def main():
pass
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
s... |
Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs.
Let the current time be time 0. Kizahashi has N jobs numbered 1 to N.
It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B... | 3 | n = int(input())
ab = sorted([list(map(int, input().split())) for _ in range(n)], key = lambda i: i[1])
t = 0
for i in ab:
t += i[0]
if t > i[1]:
print("No")
exit()
print("Yes") |
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.... | 3 | T = int(input())
for _ in range(T):
s = input()
fir = True
ans = []
ans.append(s[0])
n = len(s)
for i in range(1, n):
if len(ans) == 0:
ans.append(s[i])
continue
if ans[-1] == 'A' and s[i] == 'B':
ans.pop()
elif ans[-1] == 'B' and s[i] == 'B':
ans.pop()
else:
ans.append(s[i])
print(len(ans... |
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' — colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan... | 1 | import sys
range = xrange
input = raw_input
n = int(input())
inp = []
for c in input():
if c=='R':
inp.append(0)
elif c=='G':
inp.append(1)
else:
inp.append(2)
arg = 'RGB'
cost = [[1]*3 for _ in range(n)]
P = [[-1]*3 for _ in range(n)]
cost[0][inp[0]]=0
opp = [[k for k in range(... |
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b... | 3 | n, m = map(int, input().split())
a, b, c = zip(*[list(map(int, input().split())) for i in range(m)])
dist = [[1e18]*n for i in range(n)]
for i in range(m):
dist[a[i]-1][b[i]-1] = dist[b[i]-1][a[i]-1] = min(dist[a[i]-1][b[i]-1], c[i])
for k in range(n):
for i in range(n):
for j in range(n):
... |
Recently Petya walked in the forest and found a magic stick.
Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer:
1. If the chosen number a is even, then the spell will turn it into 3a/2;
2. If t... | 3 | ii = lambda: int(input())
iia = lambda: list(map(int,input().split()))
isa = lambda: list(input().split())
t = ii()
for i in range(t):
x,y = iia()
if(x == 1 and y > 1) or (x == 3 and y > 3) or (x == 2 and y > 3):
print("NO")
else:
print("YES") |
Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.
Mike has n sweets with sizes a_1, a_2, …, a_n. All his sweets have different sizes. That is, there is no such pair ... | 3 | from collections import defaultdict
mi = lambda: [int(i) for i in input().split()]
n = int(input())
a = sorted(mi())
b = defaultdict(int)
for i in range(n):
for j in range(i + 1, n):
sum = a[i] + a[j]
b[sum] += 1
print(max(b.values()))
|
Points:10
The Indian Heights School believes that learning with the aid of technology is the fastest way to do so. It is a pioneer in innovation and virtual classrooms in the country. Keeping in accordance with its practices, the school wants to integrate software and automate various functions at the classroom level. ... | 1 | def fact(x):
i=1
ans=1
while i<=x:
ans=ans*i
i=i+1
return ans
test=input()
for num in range(test):
f=raw_input().split()
x,y=(int(f[0]),int(f[1]))
if x-y<0:
print '1'
else:
print (fact(x)/(fact(y)*fact(x-y))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.