name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
p01906 Weight Range | problem
There are many $ N $ colored balls of different weights in the queue. The queue is in ascending order from the beginning: $ 1,2,3, \ dots, N-1, N, 1,2,3, \ dots, N-1, N, 1,2,3, \ dots $ The balls are lined up, followed by the balls of color $ N $, followed by the balls of color $ 1 $. Balls of the same color w... | ```python
def list_eq(get_num, first):
if first == 1:
return False
for i in range(len(get_num)-1):
if get_num[0] != get_num[i+1]:
return False
return True
a_raw = input().split(' ')
b_raw = input().split(' ')
a = [int(n) for n in a_raw]
b = [int(n) for n in b_raw]
get_num = [0... |
p02044 Equal Split | Dutch treat
You have organized a party to pray for the good performance of the ICPC 2019 Yokohama Regional Domestic Qualifiers. There are N participants in this party.
Since it costs M yen in total to hold this party, we decided to collect M / N yen from each of the N participants. Since M is divisible by N, there is... | ```python
while 1:
n,m=map(int, input().split())
if n == 0:
break
a = list(map(int, input().split()))
c = 0
for i in range(n):
c += min(m//n, a[i])
print(c)
``` |
p02329 Coin Combination Problem | You have 4 bags A, B, C and D each of which includes N coins (there are totally 4N coins). Values of the coins in each bag are ai, bi, ci and di respectively.
Find the number of combinations that result when you choose one coin from each bag (totally 4 coins) in such a way that the total value of the coins is V. You s... | ```python
import sys
from collections import defaultdict
if __name__ == '__main__':
n, v = map(int, sys.stdin.readline().split())
a = tuple(map(int, sys.stdin.readline().split()))
b = tuple(map(int, sys.stdin.readline().split()))
c = tuple(map(int, sys.stdin.readline().split()))
d = tuple(map(int, ... |
p02474 Multiplication of Big Integers | Multiplication of Big Integers
Given two integers $A$ and $B$, compute the product, $A \times B$.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the product in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
Sample Input 1
5 8
Sample Ou... | ```python
s = input().split()
print(int(s[0]) * int(s[1]))
``` |
1031_C. Cram Time | In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.
Lesha knows that today he can study for at most a hours, and he will have b hours to study tomorro... | ```python
a = input()
(a,b) = a.split(" ")
a = int(a)
b = int(b)
def binary_search(val):
(l,r,ans)=(1,val,-1)
while l<=r:
mid = (l+r)//2
if mid*(mid+1) <= 2*val:
ans = mid
l = mid+1
else:
r = mid-1
return ans
val = binary_search(a+b)
lista = []
listb = []
vis = [0]*(val+1)
t = val
while a>0 and t>... |
1054_C. Candies Distribution | 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... | ```python
'''
the max element would have 0 0 i both l,r
'''
from collections import defaultdict
def f(l,r):
cnts=defaultdict(list)
lmax=[0]*len(l)
rmax=[0]*len(l)
for i in range(len(l)):
cnts[l[i]+r[i]].append(i)
mx=len(l)
ans=[0]*(len(l))
for i in sorted(cnts):
# print(lma... |
1076_C. Meme Problem | Try guessing the statement from this picture:
<image>
You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a ⋅ b = d.
Input
The first line contains t (1 ≤ t ≤ 10^3) — the number of test cases.
Each test case contains one integer d (0 ≤ d ≤ 10^3).
... | ```python
import decimal
from math import*
decimal.Context(prec=20)
c=int(input())
for i in range(c):
n=int(input())
n=decimal.Decimal(n)
if n*n - 4*n < 0:
print('N')
elif n*n - 4*n == 0:
print('Y '+ str(int(n/2))+ '.000000000 ' + str(int(n/2))+ '.000000000')
else:
x... |
1097_C. Yuhao and a Parenthesis | One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting c... | ```python
n = int(input())
a = dict()
b = dict()
for i in range(n):
s = input()
k = 0
max_k = 0
op = True
for j in s:
if j == '(':
k += 1
else:
k -= 1
if k < max_k:
max_k = k
if k < 0:
op = False
if op == Fal... |
1118_D1. Coffee and Coursework (Easy version) | The only difference between easy and hard versions is the constraints.
Polycarp has to write a coursework. The coursework consists of m pages.
Polycarp also has n cups of coffee. The coffee in the i-th cup has a_i caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups i... | ```python
import sys,os,io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
from bisect import bisect_left , bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')
def isPrime(x):
for i in range(2,x):
... |
1144_G. Two Merged Sequences | Two integer sequences existed initially, one of them was strictly increasing, and another one — strictly decreasing.
Strictly increasing sequence is a sequence of integers [x_1 < x_2 < ... < x_k]. And strictly decreasing sequence is a sequence of integers [y_1 > y_2 > ... > y_l]. Note that the empty sequence and the s... | ```python
def main():
n = int(input())
a = list(map(int, input().split()))
result = [0] * n
last_increasing = -1
last_decreasing = 200001
for i, x in enumerate(a):
if i == n - 1:
if x < last_decreasing:
result[i] = 1
elif x <= last_increasing:
... |
1165_F1. Microtransactions (easy version) | The only difference between easy and hard versions is constraints.
Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.
E... | ```python
def check(x):
last=[0]*(n+1)
for i in tmp:
if i[0]>x:
break
else:
last[i[1]]=i[0]
sal=[0]*(x+1)
for i in range(1,n+1):
sal[last[i]]+=lis[i-1]
c=0
for i in range(1,x+1):
c+=1
if sal[i]>=c:
sal[i]-=c
... |
1203_B. Equal Rectangles | You are given 4n sticks, the length of the i-th stick is a_i.
You have to create n rectangles, each rectangle will consist of exactly 4 sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only... | ```python
q = int(input())
for w in range(q):
n = int(input())
a = list(map(int, input().split()))
a.sort()
n *= 4
x = a[0] * a[n - 1]
ok = 1
for i in range(0, n // 2, 2):
if a[i] * a[n - i - 1] != x or a[i] != a[i + 1] or a[n - i - 1] != a[n - i - 2]:
ok = 0
... |
1245_A. Good ol' Numbers Coloring | Consider the set of all nonnegative integers: {0, 1, 2, ...}. Given two integers a and b (1 ≤ a, b ≤ 10^4). We paint all the numbers in increasing number first we paint 0, then we paint 1, then 2 and so on.
Each number is painted white or black. We paint a number i according to the following rules:
* if i = 0, it ... | ```python
def gcd(a,b):
if a==0:
return b
elif b==0:
return a
elif a>=b:
return gcd(a%b,b)
else:
return gcd(a,b%a)
t=int(input())
for i in range(t):
a,b=input().strip().split(" ")
a,b=[int(a),int(b)]
if gcd(a,b)==1:
print("Finite")
else:
pr... |
1286_B. Numbers on Tree | Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first... | ```python
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import collections
from collections import defaultdict
n=int(input())
c,root=[],0
graph=defaultdict(list)
for i in range(n):
a,b=map(int,input().split())
if a!=0:
graph[i+1].append(a)
graph[a].append(i... |
1305_C. Kuroni and Impossible Calculation | To become the king of Codeforces, Kuroni has to solve the following problem.
He is given n numbers a_1, a_2, ..., a_n. Help Kuroni to calculate ∏_{1≤ i<j≤ n} |a_i - a_j|. As result can be very big, output it modulo m.
If you are not familiar with short notation, ∏_{1≤ i<j≤ n} |a_i - a_j| is equal to |a_1 - a_2|⋅|a_1 ... | ```python
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def main():
n,m = map(int,input().split())
a = list(map(int,input().split()))
lst = [0]*m
for i in a:
lst[i%m] += 1
if max(lst) >= 2:
print(0)
else:
ans =... |
136_C. Replacement | Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that als... | ```python
n = input()
li = list(map(int, input().split(" ")))
li.sort()
if li[-1] != 1: li.insert(0, 1)
else: li.insert(0, 2)
del li[-1]
li.sort()
print(" ".join(map(str, li)))
``` |
1392_C. Omkar and Waterslide | Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.
Omkar currently has n supports arranged in a line, the i-th of which has height a_i. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in he... | ```python
import sys
T = int(sys.stdin.readline().strip())
for t in range (0, T):
n = int(sys.stdin.readline().strip())
a = list(map(int, sys.stdin.readline().strip().split()))
ans = 0
for i in range (1, n):
if a[i] < a[i-1]:
ans = ans + a[i-1] - a[i]
print(ans)
``` |
1433_D. Districts Connection | 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... | ```python
from collections import Counter
def solve(a,n):
if len(set(a)) == 1:
print("NO")
return
res = []
d = {}
for i in range(n):
if d.get(a[i]):
pass
else:
d[a[i]] = i+1
key = list(d.keys())
cen = key[0]
print("YES")
for i in r... |
1458_C. Latin Square | You are given a square matrix of size n. Every row and every column of this matrix is a permutation of 1, 2, …, n. Let a_{i, j} be the element at the intersection of i-th row and j-th column for every 1 ≤ i, j ≤ n. Rows are numbered 1, …, n top to bottom, and columns are numbered 1, …, n left to right.
There are six t... | ```python
import sys,io,os
Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
Y=lambda:[*map(int,Z().split())]
def I(M):
n=len(M)
nM=[[0]*n for i in range(n)]
for x in range(n):
for y in range(n):
nM[x][M[x][y]-1]=y+1
return nM
def C(M):
n=len(M)
nM=[[0]*n for i in range(n... |
1481_C. Fence Painting | You finally woke up after this crazy dream and decided to walk around to clear your head. Outside you saw your house's fence — so plain and boring, that you'd like to repaint it.
<image>
You have a fence consisting of n planks, where the i-th plank has the color a_i. You want to repaint the fence in such a way that t... | ```python
from sys import stdin
import sys
tt = int(stdin.readline())
for loop in range(tt):
n,m = map(int,stdin.readline().split())
a = list(map(int,stdin.readline().split()))
b = list(map(int,stdin.readline().split()))
c = list(map(int,stdin.readline().split()))
dic = [ [] for i in range(n+1) ... |
1508_D. Swap Pass | Based on a peculiar incident at basketball practice, Akari came up with the following competitive programming problem!
You are given n points on the plane, no three of which are collinear. The i-th point initially has a label a_i, in such a way that the labels a_1, a_2, ..., a_n form a permutation of 1, 2, ..., n.
Yo... | ```python
import sys,io,os
try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
except:Z=lambda:sys.stdin.readline().encode()
from math import atan2
from collections import deque
def path(R):
H=deque();H.append(R)
while P[R]>=0:
R=P[R];H.append(R)
if len(H)>2:P[H.popleft()]=H[-1]
return... |
1534_E. Lost Array | This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, whi... | ```python
from sys import stdout
def reverse(n, req):return [x for x in range(1, n + 1) if x not in req]
def solve():
n, k = (int(x) for x in input().split())
if n % 2 == 1 and k % 2 == 0:print(-1);stdout.flush();return
elif n % k == 0:
xor = 0;curr_idx = 1
while curr_idx <= n:next_idx = cur... |
181_C. Trading Business | To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the sellin... | ```python
import sys
profit = 0
initial = (list(map(int, sys.stdin.readline().split())))
num_planet = initial[0]
num_goods = initial[1]
capacity = initial[2]
stonks = []
for i in range(0, num_planet):
#print('Name planetu')
name_Planet = str(sys.stdin.readline())
planet = []
for j in range (0, num_goo... |
278_C. Learning Languages | 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... | ```python
class UnionFind:
def __init__(self, n, m):
self.data = [i for i in range(n+m)]
self.size = [0]*(m+n)
def union(self, u, v):
up = self.find(u)
vp = self.find(v)
if up == vp:
return
if self.size[up] <= self.size[vp]:
self.data[up] = vp
self.size[vp] += self... |
300_B. Coach | A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.
Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the sa... | ```python
n,m = map(int, input().split())
arr = [i for i in range(n+1)]
mem = {}
for i in range(m):
a,b = map(int, input().split())
if arr[a] in mem:
mem[arr[a]].append(arr[b])
arr[b] = arr[a]
elif arr[b] in mem:
mem[arr[b]].append(arr[a])
arr[a] = arr[b]
else:
me... |
325_E. The Red Button | Piegirl found the red button. You have one last chance to change the inevitable end.
The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to... | ```python
# METO Bot 0.9.9.1
n=int(input())
if n&1:
print(-1)
else:
D,R=[False]*(10**6),[0]*(10**6)
i,j=0,0
while True:
D[j]=True
R[i]=j
i+=1
if not D[(j+n)>>1]:
j=(j+n)>>1
elif not D[j>>1]:
j=j>>1
else:
break
print(" ".join(str(R[i]) for i in range(n,-1,-1)))
``... |
349_A. Cinema Line | The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the... | ```python
n = int(input())
L = list(map(int,input().split()))
a=p=0
for i in L:
if i==25:
a+=1
elif i==50:
a-=1
p+=1
else:
if p>0:
p-=1
a-=1
else:
a-=3
if a<0:
print('NO')
break
else:
print('YES')
``` |
443_C. Borya and Hanabi | Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game.
Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding n cards. The game is somewhat complicated by the fact that everybody sees Borya's cards excep... | ```python
n = int(input())
data = set(input().split())
temp = 'RGBYW'
c = []
res = 10
for i in data:
p1 = temp.find(i[0])
p2 = int(i[1]) - 1
c.append(2 ** p1 + 2 ** (p2 + 5))
for i in range(1024):
ok = True
for j in range(len(c) - 1):
for k in range(j + 1, len(c)):
if (c[j] & i) ... |
489_C. Given Length and Sum of Digits... | You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
Input
The single line of the input contains a pa... | ```python
m,s = list(map(int,input().split()))
flag = True
large = 0
small = 0
m1 = m-1
m2 = 0
s1 = s
if s==0 and m==1:
small,large = 0,0
flag = False
elif s>9*m or s<1:
flag = False
large = -1
small = -1
if flag:
while (s1 != 0):
if s1 >9:
large += 9*10**(m1)
small += 9*10**(m2)
s1 -= 9
m1 -= 1
... |
513_B1. Permutations | You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn... | ```python
import sys
import math
import itertools
TESTING = False
def helper(length, knum):
if length <= 1: return [1]
possibilties = pow(2, length - 1);
if knum <= possibilties / 2:
temp = helper(length - 1, knum)
for i in range(len(temp)): temp[i]+=1
return [1]+temp;
res = he... |
538_C. Tourist's Notes | A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. ... | ```python
"""
Satwik_Tiwari ;) .
20 june , 2020 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import B... |
60_A. Where Are My Flakes? | <image>
One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like "Hidden to the l... | ```python
n, m = input().split(' ')
n = int(n)
m = int(m)
hints = {}
max_right = None
min_left = None
if m > 0:
for i in range(m):
do_nothing = False
line = input().split(' ')
hint_position = int(line[4])-1
if line[2] == 'left':
hint_box = hint_position - 1
... |
630_F. Selection of Personnel | One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the n... | ```python
from math import factorial
def c(n, k):
cur = factorial(n) // factorial(k)
return cur // factorial(n - k)
n = int(input())
ans = c(n, 5) + c(n, 6) + c(n, 7)
print(ans)
``` |
658_C. Bear and Forgotten Tree 3 | A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only th... | ```python
n, d, h = map(int, input().split())
if d > 2 * h or (h == 0 and n > 1) or (d == 1 and n > 2):
print(-1)
else:
fr = 2
for i in range(h):
print('{} {}'.format(fr - 1, fr))
fr += 1
if d == h:
while fr <= n:
print('2 {}'.format(fr))
fr += 1
else:
last, next = 1, h + 2
for i in range(d - h):
... |
725_D. Contest Balloons | One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by 1. For example, if there ... | ```python
import sys
input = sys.stdin.readline
from heapq import heappop, heappush, heapify
n = int(input())
b, _ = map(int, input().split())
heap = []
heap2 = []
for _ in range(n-1):
t, w = map(int, input().split())
if t > b:
heap.append(w + 1 - t)
else:
heap2.append((-t, -w))
heapify(hea... |
747_D. Winter Is Coming | The winter in Berland lasts n days. For each day we know the forecast for the average air temperature that day.
Vasya has a new set of winter tires which allows him to drive safely no more than k days at any average air temperature. After k days of using it (regardless of the temperature of these days) the set of win... | ```python
n,k=map(int,input().split())
d=list(map(int,input().split()))
p=[]
count=0
count1=0
for i in range(len(d)):
if d[i]>=0:
count+=1
if d[i]<0 or i==len(d)-1:
p.append(count)
count=0
count1+=1
if d[len(d)-1]>=0:
count1-=1
if count1==0:
print(0)
exit()
a=p.pop() ... |
770_A. New Password | Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.
Innokentiy decides that new password should satisfy the following conditions:
* the length of the password must be equal to n,
* the password should con... | ```python
n, k = eval(input().rstrip().replace(" ", ","))
k = min(k, 26)
letters = [chr(i) for i in range(97, 123)]
for i in range(n):
print(letters[i%k], end="")
``` |
887_C. Solution for Cube | During the breaks between competitions, top-model Izabella tries to develop herself and not to be bored. For example, now she tries to solve Rubik's cube 2x2x2.
It's too hard to learn to solve Rubik's cube instantly, so she learns to understand if it's possible to solve the cube in some state using 90-degrees rotation... | ```python
# Main maut ko takiya, aur kafan ko chaadar banakar audhta hoon!
def R(b):
c=[]
for i in b:
c.append(i)
c[1]=b[5]
c[3]=b[7]
c[5]=b[9]
c[7]=b[11]
c[9]=b[22]
c[11]=b[20]
c[22]=b[1]
c[20]=b[3]
d=[]
for i in range(23):
if(c[i]!=c[i+1]):
d.append(c[i])
d.append(c[-1])
if(len(d)==6):
ret... |
90_C. Robbery | It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has n cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from 1 to n from the left to the right.
Unfortunately, Joe ... | ```python
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
if n % 2 == 0:
print('0')
else:
print(min(m // (n // 2 + 1) * k, min(a[::2])))
# Made By Mostafa_Khaled
``` |
959_A. Mahmoud and Ehab and the even-odd game | Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that:
* 1 ≤ a ≤ n.
* If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has... | ```python
import sys
def solve():
n = int(input())
if n%2 == 0:
ans = "Mahmoud"
else:
ans = "Ehab"
return ans
ans = solve()
print(ans)
``` |
985_F. Isomorphic Strings | You are given a string s of length n consisting of lowercase English letters.
For two given strings s and t, say S is the set of distinct characters of s and T is the set of distinct characters of t. The strings s and t are isomorphic if their lengths are equal and there is a one-to-one mapping (bijection) f between S... | ```python
def getIntList():
return list(map(int, input().split()));
def getTransIntList(n):
first=getIntList();
m=len(first);
result=[[0]*n for _ in range(m)];
for i in range(m):
result[i][0]=first[i];
for j in range(1, n):
curr=getIntList();
for i in range(m):
... |
p02579 AtCoder Beginner Contest 176 - Wizard in Maze | A maze is composed of a grid of H \times W squares - H vertical, W horizontal.
The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is `#` and a road if S_{ij} is `.`.
There is a magician in (C_h,C_w). He can do the following two kinds of moves:
* Move A: Walk to a ... | ```python
from collections import deque
H,W=map(int,input().split())
C=tuple(map(int,input().split()))
D=tuple(map(int,input().split()))
S=["*"*(W+4)]*(H+4)
for x in range(H):
S[x+2]="**"+input()+"**"
V=[]
for a in range(-2,3):
for b in range(-2,3):
if not(a==b==0):
if abs(a)+abs(b)<=1:
... |
p02710 AtCoder Beginner Contest 163 - path pass i | We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. Additionally, each vertex is painted in a color, and the color of Vertex i is c_i. Here, the color of each vertex is represented by an integer between 1 and N (inclusive). The same integer corresponds to the same col... | ```python
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def EulerTour(graph, root=1):
N = len(graph) - 1
parent = [0] * (N + 1)
stack = [-root, root]
tour = []
ind_L = [0] * (N + 1)
ind_R = [0] * (N + 1)
i = -1
while... |
p02839 AtCoder Beginner Contest 147 - Balanced Path | We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.
The square (i, j) has two numbers A_{ij} and B_{ij} written on it.
First, for each square, Takahashi paints one of the written numbers red and the other blue.
Then... | ```python
from sys import stdin
input = stdin.buffer.readline
h, w = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(h)]
b = [list(map(int, input().split())) for _ in range(h)]
dp = [0] * -~w
dp[0] = 1 << 6400
for i in range(h):
for j in range(w):
t = dp[j]
if j:
... |
p02976 AtCoder Grand Contest 035 - Even Degrees | You are given a simple connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge connects Vertex A_i and Vertex B_i. Takahashi will assign one of the two possible directions to each of the edges in the graph to make a directed graph. Determine if it is possible to make ... | ```python
n, m, *L = map(int, open(0).read().split())
con = [[] for _ in range(n)]
for s, t in zip(*[iter(L)] * 2):
con[s - 1] += t - 1,
con[t - 1] += s - 1,
# 辺を取り出して木をつくる
tree = [[] for _ in range(n)]
lev = [0] * n
vis = [False] * n
vis[0] = True
reserve = set()
q = [0]
while q:
cur = q.pop()
for nxt in con[cur]... |
p03112 AtCoder Beginner Contest 119 - Lazy Faith | Along a road running in an east-west direction, there are A shrines and B temples. The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.
Answer the following Q queries:
... | ```python
INF = 1e20
A, B, Q = [int(i) for i in input().split()]
S = [-INF] + [int(input()) for _ in range(A)] + [INF]
T = [-INF] + [int(input()) for _ in range(B)] + [INF]
X = [int(input()) for _ in range(Q)]
from bisect import bisect_left
mins = []
for x in X:
s = bisect_left(S, x)
t = bisect_left(T, x)
... |
p03415 AtCoder Beginner Contest 090 - Diagonal String | We have a 3×3 square grid, where each square contains a lowercase English letters. The letter in the square at the i-th row from the top and j-th column from the left is c_{ij}.
Print the string of length 3 that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bot... | ```python
s=open(0).read().split()
print(s[0][0]+s[1][1]+s[2][2])
``` |
p03575 AtCoder Beginner Contest 075 - Bridge | You are given an undirected connected graph with N vertices and M edges that does not contain self-loops and double edges.
The i-th edge (1 \leq i \leq M) connects Vertex a_i and Vertex b_i.
An edge whose removal disconnects the graph is called a bridge.
Find the number of the edges that are bridges among the M edges.... | ```python
n, m = map(int, input().split(" "))
a = [list(map(int, input().split(" "))) for i in range(m)]
a_connects = [[] for i in range(n)]
for x, y in a:
a_connects[x-1].append(y-1)
a_connects[y-1].append(x-1)
a_connect_sums = [len(connect) for connect in a_connects]
bridge_count = 0
while 1 in a_connect_sums:
x... |
p03730 AtCoder Beginner Contest 060 - Choose Integers | We ask you to select some number of positive integers, and calculate the sum of them.
It is allowed to select as many integers as you like, and as large integers as you wish. You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.
Your objecti... | ```python
a,b,c=map(int,input().split())
for i in range(a,b*a+1,a):
if i%b==c: print('YES');break
else:
print('NO')
``` |
p03894 CODE FESTIVAL 2016 Relay (Parallel) - Magician | You have N cups and 1 ball.
The cups are arranged in a row, from left to right.
You turned down all the cups, then inserted the ball into the leftmost cup.
Then, you will perform the following Q operations:
* The i-th operation: swap the positions of the A_i-th and B_i-th cups from the left. If one of these cups co... | ```python
n, q = [ int(v) for v in input().split() ]
num = [ 0 for i in range(n) ]
num[0] = 1
num[1] = 2
p = 0
for i in range(q):
a, b = [ int(v)-1 for v in input().split() ]
num[a], num[b] = num[b], num[a]
if num[a] == 1:
p = a
elif num[b] == 1:
p = b
if p > 0:
num[p-1] = 2
... |
p00000 QQ | Write a program which prints multiplication tables in the following format:
1x1=1
1x2=2
.
.
9x8=72
9x9=81
Input
No input.
Output
1x1=1
1x2=2
.
.
9x8=72
9x9=81
Example
Input
Output | ```python
r=range
s=str
for i in r(1,10):
for u in r(1,10):
print(s(i)+'x'+s(u)+'='+s(i*u))
``` |
p00265 Modular Query | Give you N cards. Only one natural number is written on each card. However, the same number is never written.
From now on, as a question, I will say an appropriate natural number. Please answer the largest remainder you get when you divide the number on the card you have by the number I said.
For example, suppose you... | ```python
# AOJ 0270: Modular Query
# Python3 2018.6.26 bal4u
N, Q = map(int, input().split())
tbl = [0]*300005
nmax, tbl[0] = 0, 1
c = list(map(int, input().split()))
for k in c:
tbl[k] = 1
if k > nmax: nmax = k
tbl[k & 1] = 1
tbl[k & 3] = 1
tbl[k & 7] = 1
for i in range(Q):
q = int(input())
if q > nmax: print... |
p00452 Darts | problem
You have to play a darts game with the following rules.
You can throw up to four arrows towards the target. You don't have to throw all four, you don't have to throw one. The target is divided into N parts. The score P1, ..., PN is written in each part. The total score S of the place where the arrow is stuck ... | ```python
from time import perf_counter
from itertools import combinations_with_replacement
from bisect import bisect_right
from functools import lru_cache
def solve1(darts, scores, point, target):
if darts == 3 or point > target:
if point > target:
return 0
else:
pos = bis... |
p00643 Rolling Dice | The north country is conquered by the great shogun-sama (which means king). Recently many beautiful dice which were made by order of the great shogun-sama were given to all citizens of the country. All citizens received the beautiful dice with a tear of delight. Now they are enthusiastically playing a game with the dic... | ```python
T, S, E, W, N, B = range(6)
class Dice:
def __init__(self):
self.state = list(range(6))
def __eq__(self, dice):
return self.state == dice.state
def __gt__(self, dice):
return self.state > dice.state
def copy(self):
dice = Dice()
dice.state = [x for ... |
p01052 Movie | Problem
Taro decided to watch one movie every day at a nearby movie theater during the summer vacation. (Taro has 31 days of summer vacation from August 1st to August 31st.)
The theater is set to show n movies during the summer vacation. Each movie is assigned a number from 1 to n, and the i-th movie will only be sho... | ```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
N = int(input())
As = []
Bs = []
movies = [[] for x in range(31)]
for n in range(N):
a, b = map(int, input().split())
a -= 1
b -= 1
As.append(a)
Bs.append(b)
for day in range(a, b+1):
movies[day].append(n)
picked = [False] * N
an... |
p01321 Final Examination! | Yui Hirasawa, who attends private Sakuragaoka Girls' High School, has to make a career hope by the day after tomorrow, but the trouble is that she hasn't decided anything yet. When I consulted with my friend Wa, I knew that my first choice was K University, so I consulted with my career guidance teacher to see if I cou... | ```python
while True:
n = int(input())
if n == 0:
break
total = []
for _ in range(n):
total.append(sum(list(map(int,input().split()))))
total.sort()
print(total[-1],total[0])
``` |
p01489 IkaNumber | Example
Input
5
Output
5 | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def fibonacci(N, M):
RA = RD = 1; RB = RC = 0
XA = XB = XC = 1; XD = 0
while N:
if N & 1:
RA, RB, RC, RD = (RA*XA + RB*XC) % M, (RA*XB + RB*XD) % M, (RC*XA + RD*XC) % M, (RC*XB + RD*XD) % M
XA, XB, XC, X... |
p01802 Koto Municipal Subway | Koto Municipal Subway
Koto Municipal Subway
Koto City is a famous city whose roads are in a grid pattern, as shown in the figure below. The roads extending from north to south and the roads extending from east to west are lined up at intervals of 1 km each. Let Koto station at the southwestern intersection of Koto ci... | ```python
def main():
while 1:
d,e= map(int, input().split())
if d == e == 0:
break
x = d
y = 0
ans = abs(d-e)
while y != d:
a = abs((x ** 2 + y ** 2) ** 0.5 - e)
ans = min(a,ans)
x -= 1
y += 1
print(... |
p02217 Tree of Peony | Problem statement
There is a tree consisting of $ N $ vertices $ N-1 $ edges, and the $ i $ th edge connects the $ u_i $ and $ v_i $ vertices.
Each vertex has a button, and the button at the $ i $ th vertex is called the button $ i $.
First, the beauty of the button $ i $ is $ a_i $.
Each time you press the button ... | ```python
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [li... |
p02370 Topological Sort | <image>
A directed acyclic graph (DAG) can be used to represent the ordering of tasks. Tasks are represented by vertices and constraints where one task can begin before another, are represented by edges. For example, in the above example, you can undertake task B after both task A and task B are finished. You can obt... | ```python
from collections import deque
from typing import List, Optional
def topological_sort(
graph: List[List[int]], in_degrees: List[int], first_index: int = 0
) -> Optional[List[int]]:
"""Topological sort that uses Kahn's algorithm and is able to detect cycles.
Returns:
If the given graph is ... |
1005_A. Tanya and Stairways | Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps,... | ```python
scalini = input()
conti_tania = input().split(" ")
numero_scale = 0
numero_scalini = []
n = 0
conta_scalini = ""
count = 1
x = 0
lista = []
conti_tania.append('0')
for n in range(int(len(conti_tania))-1):
if int(conti_tania[n+1]) > int(conti_tania[n]):
count += 1
if int(conti_tania... |
1028_G. Guess the number | This problem is interactive.
You should guess hidden number x which is between 1 and M = 10004205361450474, inclusive.
You could use up to 5 queries.
In each query, you can output an increasing sequence of k ≤ x integers, each between 1 and M, inclusive, and you will obtain one of the following as an answer:
* ei... | ```python
from sys import stdin, stdout
max_k=10000
max_shift = [max_k]
for t in range(1, 5):
max_shift.append(max_shift[t-1]*(max_k+1)+max_k)
def get_right(left, t): # [left...right]
if left >= max_k:
return left + max_shift[t-1] - 1
k = left
if k > max_k:
k = max_k
if t == 1:
... |
1047_C. Enlarge GCD | Mr. F has n positive integers, a_1, a_2, …, a_n.
He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers.
But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward.
... | ```python
from sys import stdin
from collections import deque
mod = 10**9 + 7
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split()... |
1093_A. Dice Rolling | Mishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice).
Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls M... | ```python
"""
██╗ ██████╗ ██╗ ██████╗ ██████╗ ██╗ █████╗
██║██╔═══██╗██║ ╚════██╗██╔═████╗███║██╔══██╗
██║██║ ██║██║ █████╔╝██║██╔██║╚██║╚██████║
██║██║ ██║██║ ██╔═══╝ ████╔╝██║ ██║ ╚═══██║
██║╚██████╔╝██║ ███████╗╚██████╔╝ ██║ █████╔╝
╚═╝ ╚═════╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚════╝
██████╗ ██╗██╗... |
1113_A. Sasha and His Trip | Sasha is a very happy guy, that's why he is always on the move. There are n cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from 1 to n in increasing order. The distance between any two adjacent cities is equal to 1 kilometer. Since all roads in... | ```python
n,v=[int(x) for x in input().split()]
if n<=v+1:
print(n-1)
else:
print(v+(n-v-1)*(n-v-2)//2+(n-v-1)*2)
``` |
1141_D. Colored Boots | There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot... | ```python
#Bhargey Mehta (Sophomore)
#DA-IICT, Gandhinagar
import sys, math, queue
sys.setrecursionlimit(1000000)
#sys.stdin = open("input.txt", "r")
n = int(input())
l = list(input())
r = list(input())
ls = {chr(i):[] for i in range(97, 97+26)}
rs = {chr(i):[] for i in range(97, 97+26)}
lc = []
rc = []
for i in range... |
1182_C. Beautiful Lyrics | You are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.
Each lyric consists of two lines. Each line consists of two words separated by whitespace.
A lyric is beau... | ```python
from sys import stdin
n = int(stdin.readline())
vowels = {'a', 'e', 'o', 'i', 'u'}
words = []
for i in range(n):
words.append(stdin.readline())
all_pairs = {}
sec_pairs = {}
for item in words:
cnt, last = 0, -1
for i in item:
if i in vowels:
cnt += 1
last = i
# all_pairs
if cnt not in all... |
1260_D. A Game with Traps | You are playing a computer game, where you lead a party of m soldiers. Each soldier is characterised by his agility a_i.
The level you are trying to get through can be represented as a straight line segment from point 0 (where you and your squad is initially located) to point n + 1 (where the boss is located).
The le... | ```python
import sys
import math
from collections import defaultdict,Counter,deque
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.filen... |
1326_D2. Prefix-Suffix Palindrome (Hard version) | This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the fol... | ```python
# -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i ... |
1345_D. Monopole Magnets | A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowe... | ```python
import sys
n,m = map(int,input().split())
grid = [list(input()) for _ in range(n)]
check_row = [0 for _ in range(n)]
check_column =[0 for _ in range(m)]
flg_column = 0
flg_row = 0
for i in range(n):
check_1 = grid[i]
flg = 0
for j in range(m):
if flg == 0 and check_1[j]=="#":
f... |
1367_C. Social Distance | Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ... | ```python
import sys
input = lambda: sys.stdin.readline().strip()
inp = lambda: list(map(int,input().split()))
for _ in range(int(input())):
n,d = inp()
a = [int(i) for i in str(input())]
f1 = f = True
c = ans =0
for i in range(n):
if f==True:
if a[i]==0:
c+=1
else:
f = False
c = 0
if c==d+1... |
1388_C. Uncle Bogdan and Country Happiness | Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.
There are n cities and n−1 undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities a... | ```python
import sys
input=sys.stdin.buffer.readline
for _ in range(int(input())):
n,m=map(int,input().split())
pr=list(map(int,input().split()))
hr=list(map(int,input().split()))
dic={}
dis={}
people={}
for i in range(1,n+1):
dic[i]=[]
dis[i]=0
people[i]=-1
for i... |
1409_A. Yet Another Two Integers Problem | You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | ```python
import math
t=int(input())
while(t>0):
l=(input().split())
a=int(l[0])
b=int(l[1])
mov=math.ceil(math.fabs(b-a)/10)
print(mov)
t=t-1
``` |
142_D. Help Shrek and Donkey 2 | Having learned (not without some help from the Codeforces participants) to play the card game from the previous round optimally, Shrek and Donkey (as you may remember, they too live now in the Kingdom of Far Far Away) have decided to quit the boring card games and play with toy soldiers.
The rules of the game are as f... | ```python
def get(a):
global m
R = -1
G = -1
mi = -1
for i in range(m):
if a[i] == '-':
mi = i
elif a[i] == "R":
R = i
else:
G = i
return G, R, mi
n, m, k = map(int, input().split())
draw = [0, 0]
t = []
for i in range(n):
G, R, m... |
1453_A. Cancel the Trains | 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... | ```python
t=int(input())
while t:
n,m=map(int,(input().split()))
a=set(map(int,input().split()))
b=set(map(int,input().split()))
print(len(a&b))
t=t-1
``` |
1476_F. Lanterns | There are n lanterns in a row. The lantern i is placed in position i and has power equal to p_i.
Each lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the i-th lantern is turned to the left, it illuminates all such lanterns j that j ∈ [i - p_i, i - 1]. Similarly,... | ```python
from bisect import bisect_left;from math import inf
class ST:
def __init__(self,arr):
n=len(arr);mx=n.bit_length();self.st=[[0]*mx for i in range(n)]
for i in range(n):self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):self.st[i][j]=max(self.st[i][j-1... |
1503_C. Travelling Salesman Problem | There are n cities numbered from 1 to n, and city i has beauty a_i.
A salesman wants to start at city 1, visit every city exactly once, and return to city 1.
For all i≠ j, a flight from city i to city j costs max(c_i,a_j-a_i) dollars, where c_i is the price floor enforced by city i. Note that there is no absolute val... | ```python
n=int(input());a=sorted([*map(int,input().split())]for i in range(n));c=sum(a[0]);t=a[0][1]
for w in a[1:]:
t+=w[1]
if w==a[-1]or sum(w)>c:t+=max(w[0]-c,0);c=sum(w)
print(t)
``` |
1527_A. And Then There Were K | Given an integer n, find the maximum value of integer k such that the following condition holds:
n & (n-1) & (n-2) & (n-3) & ... (k) = 0 where & denotes the [bitwise AND operation.](https://en.wikipedia.org/wiki/Bitwise_operation#AND)
Input
The first line contains a single integer t (1 ≤ t ≤ 3 ⋅ 10^4). Then t test... | ```python
from math import log
from math import floor
t = int(input())
for i in range(t):
n = int(input())
#print(n)
k = 2**(floor(log(n,2)))-1
print(k)
``` |
178_D1. Magic Squares | The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.
The magic square is a matrix of size n × n. The elements of this matrix are integers.... | ```python
import sys, random
def f(b):
global a
a = [[0] * n for o in range(n)]
for i in range(n):
for j in range(n):
a[i][j] = b[i * n + j]
rez = 0
for i in range(n):
ns = 0
for j in range(n):
ns += a[i][j]
rez += abs(su - ns)
for j in ... |
200_C. Football Championship | Any resemblance to any real championship and sport is accidental.
The Berland National team takes part in the local Football championship which now has a group stage. Let's describe the formal rules of the local championship:
* the team that kicked most balls in the enemy's goal area wins the game;
* the victor... | ```python
import copy
teams = {}
times = {}
def put_team(s):
if not s[0] in teams:
teams[s[0]] = [0, 0, 0, s[0]]
if not s[1] in teams:
teams[s[1]] = [0, 0, 0, s[1]]
g1, g2 = map(int, s[2].split(':'))
teams[s[0]][1] -= g1 - g2
teams[s[1]][1] -= g2 - g1
teams[s[0]][2] -= g1
t... |
225_B. Well-known Numbers | Numbers k-bonacci (k is integer, k > 1) are a generalization of Fibonacci numbers and are determined as follows:
* F(k, n) = 0, for integer n, 1 ≤ n < k;
* F(k, k) = 1;
* F(k, n) = F(k, n - 1) + F(k, n - 2) + ... + F(k, n - k), for integer n, n > k.
Note that we determine the k-bonacci numbers, F(k, n), on... | ```python
def s():
[s,k] = list(map(int,input().split()))
d = [0]
d.append(1)
t = 0
r = []
while t < s:
t = sum(d[-min(k,len(d)):])
d.append(t)
for i in reversed(d):
if i <= s:
s -= i
r.append(i)
if i == 0:
break
... |
274_A. k-Multiple Free Set | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-mu... | ```python
n, k = [int(x) for x in input().split()]
a = sorted([int(x) for x in input().split()])
s = set(a)
l = 0
for x in a:
t = 1
while x in s:
l += t
t = 1 - t
s.remove(x)
x *= k
print(l)
``` |
320_A. Magic Numbers | A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not.
You're given a number. Determine if it is a magic number or not.
Input
The first line of input contains ... | ```python
a=input()
result=1
if a[0]!='1':
print('NO')
result=0
else:
for i in range(len(a)):
if a[i]!='1' and a[i]!='4':
print('NO')
result=0
break
if result==1:
length=len(a)
for i in range(length-2):
if a[i]=='4' and a[i+1]=='4' ... |
368_C. Sereja and Algorithm | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps:
1. Find any continuous subsequence (substring) of three characters of string q, which does... | ```python
def f(t): return t[2] - t[0] > 1
t = input()
n, m, p = len(t), int(input()), {'x': 0, 'y': 1, 'z': 2}
s = [[0] * (n + 1) for i in range(3)]
for i, c in enumerate(t, 1): s[p[c]][i] = 1
for i in range(3):
for j in range(1, n): s[i][j + 1] += s[i][j]
a, b, c = s
q, d = [map(int, input().split()) for ... |
390_D. Inna and Sweet Matrix | Inna loves sweets very much. That's why she decided to play a game called "Sweet Matrix".
Inna sees an n × m matrix and k candies. We'll index the matrix rows from 1 to n and the matrix columns from 1 to m. We'll represent the cell in the i-th row and j-th column as (i, j). Two cells (i, j) and (p, q) of the matrix ar... | ```python
string = input()
l = string.split(" ")
n, m, k = int(l[0]),int(l[1]),int(l[2])
l = [{(1,1),}]
count = 1
In = 0
while count < k:
s = set()
for i in l[In]:
x = i[0]+1
y = i[1]
if x<=n and y<=m:
t = [0,0]
t[0],t[1] = x, y
s.add(tuple(t))
x = i[0]
y = i[1]+1
if x<=n and y<=m:
t = [0,0]
... |
412_C. Pattern | Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.
In this task, a pattern will be a string con... | ```python
n = int(input())
matrix = []
for _ in range(n):
pattern = list(input())
matrix.append(pattern)
m = len(matrix[0])
answer = []
for i in range(m):
memo = set()
question = False
for j in range(n):
if matrix[j][i].isalpha():
memo.add(matrix[j][i])
else:
... |
439_E. Devu and Birthday Celebration | Today is Devu's birthday. For celebrating the occasion, he bought n sweets from the nearby market. He has invited his f friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each f... | ```python
import itertools
import functools
import operator
N = 100001
P = 10**9 + 7
fact = [1]
for i in range(1, N):
fact.append(fact[-1] * i % P)
inv = [0, 1]
for i in range(2, N):
inv.append(P - P // i * inv[P % i] % P)
inv_fact = [1]
for i in range(1, N):
inv_fact.append(inv_fact[-1] * inv[i] % P)
least_div ... |
461_B. Appleman and Tree | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.
Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree... | ```python
from collections import UserDict
class Tree(UserDict):
def __init__(self, g):
super().__init__()
for name, value in enumerate(g, 1):
self[value] = name
def __setitem__(self, name, value):
if name in self:
if value is not None:
self[nam... |
485_A. Factory | One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were x details in the factory storage, then by the end of the day the factory has to produce <image> (remainder after dividing x by m) more details. Unfortunately, no c... | ```python
(n,m) = input().split()
n=int(n)
m=int(m)
for i in range(0,10**5):
n+=n%m
if n%m == 0:
break
if (n%m == 0): print("Yes")
else: print('No')
``` |
509_A. Maximum in Table | An n × n table a is defined as follows:
* The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n.
* Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin... | ```python
n = int(input())
list1 = []
list2 = [1 for i in range(n)]
list3 = [1] + [0 for i in range(n-1)]
list1.append(list2)
for i in range(n-1):
list1.append(list3)
for i in range(1,n):
for j in range(1,n):
list1[i][j] = list1[i-1][j] + list1[i][j-1]
list4 = []
for i in range(n):
list4.append(max(... |
533_C. Board Game | Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) to (x - 1, y) or (x, y - 1). Vasiliy can move his pawn from (x, y) to one of cells: ... | ```python
"""
Author - Satwik Tiwari .
15th Jan , 2021 - Thursday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io ... |
558_B. Amr and The Large Array | Amr has got a large array of size n. Amr doesn't like large arrays so he intends to make it smaller.
Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegme... | ```python
from collections import defaultdict
_ = input()
nums = list(map(int, input().split()))
freqs = defaultdict(list)
_max = -1
for i, k in enumerate(nums):
freqs[k].append(i + 1)
_max = max(_max, len(freqs[k]))
start = 1
end = len(nums)
length = end - start
for k, v in freqs.items():
if len(v)... |
652_A. Gabriel and Caterpillar | The 9-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height h1 cm from the ground. On the height h2 cm (h2 > h1) on the same tree hung an apple and the caterpillar was crawling to the apple.
Gabriel is interested when the caterpill... | ```python
#! /usr/bin/env python3
'''
' Title:
' Author: Cheng-Shih, Wong
' Date:
'''
import math
h1, h2 = map(int, input().split())
a, b = map(int, input().split())
if h1+a*8 >= h2: print(0)
elif a <= b: print(-1)
else:
print( math.ceil((h2-h1-8*a)/(12*(a-b))) )
``` |
6_D. Lizards and Basements 2 | This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced.
Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the las... | ```python
n, a, b = list(map(int, input().split(" ")))
h = list(map(lambda x: int(x) + 1, input().split(" ")))
dp = [[[-1] * 17 for j in range(17)] for i in range(n)]
num = [[[0] * 17 for j in range(17)] for i in range(n)]
health = [[[0] * 17 for j in range(17)] for i in range(n)]
result = []
def recursion(i, j, k):
... |
722_A. Broken Clock | You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.
You are given a time in format HH:MM that is currently displayed on the broken ... | ```python
import logging
import copy
import sys
import math
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
#def solve(firstLine):
def solve(formatStr, timeStr):
if int(timeStr[3]) > 5 :
timeStr = timeStr[:3] + "0" + timeStr[4:]
if formatStr == 24:
if int(timeStr[0]) > 2... |
743_D. Chloe and pleasant prizes | Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes.
They took n prizes for the contestants and wrote on each of them a unique id (integer f... | ```python
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mo... |
767_A. Snacktower | According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be ... | ```python
n = int(input())
s = list(map(int, input().split()))
e1 = []
e2 = set()
f = '\n'
r = ''
for i in s:
'''e1.append(i)
while n in e1:
print(n, end=' ')
n -= 1
print()'''
e2.add(i)
while n in e2:
print(n, end=' ')
n -= 1
print()
``` |
811_B. Vladik and Complicated Book | Vladik had started reading a complicated book about algorithms containing n pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation P = [p1, p2, ..., pn], where pi denotes the number of page that should be read i-th in turn.
Sometimes Vladik’s mom so... | ```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
n,m=map(int,input().strip().split())
a=input()
b=list(map(int,a.strip().split()))
for i in range(m):
L,R,k=map(int,input().strip().split())
L-=1
R-=1
k-=1
sum=0
j=L
while j<=R:
if b[j]<b[k]:
sum+=1
j+=1
if ... |
837_D. Round Subset | Let's call the roundness of the number the number of zeros to which it ends.
You have an array of n numbers. You need to choose a subset of exactly k numbers so that the roundness of the product of the selected numbers will be maximum possible.
Input
The first line contains two integer numbers n and k (1 ≤ n ≤ 200, ... | ```python
import sys
n, K = map(int, input().split())
a = list(map(int, input().split()))
m2, m5 = [0]*n, [0]*n
for i, x in enumerate(a):
while x % 2 == 0:
x //= 2
m2[i] += 1
while x % 5 == 0:
x //= 5
m5[i] += 1
dp = [[-10**9]*5100 for _ in range(K)]
dp[0][0] = 0
for i in ra... |
883_F. Lost in Transliteration | There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland s... | ```python
c=[]
n=int(input())
for uygf in range(n):
s=list(input())
l=len(s)
i=0
p=[]
d=['u','o','k','h']
while(i<l):
if(s[i] not in d):
p.append(s[i])
i+=1
elif(s[i]=='u'):
p.append('o')
p.append('o')
i+=1
elif(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.