name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
451_D. Count Good Substrings | We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good ... | ```python
s = input()
blocks = []
evenA = [0]
oddA = [0]
evenB = [0]
oddB = [0]
even = True
for x in s:
evenA.append(evenA[-1])
oddA.append(oddA[-1])
evenB.append(evenB[-1])
oddB.append(oddB[-1])
if x == 'a':
if even:
evenA[-1] += 1
else:
oddA[-1] += 1
... |
474_C. Captain Marmot | Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.
Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments com... | ```python
#a+b-y
#x+b-a
#1 -
import sys
input=sys.stdin.readline
def distSq(p1,p2):
return (p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])
def isSquare(p1, p2, p3, p4):
d2 = distSq(p1, p2) # from p1 to p2
d3 = distSq(p1, p3) # from p1 to p3
d4 = distSq(p1, p4) # from p1 to p4
#... |
521_C. Pluses everywhere | Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no ... | ```python
n, k = map(int, input().split())
t = list(map(int, input()))
p, d = 1, 10 ** 9 + 7
s, f = 0, [1] * n
for i in range(2, n): f[i] = (i * f[i - 1]) % d
c = lambda a, b: 0 if a > b else (f[b] * pow(f[a] * f[b - a], d - 2, d)) % d
if k:
u = [0] * (n + 1)
p = [1] * (n + 1)
for i in range(n):
... |
618_B. Guess the Permutation | Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n.
Bob gave you all the values of ai, j that he wro... | ```python
# from pprint import pprint
n = int(input())
a = []
for i in range(n):
row = [int(k) for k in input().split()]
a.append(row)
result = [0] * n
for k in range(1, n):
# print('k=', k)
for i in range(n):
countK = 0
countNonK = 0
for j in range(n):
if a[i][j] =... |
638_D. Three-dimensional Turtle Super Computer | A super computer has been built in the Turtle Academy of Sciences. The computer consists of n·m·k CPUs. The architecture was the paralellepiped of size n × m × k, split into 1 × 1 × 1 cells, each cell contains exactly one CPU. Thus, each CPU can be simultaneously identified as a group of three numbers from the layer nu... | ```python
def main():
s = input().split()
n, m, k = int(s[0]), int(s[1]), int(s[2])
processor = []
for x in range(n):
for y in range(m):
s = input()
for z in s:
processor.append(int(z) == 1)
if x < n - 1:
emptyLine = input()
counter... |
690_A1. Collective Mindsets (easy) | Tonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage.
... | ```python
n = int(input())
print(n // 2 + n % 2)
``` |
712_D. Memory and Scores | Memory and his friend Lexa are competing to get higher score in one popular computer game. Memory starts with score a and Lexa starts with score b. In a single turn, both Memory and Lexa get some integer in the range [ - k;k] (i.e. one integer among - k, - k + 1, - k + 2, ..., - 2, - 1, 0, 1, 2, ..., k - 1, k) and add... | ```python
mod=10**9+7
f=[0]*500000
def POW(a,b):
if(b==0):
return 1
if(b&1):
return POW(a,b//2)**2*a%mod
else:
return POW(a,b//2)**2
def C(n,m):
if(m>n):
return 0
t=f[n]*POW(f[m],mod-2)%mod*POW(f[n-m],mod-2)%mod
return t
f[0]=1
for i in range(1,500000):
f[i]=f[i-1]*i%mod
a,b,k,t=map(int,input().split... |
733_C. Epidemic in Monstropolis | There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.
Soon, monsters became hungry and began to eat each other.
One monster can eat other monster if its weight is strictly greater than the weight of the monste... | ```python
def main():
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
sum1, sum2 = 0, 0
for i in a:
sum1 += i
for i in b:
sum2 += i
# validar que podemos obtener solucion
if sum1 != sum2:
print('NO')
... |
779_A. Pupils Redistribution | In Berland each high school student is characterized by academic performance — integer value between 1 and 5.
In high school 0xFF there are two groups of pupils: the group A and the group B. Each group consists of exactly n students. An academic performance of each student is known — integer value between 1 and 5.
Th... | ```python
n = int(input())
linea = list(map(int, input().split()))
lineb = list(map(int, input().split()))
lines = linea + lineb
c1 = lines.count(1)
c2 = lines.count(2)
c3 = lines.count(3)
c4 = lines.count(4)
c5 = lines.count(5)
cc1 = linea.count(1)
cc2 = linea.count(2)
cc3 = linea.count(3)
cc4 = linea.count(4)
cc5 = l... |
825_E. Minimal Labels | You are given a directed acyclic graph with n vertices and m edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected.
You should assign labels to all vertices in such a way that:
* Labels form a valid permutation of length n — an integer sequence such that each integ... | ```python
#!/usr/local/bin/python3
from collections import defaultdict
import heapq
num_nodes, num_edges = map(int, input().split())
ins = defaultdict(set)
out = defaultdict(int)
for _ in range(num_edges):
node_out, node_in = map(int, input().split())
ins[node_in].add(node_out)
out[node_out] += 1
zeros... |
870_A. Search for Pretty Integers | You are given two lists of non-zero digits.
Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 9) — the length... | ```python
a,b=map(int,input().split())
s=input().split()
x=list(map(int,s))
s=input().split()
y=list(map(int,s))
o=10
for i in range(a):
for j in range(b):
if x[i]==y[j]:
if x[i]<o:
o=x[i]
x1=min(x)
y1=min(y)
if o<10:
print(o)
else:
print(min(y1,x1)*10+max(x1,y1))
``` |
918_A. Eleven | Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters.
<image>
Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested th... | ```python
n=int(input())
a,b,r=1,2,''
for i in range(1,n+1):
if i==a: r+='O';a,b=b,a+b
else: r+='o'
print(r)
``` |
940_A. Points on the line | We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round.
The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1, 3, 2, 1} is 2.
Diame... | ```python
n,d = map(int,input().split())
a=list(map(int,input().split()))
a.sort();
i=0
cnt=0
cnt1=0
if n==1:
print("0")
else:
for i in range(n):
cnt=0
for j in range(i+1,n):
d1=a[j]-a[i]
if d1>d:
break;
cnt+=1
if(cnt1<cnt):
... |
967_D. Resource Distribution | One department of some software company has n servers of different specifications. Servers are indexed with consecutive integers from 1 to n. Suppose that the specifications of the j-th server may be expressed with a single integer number c_j of artificial resource units.
In order for production to work, it is needed ... | ```python
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
#threading.stack_size... |
993_D. Compute Power | You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume.
You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task ca... | ```python
# Codeforces Round #488 by NEAR (Div. 2)
import collections
from functools import cmp_to_key
#key=cmp_to_key(lambda x,y: 1 if x not in y else -1 )
import math
import sys
def getIntList():
return list(map(int, input().split()))
import bisect
def makePair(z):
return [(z[i], z[i+1]) for i in ... |
p02630 AtCoder Beginner Contest 171 - Replacing | You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.
You will now successively do the following Q operations:
* In the i-th operation, you replace every element whose value is B_{i} with C_{i}.
For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th... | ```python
n = int(input())
la = list(map(int, input().split()))
sa = sum(la)
l_cnt = [0]*100001
for i in la:
l_cnt[i] += 1
q = int(input())
for i in range(q):
b, c = map(int, input().split())
sa += (c-b)*l_cnt[b]
print(sa)
l_cnt[c] += l_cnt[b]
l_cnt[b] = 0
``` |
p02761 AtCoder Beginner Contest 157 - Guess The Number | If there is an integer not less than 0 satisfying the following conditions, print the smallest such integer; otherwise, print `-1`.
* The integer has exactly N digits in base ten. (We assume 0 to be a 1-digit integer. For other integers, leading zeros are not allowed.)
* The s_i-th digit from the left is c_i. \left(i ... | ```python
N,M = map(int,input().split())
SCdash = [[int(i) for i in input().split()] for m in range(M)]
SC = [[scc[0]-1,str(scc[1])] for scc in SCdash]
SG = [(0,10),(10,100),(100,1000)]
for x in range(*SG[N-1]):
keta = str(x)
if all([keta[s]==c for s,c in SC]):
print(x)
exit()
print(-1)
``` |
p03031 AtCoder Beginner Contest 128 - Switches | We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.
Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.
How ... | ```python
N,M = map(int,input().split())
S = [[int(i)-1 for i in input().split()] for _ in range(M)]
P = [int(i) for i in input().split()]
ans = 0
for i in range(1<<N):
for j in range(M):
cnt = 0
for s in S[j][1:]:
if i >> s & 1: cnt += 1
if cnt%2 != P[j]: break
else:
... |
p03172 Educational DP Contest - Candies | There are N children, numbered 1, 2, \ldots, N.
They have decided to share K candies among themselves. Here, for each i (1 \leq i \leq N), Child i must receive between 0 and a_i candies (inclusive). Also, no candies should be left over.
Find the number of ways for them to share candies, modulo 10^9 + 7. Here, two way... | ```python
mod = 10**9+7
def comb(a,b):
return fact[a]*inv[b]*inv[a-b]%mod
n,k = map(int, input().split())
a = list(map(int, input().split()))
fact = [1]
for i in range(n+k):
fact.append(fact[-1]*(i+1)%mod)
inv = [1]*(n+k+1)
inv[n+k] = pow(fact[n+k],mod-2,mod)
for i in range(n+k)[::-1]:
inv[i] = inv[i+... |
p03318 AtCoder Beginner Contest 101 - Snuke Numbers | Let S(n) denote the sum of the digits in the decimal notation of n. For example, S(123) = 1 + 2 + 3 = 6.
We will call an integer n a Snuke number when, for all positive integers m such that m > n, \frac{n}{S(n)} \leq \frac{m}{S(m)} holds.
Given an integer K, list the K smallest Snuke numbers.
Constraints
* 1 \leq K... | ```python
import math
def next_sunuke(N):
D = math.ceil(math.log(N,10) + 1)
z = str(N)
zx = [int(z[:1]) for z in z]
Z = N / sum(zx)
ret_val = N
# print(Z)
ret_vals = [ret_val]
for d in range(0, D):
x = ( (10 ** (d + 1)) * math.floor((N / (10 ** (d+1))) + 1 ) ) - 1
# print(... |
p03474 AtCoder Beginner Contest 084 - Postal Code | The postal code in Atcoder Kingdom is A+B+1 characters long, its (A+1)-th character is a hyphen `-`, and the other characters are digits from `0` through `9`.
You are given a string S. Determine whether it follows the postal code format in Atcoder Kingdom.
Constraints
* 1≤A,B≤5
* |S|=A+B+1
* S consists of `-` and di... | ```python
a, b = map(int, input().split())
s = input()
t = s.split('-')
print('Yes' if s[a] == '-' and len(t) == 2 else 'No')
``` |
p03637 AtCoder Beginner Contest 069 - 4-adjacent | We have a sequence of length N, a = (a_1, a_2, ..., a_N). Each a_i is a positive integer.
Snuke's objective is to permute the element in a so that the following condition is satisfied:
* For each 1 ≤ i ≤ N - 1, the product of a_i and a_{i + 1} is a multiple of 4.
Determine whether Snuke can achieve his objective.
... | ```python
N=int(input())
a=list(map(int,input().split()))
odd=0
m2=0
m4=0
for n in a:
if n%2==1:
odd+=1
elif n%4!=0:
m2+=1
else:
m4+=1
if m4>=odd or (m2==0 and m4>=odd-1):
print('Yes')
else:
print('No')
``` |
p03794 Mujin Programming Challenge 2017 - Oriented Tree | There is a tree T with N vertices, numbered 1 through N. For each 1 ≤ i ≤ N - 1, the i-th edge connects vertices a_i and b_i.
Snuke is constructing a directed graph T' by arbitrarily assigning direction to each edge in T. (There are 2^{N - 1} different ways to construct T'.)
For a fixed T', we will define d(s,\ t) fo... | ```python
# doc: git.io/vy4co
def graph(inp):
nodes = dict()
N = None
for line in inp.splitlines():
if N is None:
N = int(line.strip())
for k in range(1, N + 1):
nodes[k] = set()
continue
i, k = map(int, line.split())
nodes[i].add(k... |
p03963 AtCoder Beginner Contest 046 - Painting Balls with AtCoDeer | There are N balls placed in a row. AtCoDeer the deer is painting each of these in one of the K colors of his paint cans. For aesthetic reasons, any two adjacent balls must be painted in different colors.
Find the number of the possible ways to paint the balls.
Constraints
* 1≦N≦1000
* 2≦K≦1000
* The correct answer i... | ```python
a, b = [int(i) for i in input().split()]
print(b * (b-1) ** (a - 1))
``` |
p00054 Sum of Nth decimal places | Assume that a, b, and n are all positive integers. Let f (i) be the i-th fraction of the fraction a / b (0 ≤ f (i) ≤ 9). At this time, let s be the sum of f (i) from i = 1 to n.
s = f (1) + f (2) + ... + f (n)
Create a program that reads a, b, n, outputs s, and exits.
Input
The input consists of multiple dataset... | ```python
while 1:
try: a,b,c=map(int,input().split())
except:break
print(sum(a*10**(i+1)//b%10 for i in range(c)))
``` |
p00184 Tsuruga Castle | Tsuruga Castle, a symbol of Aizuwakamatsu City, was named "Tsuruga Castle" after Gamo Ujisato built a full-scale castle tower. You can overlook the Aizu basin from the castle tower. On a clear day, you can see Tsuruga Castle from the summit of Mt. Iimori, which is famous for Byakkotai.
<image>
We decided to conduct... | ```python
while True:
n = int(input())
if n == 0:
break
To_lis = [0,0,0,0,0,0,0]
for i in range(n):
tosi = int(input())
if tosi < 10:
To_lis[0] += 1
elif tosi < 20:
To_lis[1] += 1
elif tosi < 30:
To_lis[2] += 1
elif tosi... |
p00340 Rectangle | The educational program (AHK Education) of the Aiz Broadcasting Association broadcasts a handicraft program for children, "Play with Tsukuro". Today is the time to make a rectangle with sticks, but I would like to see if I can make a rectangle using the four sticks I prepared. However, the stick must not be cut or brok... | ```python
s = input().split()
for j in range(len(s)):
for k in range(j-1,-1,-1):
if s[k] >= s[k+1]:
s[k],s[k+1] = s[k+1],s[k]
if s[1] == s[0]:
if s[2] == s[3]:
print("yes")
else:
print("no")
else:
print("no")
``` |
p00534 Silk Road | problem
In the area where Kazakhstan is now located, there used to be a trade route called the "Silk Road".
There are N + 1 cities on the Silk Road, numbered from west as city 0, city 1, ..., city N. The distance between city i -1 and city i (1 ≤ i ≤ N) is Di.
JOI, a trader, decided to start from city 0, go through ... | ```python
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): retur... |
p00839 Organize Your Train | In the good old Hachioji railroad station located in the west of Tokyo, there are several parking lines, and lots of freight trains come and go every day.
All freight trains travel at night, so these trains containing various types of cars are settled in your parking lines early in the morning. Then, during the daytim... | ```python
def solve(file_input, x, y):
exch1 = [] # forward - forward
exch2 = [] # forward - reverse
exch3 = [] # reverse - forward
for i in range(y):
p, P, space, q, Q = file_input.readline().rstrip()
p = int(p)
q = int(q)
if P == 'E':
if Q == 'W':
... |
p00971 Shortest Common Non-Subsequence | Shortest Common Non-Subsequence
A subsequence of a sequence $P$ is a sequence that can be derived from the original sequence $P$ by picking up some or no elements of $P$ preserving the order. For example, "ICPC" is a subsequence of "MICROPROCESSOR".
A common subsequence of two sequences is a subsequence of both seque... | ```python
def main():
p=input()
q=input()
lp=len(p)
lq=len(q)
memop=[[0,0] for _ in [0]*(lp+2)]
memoq=[[0,0] for _ in [0]*(lq+2)]
memop[lp+1]=[lp+1,lp+1]
memoq[lq+1]=[lq+1,lq+1]
memop[lp]=[lp+1,lp+1]
memoq[lq]=[lq+1,lq+1]
for i in range(lp-1,-1,-1):
if p[i]=="0":... |
p01103 A Garden with Ponds | A Garden with Ponds
Mr. Gardiner is a modern garden designer who is excellent at utilizing the terrain features. His design method is unique: he first decides the location of ponds and design them with the terrain features intact.
According to his unique design procedure, all of his ponds are rectangular with simple ... | ```python
while True:
d, w = map(int, input().split())
if d == 0:break
mp = [list(map(int, input().split())) for _ in range(d)]
def solve():
ans = 0
for left in range(w - 1):
for right in range(w - 1, left + 1, -1):
for top in range(d - 1):
for under in range(d - 1, top + 1, -1):... |
p01556 ConvexCut | A convex polygon consisting of N vertices is given. The coordinates of each vertex are represented counterclockwise by (X1, Y1), (X2, Y2), ……, (XN, YN). No matter what straight line passes through the point P, find the coordinates of the point P so that the areas of the two convex polygons obtained after cutting are eq... | ```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**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in ... |
p01711 Idempotent Filter | Problem Statement
Let's consider operations on monochrome images that consist of hexagonal pixels, each of which is colored in either black or white. Because of the shape of pixels, each of them has exactly six neighbors (e.g. pixels that share an edge with it.)
"Filtering" is an operation to determine the color of a... | ```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 = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in ... |
p01991 Namo.. Cut | C: Namo .. Cut
problem
-Defeat the mysterious giant jellyfish, codenamed "Nari"-
"Nari" has a very strong vitality, so if you don't keep cutting quickly, it will be revived in a blink of an eye. We are making trial and error every day to find out how to cut "Nari" efficiently. In the process, you needed the help of ... | ```python
# サイクル検出
import sys
sys.setrecursionlimit(10**7)
def dfs(G, v, p):
global pos
seen[v] = True
hist.append(v)
for nv in G[v]:
# 逆流を禁止する
if nv == p:
continue
# 完全終了した頂点はスルー
if finished[nv]:
continue
# サイクルを検出
if seen[nv] ... |
p02137 Special Chat | Problem
The popular video posting site "ZouTube" is now in the midst of an unprecedented "virtual ZouTuber" boom. Among them, the one that has been attracting particular attention recently is the junior virtual ZouTuber "Aizumarim (commonly known as Azurim)".
As a big fan of Azlim, you're going to send her a "special... | ```python
print(int(input())//500*500)
``` |
p02278 Minimum Cost Sort | You are given $n$ integers $w_i (i = 0, 1, ..., n-1)$ to be sorted in ascending order. You can swap two integers $w_i$ and $w_j$. Each swap operation has a cost, which is the sum of the two integers $w_i + w_j$. You can perform the operations any number of times.
Write a program which reports the minimal total cost to... | ```python
n = int(input())
A = [int(i) for i in input().split()]
B = A.copy()
B.sort()
ans = 0
for i in B:
ixB = B.index(i)
counter = 0
while(True):
ixA = A.index(i)
if ixA == ixB:
break
else:
counter += 1
num = B[ixA]
ixN = A.index(num... |
p02425 Bit Flag | A state with $n$ flags of ON or OFF can be represented by a sequence of bits where $0, 1, ..., n-1$ -th flag corresponds to 1 (ON) or 0 (OFF). The state can be managed by the corresponding decimal integer, because the sequence of bits is a binary representation where each bit is 0 or 1.
Given a sequence of bits with 6... | ```python
q = int(input())
bit_flag = 0
BIT_MASK = (1 << 64) - 1
for _ in range(q):
command, *list_num = input().split()
if command == "0":
# test(i)
i = int(list_num[0])
if bit_flag & (2 ** i):
print(1)
else:
print(0)
elif command == "1":
... |
1008_D. Pave the Parallelepiped | You are given a rectangular parallelepiped with sides of positive integer lengths A, B and C.
Find the number of different groups of three integers (a, b, c) such that 1≤ a≤ b≤ c and parallelepiped A× B× C can be paved with parallelepipeds a× b× c. Note, that all small parallelepipeds have to be rotated in the same d... | ```python
from sys import stdin
from math import gcd
def main():
input()
l = stdin.read().splitlines()
d = [3., 1., 2., 2., 2., 1.] * 16667
for i in range(4, 100001):
for j in range(i, 100001, i):
d[j] += 1.
for i, s in enumerate(l):
a, b, c = map(int, s.split())
... |
1031_B. Curiosity Has No Limits | When Masha came to math classes today, she saw two integer sequences of length n - 1 on the blackboard. Let's denote the elements of the first sequence as a_i (0 ≤ a_i ≤ 3), and the elements of the second sequence as b_i (0 ≤ b_i ≤ 3).
Masha became interested if or not there is an integer sequence of length n, which e... | ```python
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
import threading
BUFSIZE = 819... |
1054_B. Appending Mex | Initially Ildar has an empty array. He performs n steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array.
The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset [0... | ```python
n = int(input())
data = input().split()
max = 0
for i in range(n):
back = max
if max<int(data[i]):
max=int(data[i])
if i==0 and data[i]!="0":
print(1)
exit()
elif int(data[i])>back+1:
print(i+1)
exit()
if int(data[i])<=back+1:
print(-1)
``` |
1076_B. Divisor Subtraction | You are given an integer number n. The following algorithm is applied to it:
1. if n = 0, then end algorithm;
2. find the smallest prime divisor d of n;
3. subtract d from n and go to step 1.
Determine the number of subtrations the algorithm will make.
Input
The only line contains a single integer n (2 ≤... | ```python
from collections import deque as de
import math
class My_stack():
def __init__(self):
self.data = []
def my_push(self, x):
return (self.data.append(x))
def my_pop(self):
return (self.data.pop())
def my_peak(self):
return (self.data[-1])
def my_contains(self,... |
1097_B. Petr and a Combination Lock | Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360 degrees and a pointer which initially points at zero:
<image>
Petr called his car dealer, who in... | ```python
n = int(input())
a = [0]
for _ in range(n):
curr = int(input())
mods = []
for o in a:
mods.extend([o + curr, o - curr])
a = mods[:]
#print(a)
print("YES" if any(x%360 == 0 for x in a) else "NO")
``` |
1118_C. Palindromic Matrix | Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.
For example, the following matrices are palindromic:
<image>
The following matrices are not palindromic because they change... | ```python
import os
from io import BytesIO, StringIO
#input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import defaultdict
def input_as_list():
return list(map(int, input().split()))
def array_of(f, *dim):
return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()
def main... |
1144_F. Graph Without Long Directed Paths | You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph.
You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the numb... | ```python
# lista doble enlazada o(1) en operaciones en los bordes
from collections import deque
def solve():
global n, m
n, m = map(lambda x: int(x), input().split())
global maxValue
maxValue = n**2
graph = [[] for _ in range(0, n)]
edges = []
for _ in range(0, m):
u, v = map(lamb... |
1165_E. Two Arrays and Sum of Functions | You are given two arrays a and b, both of length n.
Let's define a function f(l, r) = ∑_{l ≤ i ≤ r} a_i ⋅ b_i.
Your task is to reorder the elements (choose an arbitrary order of elements) of the array b to minimize the value of ∑_{1 ≤ l ≤ r ≤ n} f(l, r). Since the answer can be very large, you have to print it modulo... | ```python
m=998244353
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
a=sorted([a[i]*(i+1)*(n-i) for i in range(n)])
b.sort(reverse=True)
ans=0
for i in range(n):
ans=(ans+(a[i]*b[i])%m)%m
print(ans)
``` |
1184_D1. Parallel Universes (Easy) | The Third Doctor Who once correctly said that travel between parallel universes is "like travelling sideways". However, he incorrectly thought that there were infinite parallel universes, whereas in fact, as we now all know, there will never be more than 250.
Heidi recently got her hands on a multiverse observation to... | ```python
n,k,m,t=map(int,input().split())
for i in range(t):
a,b=map(int,input().split())
if a==1:
if b<=k:
k+=1
n+=1
print(n,k)
else :
if k>b:
n=n-b
k=k-b
else :
n=b
print(n,k)
``` |
1203_A. Circle of Students | There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation).
Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after... | ```python
t=int(input())
while t:
n=int(input())
a=list(map(int,input().split()))
b=[0]*n
for i in range(n):
b[a[i]-1]=i+1
k=0
flag=0
# print(b)
if n==1:
print("YES")
elif abs(b[0]-b[1])==1 or abs(b[0]-b[1])==n-1:
if abs(b[0]-b[1])==1:
k=b[0]-b[1]
else:
k=b[1]-b[2]
for j in range(1,n):
if j=... |
121_C. Lucky Permutation | Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how ... | ```python
def lucky(x):
s=str(x)
return s.count('4')+s.count('7')==len(s)
def Gen_lucky(n):
if(len(n)==1):
if(n<"4"):
return 0
if(n<"7"):
return 1
return 2
s=str(n)
if(s[0]<'4'):
return 0
if(s[0]=='4'):
return Gen_lucky(s[1:])
... |
1244_G. Running in Pairs | Demonstrative competitions will be held in the run-up to the 20NN Berlatov Olympic Games. Today is the day for the running competition!
Berlatov team consists of 2n runners which are placed on two running tracks; n runners are placed on each track. The runners are numbered from 1 to n on each track. The runner with nu... | ```python
n, t = [int(i) for i in input().split()]
import os
def tr(qq):
return (qq*(qq+1))//2
if t < tr(n):
print(-1)
exit()
upp = 2 * (tr(n) - tr(n//2))
if n % 2 == 1:
upp -= (n+1)//2
if t >= upp:
# print(upp)
# exit()
os.write(1, (str(upp) + '\n').encode())
ans = list(range(1, n+1... |
1286_A. Garland | Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland.... | ```python
def ip():
n=int(input())
a=list(map(int,input().split()))
rem=set([i for i in range(1,n+1)])-set(a)
if n==1:
return 0
o=e=0
for i in rem:
if i%2==0:
e+=1
else:
o+=1
ct=0
i=0
while i<len(a) and a[i]==0:
i+=1
if i... |
1305_B. Kuroni and Simple Strings | Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!
... | ```python
s = input()
to_ans = [False for _ in range(len(s))]
def solve(s, left, right): #right inclusive
if left >= right:
return
while left <= right and s[left] == ")":
left += 1
while right >= left and s[right] == "(":
right -= 1
if left >= right:
return
else:
to_ans[left] = True
to_ans[right] = Tr... |
1349_D. Slime and Biscuits | Slime and his n friends are at a party. Slime has designed a game for his friends to play.
At the beginning of the game, the i-th player has a_i biscuits. At each second, Slime will choose a biscuit randomly uniformly among all a_1 + a_2 + … + a_n biscuits, and the owner of this biscuit will give it to a random unifor... | ```python
import os
import sys
input = sys.stdin.buffer.readline
#sys.setrecursionlimit(int(2e5))
from collections import deque
import math
# list(map(int, input().split()))
#####################################################################################
class CF(object):
def __init__(self):
self.mo... |
136_B. Ternary Logic | Little Petya very much likes computers. Recently he has received a new "Ternatron IV" as a gift from his mother. Unlike other modern computers, "Ternatron IV" operates with ternary and not binary logic. Petya immediately wondered how the xor operation is performed on this computer (and whether there is anything like it... | ```python
def untor(a, c):
res = ''
while a or c:
a, ma = divmod(a, 3)
c, mc = divmod(c, 3)
x = 0
while (ma + x)%3 != mc:
x += 1
res = str(x) + res
try:
return int(res, 3)
except Exception as e:
return 0
a, c = map(int, input().split()... |
1392_B. Omkar and Infinity Clock | Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:
You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k ope... | ```python
t=int(input())
for i in range(t):
n,k=map(int,input().split())
ar=list(map(int,input().split()))
m=max(ar)
new=[]
for i in range(n):
new.append(m-ar[i])
if k%2==0:
mx=max(new)
for j in range(n):
new[j]=mx-new[j]
print(*new)
``` |
1433_C. Dominant Piranha | There are n piranhas with sizes a_1, a_2, …, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.
Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the... | ```python
for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
if len(set(l))==1:
print(-1)
else:
m=max(l)
for i in range(n):
if i>0:
if i<n-1:
if l[i]==m and (l[i-1]<m or l[i+1]<m):
print(i+1)
break
else:
if l[i]==m and l[i-1]<m:
print(i+1)
... |
1458_B. Glass Half Spilled | There are n glasses on the table numbered 1, …, n. The glass i can hold up to a_i units of water, and currently contains b_i units of water.
You would like to choose k glasses and collect as much water in them as possible. To that effect you can pour water from one glass to another as many times as you like. However, ... | ```python
n=int(input())
dp=[[-10**8]*(10002) for _ in range(n+1)]
dp[0][0]=0
total=0
for i in range(n):
a,b=map(int,input().split())
total+=b
for k in range(n-1,-1,-1):
for c in range(10001-a,-1,-1):
dp[k+1][c+a]=max(dp[k+1][c+a],dp[k][c]+b)
ans = [0 for i in range(n+1)]
for j in range(... |
1481_B. New Colony | After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you).
<image>
You are given an array h_1, h_2, ..., ... | ```python
import collections
import string
import math
import copy
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" ... |
1508_C. Complete the MST | As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows.
You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all... | ```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... |
1534_D. Lost Tree | This is an interactive problem.
Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n.
The game master only allows him to ask one type of question:
* Little Dormi picks a node r (1 ≤ r ≤ n), and the... | ```python
res = []
n = int(input())
print('?', 1, flush=True)
arr = list(map(int, input().split()))
for v,d in enumerate(arr):
if d==1:
res.append([0,v])
one = [v for v,d in enumerate(arr) if d&1]
two = [v for v,d in enumerate(arr) if v and not (d&1)]
if len(one)>len(two):
one, two = two, one
for u in o... |
181_B. Number of Triplets | You are given n points on a plane. All points are different.
Find the number of different groups of three points (A, B, C) such that point B is the middle of segment AC.
The groups of three points are considered unordered, that is, if point B is the middle of segment AC, then groups (A, B, C) and (C, B, A) are consi... | ```python
n = int(input())
points_array = []
cords = []
for i in range(2001):
cords.append([False] * 2001)
for i in range(n):
x, y = [a for a in input().split()]
points_array.append([int(x), int(y)])
cords[int(x)+1000][int(y)+1000] = True
count = 0
for i in range(n):
for j in range(i+1, n):
... |
204_D. Little Elephant and Retro Strings | The Little Elephant has found a ragged old black-and-white string s on the attic.
The characters of string s are numbered from the left to the right from 1 to |s|, where |s| is the length of the string. Let's denote the i-th character of string s as si. As the string is black-and-white, each character of the string is... | ```python
Mod=1000000007
n,k=map(int,input().split(' '))
s=' '+input()
f,fs,g,gs,w=[0]*1000005,[0]*1000005,[0]*1000005,[0]*1000005,[0]*1000005
qx,qw,qb=[0]*1000005,[0]*1000005,[0]*1000005
q=0
f[0]=fs[0]=1
for i in range(1,n+1):
lg=(i-k if i-k>=q else q)
if s[i]!='B':
f[i]=fs[i-1]-fs[lg-1]+Mod
f[i]-=(Mod if f[i]>=... |
253_A. Boys and Girls | There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i < n + m) such that positions with indexes i... | ```python
import os.path
import sys
if os.path.exists('input.txt'):
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
n,m=[int(x) for x in input().split(' ')]
x=min(n,m)
#print(x)
if n<m:
ans=x*"GB"
else:
ans=x*'BG'
n=n-x
m=m-x
#print(n,m)
if n!=0:
ans+=n*'B'
if m!=0:
ans+=... |
278_B. New Problem | Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems.
You've got the titles of n last problems — the strings, consisting of lowercase English letters. Your... | ```python
from itertools import *
alphabet="abcdefghijklmnopqrstuvwxyz";
def isValid(s, names):
for name in names:
if name.find(s)!=-1:
return False
return True
def newProblem(names):
for i in range(1,3):
for s in product(alphabet, repeat=i):
st=""
for ... |
300_A. Array | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:
1. The product of all numbers in the first set is less than zero ( < 0).
2. The product of all numbers in the second set is greater than zero ( > 0).
3. The product of a... | ```python
n=int(input())
a=list(map(int,input().split()))
b=[]
k=0
k1=0
for i in range(0,n):
if(a[i]==0):
b.append(a[i])
elif(a[i]>0):
if(k==0):
k=a[i]
else:
b.append(a[i])
elif(a[i]<0):
if(k1==0):
k1=a[i]
else:
b.append... |
372_A. Counting Kangaroos is Fun | There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.
Each kangaroo can hold at most one kangaroo, and the kangaroo who is ... | ```python
# Made By Mostafa_Khaled
bot = True
import math,sys
n=int(input());k=n
a=sorted([int(x) for x in sys.stdin.read().strip().split('\n')])
p1=math.floor((n-1)/2);p2=n-1
while p1>=0:
if 2*a[p1]<=a[p2]:
k-=1;a[p2]=0;p2-=1
p1-=1
k=max(math.ceil(n/2),k)
sys.stdout.write(str(k))
# Made By ... |
393_C. Blocked Points | Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if:
* the Euclidean distance between A and B is one unit and neither A nor B is blocked;
* or there is some inte... | ```python
from math import sqrt
n = int(input())
if n == 0:
print(1)
else:
print(4 * int(n * sqrt(2)))
``` |
416_D. Population Size | Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.
Polycarpus believes that if... | ```python
n = int(input())
a = list(map(int, input().split()))
i = 0
ans = 0
while i < n:
ans += 1
i1 = i
while i1 < n and a[i1] == -1:
i1 += 1
if i1 == n:
break
i2 = i1 + 1
while i2 < n and a[i2] == -1:
i2 += 1
if i2 == n:
break
dist = i2 - i1
step = ... |
443_B. Kolya and Tandem Repeat | Kolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string.
Then Borya came and said that the new string contained a tandem repeat of length l as a substring. How large could l be?
See notes for definition of a tandem repeat.
I... | ```python
s=input()
k=int(input())
n=len(s)
if k>=n:
print(int(2*((n+k)//2)))
raise SystemExit
ll=0
for i in range(k+1):
for l in range((n+i)//2,i-1,-1):
if s[n-(l-i):n]==s[n+i-2*l:n-l]:
if l>ll:
ll=l
break
j=ll
while 2*j<=n:
j=j+1
for i in range(n-2*j):
if s[... |
465_C. No to Palindromes! | Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.
Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable st... | ```python
import sys
def main():
# fin = open("input.txt", "r")
fin = sys.stdin
fout = sys.stdout
L = list("abcdefghijklmnopqrstuvwxyz")
n, p = map(int, fin.readline().split())
A = list(fin.readline())
for i in range(n - 1, 1, -1):
pr = ord(A[i - 1]) - ord("a")
pp = ord(A... |
489_B. BerSU Ball | The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m... | ```python
n = int(input())
b = list(map(int, input().split()))
m = int(input())
g = list(map(int, input().split()))
b.sort()
g.sort()
res = 0
i = 0
j = 0
while i < n and j < m:
if abs(b[i]-g[j]) <= 1:
res += 1
i += 1
j += 1
elif b[i] > g[j]:
j += 1
else:
i += 1
... |
513_A. Game | Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f... | ```python
n1 , n2 , k1 , k2 = map(int , (input().split(" ")))
if n1 <= n2:
print('Second')
else:
print('First')
``` |
538_B. Quasi Binary | A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer n. Represent it as a sum of minimum number of quasibinary numbers.
Input
The first line contains a single... | ```python
import math
a = input()
d = int(max(a))
print(d)
dec = math.ceil(math.log10(int(a)))
c = [0]*d
if int(a) != 10**dec:
for i in a:
for j in range(int(i)):
c[j] = c[j]+10**(dec-1)
dec = dec - 1
d=''
for i in c:
d += str(i)+' '
if int(a) == 10**dec:
print(a)
else:
print... |
630_E. A rectangle | Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem.
A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will... | ```python
x1,y1,x2,y2 = input().split( )
x1=int(x1)
y1=int(y1)
x2=int(x2)
y2=int(y2)
x =int(x2 - x1)
y =int(y2 - y1)
if x % 2 == 0:
if y % 2 == 1:
n= int(int( x + 1 ) * int(y + 1) / 2)
else:
t0=int(x*y)+int(x)+int(y)
t1=int(t0)//2
n=int(t1)+1
else:
n = int((x + 1) / 2 * ( y + 1 ))
print(n)
``` |
658_B. Bear and Displayed Friends | Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.
Spring is starting and the Winter sleep is ... | ```python
str1 = input().split()
n = int(str1[0])
k = int(str1[1])
q = int(str1[2])
friends = list(map(lambda x: int(x), input().split()))
online = set()
for i in range(q):
str1 = input().split()
if str1[0] == '2':
if int(str1[1]) in online:
print("YES")
else:
print("NO... |
680_D. Bear and Tower of Cubes | Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.... | ```python
#!/usr/bin/env python3
import sys
# 1 8 27 64 125 216 343 512 729 1000
# 1-7: blocks of size 1
# 8-15: 1 block of size 2, blocks of size 1
# 16-23: 2 blocks of size 2, blocks of size 1
# 24-26: 3 blocks of size 2, blocks of size 1
# 27-34: 1 block of size 3, blocks of size 1
# Maximum will always be when y... |
703_C. Chris and Road | And while Mishka is enjoying her trip...
Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend.
Once walking with his friend, John gave Chris the following proble... | ```python
n, w, v, u = map(int, input().split())
maxwait = 0
curr = True
for i in range(n):
x, y = map(int, input().split())
maxwait = max(maxwait, x / v - y / u)
if x / v < y / u:
curr = False
if curr:
maxwait = 0
print(w / u + maxwait)
``` |
725_C. Hidden Word | Let’s define a grid to be a set of tiles with 2 rows and 13 columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid:
ABCDEFGHIJKLM
NOPQRSTUVWXYZ
We say that two t... | ```python
import sys
debug = False
def print_debug(*args, **kwargs):
if debug:
print(*args, **kwargs, file=sys.stderr)
s = input()
double = ''
for c in range(ord('A'), ord('Z')+1):
if s.count(chr(c)) == 2:
double = chr(c)
i1, i2 = [ i for i, c in enumerate(s) if c == double ]
print_debug(... |
747_C. Servers | There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to n.
It is known that during the day q tasks will come, the i-th of them is characterized with three integers: ti — the moment in seconds in which the task will come, ki — the number of servers needed to ... | ```python
n, q = map(int, input().split())
servers = [i for i in range(1, n+1)]
res, used = [], {}
for i in range(q):
t, s, d = map(int, input().split())
finish = t + d
for i in list(used.keys()):
if t >= i:
servers += used[i]
servers.sort()
del used[i]
if s ... |
794_C. Naming Company | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.
To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor ea... | ```python
from sys import *
f = lambda: sorted(stdin.readline()[:-1])
a, b = f(), f()
n = len(a)
u = v = ''
i, j = 0, -1
x, y = n - 1 >> 1, n - 2 >> 1
while x != -1:
if a[i] < b[j]:
u += a[i]
i += 1
else: v += a[i + x]
x -= 1
if y == -1: break
elif a[i] < b[j]:
u += b[j]
... |
815_B. Karen and Test | Karen has just arrived at school, and she has a math test today!
<image>
The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.
Th... | ```python
from sys import exit, stdin, stdout
n = int(stdin.readline())
a = [int(i) for i in stdin.readline().split()]
if n == 1:
print(a[0])
exit(0)
mod = 1000000007
f = [0] * (n + 1)
f[0] = 1
for i in range(1, n + 1):
f[i] = (f[i-1] * i) % mod
def f_pow(a, k):
if k == 0:
return 1
if k % 2... |
840_B. Leha and another game about graph | Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say... | ```python
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
import heapq
INF=10**9
def Dijkstra(graph, start,m):
dist=[INF]*len(graph)
parent=[INF]*len(graph)
queue=[(0, start)]
while queue:
path_len, v=heapq.heappop(queue)
if dist[v]==INF:
dist[v]=path_len
fo... |
860_C. Tests Renumeration | The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.
Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.
Vladimir wants to re... | ```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
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()... |
887_B. Cubes for Masha | Absent-minded Masha got set of n cubes for her birthday.
At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural x such she can make using her new cubes all integers from 1 to x.
To make a number Masha can rotate her cubes and put them in a row. Aft... | ```python
n = int(input())
lst = []
for i in range(n):
a = list(map(int,input().split()))
lst.append(a)
cnt = 0
ans = 0
if n == 1:
i = 1
while 1:
if i == 10: break
if i in lst[0]:
i += 1
else:
print(i - 1)
break
elif n == 2:
i = 1
f = ... |
90_B. African Crossword | An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.
To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a lette... | ```python
n, m = [int(x) for x in input().split()]
lr = []
lc = []
lst = []
for i in range(n):
l = list(input())
lr.append(l)
for i in range(m):
l = []
for j in range(n):
s = lr[j][i]
l.append(s)
lc.append(l)
for i in range(n):
for j in range(m):
s = lr[i][j]
if l... |
931_E. Game with String | Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string ... | ```python
s = input()
n = len(s)
d = {}
for i in range(n):
if s[i] not in d: d[s[i]] = []
d[s[i]].append(s[i + 1:] + s[:i])
res = 0
for k, l in d.items():
ans = 0
for j in range(n - 1):
seen, s1 = set(), set()
for i in range(len(l)):
if l[i][j] in s1: s1.remove(l[i][j])
... |
985_E. Pencils and Boxes | Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1, a2, ..., an of n integer numbers — saturation of the color of each pencil. Now Mishka wants to ... | ```python
n, k, d = list(map(int, input().split()))
a = sorted(list(map(int, input().split())))
b = [0] * n
i = j = 0
for i in range(n):
while a[i] - a[j] > d:
j += 1
b[i] = j
c = [0] * n
for i in range(k - 1, n):
c[i] = c[i - 1] + int(i - b[i] + 1 >= k and (b[i] == 0 or c[i - k] > c[b[i] - 2] or (b... |
p02578 AtCoder Beginner Contest 176 - Step | N persons are standing in a row. The height of the i-th person from the front is A_i.
We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:
Condition: Nobody in front of the person is taller than the person. Here, the height of a ... | ```python
n = int(input())
m=list(map(int,input().split()))
k=0
s=0
for i in range(n):
s+=max(0,k-m[i])
k=max(k,m[i])
print(s)
``` |
p02709 AtCoder Beginner Contest 163 - Active Infants | There are N children standing in a line from left to right. The activeness of the i-th child from the left is A_i.
You can rearrange these children just one time in any order you like.
When a child who originally occupies the x-th position from the left in the line moves to the y-th position from the left, that child... | ```python
N = int(input())
def solve(a, i, prev):
r = N - len(prev) - i + 1
p = -i*a
for j, s in enumerate(prev):
yield p+abs(j-i)*a, s+abs(j+r)*a
p = s
yield s+abs(len(prev)-i)*a,
pd = [0]
A = map(int, input().split())
for a,i in sorted(((a, i) for i, a in enumerate(A, 1)), reverse=True):
pd = [*ma... |
p02838 AtCoder Beginner Contest 147 - Xor Sum 4 | We have N integers. The i-th integer is A_i.
Find \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).
What is \mbox{ XOR }?
The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:
* When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if eith... | ```python
n=int(input())
mod=10**9+7;ans=0
a=list(map(int,input().split()))
for i in range(61):
checkbit=1 << i
cnt=sum([1 for j in a if j & checkbit])
ans+=checkbit*cnt*(n-cnt)
ans%=mod
print(ans)
``` |
p02975 AtCoder Grand Contest 035 - XOR Circle | Snuke has N hats. The i-th hat has an integer a_i written on it.
There are N camels standing in a circle. Snuke will put one of his hats on each of these camels.
If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print `Yes`; otherwise, print `No... | ```python
_, *a = map(int, open(0).read().split());z = 0
for b in a:z ^= b
print("YNeos"[z>0::2])
``` |
p03111 AtCoder Beginner Contest 119 - Synthetic Kadomatsu | You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.
Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:
* Extension Magic: Consumes 1 MP (magic point).... | ```python
n,a,b,c=map(int,input().split())
l=[int(input()) for _ in range(n)]
def dfs(i,x,y,z):
if i==n:
return abs(x-a)+abs(y-b)+abs(z-c) if x*y*z else 10**9
r1 = dfs(i+1,x+l[i],y,z)+ (10 if x>0 else 0)
r2 = dfs(i+1,x,y+l[i],z)+ (10 if y>0 else 0)
r3 = dfs(i+1,x,y,z+l[i])+ (10 if z>0 else 0)
r4 = dfs(i+... |
p03574 AtCoder Beginner Contest 075 - Minesweeper | You are given an H × W grid.
The squares in the grid are described by H strings, S_1,...,S_H.
The j-th character in the string S_i corresponds to the square at the i-th row from the top and j-th column from the left (1 \leq i \leq H,1 \leq j \leq W).
`.` stands for an empty square, and `#` stands for a square containin... | ```python
h,w = map(int,input().split())
grid = ["."*(w+2)]+["."+input()+"." for _ in range(h)]+["."*(w+2)]
for y in range(1,h+1):
for x in range(1,w+1):
if grid[y][x]=="#":
print("#",end="")
else:
print(sum(grid[i][j]=="#" for i in range(y-1,y+2) for j in range(x-1,x+2)),end="")
print("")
``` |
p03729 AtCoder Beginner Contest 060 - Shiritori | You are given three strings A, B and C. Check whether they form a word chain.
More formally, determine whether both of the following are true:
* The last character in A and the initial character in B are the same.
* The last character in B and the initial character in C are the same.
If both are true, print `YES`.... | ```python
S = input().split()
print('YES' if S[0][-1] == S[1][0] and S[1][-1] == S[2][0] else 'NO')
``` |
p03893 CODE FESTIVAL 2016 Relay (Parallel) - Trichotomy | We have a cord whose length is a positive integer. We will perform the following condition until the length of the cord becomes at most 2:
* Operation: Cut the rope at two positions to obtain three cords, each with a length of a positive integer. Among these, discard one with the longest length and one with the shorte... | ```python
x=int(input())
l,r=0,100000000000000
while r-l>1:
m=(l+r)//2
t=m
cnt=0
while m>2:
cnt+=1
m=(m-1)//2
if cnt>x:
r=t
else:
l=t
print(l)
``` |
p04052 AtCoder Grand Contest 001 - Wide Swap | You are given a permutation P_1 ... P_N of the set {1, 2, ..., N}.
You can apply the following operation to this permutation, any number of times (possibly zero):
* Choose two indices i,j (1 ≦ i < j ≦ N), such that j - i ≧ K and |P_i - P_j| = 1. Then, swap the values of P_i and P_j.
Among all permutations that can... | ```python
def invert(p, q):
for i, pi in enumerate(p): q[pi] = i
def sort_insertion(k, data, first, last):
length = last - first
if length <= 2:
if length == 2 and data[first] - data[first + 1] >= k:
data[first], data[first + 1] = data[first + 1], data[first]
return
for i in... |
p00131 Doctor's Strange Particles | Dr .: Peter. I did.
Peter: See you again? What kind of silly invention is this time?
Dr .: You invented the detector for that phantom elementary particle axion.
Peter: Speaking of Axion, researchers such as the European Organization for Nuclear Research (CERN) are chasing with a bloody eye, aren't they? Is that true... | ```python
def attack(table, i, j):
table[i][j] = 1 - table[i][j]
table[i-1][j] = 1 - table[i-1][j]
table[i+1][j] = 1 - table[i+1][j]
table[i][j-1] = 1 - table[i][j-1]
table[i][j+1] = 1 - table[i][j+1]
def printans(ans):
for i in range(1, 11):
for j in range(1, 11):
print(ans... |
p00264 East Wind | I decided to move and decided to leave this place. There is nothing wrong with this land itself, but there is only one thing to worry about. It's a plum tree planted in the garden. I was looking forward to this plum blooming every year. After leaving here, the fun of spring will be reduced by one. Wouldn't the scent of... | ```python
from math import atan2, degrees
def calc(dx, dy, d, w, a):
if dx**2 + dy**2 > a**2:
return 0
t = degrees(atan2(dy, dx))
for i in range(2):
if w - d/2 <= t + 360*i <= w + d/2:
return 1
return 0
while 1:
H, R = map(int, input().split())
if H == R == 0:
... |
p00451 Common Sub-String | problem
Given two strings, find the longest of the strings contained in both strings and write a program that answers that length.
Here, the string s included in the string t means that s appears consecutively in t. An empty string, that is, a string of length 0, is included in any string. For example, the string ABR... | ```python
def rolling_hash(S, base, MOD):
l = len(S)
h = [0]*(l + 1)
for i in range(l):
h[i+1] = (h[i] * base + ord(S[i])) % MOD
return h
C = open(0).read().split()
MOD = 358976445361682909
base = 31
for t in range(len(C)//2):
S = C[2*t]; T = C[2*t+1]
rhs = rolling_hash(S, base, MOD)
... |
p01488 TransferTrain | Example
Input
2 10
Warsaw Petersburg
3
Kiev Moscow Petersburg
150 120
3
Moscow Minsk Warsaw
100 150
Output
380 1 | ```python
from heapq import heappush, heappop
import sys
def solve():
readline = sys.stdin.readline
write = sys.stdout.write
N, TI = map(int, readline().split())
A, B = readline().split()
S = []; T = []; X = []
L = 0
L = 0
NA = set()
for i in range(N):
a = int(readline())
... |
p01650 Stack Maze | Problem Statement
There is a maze which can be described as a W \times H grid. The upper-left cell is denoted as (1, 1), and the lower-right cell is (W, H). You are now at the cell (1, 1) and have to go to the cell (W, H). However, you can only move to the right adjacent cell or to the lower adjacent cell. The followi... | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
from string import ascii_lowercase, ascii_uppercase
from collections import deque
dd = ((1, 0), (0, 1))
def solve():
H, W = map(int, readline().split())
if H == W == 0:
return False
C = [readline().strip() for i in range(H... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.