name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
313_B. Ilya and Queries | Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≤ li < ri ≤ n)... | ```python
s=input()
n=len(s)
m=int(input())
a=[0]*(n+1)
for i in range(n-1):
a[i+1]=a[i]+(s[i]==s[i+1])
ans=""
for i in range(m):
l,r=map(int,input().split())
ans+=str(a[r-1]-a[l-1])+" "
print(*ans.split(),sep="\n")
``` |
402_C. Searching for Graph | Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A sub... | ```python
for _ in range(int(input())):
n, p = map(int, input().split())
p += 2 * n
for i in range(n):
for j in range(i + 1, n):
if p == 0:
break
print(i + 1, j + 1)
p -= 1
``` |
42_D. Strange town | Volodya has recently visited a very odd town. There are N tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing to... | ```python
#codeforces 42d: strange town: math, constructive algorithm
def readGen(trans):
while 1:
for x in input().split():
yield(trans(x))
readint=readGen(int)
n=next(readint)
def constructRow(n):
can=[1 for i in range(1001)]
b=[0 for i in range(n+1)]
b[2]=1
b[3]=2
can[1]=0
can[2]=0
for k in range(4,n... |
452_B. 4-point polyline | You are given a rectangular grid of lattice points from (0, 0) to (n, m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.
A polyline defined by points p1, p2, p3, p4 consists of the line segment... | ```python
n, m = map(int, input().split())
a = ([[0, 1], [0, m], [0, 0], [0, m - 1]], [[1, 0], [n, 0], [0, 0], [n - 1, 0]], \
[[0, 1], [n, m], [0, 0], [n, m - 1]], [[1, 0], [n, m], [0, 0], [n - 1, m]], \
[[0, 0], [n, m], [0, m], [n, 0]], [[0, 0], [n, m], [n, 0], [0, m]])
for x in max(a, key = lambda a: (len(s... |
474_F. Ant colony | Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices betwe... | ```python
from math import gcd
class SegTree:
def __init__(self, arr = None, length = None):
"""
Creates a segment tree. If arr (a list) is given, length is ignored,
and we build a segment tree with underlying array arr. If no list is
given, length (an int) must be given, and we bui... |
522_A. Reposts | One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the n... | ```python
leng = int(input())
names = ["POLYCARP", 1]
others = []
max = 1
for i in range(leng):
x, y= map(str, input().split(' reposted '))
others.append(x.upper())
others.append(y.upper())
for i in range(0, leng*2, 2):
if others[i+1] in names:
num = names[names.index(others[i+1]) + 1] + 1
names.append(others[... |
549_C. The Game Of Parity | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.
The ... | ```python
n,k=[int(i) for i in input().split()]
l=[int(i) for i in input().split()]
no=0
for i in l:
no+=i%2
ne=n-no
if n==k:
if no%2:
print("Stannis")
else:
print("Daenerys")
else:
if no<=(n-k)//2:
print("Daenerys")
else:
if no%2:
if (n-k)%2 and ne<=(n-k)//... |
597_C. Subsequences | For the given sequence with n different elements find the number of increasing subsequences with k + 1 elements. It is guaranteed that the answer is not greater than 8·1018.
Input
First line contain two integer values n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 10) — the length of sequence and the number of elements in increasing ... | ```python
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def update(tree,pos,diff,si):
pos += si-1
while pos:
tree[pos] += diff
pos >>= 1
def query(tree,l,r,si):
ans,l,r = 0,l+si-1,r+si-1
while l < r:
if l&1:
... |
618_E. Robot Arm | Roger is a robot. He has an arm that is a series of n segments connected to each other. The endpoints of the i-th segment are initially located at points (i - 1, 0) and (i, 0). The endpoint at (i - 1, 0) is colored red and the endpoint at (i, 0) is colored blue for all segments. Thus, the blue endpoint of the i-th segm... | ```python
from cmath import rect
import sys
import math
from functools import reduce
class SegmentTree():
def __init__(self, L, function = lambda x,y: x+y):
self.function = function
N = self.size = len(L)
M = 1 << N.bit_length()
self.margin = 2*M - N
self.L = [None for i in ... |
690_B1. Recover Polygon (easy) | The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good.
Heidi knows that the lair can be represented as a rectangle on a lattice, with si... | ```python
n = int(input())
aux = []
grid = []
flag = True
ans = -1
um = 0
dois = 0
quatro = 0
while(n):
n-=1
x = str(int(input()))
if(x!='0'):
aux.append(x)
for i in aux:
txt = ''
for j in i:
if(j!='0'):
txt+=j
grid.... |
779_D. String Game | Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.
Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain ... | ```python
s = input()
t = input()
a = list(map(int, input().split()))
def ok(n):
bad = set()
for i in range(n):
bad.add(a[i] - 1)
pt = 0
ps = 0
while pt < len(t) and ps < len(s):
if ps in bad:
ps += 1
else:
if t[pt] == s[ps]:
ps += 1
... |
827_A. String Reconstruction | Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one.
Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more... | ```python
from sys import stdin, stdout
sze = 10 ** 6 + 1
n = int(stdin.readline())
challengers = []
strings = []
sze = 10 ** 6 + 1
cnt = [[] for i in range(sze)]
for i in range(n):
s = stdin.readline().strip().split()
num = int(s[1])
values = list(map(int, s[2:]))
strings.append(s[0])
... |
849_A. Odds and Ends | Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?
Given an integer sequence a1, a2, ..., an of length n. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.
A subse... | ```python
n = int(input())
a = list(map(int,input().split()))
if n % 2 == 0 or a[0] % 2 == 0 or a[-1] % 2 == 0:
print("NO")
else:
print("YES")
``` |
897_C. Nephren gives a riddle | What are you doing at the end of the world? Are you busy? Will you save us?
<image>
Nephren is playing a game with little leprechauns.
She gives them an infinite array of strings, f0... ∞.
f0 is "What are you doing at the end of the world? Are you busy? Will you save us?".
She wants to let more people know about i... | ```python
import sys
sys.setrecursionlimit(1500)
s1 = "What are you doing at the end of the world? Are you busy? Will you save us?"
a = "What are you doing while sending \""
b = "\"? Are you busy? Will you send \""
c = "\"?"
ans = ""
def solve(n, k):
if n == 0:
if k >= len(s1):
return "."
... |
918_D. MADMAX | As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lower... | ```python
# int(input())
# [int(i) for i in input().split()]
import sys
sys.setrecursionlimit(20000)
def go(v,w,last):
if game[v][w][last] >= 0: return(game[v][w][last])
flag = 0
move = 0
for p in edges_out[v]:
if p[1] >= last:
move = 1
if not go(w,p[0],p[1]):
... |
940_D. Alena And The Heater | "We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme."
"Little Alena got an array as a birthday present..."
The array b of length n is obtained from the array a of length n and two integers l and r (l ≤ r) using the following procedure:
b1 = b2 = b3... | ```python
import sys
n = int(input())
A = input().split()
A = [int(i) for i in A]
S = input()
L = -1000000000
R = 1000000000
for i in range(4, n):
if S[i - 1] == S[i - 2] == S[i - 3] == S[i - 4] == '0' and S[i] == '1':
L = max(max(A[i], A[i - 1], A[i - 2], A[i - 3], A[i - 4]) + 1, L)
elif S[i - 1] ==... |
96_A. Football | Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | ```python
entrada = input()
vez = -1
total = 0
perigo = False
for i in range(len(entrada)):
aux = int(entrada[i])
if(vez == aux):
total += 1
if(total == 7):
perigo = True
else:
total = 1
vez = aux
if(perigo):
print("YES")
else:
print("NO")
``` |
994_A. Fingerprints | You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.
Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse... | ```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = ''
for i in a:
if i in b:
ans = ans + str(i) + ' '
print(ans)
``` |
p02633 AtCoder Grand Contest 046 - Takahashikun The Strider | Takahashi is standing on a two-dimensional plane, facing north. Find the minimum positive integer K such that Takahashi will be at the starting position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise.
Constraints
* 1 \leq X \leq ... | ```python
from math import gcd
X=int(input())
g=gcd(X,360)
print((360)//(g))
``` |
p02764 AtCoder Beginner Contest 157 - Yakiniku Optimization Problem | Takahashi wants to grill N pieces of meat on a grilling net, which can be seen as a two-dimensional plane. The coordinates of the i-th piece of meat are \left(x_i, y_i\right), and its hardness is c_i.
Takahashi can use one heat source to grill the meat. If he puts the heat source at coordinates \left(X, Y\right), wher... | ```python
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x i... |
p02899 AtCoder Beginner Contest 142 - Go to School | Takahashi is a teacher responsible for a class of N students.
The students are given distinct student numbers from 1 to N.
Today, all the students entered the classroom at different times.
According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including... | ```python
n,*a= map(int,open(0).read().split())
b=[0]*n
for i in range(n):
b[a[i]-1]=i+1
print(*b)
``` |
p03034 AtCoder Beginner Contest 128 - Frog Jump | There is an infinitely large pond, which we consider as a number line. In this pond, there are N lotuses floating at coordinates 0, 1, 2, ..., N-2 and N-1. On the lotus at coordinate i, an integer s_i is written.
You are standing on the lotus at coordinate 0. You will play a game that proceeds as follows:
* 1. Choose... | ```python
import sys
input = sys.stdin.readline
inf = float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int, input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_, input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x i... |
p03175 Educational DP Contest - Independent Set | There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black. Here, it is not allowed to paint two adjacent vertices both in black.
Find the number of ways in which the vertices can be pa... | ```python
def read_int():
return int(input().strip())
def read_ints():
return list(map(int, input().strip().split(' ')))
def solve():
"""
OPT[node][BLACK] = product(OPT[child[i]][WHITE])
OPT[node][WHITE] = product(OPT[child[i]][WHITE|BLACK])
"""
N = read_int()
G = [[] for _ in rang... |
p03323 AtCoder Beginner Contest 100 - Happy Birthday! | E869120's and square1001's 16-th birthday is coming soon.
Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.
E869120 and square1001 were just about to eat A and B of those pieces, respectively,
when they found a note attached to the cake saying that "the same person should not t... | ```python
a,b = map(int,input().split())
print("Yay!"if a<=8 and b <=8 else ':(')
``` |
p03477 AtCoder Beginner Contest 083 - Libra | A balance scale tips to the left if L>R, where L is the total weight of the masses on the left pan and R is the total weight of the masses on the right pan. Similarly, it balances if L=R, and tips to the right if L<R.
Takahashi placed a mass of weight A and a mass of weight B on the left pan of a balance scale, and pl... | ```python
a,b,c,d = map(int, input().split())
ans = "Balanced"
if a+b > c+d: ans = "Left"
elif a+b < c+d: ans = "Right"
print(ans)
``` |
p03642 AtCoder Regular Contest 080 - Prime Flip | There are infinitely many cards, numbered 1, 2, 3, ... Initially, Cards x_1, x_2, ..., x_N are face up, and the others are face down.
Snuke can perform the following operation repeatedly:
* Select a prime p greater than or equal to 3. Then, select p consecutive cards and flip all of them.
Snuke's objective is to h... | ```python
import itertools
from math import sqrt
def chunk(a):
i = 0
res = []
while i < len(a):
res.append(a[i])
while i != len(a) - 1 and a[i + 1] == a[i] + 1:
i += 1
res.append(a[i] + 1)
i += 1
return res
def augment(g, src, dest):
o = [None] * len(g)
... |
p03799 AtCoder Regular Contest 069 - Scc Puzzle | Snuke loves puzzles.
Today, he is working on a puzzle using `S`- and `c`-shaped pieces. In this puzzle, you can combine two `c`-shaped pieces into one `S`-shaped piece, as shown in the figure below:
9b0bd546db9f28b4093d417b8f274124.png
Snuke decided to create as many `Scc` groups as possible by putting together one ... | ```python
S,C = map(int,input().split())
p = min(S,C//2)
C -= p*2
ans = p + C//4
print(ans)
``` |
p03968 AtCoder Regular Contest 062 - Building Cubes with AtCoDeer | AtCoDeer the deer has N square tiles. The tiles are numbered 1 through N, and the number given to each tile is written on one side of the tile. Also, each corner of each tile is painted in one of the 1000 colors, which are represented by the integers 0 between 999. The top-left, top-right, bottom-right and bottom-left ... | ```python
from collections import defaultdict
N, = map(int, input().split())
def normal(xs):
return tuple(min((xs[j:] + xs[:j] for j in range(1, 5))))
dd = defaultdict(int)
cc = dict()
norm = dict()
ss = []
for _ in range(N):
xs = list(map(int, input().split()))
cnd = [tuple(xs[j:] + xs[:j]) for j in rang... |
p00057 The Number of Area | If you draw a few infinitely long straight lines on an infinitely wide plane, this plane will be divided into several areas. For example, if you draw a straight line, the plane will be divided into two areas. Even if you draw the same number of straight lines, the number of areas obtained will differ depending on how y... | ```python
while 1:
try:
n = int(input())
except:break
ans = (0.5 * n * n) + (0.5 * n) + 1
print(round(ans))
``` |
p00188 Search | "Search" is an operation to obtain the desired information from a large amount of information. Familiar examples include "finding your own exam number from a large number of exam numbers" when announcing your success, or "finding Taro Aizu's phone number" from your phone book. This search operation is also widely used ... | ```python
while True:
n = int(input())
if n == 0: break
a = [int(input()) for _ in range(n)]
k = int(input())
l, r, c = 0, n-1, 0
while l <= r:
c += 1
m = (l+r) >> 1
if k == a[m]:
break
elif k < a[m]:
r = m-1
else:
l = m... |
p00343 Sevens | There is "7 rows" in the game using playing cards. Here we consider a game that simplifies it. Arrange 7 using 13 cards with numbers 1 to 13 written on each. In the match, the game progresses as follows with only two players.
1. Place 7 cards in the "field".
2. Six remaining cards will be randomly distributed to the t... | ```python
n = int(input())
for i in range(n):
F = set(map(int, input().split()))
fl = min(F); fr = max(F)
G = {i for i in range(1, 14)} - F - {7}
gl = min(G); gr = max(G)
memo = {}
def dfs(s, t, u):
if (s, t, u) in memo:
return memo[s, t, u]
T = [G, F][u]
res... |
p00539 JOI Park | JOI Park
In preparation for the Olympic Games in IOI in 20XX, the JOI Park in IOI will be developed. There are N squares in JOI Park, and the squares are numbered from 1 to N. There are M roads connecting the squares, and the roads are numbered from 1 to M. The road i (1 ≤ i ≤ M) connects the square Ai and the square ... | ```python
from heapq import heappush, heappop
INF = 10 ** 20
n, m, c = map(int, input().split())
edges = [[] for _ in range(n)]
edges_dict = {}
d_cost = 0
for _ in range(m):
a, b, d = map(int, input().split())
a -= 1
b -= 1
edges[a].append((b, d))
edges[b].append((a, d))
edges_dict[(a, b)] = d
d_cost += ... |
p00701 Pile Up! | There are cubes of the same size and a simple robot named Masato. Initially, all cubes are on the floor. Masato can be instructed to pick up a cube and put it on another cube, to make piles of cubes. Each instruction is of the form `pick up cube A and put it on cube B (or on the floor).'
When he is to pick up a cube, ... | ```python
while(1):
m=int(input())
if m==0: break
#root, before, next, top, rank
A=[[i for i in range(m+1)],[0 for i in range(m+1)],[0 for i in range(m+1)],[i for i in range(m+1)],[1 for i in range(m+1)]]
while(1):
I,J=map(int, input().split())
if I==0: break
if I=... |
p00842 Network Mess | Gilbert is the network admin of Ginkgo company. His boss is mad about the messy network cables on the floor. He finally walked up to Gilbert and asked the lazy network admin to illustrate how computers and switches are connected. Since he is a programmer, he is very reluctant to move throughout the office and examine c... | ```python
def solve():
from sys import stdin
f_i = stdin
# function to update distance between switch and computer
def dfs(sw_id, prev, dist):
switch[sw_id].append(dist)
for next_sw in adj[sw_id]:
if next_sw != prev:
dfs(next_sw, sw_id, dist + 1)
... |
p01106 Folding a Ribbon | Folding a Ribbon
Think of repetitively folding a very long and thin ribbon. First, the ribbon is spread out from left to right, then it is creased at its center, and one half of the ribbon is laid over the other. You can either fold it from the left to the right, picking up the left end of the ribbon and laying it ove... | ```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def rdp_trace(n: int, i: int) -> list:
def loop(n: int, i: int) -> list:
if n == 1:
return []
if i <= n // 2:
rval = loop(n // 2, (n // 2) - i + 1)
rval.append(i)
return rval
else:
... |
p01721 Wave Attack | The fearless Ikta has finally hunted down the infamous Count Big Bridge! Count Bigbridge is now trapped in a rectangular room w meters wide and h meters deep, waiting for his end.
If you select a corner of the room and take the coordinate system so that the width direction is the x-axis and the depth direction is the ... | ```python
def solve():
w, h, v, t, x, y, p, q = map(int, input().split())
def count(a, b):
res = 0
C = v*t
ky = 0
while 1:
B = b + 2*h*ky
D = C**2 - (B - y)**2
if D < 0:
break
SQ = D**.5 + 1e-7
k0 = int((... |
p01859 Match Peas War | B: Nakajima, let's do that! --Match Peas War -
problem
Nakajima "Uhh ..."
Isono "Nakajima, are you okay?"
Nakajima "... I feel like I was having an unpleasant dream."
Isono "What kind of dream do you have?"
Nakajima "Dream to play infinitely"
Isono "I don't know what it means. Well, Nakajima, let's do that!"
Na... | ```python
li, ri = map(int, input().split())
ln, rn = map(int, input().split())
ISONO = True
NAKAJIMA = False
def search(li, ri, ln, rn, turn):
if li == None and ri == None:
return False
if ln == None and rn == None:
return True
if turn == ISONO:
ret = False
if li and ln:
ret = ret or sear... |
p02140 Gridgedge | Problem
There is a grid of $ R \ times C $ squares with $ (0, 0) $ in the upper left and $ (R-1, C-1) $ in the lower right. When you are in a square ($ e $, $ f $), from there $ (e + 1, f) $, $ (e-1, f) $, $ (e, f + 1) $, $ (e) , f-1) $, $ (e, 0) $, $ (e, C-1) $, $ (0, f) $, $ (R-1, f) $ can be moved at a cost of $ 1 ... | ```python
from collections import deque
R,C,ay,ax,by,bx = map(int,input().split())
MOD = INF = 10**9+7
dists = [[INF]*C for i in range(R)]
dists[ay][ax] = 0
ptns = [[0]*C for i in range(R)]
ptns[ay][ax] = 1
q = deque([(0,ax,ay)])
dxs = [1,0,-1,0]
dys = [0,1,0,-1]
ans_d = None
while q:
d,x,y = q.popleft()
if an... |
p02281 Tree Walk | Binary trees are defined recursively. A binary tree T is a structure defined on a finite set of nodes that either
* contains no nodes, or
* is composed of three disjoint sets of nodes:
- a root node.
- a binary tree called its left subtree.
- a binary tree called its right subtree.
Your task is to write a program ... | ```python
def preorder(tree, now):
if now == -1:
return []
else:
left = tree[now][0]
right = tree[now][1]
return [now] + preorder(tree, left) + preorder(tree, right)
def inorder(tree, now):
if now == -1:
return []
else:
left = tree[now][0]
right ... |
p02428 Enumeration of Subsets II | You are given a set $T$, which is a subset of $U$. The set $U$ consists of $0, 1, ... n-1$. Print all sets, each of which is a subset of $U$ and includes $T$ as a subset. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a ... | ```python
if __name__ == "__main__":
bit = int(input())
k, *E = map(lambda x: int(x), input().split())
m = sum(1 << e for e in E)
if (0 == m):
print(f"0:")
for d in range(1, 1 << bit):
if (d & m == m):
print(f"{d}: ", end="")
print(" ".join([str(elem) for ele... |
1007_B. 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())
... |
1030_B. Vasya and Cornfield | Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the fie... | ```python
n,d = map(int,input().split())
m = int(input())
x = []
y = []
k = 2*n-d
for i in range(m):
a = list(map(int,input().split()))
x.append(a[0])
y.append(a[1])
for i in range(m):
if x[i] >= 0 and x[i] <= n and y[i] >= 0 and y[i] <= n:
if y[i] <= d + x[i] and y[i] >= x[i] - d and y[i] >= -x[i]+d and y[... |
1075_A. The King's Race | On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column.
The white ki... | ```python
a=int(input())
n, m=map(int, input().split())
mh=min(abs(1-n),abs(1-m))
mb=min(abs(a-n),abs(a-m))
if mh<=mb:
print("White")
else:
print("Black")
``` |
1096_B. Substring Removal | You are given a string s of length n consisting only of lowercase Latin letters.
A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not.
Your task is to calculate the number of ways to remove exactly one substring from thi... | ```python
n=int(input())
s=input()
cntl=1
cntr=1
for i in range(1,len(s)):
if(s[0]==s[i]):
cntl+=1
else:
break
for i in range(n-2,-1,-1):
if(s[n-1]==s[i]):
cntr+=1
else:
break
if(s[0]!=s[n-1]):
ans=(cntl+cntr+1)%998244353
print(ans)
else:
ans=((cntl+1)*(cntr+1))%998244353
print(ans)
``` |
1117_C. Magic Ship | You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2).
You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds t... | ```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
from collections import deque
impo... |
1143_E. Lynyrd Skynyrd | Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the ... | ```python
# 注意array cache順序 QQ
from math import log, floor
"""
class RMQ:
'''
maximum version rmq
query: max([l, r])
'''
def __init__(self, nums):
size = floor(log(len(nums)) // log(2)) + 1
self.nums = [nums]
for i in range(1, size):
last = self.nu... |
1163_D. Mysterious Code | During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string c consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited wi... | ```python
import sys
from array import array # noqa: F401
from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def build_next_table(s):
s = '*' + s + '*'
n = len(s) - 1
kmp = [0] * (n + 1)
next_table = [[... |
1243_E. Sum Balance | Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbe... | ```python
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
k = int(input())
d = {}
aa = []
sa = []
for i in range(k):
ni, *a = map(int, input().split())
for ai in a:
d[ai] = i
aa.append(a)
sa.append(sum(a))
s = sum(sa)
if s%k != 0:
print("No")
exit()
s //= k
... |
1263_D. Secret Passwords | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters.
Hacker went home and started preparing to... | ```python
from sys import stdin
inp = lambda: stdin.readline().strip()
n = int(inp())
def dfs(visited, graph, node):
if not visited[node]:
visited[node] = True
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
adj = [set() for x in range(26)]
visited = [True]*26
for i in ... |
1304_B. Longest Palindrome | Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong lo... | ```python
n,m=map(int,input().split())
a=[input() for x in range(n)]
z=[]
p=[]
for x in range(n):
for y in range(x+1,n):
if a[x]==a[y][::-1]:
z.append((x,y))
if a[x]==a[x][::-1]:
p.append(x)
if x==n-1:
if a[x]==a[x][::-1]:
p.append(x)
ans=''
for x in z... |
1328_C. Ternary XOR | A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.
You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.
Let's define the ternary XOR operation ⊙ of two ternary n... | ```python
from sys import stdout, stdin
read = stdin.readline
write = stdout.write
t = int(read())
for _ in range(t):
n = int(read())
x = read()
a, b = ['1'], ['1']
a_gt_b = False
for d in x[1:-1]:
if d == '1':
if not a_gt_b:
a_gt_b = True
a.ap... |
1348_C. Phoenix and Distribution | Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and re... | ```python
import sys
input = sys.stdin.readline
'''
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
for CASES in range(int(input())):
sys.stdout.write(" ".join(map(str,ans))+"\n")
'''
inf = 100000000000000000 # 1e17
mod = 998244353
for CASES in range(int(inp... |
1369_A. FashionabLee | Lee is going to fashionably decorate his house for a party, using some regular convex polygons...
Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis a... | ```python
t= int(input())
for i in range (t):
g= int(input())
if(g%4==0):
print("YES")
else:
print("NO")
``` |
1413_C. Perform Easily | After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has 6 strings and an infinite number of frets numbered from 1. Fretting the fret number j on the i-th string produces the note a_{i} + j.
Tayuya wants to play a melody of n notes. Each note can be play... | ```python
import sys
input=sys.stdin.readline
a=list(map(int,input().split()))
a.sort()
n=int(input())
b=list(map(int,input().split()))
b.sort()
res=[]
for i in range(6):
for j in range(n):
res.append([b[j]-a[i],j])
res.sort()
ans=10**18
r=0
c=0
cnt=[0]*n
for l in range(n*6):
while c!=n and r<6*n:
... |
1455_C. Ping-pong | Alice and Bob play ping-pong with simplified rules.
During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return.
The one ... | ```python
import sys
import math
from collections import defaultdict,deque
input = sys.stdin.readline
def inar():
return [int(el) for el in input().split()]
def main():
t=int(input())
for _ in range(t):
alice,bob=inar()
print(alice-1,bob)
if __name__ == '__main__':
main()
``` |
1506_C. Double-ended Strings | You are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order:
* if |a| > 0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a_2 a_3 … a_n;
* if |a| > 0, delete the las... | ```python
rn=lambda:int(input())
rns=lambda:map(int,input().split())
rl=lambda:list(map(int,input().split()))
rs=lambda:input()
YN=lambda x:print('YES') if x else print('NO')
mod=10**9+7
for _ in range(rn()):
a=rs()
b=rs()
aset=set()
aset.add('')
for i in range(len(a)):
for j in range(i,len... |
152_B. Steps | One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple.
Vasya noticed that the yard is a rectangu... | ```python
n, m = [int(z) for z in input().split()]
x, y = [int(z) for z in input().split()]
k = int(input())
res = 0
i = 0
while i < k:
dx, dy = [int(z) for z in input().split()]
if dx == 0:
s = (m - y) // dy if dy > 0 else (1 - y) // dy
elif dy == 0:
s = (n - x) // dx if dx > 0 else (1 - x... |
160_D. Edges in MST | You are given a connected weighted undirected graph without any loops and multiple edges.
Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the... | ```python
import sys
from math import inf
from collections import defaultdict
class disjoinSet(object):
def __init__(self,n):
self.father = [x for x in range(0,n+1)]
self.rank = [0 for x in range(0,n+1)]
def setOf(self, x):
if(self.father[x] != x):
self.father[x] = sel... |
180_A. Defragmentation | In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to n. The disk has m recorded files, the i-th file occupies clusters with numbers ai, 1, ai, 2, ..., ai, ni. These clusters are not necessarily located consecuti... | ```python
import sys
n, m, *inp = map(int, sys.stdin.read().split())
inp.reverse()
f = [[0 for x in range(201)] for y in range(201)] #2D Array
c = [(0,0)]*201
f_size = [0]*201
def putData(f_id, s_id, c_id):
global f, c
f[f_id][s_id] = c_id
c[c_id] = (f_id, s_id)
for f_id in range(1, m+1):
f_size[... |
203_B. Game on Paper | One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game.
He took a checkered white square piece of paper, consisting of n × n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the p... | ```python
import math
from sys import stdin
from math import ceil
import sys
if __name__ == '__main__':
numbers = list(map(int, input().split()))
n = numbers[0]
m = numbers[1]
moves = [[0] * (n + 4) for _ in range(n + 4)]
for i in range(m):
listOfMoves = list(map(int, input().split()))
... |
228_A. Is your horseshoe on the other hoof? | Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | ```python
l=list(map(int,input().split()))
i=list(set(l))
print(abs(len(i)-len(l)))
``` |
251_D. Two Sets | Little Petya likes numbers a lot. Recently his mother has presented him a collection of n non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to g... | ```python
base = [-1] * 60
how = [-1] * 60
who = [-1] * 60
n = int(input())
arr = list(map(int, input().split()))
x = 0
for a in arr:
x ^= a
mapper = [-1] * 60
ind = 59
ind_start = bin(x).count('1') - 1
for bit in reversed(range(60)):
if (1 << bit) & x :
mapper[bit] = ind_start
ind_start -= ... |
29_B. Traffic Lights | A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on fo... | ```python
# n=int(input())
l,d,v,g,r=map(int,input().split())
z=d/v
y=(l-d)/v
temp=z
light=True
x=0
# print(z,y)
while(1):
if(x%2==0):
if(temp>=g):
temp-=g
light=False
else:
break
else:
if(temp>=r):
temp-=r
light=True
el... |
347_C. Alice and Bob | It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two di... | ```python
from sys import *
from math import *
from string import *
from operator import *
from functools import *
from fractions import *
from collections import *
setrecursionlimit(10**7)
dX= [-1, 1, 0, 0,-1, 1,-1, 1]
dY= [ 0, 0,-1, 1, 1,-1,-1, 1]
RI=lambda: list(map(int,input().split()))
RS=lambda: input().rstrip().... |
370_D. Broken Monitor | Innocentius has a problem — his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus.
Innocentius is touch-typing a program that pain... | ```python
#!/usr/bin/python3
def readln(): return list(map(int, input().split()))
import sys
def exit():
print(-1)
sys.exit()
n, m = readln()
mon = [list(input()) for _ in range(n)]
hor = [i for i in range(n) if mon[i] != ['.'] * m]
rmon = list(zip(*mon))
ver = [j for j in range(m) if rmon[j] != ('.',) * n]
m... |
392_A. 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, floor
def calc(n):
if n == 0:
return 1
# y = n
# x = 1
# c = 0
# while x - y < 0:
# if x ** 2 + y ** 2 <= n ** 2:
# c += 1
# x += 1
# continue
# if x ** 2 + y ** 2 > n ** 2:
# y -= 1
x = fl... |
415_B. Mashmokh and Tokens | Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of ... | ```python
def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return [str(x) for x in stdin.readline().split()]
from sys import stdin
from math import floor
n, a, b = arr_inp(1)
arr = a... |
464_A. 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
n, p = map(int, input().split())
s = list(ord(i) - 97 for i in input())
for i in range(n - 1, -1, -1):
for j in range(s[i] + 1, p):
if (i < 1 or j != s[i - 1]) and (i < 2 or j != s[i - 2]):
s[i] = j
for i in range(i + 1, n):
for j in range(p):
... |
510_D. Fox And Jumping | Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After app... | ```python
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
# from itertools import permutations,combinations
d... |
560_A. Currency System in Geraldion | A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of ea... | ```python
n=int(input())
l=list(map(int,input().split()));print(1 if 1 not in l else -1)
``` |
586_C. Gennady the Dentist | Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.
All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with... | ```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
n = int(input())
C = [list(map(int,input().split())) for i in range(0,n)]
ans = []
for i in range(n):
v, d, p = C[i]
if p >= 0:
count = 0
d0 = 0
for j in range(i + 1, n):
if C[j][2] >= 0:
C[j][2] -= m... |
608_D. Zuma | Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.
In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is ... | ```python
from sys import stdin
n=int(input())
s=list(map(int,stdin.readline().strip().split()))
dp=[[-1 for i in range(501)] for j in range(500)]
def sol(i,j):
if i>j:
return 0
if i==j:
return 1
if dp[i][j]!=-1:
return dp[i][j]
x=502
if s[i]==s[i+1]:
x=min(x,sol(i+2,... |
656_B. Scrambled | Btoh yuo adn yuor roomatme lhoate wianshg disehs, btu stlil sdmoeboy msut peorrfm tihs cohre dialy. Oen dya yuo decdie to idourtcne smoe syestm. Yuor rmmotaoe sstgegus teh fooniwllg dael. Yuo argee on tow arayrs of ientgres M adn R, nmebur upmicnog dyas (induiclng teh cunrret oen) wtih sicsescuve irnegets (teh ceurrnt ... | ```python
n = int(input())
m = list(map(int, input().split()))
r = list(map(int, input().split()))
days = 0
for day in range(1, 100001):
for index in range(n):
if day % m[index] == r[index]:
days += 1
break
print(days / 100000)
``` |
67_B. Restoration of the Permutation | Let A = {a1, a2, ..., an} be any permutation of the first n natural numbers {1, 2, ..., n}. You are given a positive integer k and another sequence B = {b1, b2, ..., bn}, where bi is the number of elements aj in A to the left of the element at = i such that aj ≥ (i + k).
For example, if n = 5, a possible A is {5, 1, 4... | ```python
s = input()
l = s.split()
n = int(l[0])
k = int(l[1])
s = input()
l = s.split()
b = [-1]
for i in range(1, n + 1):
b.append(int(l[i - 1]))
for i in range(1, n + 1):
j = 1
while b[j] != 0:
j += 1
b[j] -= 1
print(j, end = ' ')
for t in range(1, n + 1):
if j - k >=... |
702_B. Powers of Two | You are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x).
Input
The first line contains the single positive integer n (1 ≤ n ≤ 105) — the number of integers.
The second line contains n positive integers ... | ```python
# @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-08-20 23:46
# @url:https://codeforc.es/problemset/problem/702/B
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio
BUFSIZE = 8192
BUFSIZE = 8192... |
724_C. Ray Tracing | There are k sensors located in the rectangular room of size n × m meters. The i-th sensor is located at point (xi, yi). All sensors are located at distinct points strictly inside the rectangle.
Opposite corners of the room are located at points (0, 0) and (n, m). Walls of the room are parallel to coordinate axes.
At... | ```python
def main():
nx, my, k = list(map(int, input().strip().split()))
my *= 2
nx *= 2
diags = [[] for i in range(nx + my)]
answers = [-1] * k
for i in range(k):
x,y = list(map(int, input().strip().split()))
def add(x, y, i):
diag_index = nx + (y - x)
diags[diag_index].append( (x,y,i) )
add(x, ... |
746_C. Tram | The tram in Berland goes along a straight line from the point 0 to the point s and back, passing 1 meter per t1 seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points x = 0 and x = s.
Igor is at the point x1. He should reach the point... | ```python
def codeforces(max_point, start, finish, tram_speed, legs_speed,
tram_point, direction):
if tram_point == start:
time_to_start = 0
elif start > tram_point:
if direction == 1:
time_to_start = (start - tram_point) * tram_speed
else:
directio... |
769_C. Cycle In Maze | The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. In... | ```python
import math
from collections import deque
def main():
n, m, k = list(map(int, input().split()))
grid = ["" for _ in range(n)]
x, y = 0, 0
for i in range(n):
grid[i] = input()
if 'X' in grid[i]:
x, y = i, grid[i].index('X')
if k % 2 == 1:
print("IMPOSSIBLE")
return
dx = [1, 0, 0, -1]
dy ... |
793_C. Mice problem | Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them.
The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located i... | ```python
import math
n = int(input())
x1, y1, x2, y2 = map(int, input().split())
t1 = 0
t2 = math.inf
yes = True
for i in range(n):
x, y, vx, vy = map(int, input().split())
if vx == 0:
if x <= x1 or x >= x2:
yes = False
break
else:
tt1 = (x1-x)/vx
tt2 = (x2-x)/vx
tt1, tt2 = min(tt1,... |
85_A. Domino | We all know the problem about the number of ways one can tile a 2 × n field by 1 × 2 dominoes. You probably remember that it goes down to Fibonacci numbers. We will talk about some other problem below, there you also are going to deal with tiling a rectangular field with dominoes.
You are given a 4 × n rectangular fie... | ```python
def computeTiling(n):
if n == 1:
print("a\na\nf\nf")
return
for tiling in generateRowTilings(n):
print("".join(tiling))
def generateRowTilings(n):
for (rowNum, firstTile, pattern) in generateRowTilingPatterns(n):
yield makeRowTiling(rowNum, firstTile, pattern,... |
886_A. ACM ICPC | In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams.
After practice competition, participant number i got a score of ai. Team s... | ```python
a = list(map(int, input().split()))
summ = sum(a)
res = 'NO'
if summ % 2 != 1 :
summ //= 2
for i in range(4) :
for j in range(i + 1, 5) :
for k in range(j + 1, 6) :
if a[i] + a[j] + a[k] == summ :
res = 'YES'
print(res)
``` |
909_A. Generate Login | The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and ... | ```python
s=input().split(" ")
m=s[0]
j=s[1]
list=[]
for x in range(len(m)):
p=m[0:x+1]
p=p+j[0]
list.append(p)
list.sort()
print(list[0])
``` |
930_C. Teodor is not a liar! | Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge [1;m] segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor ... | ```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... |
958_D1. Hyperspace Jump (easy) | The Rebel fleet is on the run. It consists of m ships currently gathered around a single planet. Just a few seconds ago, the vastly more powerful Empire fleet has appeared in the same solar system, and the Rebels will need to escape into hyperspace. In order to spread the fleet, the captain of each ship has independent... | ```python
m = int(input())
esc = [eval(input()) for i in range(m)]
d = {i: 0 for i in esc}
for i in esc:
d[i] += 1
for i in esc:
print(d[i], end = ' ')
``` |
984_C. Finite or not? | You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction ... | ```python
from sys import stdin, stdout
n=int(stdin.readline())
s=''
for i in range(n):
p,q,b=map(int,input().split())
for i in range(6):
b=(b*b)%q
if((p*b)%q):
s+='Infinite\n'
else:
s+='Finite\n'
print(s)
``` |
p02571 AtCoder Beginner Contest 177 - Substring | Given are two strings S and T.
Let us change some of the characters in S so that T will be a substring of S.
At least how many characters do we need to change?
Here, a substring is a consecutive subsequence. For example, `xxx` is a substring of `yxxxy`, but not a substring of `xxyxx`.
Constraints
* The lengths of ... | ```python
s,t=open(0)
print(min(sum(x!=y for x,y in zip(s[i:],t[:-1]))for i in range(len(s)-len(t)+1)))
``` |
p02702 AtCoder Beginner Contest 164 - Multiple of 2019 | Given is a string S consisting of digits from `1` through `9`.
Find the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the following condition:
Condition: In base ten, the i-th through j-th characters of S form an integer that is a multiple of 2019.
Constraints
* 1 ≤ |S| ≤ 200000
* S is a string c... | ```python
s=input()[::-1]
ans=0
u=0
d=1
l=[0]*2019
l[0]=1
for i in map(int,s):
u=(u+(i*d)%2019)%2019
l[u]+=1
d=d*10%2019
for i in l:
ans+=i*(i-1)//2
print(ans)
``` |
p02831 AtCoder Beginner Contest 148 - Snack | Takahashi is organizing a party.
At the party, each guest will receive one or more snack pieces.
Takahashi predicts that the number of guests at this party will be A or B.
Find the minimum number of pieces that can be evenly distributed to the guests in both of the cases predicted.
We assume that a piece cannot be ... | ```python
import math
A,B=map(int,input().split())
print(int((A*B)/math.gcd(A,B)))
``` |
p03103 AtCoder Beginner Contest 121 - Energy Drink Collector | Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.
There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.
What is the minimum amount of money with which he can bu... | ```python
n,m = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(n)]
A.sort()
ans = 0
cnt = 0
for a in A:
tmp = min(m-cnt,a[1])
ans += tmp*a[0]
cnt+=tmp
if cnt >= m:
break
print(ans)
``` |
p03251 AtCoder Beginner Contest 110 - 1 Dimensional World's Tale | Our world is one-dimensional, and ruled by two empires called Empire A and Empire B.
The capital of Empire A is located at coordinate X, and that of Empire B is located at coordinate Y.
One day, Empire A becomes inclined to put the cities at coordinates x_1, x_2, ..., x_N under its control, and Empire B becomes incli... | ```python
N,M,X,Y=map(int,input().split())
x=list(map(int,input().split()))
y=list(map(int,input().split()))
if max(max(x),X)<min(min(y),Y):
print('No War')
else:
print("War")
``` |
p03404 AtCoder Regular Contest 093 - Grid Components | You are given two integers A and B.
Print a grid where each square is painted white or black that satisfies the following conditions, in the format specified in Output section:
* Let the size of the grid be h \times w (h vertical, w horizontal). Both h and w are at most 100.
* The set of the squares painted white is ... | ```python
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate
def read_ints():
return list(map(int, read().split()))
def read_a_int():
return int(read())
def read_tuple(H):
'''
H is number of rows
'''
ret = []
for _ in range(H):
ret.a... |
p03567 CODE FESTIVAL 2017 qual C - Can you get AC? | Snuke built an online judge to hold a programming contest.
When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring. (The judge can return any two-character substring of S.)
Determine whether the judge can return the ... | ```python
S = input()
for s, ns in zip(S, S[1:]):
if s + ns == "AC":
print("Yes")
exit()
print("No")
``` |
p03722 AtCoder Beginner Contest 061 - Score Attack | There is a directed graph with N vertices and M edges. The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i. We will play the following single-player game using this graph and a piece.
Initially, the piece is placed at vertex 1, and the score of the player is set to 0. The player can move t... | ```python
n, m = map(int, input().split())
abc = [list(map(int, input().split())) for _ in range(m)]
def bellman_ford(s, g):
dist = [float("inf")] * n
dist[s] = 0
negative = [False] * n
for i in range(2 * n):
for a, b, c in abc:
a -= 1
b -= 1
c = -c
if dist[b] > dist[a] + c:
dist[b] = dist[a] +... |
p04043 AtCoder Beginner Contest 042 - Iroha and Haiku (ABC Edition) | Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.
To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of... | ```python
print("YES" if [5,5,7] == sorted(list(map(int,input().split()))) else "NO")
``` |
p00124 League Match Score Sheet | There are league games and tournament games in sports competitions. In soccer league games, points are given to each of the wins, losses, and draws, and the rankings are competed based on the points. The points are win (3 points), negative (0 points), and draw (1 point), respectively.
Enter the number of teams and the... | ```python
b=False
while True:
n = int(input())
if n==0:break
d=dict()
if b:print()
b=True
for _ in range(n):
line = input().split()
tmp = int(line[1])*3+int(line[3]*1)
if tmp in d:
d[tmp].append(line[0])
else:
d[tmp] = []
d[tmp]... |
p00257 Making Sugoroku | Taro made a sugoroku so that everyone can play at the children's association event. In order to make the game interesting, I wrote instructions such as "advance 6" and "back 5" in some of the sugoroku squares other than "Furidashi" and "Agari". Turn the roulette wheel to advance as many times as you can, and if an inst... | ```python
while True:
m = int(input())
if not m:
break
n = int(input())
ds = [0] + [int(input()) for _ in range(n)] + [0]
g = [[] for _ in range(n+2)]
rg = [[] for _ in range(n+2)]
for i in range(n+2):
for j in range(min(n+1,i+1),min(n+1,i+m)+1):
j = max(0,min(n+... |
p00444 Change | problem
Taro often shop at JOI general stores. At JOI general stores, there are enough coins of 500 yen, 100 yen, 50 yen, 10 yen, 5 yen, and 1 yen, and we always pay the change so that the number of coins is the smallest. Create a program to find the number of coins included in the change you receive when Taro goes sh... | ```python
while True:
x = int(input())
if x == 0:
break
else:
x=1000-x
a=x//500
b=(x-500*a)//100
c=(x-(500*a+100*b))//50
d=(x-(500*a+100*b+50*c))//10
e=(x-(500*a+100*b+50*c+10*d))//5
f=(x-(500*a+100*b+50*c+10*d+5*e))//1
print(a+b+c+d+e+... |
p00909 Never Wait for Weights | In a laboratory, an assistant, Nathan Wada, is measuring weight differences between sample pieces pair by pair. He is using a balance because it can more precisely measure the weight difference between two samples than a spring scale when the samples have nearly the same weight.
He is occasionally asked the weight dif... | ```python
class Value_UnionFind():
def __init__(self,n):
self.par = [i for i in range(n)]
self.differ_weight = [0] * n
self.rank = [0] * n
def root(self,x):
if x == self.par[x]:
return x
r = self.root(self.par[x])
self.differ_weight[x] += self.differ... |
p01928 Matryoshka Doll | Matryoshka
Matryoshka is a famous Russian folk craft doll. Matryoshka can be divided into upper and lower parts, and when opened, there is another smaller doll inside. The nesting structure is such that when the small doll that appears is opened, a smaller doll is contained.
<image>
You found an unusually shaped ma... | ```python
import heapq
class MinCostFlow:
class Edge:
def __init__(self,to,cap,rev,cost):
self.to = to
self.cap = cap
self.rev = rev
self.cost = cost
def __init__(self,n,inf=1000000007):
self.n = n
self.inf = inf
self.e = [[] for ... |
p02208 Cutlet Sandwich | Cutlet Sandwich
In some worlds, there are $ X $ types of "sandwiches", $ Y $ types of "cutlets", and $ Z $ types of "curry" foods.
There is a $ N $ type of "cutlet sandwich" in this world, and the $ i $ type of cutlet sandwich is made from the $ A_i $ type of sand and the $ B_i $ type of cutlet.
There is also a $ M ... | ```python
from collections import deque
x,y,z,n,m,s,t=map(int,input().split())
g=[[]for _ in range(x+y+z)]
for i in range(n):
a,b=map(int,input().split())
g[a-1].append(b+x-1)
g[b+x-1].append(a-1)
if i==s-1:
p,q=a-1,b+x-1
for j in range(m):
a,b=map(int, input().split())
g[a+x-1].append(b+x+y-1)
g[b+x+... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.