name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
1486_A. Shifting Stacks | You have n stacks of blocks. The i-th stack contains h_i blocks and it's height is the number of blocks in it. In one move you can take a block from the i-th stack (if there is at least one block) and put it to the i + 1-th stack. Can you make the sequence of heights strictly increasing?
Note that the number of stacks... | ```python
# https://codeforces.com/contest/1486/problem/0
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
# do magic here
t = int(input())
def check(arr):
# print(arr)
for x in range(len(arr)-1):
if arr[x+1] <= arr[x]:
return "NO"
return "YES"
for _ in ran... |
1536_C. Diluc and Kaeya | The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.
This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is eit... | ```python
from math import *
from collections import Counter,defaultdict,deque
I =lambda:int(input())
M =lambda:map(int,input().split())
LI=lambda:list(map(int,input().split()))
for _ in range(I()):
n=I()
s=input()
dc=0
kc=0
d=defaultdict(int)
for i in s:
dc+=i=="D"
kc+=i=="K"
... |
230_D. Planets | Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.
Overall the galaxy has n... | ```python
from heapq import *
n, m = map(int, input().split())
l = []
from copy import *
from bisect import *
from math import *
from sys import *
for _ in range(0, n + 2):
l.append([])
for i in range(0, m):
a, b, c = map(int, stdin.readline().split())
l[a].append((c, b))
l[b].append((c, a))
dist = [1... |
27_C. Unordered Subsequence | The sequence is called ordered if it is non-decreasing or non-increasing. For example, sequnces [3, 1, 1, 0] and [1, 2, 3, 100] are ordered, but the sequence [1, 3, 3, 1] is not. You are given a sequence of numbers. You are to find it's shortest subsequence which is not ordered.
A subsequence is a sequence that can be... | ```python
# https://codeforces.com/problemset/problem/27/C
n = int(input())
a = list(map(int, input().split()))
b = []
for i, x in enumerate(a):
if i == 0 or x!=b[-1][0]:
b.append([x, i])
ind = []
for i in range(len(b)-2):
if (b[i][0] < b[i+1][0] and b[i+1][0] > b[i+2][0]) or (b[i][0] > b[i... |
302_B. Eugeny and Play List | Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays... | ```python
# Getting input
song = list()
n,m=map(int,input().split())
song.append(0)
for i in range(n):
note, times = map(int,input().split())
total_time = song[i] +note*times
song.append(total_time)
eugeny_moments = list(map(int, input().split()))
# compu... |
350_A. TL | Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.
Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time... | ```python
m, n = map(int, input().split())
a = sorted([int(x) for x in input().split()])
b = sorted([int(x) for x in input().split()])
for i in range(100):
if (i >= a[-1] and i < b[0] and i >= 2 * a[0]):
print(i)
break
else:
print(-1)
``` |
374_B. Inna and Nine | Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.
Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine ... | ```python
s=input()
ans=0
i=1
past=int(s[0])
c=1
ans=1
while(i<len(s)):
if(int(s[i])+past==9):
c+=1
past=int(s[i])
else:
if(c%2==1 and c!=1):
ans*=(c//2+1)
c=1
past=int(s[i])
i+=1
if(c!=1 and c%2==1):
ans*=(c//2+1)
print(ans)
... |
445_C. DZY Loves Physics | DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a ... | ```python
n, m = map(int, input().split())
v = list(map(int, input().split()))
mini = 0
for i in range(m):
a, b, c = map(int, input().split())
mini = max(mini, (v[a-1]+v[b-1])/c)
print(mini)
``` |
467_D. Fedor and Essay | After you had helped Fedor to find friends in the «Call of Soldiers 3» game, he stopped studying completely. Today, the English teacher told him to prepare an essay. Fedor didn't want to prepare the essay, so he asked Alex for help. Alex came to help and wrote the essay for Fedor. But Fedor didn't like the essay at all... | ```python
from sys import stdin
from collections import defaultdict
def main():
stdin.readline()
num = {}
stat = lambda word: (word.count('r'),
len(word), num.setdefault(word, len(num)))
essay = list(map(stat, stdin.readline().lower().split()))
queue = []
for word in essay:
queue.append(word)
... |
513_G2. Inversions problem | You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
In... | ```python
f = lambda: map(int, input().split())
g = lambda k: k * k - k >> 1
n, k = f()
p = list(f())
a = [[0] * n for i in range(n)]
for i in range(n):
for j in range(i + 1, n):
if p[i] > p[j]: a[i][j] = 1
else: a[j][i] = 1
for t in range(k):
b = [[0] * n for i in range(n)]
for i in rang... |
53_E. Dead Ends | Life in Bertown has become hard. The city has too many roads and the government spends too much to maintain them. There are n junctions and m two way roads, at which one can get from each junction to any other one. The mayor wants to close some roads so that the number of roads left totaled to n - 1 roads and it were s... | ```python
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, m, k = map(int, input().split())
adj = [[] for _ in range(n)]
dp = [[0] * (1 << n) for _ in range(1 << n)]
for u, v in (map(int, input().split()) for _ in range(m)):
u, v = u - 1, v... |
568_A. Primes or Palindromes? | Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this!
Let us remind you... | ```python
import sys
p,q = map(int,sys.stdin.readline().split())
def prime(n):
#print(int(n**0.5))
for div in range(2,int(n**0.5)+1):
if n%div==0:
return False
return True
def palindrom(n):
n = str(n)
for pos in range((len(n)+1)//2):
if n[pos]!=n[-1-pos]:
... |
611_A. New Year and Days | Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015.
Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016.
Limak wants to prove how responsible a bear he is. He is going to regularly save candies for ... | ```python
s=input().split()
l1=[52,52,52,52,53,53,52]
l2=[31,29,31,30,31,30,31,31,30,31,30,31]
count=0
if s[2]=="month":
x=int(s[0])
for i in range(len(l2)):
if x<=l2[i]:
count+=1
print(count)
else:
for i in range(len(l1)):
if int(s[0])==i+1:
print(l1[i])
... |
630_P. Area of a Star | It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.
A "star" figure having n ≥ ... | ```python
import math
n, r = map(int, input().split())
a = math.pi / n
b = a / 2
print(r * math.sin(b) / math.sin(math.pi - a - b) * math.sin(a) * r * n)
``` |
65_A. Harry Potter and Three Spells | A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert a grams of sand into b grams of lead, the second one allows you to convert c grams of lead into d grams of gold a... | ```python
from functools import reduce
from operator import mul
c = list(map(int, input().split()))
r, h = reduce(mul, c[1::2], 1), reduce(mul, c[0::2], 1)
rw = r > h or (c[2] == 0 and c[3] != 0) or (c[0] == 0 and c[1] * c[3] != 0)
print("Ron" if rw else "Hermione")
``` |
729_A. Interview with Oleg | Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end... | ```python
def compute_prefix_function(p):
"""
Вычисляет префикс функцию паттерна p
:param p: паттерн для kmp
:return: преикс функцию для p
"""
s = [0] * len(p)
border = 0 # текущая граница
for i in range(1, len(p)):
while border > 0 and p[i] != p[border]:
border = s[... |
749_B. Parallelogram is Back | Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwis... | ```python
a=list(map(int, input().split()))
x1=a[0]
y1=a[1]
a=list(map(int, input().split()))
x2=a[0]
y2=a[1]
a=list(map(int, input().split()))
x3=a[0]
y3=a[1]
print(3)
print(x1+x2-x3, y1+y2-y3)
print(x1+x3-x2, y1+y3-y2)
print(x3+x2-x1, y2+y3-y1)
``` |
772_A. Voltage Keepsake | You have n devices that you want to use simultaneously.
The i-th device uses ai units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.
You have a si... | ```python
#!/usr/bin/env python3
from sys import stdin,stdout
from decimal import *
def ri():
return map(int, input().split())
getcontext().prec = 100
n, p = ri()
p = Decimal(p)
a = [Decimal(0) for i in range(n)]
b = [Decimal(0) for i in range(n)]
ab = [[Decimal(0), Decimal(0)] for i in range(n)]
A = [Decimal(0... |
797_A. k-Factorization | Given a positive integer n, find k integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to n.
Input
The first line contains two integers n and k (2 ≤ n ≤ 100000, 1 ≤ k ≤ 20).
Output
If it's impossible to find the representation of n as a product of k... | ```python
#!/usr/bin/env python
from math import sqrt
dic = {}
def kfact(n, k):
if (n, k) in dic:
return dic[(n, k)]
if k == 1:
return [n]
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
if kfact(n // i, k - 1):
result = [i] + kfact(n // i, k - 1)
... |
817_C. Really Big Numbers | Ivan likes to learn different things about numbers, but he is especially interested in really big numbers. Ivan thinks that a positive integer number x is really big if the difference between x and the sum of its digits (in decimal representation) is not less than s. To prove that these numbers may have different speci... | ```python
def nine(p) :
s=''
for i in range(p) :
s+='9'
return int(s)
def prosh(p) :
ans=0
for i in range(1,p+1) :
ans+=nine(i)*9
return ans
n,k=map(int,input().split())
l=[0]*29
for i in range(19) :
e=nine(19-i)
l[i]=int(k/e)
k-=l[i]*e
... |
863_C. 1-2-3 | Ilya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is "Bob", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, "Alice".
... | ```python
k, a, b = map(int, input().split())
A = []
for _ in range(3):
temp = [int(x) for x in input().split()]
A.append(temp)
B = []
for _ in range(3):
temp = [int(x) for x in input().split()]
B.append(temp)
flag, ac, bc, cur = 0, 0, 0, 1
m = {}
ans1, ans2 = [0]*1000, [0]*1000
while cur <= k:
if (a, b) in m and ... |
911_E. Stack Sorting | Let's suppose you have an array a, a stack s (initially empty) and an array b (also initially empty).
You may perform the following operations until both a and s are empty:
* Take the first element of a, push it into s and remove it from a (if a is not empty);
* Take the top element from s, append it to the end ... | ```python
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x... |
933_C. A Colourful Prospect | Firecrackers scare Nian the monster, but they're wayyyyy too noisy! Maybe fireworks make a nice complement.
Little Tommy is watching a firework show. As circular shapes spread across the sky, a splendid view unfolds on the night of Lunar New Year's eve.
A wonder strikes Tommy. How many regions are formed by the circl... | ```python
from decimal import *
getcontext().prec = 40
eps = Decimal('1e-10')
class Circle:
def __init__(self, x, y, r):
self.x = x
self.y = y
self.r = r
def contains(self, c):
dd = (self.x - c.x)**2 + (self.y - c.y)**2 # dd = d*d
return dd < (self.r - c.r)**2 and self.r > c.r
def in_touches(self, c)... |
987_C. Three displays | It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.
There are n displays placed along a road, and the i-th of them can display a text with font size s_i only. Maria Stepanovna wants to rent such t... | ```python
mod = 1000000007
MOD = 998244353
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
it = lambda : tuple(map(int, input().split()))
ls = lambda : list(input())
n=ii()
l=il()
c=il()
m... |
p02589 AtCoder Grand Contest 047 - First Second | Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.
You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other?
Constraints... | ```python
from collections import defaultdict
class RollingHash():
def __init__(self, s, base, mod):
self.mod = mod
self.pw = pw = [1]*(len(s)+1)
l = len(s)
self.h = h = [0]*(l+1)
v = 0
for i in range(l):
h[i+1] = v = (v * base + ord(s[i])) % mod
... |
p02720 AtCoder Beginner Contest 161 - Lunlun Number | A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:
* In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1.
For example, 1234, 1, and 334 are lunlun numbers, while ... | ```python
k=int(input())
q=["1","2","3","4","5","6","7","8","9"]
x=9
for i in q:
if x>100000:
break
x+=1
a=i[-1]
for j in ([-1,0,1]):
bb=int(a)+j
if bb<10 and bb>=0:
q.append(i+str(bb))
print(q[k-1])
``` |
p02850 AtCoder Beginner Contest 146 - Coloring Edges on Tree | Given is a tree G with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i.
Consider painting the edges in G with some number of colors. We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different.
Among the colo... | ```python
n = int(input())
vs = [[] for i in range(n)]
out = [0]*n
for i in range(n-1):
a, b = [int(i)-1 for i in input().split()]
vs[a].append([b,i+1])
vs[b].append([a,i+1])
nex = [[0,-1]]
def coloring(index,defColor):
i=0
for v in vs[index]:
if i==defColor:
i+=1
out[v... |
p02987 AtCoder Beginner Contest 132 - Fifty-Fifty | You are given a 4-character string S consisting of uppercase English letters. Determine if S consists of exactly two kinds of characters which both appear twice in S.
Constraints
* The length of S is 4.
* S consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
S
... | ```python
print("Yes" if len(set(input())) == 2 else "No")
``` |
p03128 AtCoder Beginner Contest 118 - Match Matching | Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:
* Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).
* The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectiv... | ```python
# D
N, M = map(int, input().split())
A_list = list(map(int, input().split()))
needs_list = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
# DP
DP = [-1]*(N+8)
DP[0] = 0
for i in range(N):
for a in A_list:
j = i+needs_list[a]
DP[j] = max(DP[j], DP[i]*10+a)
print(DP[N])
``` |
p03271 AtCoder Regular Contest 102 - Revenge of BBuBBBlesort! | You are given a permutation of 1,2,...,N: p_1,p_2,...,p_N. Determine if the state where p_i=i for every i can be reached by performing the following operation any number of times:
* Choose three elements p_{i-1},p_{i},p_{i+1} (2\leq i\leq N-1) such that p_{i-1}>p_{i}>p_{i+1} and reverse the order of these three.
Cons... | ```python
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
P = [0] + list(map(int,read().split()))
# permutationになっている極小区間に分ける
intervals = []
left = 0
right = -1
for i,p in enumerate(P):
if right < p:
right = p
if ... |
p03428 AtCoder Grand Contest 021 - Holes | There are N holes in a two-dimensional plane. The coordinates of the i-th hole are (x_i,y_i).
Let R=10^{10^{10^{10}}}. Ringo performs the following operation:
* Randomly choose a point from the interior of a circle of radius R centered at the origin, and put Snuke there. Snuke will move to the hole with the smallest ... | ```python
"""
@ 凸包をつくる
> 凸包内部の点に属する領域は、半径Rの円からするともはやないものとして考えて良い
> というかこの多角形自体点として考えていい!
@ 凸包の頂点vについて
> vの両隣との傾きだけあればよい
> その間の角度 / 360が答え
"""
from math import gcd, atan, pi, degrees
def cross3(a, b, c):
return (b[0]-a[0])*(c[1]-a[1]) - (b[1]-a[1])*(c[0]-a[0])
def convex_hull(ps):
qs = []
... |
p03586 Tenka1 Programmer Contest - ModularPowerEquation!! | Process the Q queries below.
* You are given two integers A_i and M_i. Determine whether there exists a positive integer K_i not exceeding 2 × 10^{18} such that A_i^{K_i} ≡ K_i (mod M_i), and find one if it exists.
Constraints
* 1 \leq Q \leq 100
* 0 \leq A_i \leq 10^9(1 \leq i \leq Q)
* 1 \leq M_i \leq 10^9(1 \leq ... | ```python
def extgcd(a, b):
if b == 0:
return 1
else:
x, y, u, v, k, l = 1, 0, 0, 1, a, b
while l != 0:
x, y, u, v = u, v, x - u * (k // l), y - v * (k // l)
k, l = l, k % l
return x
def inved(x, m):
return x % m
def gcd(x, y):
while y != 0:
x, y = y, x % y
return x
def doublin... |
p03744 AtCoder Regular Contest 072 - Dam | You are in charge of controlling a dam. The dam can store at most L liters of water. Initially, the dam is empty. Some amount of water flows into the dam every morning, and any amount of water may be discharged every night, but this amount needs to be set so that no water overflows the dam the next morning.
It is know... | ```python
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
# 各日に対して、関数:残量 -> 最適な熱量 を持つことを考える
# これは折れ線。傾きが増加する部分 → マージしてまとめる
# 常に、傾きの減少列の形で持つことになる
from collections import deque
N,L = map(int,readline().split())
m = map(int,read().split())
TV = zip(m,m... |
p00010 Circumscribed Circle of a Triangle | Write a program which prints the central coordinate $(p_x, p_y)$ and the radius $r$ of a circumscribed circle of a triangle which is constructed by three points $(x_1, y_1)$, $(x_2, y_2)$ and $(x_3, y_3)$ on the plane surface.
Constraints
* $-100 \leq x_1, y_1, x_2, y_2, x_3, y_3 \leq 100$
* $ n \leq 20$
Input
Inpu... | ```python
import sys
f = sys.stdin
def take2(iterable):
while True:
yield next(iterable), next(iterable)
#外積
def cross(v1, v2):
return v1.real * v2.imag - v1.imag * v2.real
# 線分13と線分24の交点を求める
def get_intersection(p1,p2,p3,p4):
a1 = p4 - p2
b1 = p2 - p3
b2 = p1 - p2
s1 = cross(a1, b2) / ... |
p00142 Nature of Prime Numbers | A prime number n (11, 19, 23, etc.) that divides by 4 and has 3 has an interesting property. The results of calculating the remainder of the square of a natural number (1, 2, ..., n -1) of 1 or more and less than n divided by n are the same, so they are different from each other. The number is (n -1) / 2.
The set of n... | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
if N == 0:
return False
if N == 1:
return True
*S, = set(i**2 % N for i in range(1, N))
S.sort()
L = len(S)
C = [0]*N
D = [0]*((N-1)//2)
for i in range(L):
... |
p00275 The Outcome of Bonze | One of the games that uses the Hyakunin Isshu tag is "Buddhist turning". It is a simple game that uses only picture cards, so it is widely enjoyed. There are various derivative types of rules, but the shaved turn considered here is performed by N participants according to the following rules.
* Use a total of 100 card... | ```python
while True:
n = int(input())
if n == 0:
break
player = [0 for i in range(n)]
cards = list(input())
g = 0
for i in range(100):
if cards[i] == "M":
player[i%n] += 1
elif cards[i] == "S":
g += player[i%n]+1
player[i%n] = 0
... |
p00463 Amidakuji | problem
You are playing with J using the Midakuji. The Amida lottery consists of n vertical bars and m horizontal bars. The vertical bars are numbered from 1 to n in order from the left, and the vertical bar i The positive integer si is written at the bottom of.
<image>
Figure 3-1 Example of Amidakuji (n = 4, m = 5,... | ```python
while True:
n,m,h,k = map(int,input().split())
if not n: break
s_lst = [int(input()) for _ in range(n)]
i_lst = [i for i in range(n)]
b_lst = [tuple(map(int,input().split())) for _ in range(m)]
b_lst = sorted(b_lst,key=lambda x:x[1])
pare_lst = []
for bar in b_lst:
ind = bar[0]
temp = ... |
p00929 There is No Alternative | Example
Input
4 4
1 2 3
1 3 3
2 3 3
2 4 3
Output
1 3 | ```python
N, M = map(int, input().split())
E0 = []
for i in range(M):
S, D, C = map(int, input().split())
E0.append((C, S-1, D-1))
E0.sort()
*parent, = range(N)
def root(x):
if x == parent[x]:
return x
y = parent[x] = root(parent[x])
return y
def unite(x, y):
px = root(x); py = root(y)
... |
p01499 Rabbit Game Playing | Honestly, a rabbit does not matter.
There is a rabbit playing a stage system action game. In this game, every stage has a difficulty level. The rabbit, which always needs challenges, basically wants to play more difficult stages than he has ever played. However, he sometimes needs rest too. So, to compromise, he admit... | ```python
import sys
import bisect
# ???????????¨?????????DP?
#
def main():
n,t = map(int, sys.stdin.readline().split())
levels = []
for i in range(n):
d = int(sys.stdin.readline())
levels.append(d)
levels.sort()
ans = 1
for i in range(n):
cnt = i - bisect.bisect_left... |
p01670 Medical Inspection | D - Medical Inspection
Problem Statement
The government has declared a state of emergency due to the MOFU syndrome epidemic in your country. Persons in the country suffer from MOFU syndrome and cannot get out of bed in the morning. You are a programmer working for the Department of Health. You have to take prompt mea... | ```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
sys.setrecursionlimit(10**5)
def solve():
N, M, K = map(int, readline().split())
G = [[] for i in range(N)]
for i in range(M):
a, b = map(int, readline().split())
G[a-1].append(b-1)
... |
p01812 Dark Room | A pitch-black room
When I woke up, Mr. A was in a pitch-black room. Apparently, Mr. A got lost in a dungeon consisting of N rooms. You couldn't know which room A got lost in, but fortunately he got a map of the dungeon. Let's show A the way to go and lead to a bright room.
It is known that M of the N rooms are pitch ... | ```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 = 10**9+7
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 in ... |
p02234 Matrix Chain Multiplication | The goal of the matrix-chain multiplication problem is to find the most efficient way to multiply given $n$ matrices $M_1, M_2, M_3,...,M_n$.
Write a program which reads dimensions of $M_i$, and finds the minimum number of scalar multiplications to compute the maxrix-chain multiplication $M_1M_2...M_n$.
Constraints
... | ```python
# -*- coding: utf-8 -*-
N = int(input())
p = [0 for _ in range(N+1)]
p[0], p[1] = map(int, input().split())
for n in range(2, N+1):
p[n] = list(map(int, input().split()))[1]
M = [[0]*(N+1) for _ in range(N+1)]
for n in range(N+1):
M[n][n] = 0
for l in range(2, N+1):
for i in range(1, N-l+2):
... |
p02380 Triangle | For given two sides of a triangle a and b and the angle C between them, calculate the following properties:
* S: Area of the triangle
* L: The length of the circumference of the triangle
* h: The height of the triangle with side a as a bottom edge
Input
The length of a, the length of b and the angle C are given in... | ```python
import math
pi=math.pi
a,b,si=map(float,input().split())
S=(1/2)*a*b*math.sin(math.radians(si))
c2=a*a+b*b-2*a*b*math.cos(math.radians(si))
L=a+b+math.sqrt(c2)
h=(2*S)/a
print(S)
print(L)
print(h)
``` |
1012_D. AB-Strings | There are two strings s and t, consisting only of letters a and b. You can make the following operation several times: choose a prefix of s, a prefix of t and swap them. Prefixes can be empty, also a prefix can coincide with a whole string.
Your task is to find a sequence of operations after which one of the strings ... | ```python
from sys import exit
def blokovi(x):
ret = [0]
for i in range(len(x) - 1):
if x[i] != x[i + 1]:
ret.append(i + 1)
return ret + [len(x)]
s = input()
t = input()
ss = blokovi(s)
tt = blokovi(t)
if s[-1] == 'a':
s += 'b'
else:
s += 'a'
if t[-1] == 'a':
t += 'b'
el... |
1037_D. Valid BFS? | The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows.
1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used.
2. Extract a vertex v from the head of the qu... | ```python
from sys import stdin
from collections import deque
n=int(stdin.readline())
g=dict()
for i in range(n-1):
a,b=map(int,stdin.readline().split())
g.setdefault(a, set()).add(b)
g.setdefault(b, set()).add(a)
a=[int(x) for x in stdin.readline().split()]
ans = True
if n > 1 and a[0] == 1:
q=deque()
... |
1129_C. Morse Code | In Morse code, an letter of English alphabet is represented as a string of some length from 1 to 4. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1".
Because there are 2^1+2^2+2^3+2^4 = 30 strings with le... | ```python
import os, sys
nums = list(map(int, os.read(0, os.fstat(0).st_size).split()))
MOD = 10 ** 9 + 7
BAD = ([0, 0, 1, 1], [0, 1, 0, 1], [1, 1, 1, 0], [1, 1, 1, 1])
def zfunc(s):
z = [0] * len(s)
l = r = 0
for i in range(1, len(s)):
if i <= r:
z[i] = min(r - i + 1, z[i - l])
... |
1149_D. Abandoning Roads | Codefortia is a small island country located somewhere in the West Pacific. It consists of n settlements connected by m bidirectional gravel roads. Curiously enough, the beliefs of the inhabitants require the time needed to pass each road to be equal either to a or b seconds. It's guaranteed that one can go between any... | ```python
import heapq
n,m,a,b=map(int,input().split())
graph={i:[] for i in range(n)}
for i in range(m):
u,v,w=map(int,input().split())
graph[u-1].append((v-1,w))
graph[v-1].append((u-1,w))
components=[-1]*n
comp=-1
for i in range(n):
if components[i]==-1:
comp+=1
components[i]=comp
... |
1189_C. Candies! | Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less for... | ```python
import sys
input = lambda: sys.stdin.readline().strip()
from math import log2
n = int(input())
ls = list(map(int, input().split()))
Sum = [0]
for i in ls:
Sum.append(Sum[-1]+i)
q = int(input())
for i in range(q):
a, b = map(int, input().split())
print((Sum[b]-Sum[a-1])//10)
``` |
1208_C. Magic Grid | Let us define a magic grid to be a square matrix of integers of size n × n, satisfying the following conditions.
* All integers from 0 to (n^2 - 1) inclusive appear in the matrix exactly once.
* [Bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of all elements in a row or a column must be the sa... | ```python
n = int(input())
for i in range(n):
printlist = []
m=i//4
k=i%4
for j in range(n):
printlist.append(str(4*n*m+4*j+k))
print(' '.join(printlist))
``` |
1227_C. Messy | You are fed up with your messy room, so you decided to clean it up.
Your room is a bracket sequence s=s_{1}s_{2}... s_{n} of length n. Each character of this string is either an opening bracket '(' or a closing bracket ')'.
In one operation you can choose any consecutive substring of s and reverse it. In other words,... | ```python
t=int(input())
for i in range(t):
n,k=map(int,input().split())
s=input()
s=[s[i] for i in range(n)]
limit=(k-1)*2
l=0
answer =[]
answerk=0
for r in range(n):
if s[r]=="(":
if l!=r:
answer.append([l+1,r+1])
answerk+=1
... |
1269_D. Domino for Young | You are given a Young diagram.
Given diagram is a histogram with n columns of lengths a_1, a_2, …, a_n (a_1 ≥ a_2 ≥ … ≥ a_n ≥ 1).
<image> Young diagram for a=[3,2,2,2,1].
Your goal is to find the largest number of non-overlapping dominos that you can draw inside of this histogram, a domino is a 1 × 2 or 2 × 1 recta... | ```python
n = int(input())
a = [int(i) for i in input().split()]
m = [0,0]
for i in range(n):
m[0] += a[i] // 2
m[1] += a[i] // 2
if a[i] % 2 != 0:
m[i % 2] += 1
print(int(min(m[0], m[1])))
``` |
1291_D. Irreducible Anagrams | Let's call two strings s and t anagrams of each other if it is possible to rearrange symbols in the string s to get a string, equal to t.
Let's consider two strings s and t which are anagrams of each other. We say that t is a reducible anagram of s if there exists an integer k ≥ 2 and 2k non-empty strings s_1, t_1, s_... | ```python
s = input()
mp = [ [0 for i in range(26)] for _ in range(len(s))]
for i in range(len(s)) :
mp[i][ord(s[i]) - ord('a')] += 1
if i > 0 :
for j in range(26) :
mp[i][j] += mp[i - 1][j]
for _ in range(int(input())) :
l, r = map(int, input().split())
sc = 0
for i in range(26)... |
1311_E. Construct the Binary Tree | You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last diffe... | ```python
t=int(input())
import math as m
def print_tree(l):
t=[{'p':None, 'c':[]} for i in range(sum(l))]
l2={i:[] for i in range(len(l))}
j=0
for i in range(sum(l)):
l2[j].append(i+1)
if len(l2[j])==l[j]:
j+=1
for i in range(1,len(l)):
p=0
for n in l2[i]... |
1334_C. Circle of Monsters | You are playing another computer game, and now you have to slay n monsters. These monsters are standing in a circle, numbered clockwise from 1 to n. Initially, the i-th monster has a_i health.
You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monste... | ```python
from sys import stdin, stdout
import io, os
input = stdin.buffer.readline
def inp():
return int(input())
def arrinp():
return [int(x) for x in input().split()]
l = []
def main():
t = inp()
for _ in range(t):
n = inp()
A, B = zip(*[list(map(int, input().split())) for i in range... |
1354_E. Graph Coloring | You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
1. Each vertex should be labeled by exactly one number 1, 2 or 3;
... | ```python
from collections import defaultdict,deque
import sys
input=sys.stdin.readline
def bfs(root):
visited[root]=0
parity=[1,0]
store=[root]
queue=deque([root])
while queue:
vertex=queue.popleft()
for child in graph[vertex]:
if visited[child]==-1:
vis... |
1374_D. Zero Remainder Array | You are given an array a consisting of n positive integers.
Initially, you have an integer x = 0. During one move, you can do one of the following two operations:
1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1).
2. Just increase x by 1 (x := x + 1).
... | ```python
from collections import Counter as Cnt
for _ in range(int(input())):
n, k = map(int, input().split())
a = [(int(x) % k) for x in input().split() if int(x) % k != 0]
if not a:
print(0)
else:
c = Cnt(a)
print(max(1 - x + k * c[x] for x in c))
``` |
1397_E. Monster Invaders | Ziota found a video game called "Monster Invaders".
Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns.
For the sake of simplicity, we only consider two different types of monsters and three different types of guns.
Namely, the two types of monsters are:
*... | ```python
#!/usr/bin/env python3
import io
import os
import sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def printd(*args, **kwargs):
#print(*args, **kwargs, file=sys.stderr)
#print(*args, **kwargs)
pass
def get_str():
return input().decode().strip()
def rint():
return map(int... |
1421_A. XORwice | In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.
Tzuyu gave Sana two integers a and b and a really important quest.
In order to complete the quest, Sana has to output the smallest possible value of (a ⊕ x) + (b ⊕ x) for any given x, where ⊕ denotes the [bitwise XOR operation](http... | ```python
import math
t = int(input())
for _ in range(t):
a,b = [int(x) for x in input().split()]
x = 1
ans = 0
while(x<=a or x<=b):
if (x&a!=x&b):
ans+=x
x*=2
print(ans)
``` |
1490_F. Equalize the Array | Polycarp was gifted an array a of length n. Polycarp considers an array beautiful if there exists a number C, such that each number in the array occurs either zero or C times. Polycarp wants to remove some elements from the array a to make it beautiful.
For example, if n=6 and a = [1, 3, 2, 1, 4, 2], then the followin... | ```python
def find():
n = int(input())
mas = tuple(map(int, input().split()))
count_numbers = {}
for j in mas:
count_numbers[j] = count_numbers.get(j, 0) + 1
count_set_numb = {}
for j in count_numbers:
count_set_numb[count_numbers[j]] = count_set_numb.get(count_numbers[j], 0) +... |
1513_B. AND Sequences | A sequence of n non-negative integers (n ≥ 2) a_1, a_2, ..., a_n is called good if for all i from 1 to n-1 the following condition holds true: $$$a_1 \: \& \: a_2 \: \& \: ... \: \& \: a_i = a_{i+1} \: \& \: a_{i+2} \: \& \: ... \: \& \: a_n, where \&$$$ denotes the [bitwise AND operation](https://en.wikipedia.org/wiki... | ```python
#Question B: AND Sequences
import math #for .perm()
import sys
def answer(n, a):
mn = min(a)
cmn = a.count(mn)
if cmn < 2:
#print('cmn<2')
return 0
# at least 2 of the smallest number
#mnperm = math.perm(cmn, 2)
mnperm = cmn * (cmn-1)
mdperm = 1
if n-2 > 0:
... |
1540_B. Tree Array | You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked no... | ```python
import sys
input = lambda: sys.stdin.readline().rstrip()
from collections import deque
mod = 10 ** 9 + 7
N = int(input())
E = []
for _ in range(N - 1):
x, y = map(int, input().split())
x, y = x-1, y-1
E.append((x, y))
pre = [1]
PA = [pre]
for i in range(N + 2):
ne = [0] * (i + 2)
for j, ... |
20_A. BerOS file system | The new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of ... | ```python
line = input()
words = [word for word in line.split("/") if word != ""]
print("/{} ".format('/'.join(words)))
``` |
260_A. Adding Digits | Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.
One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by... | ```python
a, b, n = map(int, input().split())
f = 0
a *= 10
while True:
if a % b == 0:
break
a += 1
if a % 10 == 0:
f = 1
break
if f == 0:
n -= 1
a *= (10 ** n)
print(a)
else:
print(-1)
``` |
284_A. Cows and Primitive Roots | The cows have just learned what a primitive root is! Given a prime p, a primitive root <image> is an integer x (1 ≤ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is.
Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given ... | ```python
def f(n):
m = 1
for i in range(1,p-1):
m = (m*n)%p
if (m-1)%p:
pass
else:
return False
if (m*n-1)%p:
return False
return True
p = int(input())
ans = 0
for i in range(1,p):
if f(i):
ans += 1
print(ans)
``` |
39_G. Inverse Function | Petya wrote a programme on C++ that calculated a very interesting function f(n). Petya ran the program with a certain value of n and went to the kitchen to have some tea. The history has no records concerning how long the program had been working. By the time Petya returned, it had completed the calculations and had th... | ```python
import re, sys, functools
def cut_modulo(x):
y = x % 32768
if (y < 0):
y += 32768
return y
class berland_cpp_int:
def __init__(self, x):
self.value = cut_modulo(int(x))
def __add__(self, x):
return berland_cpp_int(cut_modulo(self.value + x.value))
def __sub__(... |
44_A. Indian Summer | Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.... | ```python
a,e={},0
for i in range(int(input())):
c,d=list(map(str,input().split()))
if c not in a.keys():
a.update({c:[d]})
e+=1
elif d not in a[c]:
a[c].append(d)
e+=1
print(e)
``` |
519_A. A and B and Chess | A and B are preparing themselves for programming contests.
To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.
For each chess piece we know its weight:
* the queen's weight is 9,
* the rook's weight is 5,
* the ... | ```python
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 10:34:19 2018
@author: Quaint Sun
"""
line=[]
t=0
while t<8:
line=line+list(input())
t=t+1
white=line.count('Q')*9+line.count('R')*5+line.count('B')*3+line.count('N')*3+line.count('P')
black=line.count('q')*9+line.count('r')*5+line.count('b')*3+... |
545_B. Equidistant String | Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:
We will define the distance between two strings s and t of the same length consisting of digits zero and one as the num... | ```python
s = input()
t = input()
n = len(s)
f = True
count =0
ans = ''
for i in range(n):
if s[i] != t[i]:
count +=1
if f :
ans += s[i]
f = False
else:
ans += t[i]
f = True
else:
ans += s[i]
#print(count)
#print(ans)
if cou... |
593_B. Anton and Lines | The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations y = ki·x + bi. It was necessary to determine whether there is at least one point of intersection of two of these lines,... | ```python
def equation(k, x, b):
return k * x + b
num = int(input())
ans = []
x1, x2 = map(int, input().split())
for i in range(0,num):
k, b = map(int, input().split())
ans.append((equation(k, x1, b), equation(k, x2, b)))
ans.sort()
for i in range(1, num):
if (ans[i][0] > ans[i - 1][0] and ... |
614_E. Necklace | Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward).
... | ```python
import math
#import fractions
from functools import reduce
n = int(input())
odd = -1
beads = [int(x) for x in input().split()]
for i in range(n):
if beads[i]%2:
if odd >= 0:
print(0)
print(''.join(chr(ord('a') + i)*beads[i] for i in range(n)))
break
els... |
634_B. XOR Equation | Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)?
Input
The first line of the input contains two integers s and x (2 ≤ s ≤ 1012, 0 ≤ x ≤ 1012), the sum and bitwise xor of the pair of positive integers, respectively.
Output
Print a s... | ```python
s,x=map(int,input().split())
if x>s or (s-x)%2!=0:
print(0)
else:
mask=1
res=1
bit=0
ND=(s-x)//2
flag=False
while bit<50:
if (mask&x)>0:
res*=2
if mask&x>0 and ND&mask>0:
flag=True
break
mask*=2
bit+=1
if(s==x)... |
687_C. The Values You Can Make | Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is ci. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya.
Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Ar... | ```python
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
A = map(int, input().split())
#DP = [[False]*(k+2) for _ in range(k+2)]
DP = []
for _ in range(k+1):
DP.append([False for _ in range(k+1)])
DP[0][0] = True
for a in sorted(A):
for i in range(k, a-1, -1):
for j in range(0, k+1):... |
70_B. Text Messaging | Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split!
Fangy did not like ... | ```python
import re
n=int(input())
ans,sumL=1,0
for s in re.split("[.?!]", input()):
s=s.strip()+'.'
L=len(s)
if L>1:
if L>n:
print("Impossible")
exit()
if sumL+L+(sumL>0) > n:
ans+=1
sumL=L
else:
sumL=sumL+L+(sumL>0)
print(... |
730_I. Olympiad in Programming and Sports | There are n students at Berland State University. Every student has two skills, each measured as a number: ai — the programming skill and bi — the sports skill.
It is announced that an Olympiad in programming and sports will be held soon. That's why Berland State University should choose two teams: one to take part in... | ```python
#!/usr/bin/env python3
from itertools import accumulate
from heapq import heappop, heappush
def top(ppl_indices, vals, start):
Q = []
res = [0 for i in range(len(ppl_indices))]
for k, idx in enumerate(ppl_indices):
heappush(Q, -vals[idx])
if k >= start:
res[k] = res[k... |
754_D. Fedor and coupons | All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket.
The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ... | ```python
from heapq import heappop, heappush
n, k = [int(x) for x in input().split()]
cs = []
for i in range(n):
l, r = [int(x) for x in input().split()]
cs.append((l, r, i+1))
cs.sort()
h = []
for i in range(k-1):
heappush(h, [cs[i][1], cs[i][2]])
lcs = h[:]
l = -1
push_i = k-1
for i in range(k-1, n):
... |
7_A. Kalevitch and Chess | A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards.
As before, th... | ```python
e=0
s1=''
s2=''
s3=''
s4=''
s5=''
s6=''
s7=''
s8=''
for i in range(8):
s=str(input())
if(s==('B'*8)):
e=e+1
s1=s1+s[0]
s2=s2+s[1]
s3=s3+s[2]
s4=s4+s[3]
s5=s5+s[4]
s6=s6+s[5]
s7=s7+s[6]
s8=s8+s[7]
if(s1==('B'*8)):
e=e+1
if(s2==('B'*8)):
e=e+1
if(s3==('B'*... |
820_C. Mister B and Boring Game | Sometimes Mister B has free evenings when he doesn't know what to do. Fortunately, Mister B found a new game, where the player can play against aliens.
All characters in this game are lowercase English letters. There are two players: Mister B and his competitor.
Initially the players have a string s consisting of the... | ```python
def main(a, b, l, r):
qL = (l - 1) // (2 * a + 2 * b)
rL = (l - 1) % (2 * a + 2 * b) + 1
qR = (r - 1) // (2 * a + 2 * b)
rR = (r - 1) % (2 * a + 2 * b) + 1
#print(qL, qR, rL, rR)
if qL == qR:
#In b segment
if a < rL <= a + b and a < rR <= a + b:
... |
846_D. Monitor | Recently Luba bought a monitor. Monitor is a rectangular matrix of size n × m. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square k × k consisting entirely of broken pixels. She knows that q pixels are alread... | ```python
from sys import stdout
from sys import stdin
def get():
return stdin.readline().strip()
def getf():
return [int(i) for i in get().split()]
def put(a, end = "\n"):
stdout.write(str(a) + end)
def putf(a, sep = " ", end = "\n"):
stdout.write(sep.join([str(i) for i in a]) + end)
def check(lmt, qr... |
893_C. Rumor | Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.
Now he tries to solve a quest. The task is to come to a settlement named Ove... | ```python
n, m = map(int, input().split())
c = [0] + list(map(int, input().split()))
parent = [i for i in range(n + 1)]
def find(i):
while i != parent[i]:
parent[i] = parent[parent[i]]
i = parent[i]
return i
for i in range(m):
a, b = map(lambda x: find(int(x)), input().split())
if c... |
938_A. Word Correction | Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consec... | ```python
n = int(input())
s = input()
s2 = s[0]
for i in range(1,n):
if(ord(s[i]) == ord("a") or ord(s[i]) == ord("e") or ord(s[i]) == ord("i") or ord(s[i]) == ord("o") or ord(s[i]) == ord("u") or ord(s[i]) == ord("y")) and (ord(s[i - 1]) == ord("a") or ord(s[i - 1]) == ord("e") or ord(s[i - 1]) == ord("i") or ord... |
963_A. Alternating Sum | You are given two integers a and b. Moreover, you are given a sequence s_0, s_1, ..., s_{n}. All values in s are integers 1 or -1. It's known that sequence is k-periodic and k divides n+1. In other words, for each k ≤ i ≤ n it's satisfied that s_{i} = s_{i - k}.
Find out the non-negative remainder of division of ∑ _{i... | ```python
MOD = 1000000009
def xpow(desk,step):
ret=1
desk=desk%MOD
while step:
if(step%2):
ret=(ret*desk)%MOD
step=step//2
desk = (desk * desk) % MOD
return ret
if __name__ == '__main__':
n,a,b,k=map(int,input().split())
s=input()
base=0
for i in rang... |
990_D. Graph And Its Complement | Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges fro... | ```python
def generate_matrix(h):
result = [[0 for x in range(h)] for y in range(h)]
return result
def generate_m_component_matrix(h, comp):
result = generate_matrix(h)
for i in range(0, h - comp + 1):
for j in range(0, h - comp + 1):
result[i][j] = 0 if i == j else 1
return re... |
p02612 AtCoder Beginner Contest 173 - Payment | We will buy a product for N yen (the currency of Japan) at a shop.
If we use only 1000-yen bills to pay the price, how much change will we receive?
Assume we use the minimum number of bills required.
Constraints
* 1 \leq N \leq 10000
* N is an integer.
Input
Input is given from Standard Input in the following for... | ```python
int = int(input())
print((1000 - int % 1000) % 1000)
``` |
p02743 Panasonic Programming Contest 2020 - Sqrt Inequality | Does \sqrt{a} + \sqrt{b} < \sqrt{c} hold?
Constraints
* 1 \leq a, b, c \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
a \ b \ c
Output
If \sqrt{a} + \sqrt{b} < \sqrt{c}, print `Yes`; otherwise, print `No`.
Examples
Input
2 3 9
Output
No
I... | ```python
a,b,c = map(int, input().split())
if 4*a*b < (c-a-b)**2 and c > a + b:
print('Yes')
else:
print('No')
``` |
p02878 AtCoder Grand Contest 040 - Two Pieces | We have two indistinguishable pieces placed on a number line. Both pieces are initially at coordinate 0. (They can occupy the same position.)
We can do the following two kinds of operations:
* Choose a piece and move it to the right (the positive direction) by 1.
* Move the piece with the smaller coordinate to the po... | ```python
N,A,B=map(int,input().split());M=998244353;P=N+1;f=1;F=[1]*P;I=[1]*P;z=0;R=range
for n in R(1,P):F[n]=f=f*n%M
I[N]=i=pow(f,M-2,M)
for n in R(N,1,-1):I[n-1]=i=i*n%M
for k in R(min(A+1,N-B)if N-B-A else A+1):Q=N-B-k-1;z=(z+(B-k)*F[B+k-1]*I[B]*I[k]*F[Q+A-k]*I[Q]*I[A-k])%M
print(z if B else 1)
``` |
p03012 AtCoder Beginner Contest 129 - Balance | We have N weights indexed 1 to N. The mass of the weight indexed i is W_i.
We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be th... | ```python
N=int(input())
W=list(map(int,input().split()))
S=sum(W)
ans=10**9
for i in range(N+1):
ans=min(ans,abs(S-2*sum(W[:i])))
print(ans)
``` |
p03152 KEYENCE Programming Contest 2019 - Double Landscape | Consider writing each of the integers from 1 to N \times M in a grid with N rows and M columns, without duplicates. Takahashi thinks it is not fun enough, and he will write the numbers under the following conditions:
* The largest among the values in the i-th row (1 \leq i \leq N) is A_i.
* The largest among the value... | ```python
MOD = int(1e9) + 7
def binsearch(num, ary):
left = 0
right = len(ary)
while left < right:
center = (left + right) // 2
if num <= ary[center]:
left = center + 1
else:
right = center
return left
def main():
N, M = map(int, input().split())
... |
p03296 AtCoder Grand Contest 026 - Colorful Slimes 2 | Takahashi lives in another world. There are slimes (creatures) of 10000 colors in this world. Let us call these colors Color 1, 2, ..., 10000.
Takahashi has N slimes, and they are standing in a row from left to right. The color of the i-th slime from the left is a_i. If two slimes of the same color are adjacent, they ... | ```python
n=int(input())
li = list(map(int,input().split()))
a=0
for i in range(1,n):
if li[i] == li[i-1]:
li[i] = 0
a+=1
print(a)
``` |
p03454 AtCoder Regular Contest 090 - Number of Digits | For a positive integer n, let us define f(n) as the number of digits in base 10.
You are given an integer S. Count the number of the pairs of positive integers (l, r) (l \leq r) such that f(l) + f(l + 1) + ... + f(r) = S, and find the count modulo 10^9 + 7.
Constraints
* 1 \leq S \leq 10^8
Input
Input is given fro... | ```python
#!/usr/bin/env python3
import math
import random
class Prime:
seed_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
def is_prime(self, n):
is_prime_common = self.is_prime_common(n)
if is_prime_common is not None:
return... |
p03615 AtCoder Regular Contest 082 - ConvexScore | You are given N points (x_i,y_i) located on a two-dimensional plane. Consider a subset S of the N points that forms a convex polygon. Here, we say a set of points S forms a convex polygon when there exists a convex polygon with a positive area that has the same set of vertices as S. All the interior angles of the polyg... | ```python
import sys
from collections import defaultdict
# sys.stdin = open('e1.in')
def read_int_list():
return list(map(int, input().split()))
def read_int():
return int(input())
def read_str_list():
return input().split()
def read_str():
return input()
def gcd(a, b):
if b == 0:
... |
p03773 AtCoder Beginner Contest 057 - Remaining Time | Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.
In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".
The current time is A o'clock, and a contest will begin in exactly B hours. When will the contest begin? Answer in 24-hour time.
Constrain... | ```python
a,b=map(int,input().split());print((a+b)%24)
``` |
p00034 Railway Lines | There is a double-track line (up and down are separate lines and pass each other everywhere). There are 11 stations on this line, including the terminal station, and each station is called by the section number shown in the figure.
<image>
Trains depart from both terminal stations on this line at the same time and r... | ```python
while True:
try:
lst = list(map(int, input().split(',')))
v2 = lst.pop()
v1 = lst.pop()
kp = sum(lst)*v1/(v1+v2)
l = 0
for num, i in enumerate(lst):
l = l + i
if l >= kp:
print(num + 1)
break
excep... |
p00166 Area of Polygon | Create a program that inputs the vertex information of two polygons inscribed in one circle and outputs the magnitude relationship of their areas.
Assume that each vertex of the X-side is numbered counterclockwise from 1 to X (the figure shows an example when X = 4). However, the given polygon assumes that the center ... | ```python
# AOJ 0166: Area of Polygon
# Python3 2018.6.18 bal4u
import math
M = 0.00872664625997164788461845384244
EPS = 1e-8
a = [0]*2
s = [0.0]*2
while True:
eof = False
for i in range(2):
s[i] = a[i] = 0;
n = int(input())
if n == 0:
eof = True
break
for j in range(1, n):
v = int(input())
a[i]... |
p00322 Alphametic | Addition is easy to calculate by hand, but if some numbers are missing, is it easy to fill in the missing numbers? For example, in the following long division, if there is a condition that the numbers 1 to 9 appear only once, how many numbers will fit in the C and E squares? In this case, 8 is correct for C and 5 is co... | ```python
def f(n,x):
for i in range(9):
if n[i] != -1 and n[i] != x[i]: return 1
import itertools
u=[1,2,3,4,5,6,7,8,9]
a=0
n=list(map(int,input().split()))
for x in itertools.permutations(u):
if f(n,x):continue
if x[0]+x[2]+x[5]-x[8]+(x[1]+x[4]-x[7])*10+(x[3]-x[6])*100==0:a+=1
print(a)
``` |
p00492 Illumination | problem
The JOI building is a combination of regular hexagons with a side of 1 meter as shown in the figure. As Christmas is approaching, JOI decided to decorate the walls of the building with illuminations. However, since it is useless to illuminate the parts that cannot be seen from the outside, we decided to decora... | ```python
import sys
sys.setrecursionlimit(100000)
W, H = map(int, input().split())
m = [list(map(int, input().split())) for i in range(H)]
dx = [[1, 1, 1, 0, -1, 0], [0, 1, 0, -1, -1, -1]]
dy = [-1, 0, 1, 1, 0, -1]
def dfs(x, y):
if m[y][x] != 0:
return
m[y][x] = 2
for xx, yy in zip(dx[y % 2], dy):... |
p00821 Area of Polygons | Yoko’s math homework today was to calculate areas of polygons in the xy-plane. Vertices are all aligned to grid points (i.e. they have integer coordinates).
Your job is to help Yoko, not good either at math or at computer programming, get her home- work done. A polygon is given by listing the coordinates of its vertic... | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
if N == 0:
return False
P = [list(map(int, readline().split())) for i in range(N)]
L = 2000
Q = [[] for i in range(2*L+1)]
LS = []
for i in range(N):
x0, y0 = P[i-1];... |
p00952 Placing Medals on a Binary Tree | Example
Input
6
2
3
1
1
4
2
Output
Yes
Yes
Yes
No
Yes
No | ```python
n = int(input())
bits = set()
c1 = 0
count = 0
ans = []
for i in range(n):
x = int(input())
if x in bits:
y = x
while c1 < y and y in bits:
y -= 1
if y <= c1:
y = 0
if y == 0 and count != x:
c1 = max(x, c1)
ans.append("No"... |
p01085 Entrance Examination | Entrance Examination
The International Competitive Programming College (ICPC) is famous for its research on competitive programming. Applicants to the college are required to take its entrance examination.
The successful applicants of the examination are chosen as follows.
* The score of any successful applicant is ... | ```python
da = list(map(int,input().split()))
k = []
while sum(da) != 0:
for i in range(da[0]):
k.append(int(input()))
for i in range(da[0]):
k[da[0] - 1 -i] = k[da[0] - 1 -i] - k[da[0]-2 -i]
pp = k[da[1]:da[2]+1]
qq = min(pp)
for i in range(len(pp)):
if pp[i] == qq:
jj = i
print(da[1]+jj)
da = lis... |
p01693 Derangement | G --Derangement / Derangement
Story
Person D is doing research on permutations. At one point, D found a permutation class called "Derangement". "It's cool to have a perfect permutation !!! And it starts with D !!!", the person of D who had a crush on Chunibyo decided to rewrite all the permutations given to him.
Pro... | ```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 ... |
p02259 Bubble Sort | Write a program of the Bubble Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:
BubbleSort(A)
1 for i = 0 to A.length-1
2 for j = A.length-1 downto i+1
3 if A[j] < A[j-1]
4 swap A[j] and A[j-1]
Note that, indices for array ... | ```python
n = int(input())
a = list(map(int,input().split()))
flag = 1
count = 0
while flag:
flag = 0
for i in range(n-1):
if a[i] > a[i+1]:
a[i], a[i+1] = a[i+1], a[i]
count += 1
flag = 1
print(" ".join(map(str,a)))
print(count)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.