name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
600_A. Extract Numbers | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.
You ... | ```python
def main():
str = input().replace(';', ',')
input_list = str.split(',')
def pred(x):
return x.isdigit() and (x[0] != '0' or len(x) == 1)
lA = list(filter(pred, input_list))
lB = list(filter(lambda x: not pred(x), input_list))
print('"{}"'.format(','.join(lA))) if lA else print... |
622_D. Optimal Number Permutation | You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.
Let number i be in positions xi, yi (xi < yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the valu... | ```python
n = int(input())
A = [i for i in range(1, n+1, 2)]
B = [i for i in range(n-2 if n%2 else n-1, 0, -2)]
C = [i for i in range(2, n+1, 2)]
D = [i for i in range(n-1 if n%2 else n-2, 0, -2)]
ans = ' '.join(map(str, A+B+C+D+[n]))
print(ans)
``` |
670_F. Restore a Number | Vasya decided to pass a very large integer n to Kate. First, he wrote that number as a string, then he appended to the right integer k — the number of digits in n.
Magically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty substr... | ```python
a = input()
b = input()
d = [0] * 10
n = 0
for j in range(1000100):
t = str(j)
if len(t) + j == len(a):
n = j
for x in str(n):
d[ord(x) - ord('0')] -= 1
for x in a:
d[ord(x) - ord('0')] += 1
for x in b:
d[ord(x) - ord('0')] -= 1
if sum(d)==0:
print(b)
else:
A = []
B = [... |
696_C. PLEASE | As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup.
<image>
Then at one turn Barney swaps the cup in the midd... | ```python
k = int(input())
n = list(map(int, input().split()))
for i in range(k):
n[i] = bin(n[i])
n[i] = n[i][2:]
magic = 1000000007
def par(s):
if s[-1] == '0':
return True
else:
return False
def mod_pow(x, s, p):
ans = 1
for i in range(len(s)):
if s[i] == '1':
... |
717_D. Dexterina’s Lab | Dexterina and Womandark have been arch-rivals since they’ve known each other. Since both are super-intelligent teenage girls, they’ve always been trying to solve their disputes in a peaceful and nonviolent way. After god knows how many different challenges they’ve given to one another, their score is equal and they’re ... | ```python
import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
n,x=map(int,input().split())
def mult(a,b):
# compute a*b
c=[0]*128
for i in range(128):
for j in range(128):
c[i^j]+=a[i]*b[j]
return c
def quickpow(a,b):
# compute a**b
if b==1:
return a
... |
761_E. Dasha and Puzzle | Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve.
<image>
The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices.
The puzz... | ```python
n = int(input())
adj = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = map(int, input().split())
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
from collections import deque
def bfs(v):
vis = [i == v for i in range(n)]
paths = deque([[v]])
while paths:
p = paths.popl... |
784_G. BF Calculator | In this problem you will write a simple generator of Brainfuck (<https://en.wikipedia.org/wiki/Brainfuck>) calculators.
You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, when executed, will print the result of eval... | ```python
for n in str(eval(input())):
for _ in range(ord(n)):
print('+',sep='',end='')
print('.>')
``` |
831_A. Unimodal Array | Array of integers is unimodal, if:
* it is strictly increasing in the beginning;
* after that it is constant;
* after that it is strictly decreasing.
The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent.
For example, the following th... | ```python
n=int(input())
arr=list(map(int,input().split()))
s,t,p=0,0,0
for i in range(1,n) :
if arr[i] < arr[i - 1]: s = 1
elif arr[i]==arr[i-1] and s: t=1
elif arr[i]==arr[i-1] and not s: p=1
if arr[i]>arr[i-1] and (s or p):t=1
if t: print("NO")
else : print("YES")
``` |
852_B. Neural Network country | Due to the recent popularity of the Deep learning new countries are starting to look like Neural Networks. That is, the countries are being built deep with many layers, each layer possibly having many cities. They also have one entry, and one exit point.
There are exactly L layers, each having N cities. Let us look at... | ```python
from sys import stdin
input = stdin.readline
def main():
mod = 10**9 + 7
n,l,m = map(int,input().split())
ar = [0 for i in range(m)]
ar3 = [0 for i in range(m)]
def f(num):
return int(num) % m
def f2(num):
return num % 1000000007
ai1 = list(map(f,input().spli... |
876_C. Classroom Watch | Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain posi... | ```python
import sys
text = sys.stdin.read().strip()
n = int(text)
q = lambda x: sum([int(b) for b in str(x)])
e = []
for i in range(max(0, n-81), n):
if i + q(i) == n:
e.append(i)
print(len(e))
for z in e:
print(z)
``` |
8_C. Looking for Order | Girl Lena likes it when everything is in order, and looks for order everywhere. Once she was getting ready for the University and noticed that the room was in a mess — all the objects from her handbag were thrown about the room. Of course, she wanted to put them back into her handbag. The problem is that the girl canno... | ```python
import sys
def main():
BITS = [1 << sh for sh in range(24)]
B2N = {v: u for u, v in enumerate(BITS)}
def getPt():
return tuple(map(int, input().split()))
def dist(ptA, ptB):
return sum(((u - v) ** 2 for u, v in zip(ptA, ptB)))
def getBits(val):
return tuple(fil... |
922_B. Magic Forest | Imp is in a magic forest, where xorangles grow (wut?)
<image>
A xorangle of order n is such a non-degenerate triangle, that lengths of its sides are integers not exceeding n, and the xor-sum of the lengths is equal to zero. Imp has to count the number of distinct xorangles of order n to get out of the forest.
Forma... | ```python
import math
n = int(input())
ans = 0
for a in range(1, n+1):
for b in range(a, n+1):
c= a^b
if c < b or c > n:
continue
if a+b > c:
ans += 1
print(ans)
``` |
94_C. Frames | Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in ... | ```python
import math
n,m,a,b=map(int,input().split())
if (a-1)//m==(b-1)//m:
print(1)
elif (a-1)%m==0 and b%m==0:
print(1)
elif (a-1)%m==0 and b==n or m==1:
print(1)
elif (a-1)%m==0 or b%m==0 or b==n:
print(2)
elif abs((a-1)//m - (b-1)//m)==1 or m==2:
print(2)
elif (a-1)%m==b%m:
print(2)
else:... |
978_A. Remove Duplicates | Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements.
Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.
Input
The first line contains a single integer n (1 ≤ n ≤ ... | ```python
n = int(input())
A = list(map(int, input().split()))
from collections import Counter
C = Counter(A)
res = []
for a in A:
C[a] -= 1
if C[a] == 0:
res.append(a)
print(len(res))
print(*res)
``` |
p02657 AtCoder Beginner Contest 169 - Multiplication 1 | Compute A \times B.
Constraints
* 1 \leq A \leq 100
* 1 \leq B \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B
Output
Print the value A \times B as an integer.
Examples
Input
2 5
Output
10
Input
100 100
Output
10000 | ```python
a, b = [int(_) for _ in input().split()]
print(a*b)
``` |
p02786 AtCoder Beginner Contest 153 - Caracal vs Monster | Caracal is fighting with a monster.
The health of the monster is H.
Caracal can attack by choosing one monster. When a monster is attacked, depending on that monster's health, the following happens:
* If the monster's health is 1, it drops to 0.
* If the monster's health, X, is greater than 1, that monster disappear... | ```python
h = int(input())
ans = 2 ** (len(bin(h))-2) - 1
print(ans)
``` |
p02922 AtCoder Beginner Contest 139 - Power Socket | Takahashi's house has only one socket.
Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.
One power strip with A sockets can extend one empty socket into A empty sockets.
Find the minimum number of power strips required.
Constraints
* All values in inp... | ```python
a, b = map(int, input().split())
ans =-(-(b-a)//(a-1))+1
print(ans)
``` |
p03057 AtCoder Grand Contest 033 - Go around a Circle | Consider a circle whose perimeter is divided by N points into N arcs of equal length, and each of the arcs is painted red or blue. Such a circle is said to generate a string S from every point when the following condition is satisfied:
* We will arbitrarily choose one of the N points on the perimeter and place a piece... | ```python
"""
https://atcoder.jp/contests/agc033/tasks/agc033_e
Sの1文字目をRとしてよい
RB から始まる場合 → 全部交互以外無理(Nが奇数なら0)
RRB から始まる場合 → Rは3連で置けば可能…
R*X + B*Y + R*Z …
とつながっていく
どこからスタートしても、RだけをX回移動したときにBの隣に来なくてはいけない
Rの長さが1なら可能
R*?,B,R*?,…
でつながっていく
最初のRがX個連続の時
片方の端との距離がX-2tでなくてはならない
Xが偶数の時、Rの連続長さはX+1以下の奇数
Xが奇数の時、端からスタートした奴は反対... |
p03201 AtCoder Grand Contest 029 - Powers of two | Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i. He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2. Note that a ball cannot belong to multiple pairs. Find the maximum possible number of pai... | ```python
from collections import Counter
N = int(input())
As = list(map(int, input().split()))
cnt = Counter(As)
As.sort(reverse=True)
Ps = [2]
for i in range(29):
Ps.append(Ps[-1] * 2)
ans = 0
for A in As:
if cnt[A] <= 0: continue
cnt[A] -= 1
while Ps[-1] > 2 * A:
Ps.pop()
if cnt[Ps[... |
p03348 AtCoder Grand Contest 024 - Isomorphism Freak | Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees.
Also, the colorfulness of G is defined as the minimum possible number of different colors used ... | ```python
import sys
input = sys.stdin.readline
INF = (1<<60)
N = int(input())
graph = [[] for _ in range(N)]
Edges = []
for _ in range(N-1):
a, b = map(int, input().split())
graph[a-1].append(b-1)
graph[b-1].append(a-1)
Edges.append((a-1, b-1))
def bfs(s, noback):
q = [s]
D = [-1]*N
D[s]... |
p03508 Code Festival Team Relay (Parallel) - Shock | You are given an undirected graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges.
You can repeatedly perform the operation of adding an edge between two vertices. However, G must not h... | ```python
from collections import deque
N,M = map(int,input().split())
es = [[] for i in range(N)]
for i in range(M):
a,b = map(lambda x:int(x)-1,input().split())
es[a].append(b)
es[b].append(a)
a = b = 1
visited = [1,1] + [0]*(N-2)
q = deque([0])
while q:
fr = q.popleft()
for to in es[fr]:
if visited[t... |
p03669 AtCoder Grand Contest 017 - Jigsaw | We have N irregular jigsaw pieces. Each piece is composed of three rectangular parts of width 1 and various heights joined together. More specifically:
* The i-th piece is a part of height H, with another part of height A_i joined to the left, and yet another part of height B_i joined to the right, as shown below. Her... | ```python
import sys
from collections import Counter
# sys.stdin = open('e1.in')
def read_int_list():
return list(map(int, input().split()))
def read_int():
return int(input())
def read_str_list():
return input().split()
def read_str():
return input()
total_in = 0
total_out = 0
def solve():... |
p00079 Area of Polygon | Write a program that reads the coordinates of the vertices of a convex n-sided polygon (a polygon whose internal angles are less than 180 degrees, that is, a polygon that is not dented) and outputs its area. The vertices are named Vertex 1, Vertex 2, Vertex 3, ... Vertex n according to the order of edge connections.
H... | ```python
i = 0
x = []
y = []
while 1:
try:
a,b = map(float,input().split(","))
x.append(a)
y.append(b)
except EOFError:
break
S = 0
for i in range(len(x)-2):
a = ((x[0]-x[i+1]) ** 2 + (y[0]-y[i+1]) ** 2) ** 0.5
b = ((x[0]-x[i+2]) ** 2 + (y[0]-y[i+2]) ** 2) ** 0.5
c ... |
p00211 Jogging | At Akabeko Elementary School, all the students participate in a slightly unusual jogging. Students run their own lap courses at their own pace. After going around each of your courses, you will be returned to elementary school. How many laps do they all meet at the same time in elementary school after they all start el... | ```python
from fractions import gcd
from functools import reduce
from sys import stdin
def lcm_base(x, y):
return (x * y) // gcd(x, y)
def lcm(*numbers):
return reduce(lcm_base, numbers, 1)
def lcm_list(numbers):
return reduce(lcm_base, numbers, 1)
while(True):
n = int(stdin.readline())
if not n... |
p00588 Extraordinary Girl I | She is an extraordinary girl. She works for a library. Since she is young and cute, she is forced to do a lot of laborious jobs. The most annoying job for her is to put returned books into shelves, carrying them by a cart. The cart is large enough to carry many books, but too heavy for her. Since she is delicate, she w... | ```python
# AOJ 1002: Extraordinary Girl I
# Python3 2018.7.5 bal4u
import sys
from sys import stdin
input = stdin.readline
INF = 0x7fffffff
cost = ((((0,3),(1,3)),((1,2),(1,2)),((2,2),(2,2))),
(((1,2),(1,2)),((0,1),(1,2)),((1,1),(2,2))),
(((2,2),(2,2)),((1,1),(2,2)),((0,1),(3,3))))
for cno in range(int(in... |
p00725 Curling 2 | On Planet MM-21, after their Olympic games this year, curling is getting popular. But the rules are somewhat different from ours. The game is played on an ice game board on which a square mesh is marked. They use only a single stone. The purpose of the game is to lead the stone from the start to the goal with the minim... | ```python
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
N_MOVE = 4
EMPTY = 0
ROCK = 1
START = 2
GOAL = 3
INF = 100000
def in_field(field, x, y):
return y >=0 and y < len(field) and x >= 0 and x< len(field[0])
def move_to_rock(field, x, y, direction):
while(True):
x += dx[direction]
y += dy[directio... |
p00865 Expected Allowance | Hideyuki is allowed by his father Ujisato some 1000 yen bills every month for his pocket money. In the first day of every month, the number of bills is decided as follows. Ujisato prepares n pieces of m-sided dice and declares the cutback k. Hideyuki rolls these dice. The number of bills given is the sum of the spots o... | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
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... |
p01128 Railroad Conflict | Nate U. Smith runs a railroad company in a metropolitan area. In addition to his railroad company, there are rival railroad companies in this metropolitan area. The two companies are in a competitive relationship with each other.
In this metropolitan area, all lines are routed by the line segment connecting the statio... | ```python
m = int(input())
while m:
m -= 1
ax, ay, bx, by = map(int, input().split())
n = int(input())
dx, dy = bx - ax, by - ay
intersections = set()
while n:
n -= 1
sx, sy, tx, ty, o, l = map(int, input().split())
tdx, tdy = tx - sx, ty - sy
asx, asy = sx - ax, ... |
p01267 Luck Manipulator | Nathan O. Davis is trying to capture a game and struggling to get a very rare item. This rare item can be obtained by arranging special patterns in a row on a casino slot machine. The slot machine has N reels, and pressing the button once stops the currently rotating leftmost reel. Therefore, you need to press the butt... | ```python
def calc(A, B, C, X):
return (A * X + B) % C
while True:
N, A, B, C, X = map(int, input().split())
if N == 0 and A == 0 and B == 0 and C == 0 and X == 0:
break
Y = list(map(int, input().split()))
flame = 0
while True:
if flame > 10000:
print(-1)
... |
p01437 Infinity Maze | Dr. Fukuoka has placed a simple robot in a two-dimensional maze. It moves within the maze and never goes out of the maze as there is no exit.
The maze is made up of H × W grid cells as depicted below. The upper side of the maze faces north. Consequently, the right, lower and left sides face east, south and west respec... | ```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 ... |
p01743 Clique Coloring | There is a complete graph of m vertices. Initially, the edges of the complete graph are uncolored. Sunuke did the following for each i (1 ≤ i ≤ n): Select ai vertices from the complete graph and color all edges connecting the selected vertices with color i. None of the sides were painted in multiple colors. Find the mi... | ```python
N = int(input())
A = [int(input()) for i in range(N)]
INF = 10**18
N2 = 2**N
def dfs(i, D):
if i == N:
return sum(D)
b = 1 << i
a = A[i]
def sel(j, state, u):
if j == N2:
D2 = D[:]
for e in u:
D2[e] -= 1
D2[e | b] += 1
... |
p01883 Parentheses | Example
Input
1
Output
)( | ```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 ... |
p02020 Tea Party | F: Tea Party
Yun decided to hold a tea party at the company.
The shop sells $ N $ sets of bread, each containing $ A_1, A_2, A_3, \ dots, A_N $.
Yun decided to make a sandwich by combining two breads into a pair.
Yun-san is very careful, so I want to make sure that I don't have any leftover bread.
Calculate how ma... | ```python
N = int(input())
A = list(map(int, input().split()))
oc = 0
mi = 1e9
for a in A:
if a % 2:
oc += 1
mi = min(mi, a)
print((sum(A) - [0, mi][oc % 2]) // 2)
``` |
p02162 AOJ50M | Problem
Alice and Bob are competing in the 50m dash.
However, in this world, the higher the AOJ rate is, the better, so the higher the AOJ rate wins.
If there is no AOJ rate on either side, there is no comparison, so there is no choice but to compete in the 50m sprint time. In this case, the one with the shorter time ... | ```python
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
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 in sys.stdin.readline(... |
p02303 Closest Pair | For given n points in metric space, find the distance of the closest points.
Constraints
* 2 ≤ n ≤ 100,000
* -100 ≤ x, y ≤ 100
Input
n
x0 y0
x1 y1
:
xn-1 yn-1
The first integer n is the number of points.
In the following n lines, the coordinate of the i-th point is given by two real numbers xi and yi. Each valu... | ```python
import sys
from operator import itemgetter
from itertools import permutations
from math import sqrt
def solve(a: list):
length = len(a)
if length <= 3:
return min(sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2) for p1, p2 in permutations(a, 2))
x_set_len = len(set(x for (x, _) in a))
axis = ... |
p02450 Permutation Enumeration | For given an integer $n$, print all permutations of $\\{1, 2, ..., n\\}$ in lexicographic order.
Constraints
* $1 \leq n \leq 9$
Input
An integer $n$ is given in a line.
Output
Print each permutation in a line in order. Separate adjacency elements by a space character.
Examples
Input
2
Output
1 2
2 1
Inpu... | ```python
from itertools import permutations
import sys
write = sys.stdout.write
N = int(sys.stdin.readline())
for p in permutations(map(str, range(1, N + 1)), r = N):
write(" ".join(p))
write("\n")
``` |
1030_D. Vasya and Triangle | Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutio... | ```python
# import math
n, m, k = [int(x) for x in input().split()]
a = n
b = k
if (2 * n * m) % k != 0:
print("no")
else:
c = a % b
while (c != 0):
a = b
b = c
c = a % b
# print(b)
# b is GCD
if b == 1:
x = n
y = 2 * m // k
else:
if b != k:
x = n // b
y = 2 * m // (k // b)
else:
x = 2 * ... |
1053_B. Vasya and Good Sequences | Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 10... | ```python
import os
import sys
from io import BytesIO, IOBase
# region fastio
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" not in file.mode
self.write = self... |
1075_C. The Tower is Going Home | On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Ever... | ```python
import bisect
n, m = map(int, input().split())
ar1 = [1] + [int(input()) for _ in range(n)]
ar1.append(10 ** 9)
ar1.sort()
ar2 = [list(map(int, input().split())) for _ in range(m)]
kek = list()
for x in ar2:
j1 = bisect.bisect_left(ar1, x[0])
j2 = bisect.bisect_right(ar1, x[1])
if x[0] == 1:
... |
1096_D. Easy Problem | Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length n consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaa... | ```python
_ = input()
s = input()
a = list(map(int, input().split()))
hard = "hard"
dp = [0]*4
for i in range(len(s)):
if s[i] == hard[0]:
dp[0] += a[i]
for j in range(1, 4):
if s[i] == hard[j]:
# If same letter, either leave as-is (extend prefix) or remove it
dp[j] = m... |
1117_E. Decypher the String | This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You m... | ```python
from itertools import chain, cycle, islice, repeat
from operator import itemgetter
d = 26
a = ord('a')
t = input()
n = len(t)
p = [0]*n
for b in (d ** 2, d, 1):
if n >= b:
q = (repeat(chr(a + i), b) for i in range(d))
q = chain.from_iterable(q)
q = cycle(q)
q = islice(q, ... |
1144_A. Diverse Strings | A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are n... | ```python
import string
alphabet = string.ascii_lowercase
n = int(input())
for i in range(n):
s = list(input())
if len(s) > 26 or len(s) > len(set(s)):
print("No")
else:
s.sort()
ind = alphabet.index(s[0])
if alphabet[ind+len(s)-1] == s[-1]:
print("Yes")
else:
print("No")
``` |
1184_B2. The Doctor Meets Vader (Medium) | Thanks to the Doctor's help, the rebels managed to steal enough gold to launch a full-scale attack on the Empire! However, Darth Vader is looking for revenge and wants to take back his gold.
The rebels have hidden the gold in various bases throughout the galaxy. Darth Vader and the Empire are looking to send out their... | ```python
def naiveSolve():
return
def floyd_warshall(n, edges):
dist = [[0 if i == j else float("inf") for i in range(n)] for j in range(n)]
# dist = [[float("inf") for i in range(n)] for j in range(n)] # if nodes are not directly connected to themselves
# pred = [[None] * n for _ in r... |
1202_B. You Are Given a Decimal String... | Suppose you have a special x-y-counter. This counter can store some value as a decimal number; at first, the counter has value 0.
The counter performs the following algorithm: it prints its lowest digit and, after that, adds either x or y to its value. So all sequences this counter generates are starting from 0. For ... | ```python
from collections import*
s=input()
c=Counter((ord(y)-ord(x))%10for x,y in zip(s,s[1:]))
for i in range(100):
a = [-1] * 10
for j in range(1, 11):
for k in range(j+1):
x = ((j - k) * (i//10) + k * (i%10)) % 10
if a[x] == -1:
a[x] = j-1
z = 0
for x in c:
if a[x] == -1:
z = -1
break
els... |
1244_B. Rooms and Staircases | Nikolay lives in a two-storied house. There are n rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between 1 and n).
If Nikolay is currently in some room, he c... | ```python
def solve(n, s):
is_stairs = [s[x] == '1' for x in range(n)]
if not any(is_stairs):
return n
if is_stairs[0] or is_stairs[-1]:
return n * 2
else:
min_idx = max_idx = None
for i in range(n):
if not is_stairs[i]:
continue
if not min_idx:
min_idx = i
max_idx = i
return max(max_idx... |
1285_B. Just Eat It! | Today, Yasser and Adel are at the shop buying cupcakes. There are n cupcake types, arranged from 1 to n on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type i is an integer a_i. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.
Yasser, ... | ```python
t = int(input())
def max_subarray(arr):
max_ending = max_current = arr[0]
for i in arr[1:]:
max_ending = max(i, max_ending + i)
max_current = max(max_current, max_ending)
return max_current
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
if ma... |
1304_D. Shortest and Longest LIS | Gildong recently learned how to find the [longest increasing subsequence](https://en.wikipedia.org/wiki/Longest_increasing_subsequence) (LIS) in O(nlog{n}) time for a sequence of length n. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though the... | ```python
def main():
t=int(input())
allans=[]
for _ in range(t):
n,s=input().split()
n=int(n)
s=s+'$'
seq=[] # [isIncreasing,length]
prev=None
l=0
for c in s:
if c!=prev:
if l>0: # not first
... |
1328_E. Tree Queries | You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there ... | ```python
# verified: ABC014-D
# calculate LCA O(logN) for each query
# kprev[k][i]: 2^k parent of node i
# if there is no node returns "None"
# Depth[i]: Depth of node i from rootNode
class Doubling():
def __init__(self, graph, rootNode=0):
self.graph = graph
self.N = len(graph)
self.Log... |
1348_E. Phoenix and Berries | Phoenix is picking berries in his backyard. There are n shrubs, and each shrub has a_i red berries and b_i blue berries.
Each basket can contain k berries. But, Phoenix has decided that each basket may only contain berries from the same shrub or berries of the same color (red or blue). In other words, all berries in a... | ```python
n,k=map(int,input().split())
totA=0
totB=0
A=[0]
B=[0]
dp=[]
for i in range(n+1):
h=[]
for j in range(k):
h.append(False)
dp.append(h)
dp[0][0]=True
for i in range(n):
a,b=map(int,input().split())
A.append(a)
B.append(b)
totA+=a
totB+=b
for i in range(1,n+1):
... |
1369_C. RationalLee | Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought n integers, now it's time to distribute them between his friends rationally...
Lee has n integers a_1, a_2, …, a_n in his backpack and he has k friends. Lee would like to distribute all integers in his backpack betwe... | ```python
import sys
input = lambda:sys.stdin.readline().strip()
t = int(input())
while t:
t-=1
n,k = map(int,input().split())
a = list(map(int,input().split()))
w = list(map(int,input().split()))
adj = [[] for _ in range(k)]
a.sort()
w.sort()
i = 0
for i in range(k):
adj[i]... |
1391_B. Fix You | Consider a conveyor belt represented using a grid consisting of n rows and m columns. The cell in the i-th row from the top and the j-th column from the left is labelled (i,j).
Every cell, except (n,m), has a direction R (Right) or D (Down) assigned to it. If the cell (i,j) is assigned direction R, any luggage kept o... | ```python
for _ in range(int(input())):
n,m=map(int,input().split())
a,result=[],0
for i in range(n):
a.append(input())
for i in range(n):
if i==n-1:
for k in range(m):
if a[n-1][k]=='D':
a[n-1]=a[i][:k]+'R'+a[i][k+1:]
r... |
1413_E. Solo mid Oracle | Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the ... | ```python
# region fastio # from https://codeforces.com/contest/1333/submission/75948789
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.BytesIO()
self.writable = "x" in file.mode or "r" not ... |
1455_E. Four Points | You are given four different integer points p_1, p_2, p_3 and p_4 on XY grid.
In one step you can choose one of the points p_i and move it in one of four directions by one. In other words, if you have chosen point p_i = (x, y) you can move it to (x, y + 1), (x, y - 1), (x + 1, y) or (x - 1, y).
Your goal to move poin... | ```python
import sys,os,io
input = sys.stdin.readline
#input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from random import *
T = int(input())
ans = [0]*T
for t in range(T):
X,Y = [0]*4,[0]*4
A = [0]*4
for i in range(4):
X[i],Y[i] = map(int, input().split())
# X[i], Y[i] = choices(range(1,11),k=... |
147_A. Punctuation | You are given a text that consists of lowercase Latin letters, spaces and punctuation marks (dot, comma, exclamation mark and question mark). A word is defined as a sequence of consecutive Latin letters.
Your task is to add spaces to the text by the following rules:
* if there is no punctuation mark between two wor... | ```python
import re
s = input()+"a"
s = re.sub('\s+', ' ', s)
r = '.,?!'
for i in r:
t = s.split(i)
s = ""
for j in t:
s += j.strip() + i + " "
s = s[:-2]
print(s[:-1])
``` |
1506_E. Restoring the Permutation | A permutation is a sequence of n integers from 1 to n, in which all numbers occur exactly once. For example, [1], [3, 5, 2, 1, 4], [1, 3, 2] are permutations, and [2, 3, 2], [4, 3, 1], [0] are not.
Polycarp was presented with a permutation p of numbers from 1 to n. However, when Polycarp came home, he noticed that in ... | ```python
import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range (t):
n = int(input())
a = [int(i) for i in input().split()]
vis = [0]*(n+1)
vis[a[0]]=1
for i in range (1,n):
if a[i]!=a[i-1]:
vis[a[i]]=1
mini = [a[0]]
... |
161_A. Dress'em in Vests! | The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line.
The Two-dimensional kingdom has a regular army of n people. Each soldier registered himse... | ```python
n, m, x, y = map(int, input().split())
a_n = [i for i in map(int, input().split())]
b_m = [i for i in map(int, input().split())]
count = 0
result = []
i = 0
j = 0
while j < m and i < n:
if b_m[j] > a_n[i] + y:
i += 1
elif b_m[j] < a_n[i] - x:
j += 1
else:
count += 1
... |
180_C. Letter | Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase.
Patrick believes that a message is fancy if any uppercase letter stands to... | ```python
import os
import sys
from io import BytesIO, IOBase
def main():
import bisect
import math
# import itertools
# import heapq
# from queue import PriorityQueue, LifoQueue, SimpleQueue
# import sys.stdout.flush() use for interactive problems
alpha = 'abcdefghijklmnopqrstuvwxyz'
... |
203_D. Hit Ball | When Valera was playing football on a stadium, it suddenly began to rain. Valera hid in the corridor under the grandstand not to get wet. However, the desire to play was so great that he decided to train his hitting the ball right in this corridor. Valera went back far enough, put the ball and hit it. The ball bounced ... | ```python
from fractions import Fraction
from math import inf
a, b, m = map(int, input().split(' '))
x, y, z = map(int, input().split(' '))
cx, cy, cz = Fraction(a / 2), Fraction(m), Fraction(0)
while cy > 0:
if cx == 0:
x = abs(x)
elif cx == a:
x = -abs(x)
if cz == 0:
z = abs(z)... |
252_A. Little Xor | Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.
The ... | ```python
import itertools
import functools
def allSubArrays(xs):
n = len(xs)
indices = list(range(n+1))
for i,j in itertools.combinations(indices,2):
yield xs[i:j]
n=int(input())
my_list=list(map(int,input().split(" ")))
list_=list(allSubArrays(my_list))
for i in range(len(list_)):
list_[i]=fun... |
277_B. Set of Points | Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of n points with the convexity of exactly m. Your set of points should not contain three points that lie on a straight line.
Input
The single line contains two integers n and m... | ```python
def f(x):
return int(x * x + 1e7)
def g(x):
return -f(x)
n, m = map(int, input().split())
if(m == 3):
if(n == 3):
print('0 0')
print('1 0')
print('0 1')
elif(n == 4):
print('0 0')
print('1 1')
print('10000 0')
print('0 10000')
... |
29_D. Ant on the Tree | Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.
An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of ver... | ```python
n = int(input())
adj = [[] for i in range(n)]
adj2 = [[] for i in range(n)]
for i in range(n-1):
u,v = map(int,input().split())
adj[u-1].append(v-1)
adj[v-1].append(u-1)
leaf = {}
a = list(map(int,input().split()))
for i in range(len(a)):
leaf[a[i]-1] = i
inf = 200000
def dfs1(v,frm,adj2):
... |
371_A. K-Periodic Array | This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2.
Array a is k-period if its length is divisible by k and there is such array b of length k, that a is represented by array b written exactly <image> times consecutively. In other words, array a is k-periodic, if it has period... | ```python
n, k = map(int, input().split())
a = list(map(int, input().split()))
print(sum(min(x.count(1), x.count(2)) for x in (a[i::k] for i in range(k))))
``` |
415_D. Mashmokh and ACM | Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced prog... | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,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 sys.stdin.re... |
442_B. Andrey and Problem | Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him.
Help Andrey choose... | ```python
n=int(input())
from itertools import combinations
a = sorted(list(map(float, input().split())), reverse=True)
#a=[0.01]*100
if max(a) == 1:
print(1)
quit()
n=len(a)
pre = [1]*100
pre[0] = 1 - a[0]
for i in range(1, n):
pre[i] = pre[i-1] * (1-a[i])
ans = 0
for i in range(1,n+1):
anss=0
fo... |
464_C. Substitutes in Number | Andrew and Eugene are playing a game. Initially, Andrew has string s, consisting of digits. Eugene sends Andrew multiple queries of type "di → ti", that means "replace all digits di in string s with substrings equal to ti". For example, if s = 123123, then query "2 → 00" transforms s to 10031003, and query "3 → " ("rep... | ```python
mod=pow(10,9)+7
def sub_and_eval(n):
if n=='':
return 0
ans=v[int(n[0])]
for i in range(1,len(n)):
ans=(d[int(n[i])]*ans+v[int(n[i])])%mod
return ans
def prod_d(n):
ans=1
for e in n:
ans=ans*d[int(e)]%mod
return ans
s=input()
v={i:i for i in range(10)}
d={i:... |
488_B. Candy Boxes | There is an old tradition of keeping 4 boxes of candies in the house in Cyberland. The numbers of candies are special if their arithmetic mean, their median and their range are all equal. By definition, for a set {x1, x2, x3, x4} (x1 ≤ x2 ≤ x3 ≤ x4) arithmetic mean is <image>, median is <image> and range is x4 - x1. Th... | ```python
n=int(input())
if n==0:
print('YES')
print(1)
print(1)
print(3)
print(3)
else:
lis=[]
for i in range(n):
lis.append(int(input()))
lis.sort()
if n==1:
print('YES')
print(lis[0])
print(3*lis[0])
print(3*lis[0])
if n==2:
if... |
512_A. Fox And Names | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in l... | ```python
import sys
import heapq
n = int(sys.stdin.readline().strip())
w = []
g = {i:set({}) for i in "azertyuiopqsdfghjklmwxcvbn"}
for i in range(n):
w.append(sys.stdin.readline().strip())
for i in range(n-1):
idx = 0
while idx < min(len(w[i]), len(w[i+1])) - 1 and w[i][idx] == w[i+1][idx]:
idx += 1
if w[i][id... |
536_B. Tavas and Malekas | Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead.
<image>
Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions... | ```python
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" not in file.mode
self.write = self.buffer.write if se... |
560_C. Gerald's Hexagon | Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.
... | ```python
a,b,c,d,e,f=map(int,input().split())
print((a+b+c)**2-a**2-c**2-e**2)
``` |
586_E. Alice, Bob, Oranges and Apples | Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a let... | ```python
def gcd(x, y):
while y > 0:
x, y = y, x % y
return x
x, y = map(int, input().split())
if gcd(x, y) != 1:
print ("Impossible")
exit(0)
res = ""
while x > 0 and y > 0:
if y > x:
if x == 1:
y -= 1
res = res + str(y // x) + "B"
y = y % x
else:
... |
609_A. USB Flash Drives | Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes.
Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.
Input
The first line contai... | ```python
n = int(input())
m = int(input())
a = []
for i in range(n):
a.append(int(input()))
a.sort(reverse=True)
for i in range(n):
m -= a[i]
if m <= 0:
print(i+1)
exit()
``` |
656_D. Rosetta Problem |
++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+
++++++++++>++++++++++++>+++++++++++++>++++++++++++++>+++++++++++++++>+++++++
+++++++++<<<<<<<<<<<<<<<<-]>>>>>>>>>>.<<<<<<<<<<>>>>>>>>>>>>>>++.--<<<<<<<<<
<<<<<>>>>>>>>>>>>>+.-<<<<<<<<<<<<<>>>>>>>>>>>>>>--.++<<<<<<<<<<<<<... | ```python
n=eval(input())
cnt=0
while n:
a=n%8
n=n//8
if a==1:
cnt+=1
print(cnt)
``` |
67_D. Optical Experiment | Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.
There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each... | ```python
from bisect import bisect_left as bl
I=10000000
n=int(input())+1
c=[0]*n
for i,x in enumerate(map(int,input().split())): c[x]=i
d = [n-c[int(x)] for x in input().split()]
c=[I]*n
for i in d: c[bl(c,i)]=i
print( c.index(I))
``` |
702_D. Road to Post Office | Vasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to d kilometers.
Vasiliy's car is not new — it breaks after driven every k kilometers and Vasiliy needs t seconds to repair it. After repairing his car Vasiliy can drive again (but after k kilometers it will ... | ```python
import math
d, k, a, b, t = map(int, input().split())
distance = a * t /((b -a )*b) + t /b
time = 0
n = math.ceil((d-distance)/k)
# print(distance)
# print(n)
if (k>d):
print(d*a)
exit(0)
if (k<distance):
time = k*a + (d-k)*b
print(time)
exit(0)
if (n*k >=d):
time = a*d + d//k*t
... |
746_E. Numbers Exchange | Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct.
Nikolay has m cards, distinct numbers from 1 to m are written ... | ```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
counter = 0
s = set(a)
nech = set()
chet = set()
for elem in a:
if elem % 2:
nech.add(elem)
else:
chet.add(elem)
while len(nech) > n // 2:
nech.pop()
while len(chet) > n // 2:
chet.pop()
l_n = set([i for... |
793_E. Problem of offices | Earlier, when there was no Internet, each bank had a lot of offices all around Bankopolis, and it caused a lot of problems. Namely, each day the bank had to collect cash from all the offices.
Once Oleg the bank client heard a dialogue of two cash collectors. Each day they traveled through all the departments and offic... | ```python
n=int(input())
num=input().split(' ')
l=[0]*4
for i in range(4):
l[i]=int(num[i])
t=tuple(l)
a,b,c,d=t
p=[0]*(n+1)
num=input().split(' ')
mp=[list() for _ in range(n+1)]
for i in range(2,n+1):
p[i]=int(num[i-2])
mp[p[i]].append(i)
s=[0]*(n+1)
def sof(i):
if s[i]!=0:
return s[i]
... |
814_B. An express train to reveries | Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.
On that night, Sengoku constructed a permutation p1, p2, ..., pn of integers from 1 t... | ```python
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
# generate all 4 possibilities
dupa = []
dupb = []
for i in range(len(a)):
try:
index = a[i+1:].index(a[i])
dupa.append(i)
dupa.append(index+i+1)
break
except ValueError:
... |
83_B. Doctor | There are n animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number i in the queue will have to visit his... | ```python
from sys import stdin, stdout
n, k = map(int, stdin.readline().split())
values = list(map(int, stdin.readline().split()))
if sum(values) < k:
stdout.write('-1')
elif sum(values) > k:
l = 0
r = k + 1
while (r - l > 1):
m = (r + l) // 2
cnt = 0
for i in range(n)... |
886_C. Petya and Catacombs | A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages ... | ```python
c = int(input())
a = list(map(int, input().split()))
res = 0
b = []
for i in range(len(a)):
b.append(False)
for i in range(len(a)):
k = len(a) - i - 1
m = 0
while b[k] == False:
b[k] = True
k = a[k] - 1
m = 1
if (k == -1):
break
if m == 1:
... |
909_C. Python Indentation | In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An ex... | ```python
M=10**9+7
n=int(input())
a=[]
for i in range(n):
a.append(input())
dp=[[0]*(n+5) for i in range(n+2)]
dp[0][0]=1
for i in range(1,n):
count=0
if a[i-1]=='f':
for j in range(n-2,-1,-1):
if dp[i-1][j]>0:
dp[i][j+1]=(dp[i][j+1]+dp[i-1][j])%M
else:
for j... |
958_E1. Guard Duty (easy) | The Rebel fleet is afraid that the Empire might want to strike back again. Princess Heidi needs to know if it is possible to assign R Rebel spaceships to guard B bases so that every base has exactly one guardian and each spaceship has exactly one assigned base (in other words, the assignment is a perfect matching). Sin... | ```python
(R,B)=map(int,input().split())
for i in range(R+B):
x=input()
if R==B:
print('Yes')
else:
print('No')
``` |
p02573 AtCoder Beginner Contest 177 - Friends | There are N persons called Person 1 through Person N.
You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.
If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.
Ta... | ```python
from collections import deque
n,m=map(int,input().split())
f=[[] for i in range(n+1)]
for i in range(m):
a,b=map(int,input().split())
f[a].append(b)
f[b].append(a)
g=[0]*(n+1)
p=[0]*(n+1)
for i in range(1,n+1):
if p[i]==0:
p[i]=i
data=[i]
data=deque(data)
while... |
p02704 AtCoder Beginner Contest 164 - I hate Matrix Construction | Given are an integer N and arrays S, T, U, and V, each of length N. Construct an N×N matrix a that satisfy the following conditions:
* a_{i,j} is an integer.
* 0 \leq a_{i,j} \lt 2^{64}.
* If S_{i} = 0, the bitwise AND of the elements in the i-th row is U_{i}.
* If S_{i} = 1, the bitwise OR of the elements in the i-th... | ```python
from functools import reduce
import operator
N = int(input())
Ss = list(map(int, input().split()))
Ts = list(map(int, input().split()))
Us = list(map(int, input().split()))
Vs = list(map(int, input().split()))
mat = [[0] * N for _ in range(N)]
counts_r = [[0] * 64 for _ in range(N)]
counts_c = [[0] * 64 for ... |
p02833 AtCoder Beginner Contest 148 - Double Factorial | For an integer n not less than 0, let us define f(n) as follows:
* f(n) = 1 (if n < 2)
* f(n) = n f(n-2) (if n \geq 2)
Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).
Constraints
* 0 \leq N \leq 10^{18}
Input
Input is given from Standard Input in the following format:
... | ```python
n=int(input())
if n%2==1:print(0);exit()
A=0
add=10
while n>=add:
A +=n//add
add *=5
print(A)
``` |
p02970 AtCoder Beginner Contest 134 - Golden Apple | There are N apple trees in a row. People say that one of them will bear golden apples.
We want to deploy some number of inspectors so that each of these trees will be inspected.
Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector ... | ```python
a,b = map(int, input().split())
t = 2*b + 1
print((a-1)//t+1)
``` |
p03106 AtCoder Beginner Contest 120 - K-th Common Divisor | You are given positive integers A and B.
Find the K-th largest positive integer that divides both A and B.
The input guarantees that there exists such a number.
Constraints
* All values in input are integers.
* 1 \leq A, B \leq 100
* The K-th largest positive integer that divides both A and B exists.
* K \geq 1
In... | ```python
A,B,K = map(int,input().split())
L = []
for i in range(1,101):
if A%i == 0 and B%i == 0:
L.append(i)
print(L[len(L)-K])
``` |
p03253 AtCoder Beginner Contest 110 - Factorization | You are given positive integers N and M.
How many sequences a of length N consisting of positive integers satisfy a_1 \times a_2 \times ... \times a_N = M? Find the count modulo 10^9+7.
Here, two sequences a' and a'' are considered different when there exists some i such that a_i' \neq a_i''.
Constraints
* All valu... | ```python
n, m = map(int, input().split())
yd = {}
i = 2
while m != 1:
while m % i == 0:
if i in yd:
yd[i] += 1
else:
yd[i] = 1
m //= i
i += 1
ans = 1
for v in yd.values():
start = v + n - 1
c = 1
for _ in range(v):
c *= start
start -= 1
d = 1
for _v in range(v):
d *=... |
p03406 AtCoder Regular Contest 093 - Dark Horse | There are 2^N players, numbered 1, 2, ..., 2^N. They decided to hold a tournament.
The tournament proceeds as follows:
* Choose a permutation of 1, 2, ..., 2^N: p_1, p_2, ..., p_{2^N}.
* The players stand in a row in the order of Player p_1, Player p_2, ..., Player p_{2^N}.
* Repeat the following until there is only ... | ```python
import sys
input = sys.stdin.readline
def main():
def com(com_n, com_r):
return fac[com_n] * inv[com_r] * inv[com_n - com_r] % md
md = 10 ** 9 + 7
n, m = map(int, input().split())
aa = list(map(lambda x: int(x) - 1, input().split()))
n2 = 2 ** n
# combinationの準備
n_max = ... |
p03569 CODE FESTIVAL 2017 qual C - Inserting 'x' | We have a string s consisting of lowercase English letters. Snuke can perform the following operation repeatedly:
* Insert a letter `x` to any position in s of his choice, including the beginning and end of s.
Snuke's objective is to turn s into a palindrome. Determine whether the objective is achievable. If it is ... | ```python
s = list(input())
l = 0
r = len(s)-1
cnt = 0
while r-l >0:
if s[r] == s[l]:
l += 1
r -= 1
elif s[r] != s[l] and s[r] == "x":
r -=1
cnt += 1
elif s[r] != s[l] and s[l] == "x":
l += 1
cnt += 1
else:
print(-1)
exit()
print(cnt)
``` |
p03724 AtCoder Grand Contest 014 - Unplanned Queries | Takahashi is not good at problems about trees in programming contests, and Aoki is helping him practice.
First, Takahashi created a tree with N vertices numbered 1 through N, and wrote 0 at each edge.
Then, Aoki gave him M queries. The i-th of them is as follows:
* Increment the number written at each edge along the... | ```python
N,M = map(int,input().split())
cnt = [0]*(N+10)
for i in range(M):
a,b = map(int,input().split())
cnt[a]+=1
cnt[b]+=1
for c in cnt:
if c%2 == 1:
print('NO')
import sys
sys.exit()
print('YES')
``` |
p03888 CODE FESTIVAL 2016 Relay (Parallel) - Equivalent Resistance | In an electric circuit, when two resistors R_1 and R_2 are connected in parallel, the equivalent resistance R_3 can be derived from the following formula:
* \frac{1}{R_1} + \frac{1}{R_2} = \frac{1}{R_3}
Given R_1 and R_2, find R_3.
Constraints
* 1 \leq R_1, R_2 \leq 100
* R_1 and R_2 are integers.
Input
The inp... | ```python
# -*- coding:utf-8 -*-
r1,r2 = map(int, input().split())
print((r1*r2)/(r1+r2))
``` |
p04047 AtCoder Grand Contest 001 - BBQ Easy | Snuke is having a barbeque party.
At the party, he will make N servings of Skewer Meal.
<image>
Example of a serving of Skewer Meal
He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i. Also, he has an infinite supply of ingredients.
To make a serving of Skew... | ```python
n=int(input())
l=sorted(list(map(int, input().split())))
ll=l[::2]
print(sum(ll))
``` |
p00126 Puzzle | Taro is playing with a puzzle that places numbers 1-9 in 9x9 squares. In this puzzle, you have to arrange the numbers according to the following rules.
* One number appears exactly once in the same column
* A number appears exactly once on the same line
* In each of the 3x3 ranges separated by double lines, a number a... | ```python
n = int(input())
"""
def hor(matrix,y):
res = [True]*9
s = set()
out = set()
for i in matrix[y]:
if i in s:
out.add(i)
s.add(i)
for ind,i in enumerate(matrix[y]):
if i in out:
res[ind] = False
"""
def so(seq):
res = [False]*9
s = set... |
p00259 Finite Field Calculator | The reciprocal of all non-zero real numbers is real, but the reciprocal of an integer is not necessarily an integer. This is the reason why 3/2 * 2 = 2 even though 3.0 / 2.0 * 2.0 = 3.0 in C language. However, if you consider integers with the same remainder after dividing by a prime number as the same, you can make al... | ```python
import re
p = 0
class N(int):
def __add__(self,n):
return N((int(self) + int(n)) % p)
def __sub__(self,n):
return N((int(self) - int(n)) % p)
def __mul__(self,n):
return N((int(self) * int(n)) % p)
def __floordiv__(self,n):
if not n:
raise ZeroDivis... |
p00446 Card Game | problem
There are the following two-player card games.
* This game uses a total of 2n cards with each integer from 1 to 2n written on it. Here, n is an integer between 1 and 100.
* Deal n cards to each of the two.
* Put cards into play alternately one by one according to the following rules.
* If there are no cards i... | ```python
# AOJ 0523: Card GameI
# Python3 2018.6.30 bal4u
while True:
n = int(input())
if n == 0: break
c = [1] * (2*n+1)
for i in range(1, n+1): c[int(input())] = 0
m = [n]*2
t, ba = 0, 0
while m[0] > 0 and m[1] > 0:
f = 1
for i in range(ba+1, 2*n+1):
if t == c[i]:
ba = i
c[i] = 2
m[t] -= 1... |
p00637 Citation Format | To write a research paper, you should definitely follow the structured format. This format, in many cases, is strictly defined, and students who try to write their papers have a hard time with it.
One of such formats is related to citations. If you refer several pages of a material, you should enumerate their page num... | ```python
while True:
n = int(input())
if n == 0:
break
pages = list(map(int, input().split()))
ans = ""
while pages:
for i in range(len(pages) - 1):
if pages[i + 1] - pages[i] != 1:
s = pages[:i+1]
if i == 0:
ans += " " + str(s[0])
else:
ans += " " + ... |
p00780 Goldbach's Conjecture | Goldbach's Conjecture: For any even number n greater than or equal to 4, there exists at least one pair of prime numbers p1 and p2 such that n = p1 + p2.
This conjecture has not been proved nor refused yet. No one is sure whether this conjecture actually holds. However, one can find such a pair of prime numbers, if an... | ```python
import sys
import math
def primes(n):
sieve = [1] * (n + 1)
rt = int(math.sqrt(n))
sieve[0] = sieve[1] = 0
for p in range(2, rt + 1):
if sieve[p] == 0:
continue
k = p * 2
while k <= n:
sieve[k] = 0
k += p
r = []
for p in rang... |
p01315 Moonlight Farm | You are enthusiastic about the popular web game "Moonlight Ranch". The purpose of this game is to grow crops in the fields, sell them to earn income, and use that income to grow the ranch.
You wanted to grow the field quickly. Therefore, we decided to arrange the crops that can be grown in the game based on the income... | ```python
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def main():
whil... |
p02364 Minimum Spanning Tree | Find the sum of weights of edges of the Minimum Spanning Tree for a given weighted undirected graph G = (V, E).
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 100,000
* 0 ≤ wi ≤ 10,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0 w0
s1 t1 w1
:
s|E|-1 t|E|-1 w|E|-... | ```python
class Kruskal_UnionFind():
# 無向グラフであるという前提に注意
def __init__(self, N):
self.edges = []
self.rank = [0] * N
self.par = [i for i in range(N)]
self.counter = [1] * N
def add(self, u, v, d):
"""
:param u: 始点
:param v: 終点
:param d: コスト
... |
1016_B. Segment Occurrences | You are given two strings s and t, both consisting only of lowercase Latin letters.
The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order.
Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i... | ```python
ch=input()
l=list(map(int,ch.split()))
m=l[0]
n=l[1]
p=l[2]
s=input()
t=input()
l1=[]
for i in range(p):
ch=input()
l1.append(ch)
res=0
l2=[0]
for i in range (len(t)-1):
l2.append(0)
for i in range ((len(t)-1),len(s)):
if s[(i-len(t)+1):(i+1)]==t:
res+=1
l2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.