name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
p02471 Extended Euclid Algorithm | Extended Euclid Algorithm
Given positive integers a and b, find the integer solution (x, y) to ax + by = gcd(a, b), where gcd(a, b) is the greatest common divisor of a and b.
Constraints
* 1 ≤ a, b ≤ 109
Input
a b
Two positive integers a and b are given separated by a space in a line.
Output
Print two inte... | ```python
import sys
sys.setrecursionlimit(10 ** 7)
# 拡張Euclidの互除法
# 拡張ユークリッドの互除法
a, b = map(int, input().split())
def extgcd(a, b):
if b == 0:
return a, 1, 0
p, q = a // b, a % b
d, x, y = extgcd(b, q)
x, y = y, x - p * y
return d, x, y
reverse = False
if b > a:
a, b = b, a
r... |
1008_A. Romaji | Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant... | ```python
s=input()
a=['a','e','i','o','u']
c=0
for i in range(len(s)):
if(i==len(s)-1):
if s[i] in a or s[i]=='n':
c+=1
continue
elif s[i] in a:
c+=1
continue
elif(s[i]=='n'):
c+=1
continue
else:
if s[i+1] in a:
... |
1075_E. Optimal Polygon Perimeter | You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1... | ```python
n = int(input())
north = -100000000
south = 100000000
east = -100000000
west = 100000000
ne = -200000000
nw = -200000000
se = -200000000
sw = -200000000
for i in range(n):
x,y = map(int,input().split())
north = max(north,y)
east = max(east,x)
south = min(south,y)
west = min(west,x)
ne ... |
1096_F. Inversion Expectation | A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a p... | ```python
base=998244353;
def power(x, y):
if(y==0):
return 1
t=power(x, y//2)
t=(t*t)%base
if(y%2):
t=(t*x)%base
return t;
def inverse(x):
return power(x, base-2)
ft=[0]
for i in range(0, 200000):
ft.append(0)
def get(i):
res=0
while(i<=200000):
res+=ft[i]
... |
1144_C. Two Shuffled Sequences | Two integer sequences existed initially — one of them was strictly increasing, and the other 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 th... | ```python
n = int(input())
a = [int(s) for s in input().split()]
d = dict()
for i in a:
x = d.get(i,0)
if x == 0:
d[i] = 1
else:
d[i] += 1
up = []
down = []
for i in d.keys():
k = d[i]
if k == 1:
up.append(i)
elif k == 2:
up.append(i)
down.append(i)
el... |
1165_B. Polycarp Training | Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly 1 problem, during the second day — exactly 2 problems, during the third day — exactly 3 problems, and so on. During the k-th day he should solve k problems.
Polycarp has a list of n contests, th... | ```python
a = int(input())
b = [int(x) for x in input().split()]
b.sort()
s = 1
q = 0
for i in b:
if i >= s:
s += 1
q += 1
print(q)
``` |
1184_C1. Heidi and the Turing Test (Easy) | The Cybermen and the Daleks have long been the Doctor's main enemies. Everyone knows that both these species enjoy destroying everything they encounter. However, a little-known fact about them is that they both also love taking Turing tests!
Heidi designed a series of increasingly difficult tasks for them to spend the... | ```python
import bisect
import functools
import math
import sys
from collections import defaultdict
# input = sys.stdin.readline
rt = lambda: map(int, input().split())
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
def solve(pts):
for x1 in range(50):
for x2 in range(x1+1, 51):
... |
1202_D. Print a 1337-string... | The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given an integer n.
You have to find a sequence s consisting of digits \{1, 3, 7\} such that it has exactly n subsequences equal to 1337.
For example, seque... | ```python
import sys
t = int(sys.stdin.readline().strip())
for i in range(0, t):
n = int(sys.stdin.readline().strip())
c = 4 * 10 ** 2
d = n // (c * (c-1) // 2)
b = n % (c * (c-1) // 2)
print("133" + "7"*b + "3" * (c-2) + "7"*d)
``` |
1244_D. Paint the Tree | You are given a tree consisting of n vertices. A tree is an undirected connected acyclic graph.
<image> Example of a tree.
You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.
You have to paint the vertices so that any path consisting of exactly th... | ```python
import sys
from collections import defaultdict,deque
def getcost(ind,col1,col2,col3,count):
#print(ind,'ind',count,'count')
if count==1:
#print(col1[ind-1],'collooorr')
return col1[ind-1]
if count==2:
#print(col2[ind-1],'colllllooorrr')
return col2[ind-1]
#print... |
1264_B. Beautiful Sequence | An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to 1. More formally, a sequence s_1, s_2, …, s_{n} is beautiful if |s_i - s_{i+1}| = 1 for all 1 ≤ i ≤ n - 1.
Trans has a numbers 0, b numbers 1, c numbers 2 and d numbers 3. He wants to construct a beautiful sequenc... | ```python
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
# from itertools import permutations,combinations
d... |
1285_D. Dr. Evil Underscores | Today, as a friendship gift, Bakry gave Badawy n integers a_1, a_2, ..., a_n and challenged him to choose an integer X such that the value \underset{1 ≤ i ≤ n}{max} (a_i ⊕ X) is minimum possible, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
As always, Badawy is too ... | ```python
def solve(nums, bit):
if bit < 0: return 0
l = []
r = []
for el in nums:
if ((el >> bit) & 1): r.append(el)
else: l.append(el)
if len(l) == 0: return solve(r, bit - 1)
if len(r) == 0: return solve(l, bit - 1)
return min(solve(l, bit - 1), solve(r, bit - 1)) + (1 << bit)
n = int(input())
nums = map(... |
1329_A. Dreamoon Likes Coloring | Dreamoon likes coloring cells very much.
There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n.
You are given an integer m and m integers l_1, l_2, …, l_m (1 ≤ l_i ≤ n)
Dreamoon will perform m operations.
In i-th operation, Dreamoon will choose a number ... | ```python
n,m=map(int,input().split())
b=list(map(int,input().split()))
if sum(b)<n:print(-1)
else:
s=n+1;r=[-1]*m;i=0
for j in b[::-1]:
s=max(s-j,m-i)
if s+j-1>n:print(-1);break
r[i]=s;i+=1
else:print(*r[::-1])
``` |
1349_A. Orac and LCM | For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow:
* \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x.
* lcm(s) is the minimum positive integer x, that divisible on all integ... | ```python
from collections import Counter
from math import floor, sqrt
try:
long
except NameError:
long = int
def fac(n):
step = lambda x: 1 + (x<<2) - ((x>>1)<<1)
maxq = long(floor(sqrt(n)))
d = 1
q = 2 if n % 2 == 0 else 3
while q <= maxq and n % q != 0:
q = step(d)
d... |
1369_E. DeadLee | Lee bought some food for dinner time, but Lee's friends eat dinner in a deadly way. Lee is so scared, he doesn't want to die, at least not before seeing Online IOI 2020...
There are n different types of food and m Lee's best friends. Lee has w_i plates of the i-th type of food and each friend has two different favorit... | ```python
import sys
input = sys.stdin.readline
def line_input():
return [int(x) for x in input().split()]
def main():
n, m = line_input()
w = line_input()
adj = [[] for _ in range(n)]
edges = []
deg = [0] * n
for i in range(m):
u, v = line_input()
u, v = u - 1, v - 1
... |
1391_D. 505 | A binary matrix is called good if every even length square sub-matrix has an odd number of ones.
Given a binary matrix a consisting of n rows and m columns, determine the minimum number of cells you need to change to make it good, or report that there is no way to make it good at all.
All the terms above have their... | ```python
def f( l, a):
i, count = 0,0
for x in l:
count += x not in a[i]
#print( x, a[i], count )
i = (i+1) %2
return count
def g( l, mx ):
return min( [ f(l,mx[i]) for i in range(len(mx)) ] )
def two():
l = [ x[0]+x[1] for x in zip(input(),input())]
mx =... |
1416_A. k-Amazing Numbers | You are given an array a consisting of n integers numbered from 1 to n.
Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there i... | ```python
t = int(input())
ns = []
for i in range(t):
n = int(input())
arr = list(map(int, input().split()))
nums = set(arr)
dct1 = {}
dct2 = {num: 0 for num in nums}
for idx, el in enumerate(arr):
if el in dct1:
dct2[el] = max(dct2[el], idx - dct1[el])
else:
... |
1480_A. Yet Another String Game | Homer has two friends Alice and Bob. Both of them are string fans.
One day, Alice and Bob decide to play a game on a string s = s_1 s_2 ... s_n of length n consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.
In a move, a player must choose an index i (1 ≤ i ≤ n) ... | ```python
T = int(input())
for t in range (T):
s = input()
res = ""
for i in range (len(s)):
if (i%2 == 0):
if (s[i] == 'a'):
res += "b"
else:
res += "a"
else:
if (s[i] == 'z'):
res += "y"
e... |
1506_G. Maximize the Remaining String | You are given a string s, consisting of lowercase Latin letters. While there is at least one character in the string s that is repeated at least twice, you perform the following operation:
* you choose the index i (1 ≤ i ≤ |s|) such that the character at position i occurs at least two times in the string s, and del... | ```python
for _ in range(int(input())):
s = input(); stack = []; seen = set(); last_occurrence = {c: i for i, c in enumerate(s)}
for i, c in enumerate(s):
if c not in seen:
while stack and c > stack[-1] and i < last_occurrence[stack[-1]]: seen.discard(... |
1534_A. Colour the Flag | Today we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag).
You are given an n × m grid of "R", "W", and "." characters. "R" is red, "W" is white and "." is blank. The neighbours of a cell are those that share an edge with it (those ... | ```python
I=input
for _ in[0]*int(I()):
s=set();n,m=map(int,I().split());i=5
for _ in[0]*n:
i^=5;j=5
for x in I():j^=5;s|=(s,{ord(x)^i^j})[x>'.']
if len(s)<2:
c=s and s.pop()or 82
r=('YES',*(''.join(chr(c^((i^j)&1)*5)for i in range(m))for j in range(n)))
else:r='NO',
print(*r)
``` |
161_C. Abracadabra | Polycarpus analyzes a string called abracadabra. This string is constructed using the following algorithm:
* On the first step the string consists of a single character "a".
* On the k-th step Polycarpus concatenates two copies of the string obtained on the (k - 1)-th step, while inserting the k-th character of ... | ```python
def solve(x,l1,r1,l2,r2):
if x==0:return 1
if l1>x:
l1-=x+1
r1-=x+1
if l2>x:
l2-=x+1
r2-=x+1
ans=max(0,min(r1,r2)-max(l1,l2)+1)
if l1<=x and x<=r1 and l2<=x and x<=r2:
if l1==0 or r1==x*2:
ans=max(ans,max(x-l2,r2-x))
elif l2==0 or r2==x*2:
ans=max(ans,max(x-l1,r1-x))
else:
if l1<=x... |
180_E. Cubes | Let's imagine that you're playing the following simple computer game. The screen displays n lined-up cubes. Each cube is painted one of m colors. You are allowed to delete not more than k cubes (that do not necessarily go one after another). After that, the remaining cubes join together (so that the gaps are closed) an... | ```python
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup------------------------... |
204_A. Little Elephant and Interval | The Little Elephant very much loves sums on intervals.
This time he has a pair of integers l and r (l ≤ r). The Little Elephant has to find the number of such integers x (l ≤ x ≤ r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be inclu... | ```python
def F (x) :
if (x < 10) :
return x
rv = 9
tmp = x
len = 0
while (tmp > 0) :
len += 1
tmp = tmp // 10
d = int (x // pow(10, len-1))
tmp = 1
for i in range(len - 2) :
rv += 9 * tmp
tmp *= 10
for i in range (1, 10) :
if (... |
228_E. The Road to Berland is Paved With Good Intentions | Berland has n cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not.
The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads... | ```python
s=list(map(int,input().split()))
n=s[0]
m=s[1]
roads=[]
for i in range(0,n+1):
roads.append([])
for i in range(0,m):
s=list(map(int,input().split()))
roads[s[0]].append([s[1],s[2]])
roads[s[1]].append([s[0],s[2]])
col=[-1]*(n+1)
##def dfs(v,c):
## success=True
## col[v]=c
## for e... |
252_C. Points on Line | Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen point... | ```python
n,d=map(int,input().split())
nums=list(map(int,input().split()))
count=0
j=0
for i in range(n):
while j<n and nums[j]-nums[i]<=d:
j+=1
temp_length=(j-i-1)
count+=int((temp_length*(temp_length-1))/2)
print(count)
``` |
2_A. Winner | 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... | ```python
n = int(input())
d = {}
l = []
for _ in range(n):
name, score = input().split()
score = int(score)
l.append((name,score))
d[name] = d.get(name, 0) + score
m = max([x for x in d.values()])
ties = [x for x,y in d.items() if y == m]
# print(ties)
if len(ties) == 1:
print(ties[0])
... |
325_A. Square and Rectangles | You are given n rectangles. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).
Your task is to determine if the rectan... | ```python
xmin, ymin, xmax, ymax, a = 31400, 31400, 0, 0, 0
for i in range(int(input())):
x1, y1, x2, y2 = map(int, input().split())
xmin = min(xmin, x1)
ymin = min(ymin, y1)
xmax = max(xmax, x2)
ymax = max(ymax, y2)
a += (x2 - x1) * (y2 - y1)
print('YES' if xmax - xmin == ymax - ymin and a == (... |
371_C. Hamburgers | Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (... | ```python
st = input()
B = st.count('B')
S = st.count('S')
C = st.count('C')
b,s,c=map(int,input().split())
bp, sp, cp = map(int,input().split())
r=int(input())
lm=0; rm=int(1e15)+1
while rm-lm>1:
m=(rm+lm)//2
# print(m)
bb=max(m*B-b,0)
ss=max(m*S-s,0)
cc=max(m*C-c, 0)
#print(bp*bb+ss*sp+cc*cp)
... |
416_A. Guess a number! | A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show.
The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions:
* Is it true that y is stric... | ```python
n = int(input())
questions = []
for _ in range(n):
questions.append(input())
lower_bound, upper_bound = None, None
for q in questions:
bound = int(q.split()[1])
if (q.startswith('>') and q.endswith('Y')) or (q.startswith('<') and q.endswith('N')):
if ('Y' in q and '=' not in q) or ('N' ... |
488_D. Strip | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.
Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy:
* Each piece should contain at least l numbers.
* The difference between the maximal and the minimal number on the piece... | ```python
def split(a,n,s,l):
pieces = []
i = 1
tmpmin = a[0]
tmpmax = a[0]
tmppc = [a[0]]
while i<n:
if abs(a[i]-tmpmin)<=s and abs(a[i]-tmpmax)<=s:
tmppc.append(a[i])
if a[i]<tmpmin: tmpmin=a[i]
elif a[i]>tmpmax: tmpmax = a[i]
else:
... |
512_C. Fox And Dinner | Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.
They will have dinner around some round tables. You want to distribute foxes such that:
1. Each fox is sitting at some table.
2. Each table has at least 3 foxes sitting around it.
3... | ```python
from collections import deque
class Dinic():
def __init__(self, listEdge, s, t):
self.s = s
self.t = t
self.graph = {}
self.maxCap = 1000000
# dict các node lân cận
# e[0]: from, e[1]: to, e[2]: dung luong
for e in listEdge:
... |
560_E. Gerald and Giant Chess | Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of gia... | ```python
#!/usr/bin/env python
# 560E_chess.py - Codeforces.com 560E Chess program
#
# Copyright (C) 2015 Sergey
"""
Input
The first line of the input contains three integers:
h,w,n the sides of the board and the number of black cells
Next n lines contain the description of black cells. The ith
of these lines conta... |
587_A. Duff and Weight Lifting | Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimi... | ```python
N = int(1e6+100)
n = int(input())
arr = list(map(int, input().split()))
cnt = [0] * N
for i in arr:
cnt[i] += 1
res, s = 0, 0
for i in range(N):
s += cnt[i]
res += s % 2
s //= 2
print(res)
``` |
609_C. Load Balancing | In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.
In order to balance the load for each server, you want to reassign some tasks to make the difference betw... | ```python
input()
servers = [int(x) for x in input().split(" ", )]
servers.sort()
avg = int(sum(servers) / len(servers))
extra = sum(servers) % len(servers)
count = 0
for i in range(len(servers)):
count += abs(avg + (i >= (len(servers) - extra)) - servers[i]) / 2
print(int(count))
... |
630_B. Moore's Law | The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.
Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately ev... | ```python
n,t=map(int,input().split())
print(n*((1.000000011)**t))
``` |
656_F. Ace It! |
Input
The only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid").
Output
Output a single integer.
Examples
Input
A221033
Output
21
Input
A223635
Output
22
Input
A232726
Outpu... | ```python
s = input()
ans = 1
for i in s[1:]:
x = int(i)
if x == 0:
x = 9
ans += x
print(ans)
``` |
680_A. Bear and Five Cards | A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer.
Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards.
He is allowed to at most once discard two or three cards wi... | ```python
l=list(map(int,input().split()))
ma=0
for i in l :
k=0
for j in l :
if i==j :
k=k+1
if k>2 :
break
if k>1 :
if ma<k*i :
ma=k*i
print(sum(l)-ma)
``` |
746_G. New Roads | There are n cities in Berland, each of them has a unique id — an integer from 1 to n, the capital is the one with id 1. Now there is a serious problem in Berland with roads — there are no roads.
That is why there was a decision to build n - 1 roads so that there will be exactly one simple path between each pair of cit... | ```python
if __name__ == '__main__':
n, t, k = map(int, input().split())
a = list(map(int, input().split()))
b = [0 for _ in range(t)]
b[t-1] = a[t-1]
maxk = a[t-1]
for i in range(t-2, -1, -1):
b[i] = b[i+1]
if a[i+1] < a[i]:
b[i] += a[i] - a[i+1]
maxk += a[i]-1
if b[0] > k or maxk < k:
print(-1)
el... |
814_D. An overnight dance in discotheque | The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it?
The discotheque can be seen as an infinite xy-plane, in which there are a total of n dancers. Once someone starts moving around, they will move only inside their own movement range, which i... | ```python
n = int(input())
d = [1] * n
p = [[] for i in range(n)]
def f():
x, y, r = map(int, input().split())
return r * r, x, y
t = sorted(f() for i in range(n))
for i in range(n):
r, x, y = t[i]
for j in range(i + 1, n):
s, a, b = t[j]
if (a - x) ** 2 + (b - y) ** 2 < s:
... |
83_D. Numbers | One quite ordinary day Valera went to school (there's nowhere else he should go on a week day). In a maths lesson his favorite teacher Ms. Evans told students about divisors. Despite the fact that Valera loved math, he didn't find this particular topic interesting. Even more, it seemed so boring that he fell asleep in ... | ```python
def pr(x):
d = 2
while d * d <= x:
if x % d == 0:
return 0
d += 1
return 1
def cnt(n, k):
if not pr(k) or n < k: return 0
n1 = n // k
return n1 - sum(cnt(n1, i) for i in range(2, min(k, n1 + 1)))
a, b, k = map(int, input().split())
ans = cnt(b, k) - cn... |
909_E. Coprocessor | You are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depen... | ```python
n, m = [int(x) for x in input().split()]
tps = {i:int(t) for i, t in enumerate(input().split())}
deps = {i:0 for i in range(n)}
parents = {i:[] for i in range(n)}
leafs = {i for i in range(n)}
for i in range(m):
x, y = [int(x) for x in input().split()]
deps[x] += 1
parents[y].append(x)
if x in... |
931_B. World Cup | The last stage of Football World Cup is played using the play-off system.
There are n teams left in this stage, they are enumerated from 1 to n. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the four... | ```python
n,a,b=map(int,input().split())
a,b,r=a-1,b-1,0
while a!=b:
a//=2
b//=2
r+=1
print(r if 2**r<n else 'Final!')
``` |
985_B. Switches and Lamps | You are given n switches and m lamps. The i-th switch turns on some subset of the lamps. This information is given as the matrix a consisting of n rows and m columns where ai, j = 1 if the i-th switch turns on the j-th lamp and ai, j = 0 if the i-th switch is not connected to the j-th lamp.
Initially all m lamps are t... | ```python
def main():
n,m=map(int,input().split())
counts=[0]*m
a=[None]*n
for i in range(n):
line=input()
a[i]=line
for j in range(m):
counts[j]+=1 if line[j]=='1' else 0
if 1 not in counts:
print('YES')
return
checks=[]
for i in range(m):
if counts[i]==1:
checks.append(i)
leng=len(checks)
... |
p02575 AtCoder Beginner Contest 177 - I hate Shortest Path Problem | There is a grid of squares with H+1 horizontal rows and W vertical columns.
You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th ... | ```python
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionl... |
p02706 AtCoder Beginner Contest 163 - Homework | Takahashi has N days of summer vacation.
His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.
He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.
What is the maximum number of days Takahashi can hang out during the vacation if ... | ```python
N,X = map(int,input().split())
Y = N - sum(map(int,input().split()))
print(("-1",Y)[Y >= 0])
``` |
p02835 AtCoder Beginner Contest 147 - Blackjack | Given are three integers A_1, A_2, and A_3.
If A_1+A_2+A_3 is greater than or equal to 22, print `bust`; otherwise, print `win`.
Constraints
* 1 \leq A_i \leq 13 \ \ (i=1,2,3)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A_1 A_2 A_3
Output
If A_1+A_2+A_... | ```python
print('bwuisnt'[sum(map(int,input().split()))<22::2])
``` |
p02972 AtCoder Beginner Contest 134 - Preparing Boxes | There are N empty boxes arranged in a row from left to right. The integer i is written on the i-th box from the left (1 \leq i \leq N).
For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it.
We say a set of choices to put a ball or not in the boxes is good when the following con... | ```python
N = int(input())
A = list(map(int, input().split()))
B = [0]*(N+1)
x = []
for n in range(N):
i = N-n
BB = B[::i]
if (sum(BB))%2 == A[i-1]:
B[i] = 0
else:
B[i] = 1
x.append(str(i))
print(len(x))
print(' '.join(x))
``` |
p03108 AtCoder Beginner Contest 120 - Decayed Bridges | There are N islands and M bridges.
The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.
Initially, we can travel between any two islands using some of these bridges.
However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to t... | ```python
(N,M) = map(int,input().split())
A = [0]*M
B = [0]*M
for i in range(M):
(A[i], B[i]) = map(int,input().split())
A[i] -= 1
B[i] -= 1
parent = [-1]*N
depth = [0] * N
def boss(n):
d = 0
while parent[n] >= 0:
n = parent[n]
d += 1
return n,d
P = [1]*N
S = (N*(N-1))//2
an... |
p03255 AtCoder Grand Contest 027 - Garbage Collector | Snuke has decided to use a robot to clean his room.
There are N pieces of trash on a number line. The i-th piece from the left is at position x_i. We would like to put all of them in a trash bin at position 0.
For the positions of the pieces of trash, 0 < x_1 < x_2 < ... < x_{N} \leq 10^{9} holds.
The robot is initi... | ```python
def E(i,y):
if i==1:
return 5*y
else:
return (2*i+1)*y
def ceil(a,b):
return -((-a)//b)
N,X=map(int,input().split())
x=[int(i) for i in input().split()]
a=[0]
for i in range(N):
a.append(a[-1]+x[i])
ans=10**50
for k in range(1,N+1):
tmp=(N+k)*X
for i in range(N//k):
... |
p03408 AtCoder Beginner Contest 091 - Two Colors Card Game | Takahashi has N blue cards and M red cards. A string is written on each card. The string written on the i-th blue card is s_i, and the string written on the i-th red card is t_i.
Takahashi will now announce a string, and then check every card. Each time he finds a blue card with the string announced by him, he will ea... | ```python
from collections import*
n,*a=open(0).read().split()
blue=a[0:int(n)]
red=a[int(n)+1:]
print(max(0,max(v-Counter(red)[k] for k,v in Counter(blue).items())))
``` |
p03726 AtCoder Grand Contest 014 - Black and White Tree | There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Initially, each vertex is uncolored.
Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi:
* Select a vertex... | ```python
#設定
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
#ライブラリインポート
from collections import defaultdict
import queue
#入力受け取り
def getlist():
return list(map(int, input().split()))
INF = float("inf")
class Graph(object):
def __init__(self):
self.graph = defaultdict(list)
def __le... |
p03890 CODE FESTIVAL 2016 Relay (Parallel) - Kode Festival | Kode Festival is an anual contest where the hardest stone in the world is determined. (Kode is a Japanese word for "hardness".)
This year, 2^N stones participated. The hardness of the i-th stone is A_i.
In the contest, stones are thrown at each other in a knockout tournament.
When two stones with hardness X and Y ar... | ```python
def main():
N = int(input())
A = []
for _ in range(pow(2, N)): A.append(int(input()))
# print(A)
while len(A) > 1:
temp = []
for i in range(len(A)//2):
if A[2*i] < A[2*i+1]: temp.append(A[2*i+1] - A[2*i])
elif A[2*i] > A[2*i+1]: temp.append(A[2*i] ... |
p04049 AtCoder Grand Contest 001 - Shorten Diameter | Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K.
You are given an undirected tree with N verti... | ```python
import sys
input = sys.stdin.readline
n,k = map(int,input().split())
ab = [list(map(int,input().split())) for i in range(n-1)]
graph = [[] for i in range(n+1)]
for a,b in ab:
graph[a].append(b)
graph[b].append(a)
ans = n
rad = k//2
for center in range(1,n+1):
stack = [center]
dep = [[-1,-1] for _ in r... |
p00128 Abacus | <image>
At the request of a friend who started learning abacus, you decided to create a program to display the abacus beads. Create a program that takes a certain number as input and outputs a row of abacus beads. However, the number of digits of the abacus to be displayed is 5 digits, and the arrangement of beads fr... | ```python
f=0
while 1:
try:n=int(input())
except:break
if f:print()
f=1
a=[['*' for _ in range(5)]for _ in range(8)]
for i in range(4,-1,-1):
b=n%10
a[not b//5][i]=' '
a[b%5+3][i]=' '
n//=10
a[2]='='*5
for i in a:
print(''.join(i),end='')
p... |
p00261 Aka-beko and 40 Thieves | Aka Beko, trying to escape from 40 bandits, got lost in the city of A. Aka Beko wants to go to City B, where the new hideout is, but the map has been stolen by a bandit.
Kobborg, one of the thieves, sympathized with Aka Beko and felt sorry for him. So I secretly told Aka Beko, "I want to help you go to City B, but I w... | ```python
# -*- coding: utf-8 -*-
"""
Aka-beko and 40 Thieves
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0266
"""
import sys
def solve(s):
path = {'A': {'0': 'X', '1': 'Y'}, 'B': {'0': 'Y', '1': 'X'},
'W': {'0': 'B', '1': 'Y'}, 'X': {'0': None, '1': 'Z'}, 'Y': {'0': 'X', '1': None}, 'Z': {'0': ... |
p00448 Osenbei | problem
At IOI Confectionery, rice crackers are baked using the traditional method since the company was founded. This traditional method is to bake the front side for a certain period of time with charcoal, turn it over when the front side is baked, and bake the back side for a certain period of time with charcoal. W... | ```python
while True:
r,c = map(int, input().split())
if (r|c)==0: break
num = [0]*c
for i in range(r):
instr = input()
for j in range(c):
num[j] = num[j]*2+int(instr[2*j])
maxx = -1
for i in range(1 << r):
answer = 0
for j in range(c):
o... |
p00639 Accelerated Railgun | She catched the thrown coin that draws parabolic curve with her sparkling fingers. She is an ESPer. Yes, she is an electro-master who has the third strongest power among more than one million ESPers in the city. Being flicked by her thumb, the coin is accelerated by electromagnetic force and is shot as Fleming's right-... | ```python
# AOJ 1053: Accelerated Railgun
# Python3 2018.7.7 bal4u
EPS = 1e-7
while True:
d = float(input())
if d == 0: break
px, py, vx, vy = map(float, input().split())
ans = d+1
dp = (px*px + py*py)**0.5
dv = (vx*vx + vy*vy)**0.5
x = (px*vx + py*vy)/(dp*dv)
if abs(x+1) <= EPS: ans = dp
elif abs(1-x) <= EPS... |
p00782 Mobile Phone Coverage | A mobile phone company ACMICPC (Advanced Cellular, Mobile, and Internet-Connected Phone Corporation) is planning to set up a collection of antennas for mobile phones in a city called Maxnorm. The company ACMICPC has several collections for locations of antennas as their candidate plans, and now they want to know which ... | ```python
# AOJ 1202: Mobile Phone Coverage
# Python3 2018.7.28
from bisect import bisect_left
cno = 0
while True:
n = int(input())
if n == 0: break
tbl, xx, yy = [], set(), set()
for i in range(n):
x, y, r = map(float, input().split())
x, y, r = int(100*x), int(100*y), int(100*r)
x1, y1, x2, y2 = x-r, y-r, ... |
p00915 The Last Ant | A straight tunnel without branches is crowded with busy ants coming and going. Some ants walk left to right and others right to left. All ants walk at a constant speed of 1 cm/s. When two ants meet, they try to pass each other. However, some sections of the tunnel are narrow and two ants cannot pass each other. When tw... | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]
def LI(): return [int(x) for x i... |
p01048 Divisor | Problem
Given a natural number N less than or equal to 12, find the smallest natural number such that the number of divisors is exactly N.
Constraints
* 1 ≤ N ≤ 12
Input
One natural number N is given in one line.
Output
Output the smallest natural number on a line so that the number of divisors is exactly N.
Ex... | ```python
def solve(n):
for i in range(1,10000):
cnt=0
for j in range(1,i+1):
if i%j==0:
cnt+=1
if cnt==n:
return(i)
while True:
try:
n=int(input())
print(solve(n))
except EOFError:
break
``` |
p01180 The Closest Circle | You are given N non-overlapping circles in xy-plane. The radius of each circle varies, but the radius of the largest circle is not double longer than that of the smallest.
<image>
Figure 1: The Sample Input
The distance between two circles C1 and C2 is given by the usual formula
<image>
where (xi, yi ) is the coor... | ```python
def _get_distance(c1, c2):
return ((c1[1] - c2[1]) ** 2 + (c1[2] - c2[2]) ** 2) ** 0.5 - c1[0] - c2[0]
from itertools import combinations
def _get_min_distance(circles):
min_d = float("inf")
for c1, c2 in combinations(circles, 2):
min_d = min(min_d, _get_distance(c1, c2))
return min_... |
p01317 Mr. Rito Post Office | Problem D: Mr. Rito Post Office
You are a programmer working at a post office on a remote island. The area you live in consists of multiple islands. There is one or more port towns on each island. There may be other towns and villages in addition to them. You have to use a boat to go from one island to another. You ca... | ```python
# # AOJ 2200
#
# INF = float('inf')
#
#
# def floyd_warshall(d):
# v = len(d)
# for k in range(v):
# dk = d[k]
# for i in range(v):
# di = d[i]
# for j in range(v):
# di[j] = min(di[j], di[k] + dk[j])
#
#
# def main():
# while True:
# ... |
p01932 All Japan Association of Return home | problem
AOR Co., Ltd. (Association Of Return home) has $ N $ employees.
Employee $ i $ wants to use the elevator to go down to the $ 1 $ floor and arrives in front of the elevator on the $ F_i $ floor at time $ t_i $. You decide to remotely control an elevator that has only $ 1 $ on the $ 1 $ floor at time $ 0 $ and ... | ```python
n, d = map(int, input().split())
lst = sorted([list(map(int, input().split())) for _ in range(n)]) + [[10 ** 20, 1]]
cnt = 0
time = 0
floor = 1
ans = 0
for i in range(n):
t, f = lst[i]
if f - floor > t - time or cnt >= d:
print(-1)
break
ans += cnt * (t - time)
cnt += 1
time = t
floor = f... |
p02212 Team Making | Problem statement
When you heard that this year's KUPC can be joined as a team, you decided to talk to your friends and join as a team.
Eventually, $ 4 $ people, including you, got together.
Individual strength is expressed in ratings, and $ 4 $ person ratings are $ a $, $ b $, $ c $, and $ d $, respectively.
You d... | ```python
a,b,c,d = map(int,input().split())
tuyoi = max(a,b,c,d) + min(a,c,b,d)
print(abs(a+b+c+d-2*tuyoi))
``` |
p02366 Articulation Points | Find articulation points of a given undirected graph G(V, E).
A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|... | ```python
import sys
sys.setrecursionlimit(10**7)
v, e = list(map(int, input().split()))
G = [[] for _ in range(v)]
for _ in range(e):
s, t = map(int, input().split())
G[s].append(t)
G[t].append(s)
def solve():
used = [False for _ in range(v)]
ord = [0 for _ in range(v)]
low = [float("i... |
1012_A. Photo of The Sky | Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.
Strictly speaking, it makes a photo of all points with coordinates (x, y), such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2, where (x_1, y_1) and (x... | ```python
n=int(input())-1
s=sorted(map(int,input().split()))
sp=(s[n]-s[0])*(s[2*n+1]-s[n+1])
for i in range(n+1):
sp=min(sp,(s[n+i]-s[i])*(s[2*n+1]-s[0]))
print(sp)
``` |
1037_A. Packets | You have n coins, each of the same value of 1.
Distribute them into packets such that any amount x (1 ≤ x ≤ n) can be formed using some (possibly one or all) number of these packets.
Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single x, howeve... | ```python
import math
n, = map(int, input().split())
print(math.floor(math.log2(n)) + 1)
``` |
105_B. Dark Assembly | Dark Assembly is a governing body in the Netherworld. Here sit the senators who take the most important decisions for the player. For example, to expand the range of the shop or to improve certain characteristics of the character the Dark Assembly's approval is needed.
The Dark Assembly consists of n senators. Each of... | ```python
#!/usr/bin/env python3
n, k, A = map(int, input().rstrip().split())
senators = []
mx_bribe = 0
for i in range(n):
lvl, loy = map(int, input().rstrip().split())
senators.append((lvl, loy))
mx_bribe += (100 - loy) // 10
bribe = [0] * n
def calc(votes):
bsum, cnt, p = 0, 0, 1.0
for i, s ... |
1081_C. Colorful Bricks | On his free time, Chouti likes doing some housework. He has got one new task, paint some bricks in the yard.
There are n bricks lined in a row on the ground. Chouti has got m paint buckets of different colors at hand, so he painted each brick in one of those m colors.
Having finished painting all bricks, Chouti was s... | ```python
from math import factorial
[n, m, k] = [int(i) for i in input().split()]
mod = 998244353
l = m*((m-1)**k)
L = factorial(n-1)//factorial(n-1-k)//factorial(k)
print((l*L)%mod)
``` |
1100_C. NN and the Optical Illusion | NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles:
<image>
It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar pi... | ```python
import math
n, r = map(int, input().split())
s = math.sin(math.pi / n)
print(s*r / (1-s))
``` |
1129_A1. Toy Train (Simplified) | This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at... | ```python
n, m = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(m)]
s = [[] for _ in range(n)]
for q in a:
s[q[0]-1].append(q[1]-1)
d = []
for q in range(len(s)):
if len(s[q]) == 0:
d.append(0)
else:
p = min(s[q], key=lambda x: (x-q) % n)
d.append((len(... |
1149_A. Prefix Sum Primes | We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it — either 1 or 2.
However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in a... | ```python
n = int(input())
a = list(map(int, input().split()))
aset = set(a)
if len(aset) == 1:
print(' '.join(map(str, a)))
else:
count = [-1, -1]
for elem in a:
count[elem - 1] += 1
print(2, 1, end = ' ')
for i in range(count[1]):
print(2, end = ' ')
for i in range(count[0]):
... |
124_C. Prime Permutation | You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1.
Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1... | ```python
import sys
import math
from collections import defaultdict
MAXNUM = math.inf
MINNUM = -1 * math.inf
ASCIILOWER = 97
ASCIIUPPER = 65
def getInt():
return int(sys.stdin.readline().rstrip())
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.st... |
1269_A. Equation | Let's call a positive integer composite if it has at least one divisor other than 1 and itself. For example:
* the following numbers are composite: 1024, 4, 6, 9;
* the following numbers are not composite: 13, 1, 2, 3, 37.
You are given a positive integer n. Find two composite integers a,b such that a-b=n.
I... | ```python
n = int(input())
if n == 1:
print(15, 14)
elif n == 2:
print(16, 14)
elif n % 2 == 1:
print(n*3, n*3-n)
else:
print(n*2, n*2-n)
``` |
1291_A. Even But Not Even | Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clar... | ```python
for _ in range(int(input())):
n=int(input())
s=input()
if len(s)==1:
print(-1)
else:
#ans=s[0]
ans=''
f=0
for i in range(0,n):
if int(s[i])%2==1 and f<2:
ans+=s[i]
f+=1
#break
if f<2:
... |
1311_B. WeirdSort | You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is poss... | ```python
t=int(input())
for _ in range(t):
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=[(a[i],i) for i in range(n)]
b=sorted(b)
p=list(map(int,input().split()))
adj=[[] for i in range(n)]
for i in range(m):
p[i]=p[i]-1
for i in p:
adj[i].append(i+1)
... |
1333_F. Kate and imperfection | Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection am... | ```python
from collections import *
from math import *
N = int(5e5+5)
p = [0 for i in range(N)]
for i in range(2,N):
if(p[i] == 0):
for j in range(i*i,N,i):
if(p[j] == 0): p[j] = i
n = int(input())
a = [1 for i in range(n+1)]
primes = []
ct = 0
for i in range(1,n+1):
if p[i] == 0:
ct += 1
primes.append(i)
... |
1354_C1. Simple Polygon Embedding | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n... | ```python
import math
def solve():
n = int(input())
n *= 2
all = (n-2) * math.pi
one = math.pi - all/n
now = one
ans = 0.5
for i in range(n//2-1):
ans += max(math.cos(now), 0)
now += one
print(ans*2)
for i in range(int(input())):
solve()
``` |
1374_A. Required Remainder | You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | ```python
t=int(input())
for i in range(t):
x, y, n=map(int,input().split())
print(n-(n-y)%x)
``` |
1397_B. Power Sequence | Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change... | ```python
import math, sys
from collections import defaultdict, Counter, deque
INF = float('inf')
MOD = 10 ** 9 + 7
def gcd(a, b):
while b:
a, b = b, a%b
return a
def isPrime(n):
if (n <= 1):
return False
i = 2
while i ** 2 <= n:
if n % i == 0:
return False
i += 1
return True
def primeFactors(... |
1420_C2. Pokémon Army (hard version) | This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R... | ```python
input=__import__('sys').stdin.readline
def check(*inds):
global localmax, localmin, maxs, mins
for ind in inds:
if not ok(ind):continue
if localmax[ind]==0 and s[ind-1]<s[ind]>s[ind+1]:localmax[ind]=1;maxs+=s[ind]
if localmin[ind]==0 and s[ind-1]>s[ind]<s[ind+1]:localmin[ind]=1;mins+=s[ind]
def upd0(*... |
1439_B. Graph Subset Problem | You are given an undirected graph with n vertices and m edges. Also, you are given an integer k.
Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it.
A subset of vertices ... | ```python
import sys
input = sys.stdin.readline
testcase = int(input())
for _ in range(testcase):
n,m,k = map(int,input().split())
ab = [list(map(int,input().split())) for i in range(m)]
if k == 1:
print(2)
print(1)
continue
if k*(k-1) > 2*m:
print(-1)
continue
graph = [set() for i in rang... |
1466_B. Last minute enhancements | Athenaeus has just finished creating his latest musical composition and will present it tomorrow to the people of Athens. Unfortunately, the melody is rather dull and highly likely won't be met with a warm reception.
His song consists of n notes, which we will treat as positive integers. The diversity of a song is th... | ```python
for _ in range(int(input())):
n = int(input())
arr = list(map(int , input().split()))
arr[-1] += 1
for i in range(n-2 , -1 , -1):
if arr[i+1] > arr[i] + 1:
arr[i] += 1
print(len(set(arr)))
``` |
1490_C. Sum of Cubes | You are given a positive integer x. Check whether the number x is representable as the sum of the cubes of two positive integers.
Formally, you need to check if there are two integers a and b (1 ≤ a, b) such that a^3+b^3=x.
For example, if x = 35, then the numbers a=2 and b=3 are suitable (2^3+3^3=8+27=35). If x=4, t... | ```python
t = int(input())
f = []
for _ in range(t):
n = int(input())
cubes = {}
for i in range(1,int(n**(1./3.))+8):
cubes[i**3] = 1
for i in range(1,len(cubes)):
a = i**3
b = n - a
g = cubes.get(b)
if (g == None):
ans = "No"
else:
... |
1512_F. Education | Polycarp is wondering about buying a new computer, which costs c tugriks. To do this, he wants to get a job as a programmer in a big company.
There are n positions in Polycarp's company, numbered starting from one. An employee in position i earns a[i] tugriks every day. The higher the position number, the more tugriks... | ```python
for i in range(int(input())):
n,c=list(map(int,input().split()))
a=list(map(int,input().split()))
b=list(map(int,input().split()))
d=0
x=0
d1=-1
for i in range(n):
d2=d+max(0,-((x-c)//a[i]))
if d1==-1 or d2<d1:
d1=d2
if i!=n-1:
d+=max... |
167_B. Wizards and Huge Prize | One must train much to do well on wizardry contests. So, there are numerous wizardry schools and magic fees.
One of such magic schools consists of n tours. A winner of each tour gets a huge prize. The school is organised quite far away, so one will have to take all the prizes home in one go. And the bags that you've b... | ```python
from collections import *
f = lambda: list(map(int, input().split()))
n, l, a = f()
p, s = f(), f()
m = s.count(-1)
x = {(0, min(a, m)): 1}
r = [1]
for p, s in zip(p, s):
p /= 100
if s > 0:
y = defaultdict(int)
for (k, a), q in x.items():
y[(k, a)] += q - q ... |
209_A. Multicolored Marbles | Polycarpus plays with red and blue marbles. He put n marbles from the left to the right in a row. As it turned out, the marbles form a zebroid.
A non-empty sequence of red and blue marbles is a zebroid, if the colors of the marbles in this sequence alternate. For example, sequences (red; blue; red) and (blue) are zebr... | ```python
n=int(input())
mod=10**9+7
if n>=2:
dp=[0 for i in range(n)]
dp[0],dp[1]=1,2
ans=3
for i in range(2,n):
dp[i]=(dp[i-1]+dp[i-2])%mod
ans=(ans+dp[i])%mod
print(ans)
else:
print(1)
``` |
25_C. Roads in Berland | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance betw... | ```python
n = int(input())
mat = []
for _ in range(n):
mat.append(list(map(int, input().split())))
q = int(input())
ans= []
for _ in range(q):
x, y, w = map(int, input().split())
x-=1
y-=1
mat[x][y] = mat[y][x] = min(mat[x][y], w)
sum1 = 0
for i in range(n):
for j in range(n):
... |
354_A. Vasya and Robot | Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.
Vasya needs to collect all these items, however he won't do it by himself. He us... | ```python
import sys
n,L,r,QL,QR=map(int,sys.stdin.readline().split())
W=list(map(int,sys.stdin.readline().split()))
minn=10**10
SumsL=[0]*n
SumsR=[0]*n
s=0
for i in range(n):
s+=W[i]
SumsL[i]=s
for i in range(n-1):
ans=L*SumsL[i]+r*(s-SumsL[i])
if(n-(i+1)>i+1):
ans+=(abs(n-(i+1)-(i+1))... |
378_B. Semifinals | Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the peopl... | ```python
n = int(input())
sem1 = []
sem2 = []
l = [0,0]
for cont in range(0,n):
l = list(map(int, input().split()))
sem1.append(l[0])
sem2.append(l[1])
kmax = int(n/2)
max1 = 0
max2 = 0
for cont in range(0,n):
if sem1[max1] < sem2[max2]:
max1 += 1
else:
max2 += 1
ris1 = ['1']*(ma... |
39_D. Cubical Planet | You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment ... | ```python
#دو تا نقطه تو مختصات سه بعدی میده میگه اینا تو یک وجه از مکعل هستند یا نه
print('YES' if any(i == j for i,j in zip(list(input().split()) ,list(input().split()))) else 'NO')
``` |
449_C. Jzzhu and Apples | Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store.
Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater... | ```python
apples=int(input())
if apples<=3:
print(0)
else:
halfpr=int(apples/2)
def primes(n):
isPrime = [True for i in range(n + 1)]
isPrime[0] = isPrime[1] = False
idx = 2
while idx * idx <= n:
if isPrime[idx]:
for i in range... |
493_E. Vasya and Polynomial | Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial.
Vasya has made a bet with his friends that h... | ```python
t,a,b=map(int,input().split())
if t==2 and a==3 and b>10000: res=0
elif a==t: res=('inf' if a==1 else 2) if a==b else 0
else: res=0 if (a-b)%(t-a) else (1 if t != b else 0)
print(res)
``` |
518_D. Ilya and Escalator | Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor.
Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue ente... | ```python
import sys
n, p, t = map(str, sys.stdin.readline().split())
n = int(n)
p = float(p)
t = int(t)
def CC(nn,k):
tmp = n
t = max(nn - k, k)
for i in range(1, min(nn - k, k) + 1):
tmp = tmp * (t + i) * (1 - p) / i
if k > nn - k:
tmp = tmp * pow(1-p,k + k - nn)
return tmp
def ... |
544_D. Destroying Roads | In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any ... | ```python
from itertools import combinations_with_replacement
from collections import deque
#sys.stdin = open("input_py.txt","r")
n, m = map(int, input().split())
G = [ [] for i in range(n)]
for i in range(m):
x, y = map(int, input().split())
x-=1; y-=1
G[x].append(y)
G[y].append(x)
def BFS(s):
... |
571_A. Lengthening Sticks | You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the l... | ```python
def f(a, b, c, l):
k = min(l, a - b - c)
return 0 if a < b + c else (k + 1) * (k + 2) // 2
solve = lambda i: f(a + i, b, c, l - i) + f(b + i, c, a, l - i) + f(c + i, a, b, l - i)
a, b, c, l = map(int, input().split())
ans = (l + 1) * (l + 2) * (l + 3) // 6 - sum(solve(i) for i in range(l + 1))
print(... |
592_D. Super M | Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go ... | ```python
from collections import deque
from sys import stdin
from sys import exit
#parsea una línea
def parser():
return map(int, stdin.readline().split())
#Método usado para obtener los vértices por los que debe pasar Super M
def DFS_Discriminiting():
visited=[False for x in range(n)]
visited[numbers_of... |
614_B. Gena's Code | It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not en... | ```python
import sys
def esdist(s):
n=len(s)
if (s[0] != '1'): return True
for i in range(1,n):
if (s[i]!='0'): return True
return False
l=0
for line in sys.stdin:
if l==0: n = int(line)
else: nums = line.split()
l+=1
res = "1"
ceros = 0
for i in range(n):
s = nums[i]
if (not esdist(s)): ceros += len(s)-1... |
662_B. Graph Coloring | You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edge... | ```python
from collections import deque
n, m = map(int, input().split())
adj = [[] for i in range(n)]
for i in range(m):
u, v, c = input().split()
u, v = int(u)-1, int(v)-1
adj[u].append((v, c))
adj[v].append((u, c))
visited = S = T = None
def bfs(i, k):
q = deque([(i, 0)])
while q:
... |
709_D. Recover the String | For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}.
In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matc... | ```python
a00, a01, a10, a11 = map(int, input().split())
numZeros = 0
numOnes = 0
ans = True
for n0 in range(1, 2*a00 + 1):
if n0 * (n0 - 1) == 2 * a00:
numZeros = n0
break
elif n0 * (n0 - 1) > 2 * a00:
ans = False
break;
for n1 in range(1, 2*a11 + 1):
if n1 * (n1 - 1) == 2... |
754_A. Lesha and array splitting | One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one... | ```python
from sys import stdin
n = int(input())
a = [int(x) for x in input().split()]
f = False
for i in range(len(a)):
if a[i] != 0:
ln = i
f = True
break
if not f:
print('NO')
else:
print('YES')
l = 0
i = ln + 1
ans = []
while i < len(a):
if a[i] == 0:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.