name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
939_A. Love Triangle | As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1 ≤ fi ≤ n and fi ≠ i.
We call a love triangle a situation in which plane A likes plane... | ```python
n=int(input())
a=list(map(int,input().split()))
for i in range(n):
if a[a[a[i]-1]-1]==i+1:
print('YES')
exit(0)
print('NO')
``` |
964_C. Alternating Sum | You are given two integers a and b. Moreover, you are given a sequence s_0, s_1, ..., s_{n}. All values in s are integers 1 or -1. It's known that sequence is k-periodic and k divides n+1. In other words, for each k ≤ i ≤ n it's satisfied that s_{i} = s_{i - k}.
Find out the non-negative remainder of division of ∑ _{i... | ```python
n, a, b, k = map(int, input().split() )
s = input()
mod = (int)( 1e9 + 9 )
ans = 0
t = (int)( (n + 1) / k )
def modInverse(a):
return pow(a, mod - 2, mod)
i = 0
for ind in range( len(s) ):
first = ( pow(a, n - i, mod ) * pow( b, i, mod ) ) % mod
num = ( pow( b, k, mod ) * modInverse( pow... |
991_D. Bishwock | Bishwock is a chess figure that consists of three squares resembling an "L-bar". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states:
XX XX .X X.
X. .X XX XX
Bishwocks don't attack any squares and can even occupy on the adjacent square... | ```python
def main():
a, b = [i for i in input()], [i for i in input()]
l = len(a)
c = 0
for i in range(l - 1):
if a[i] == '0':
if b[i] == '0':
if a[i + 1] == '0':
c += 1
a[i], b[i], a[i + 1] = 1, 1, 1
elif b[i +... |
p02619 Introduction to Heuristics Contest - Scoring | You will be given a contest schedule for D days. For each d=1,2,\ldots,D, calculate the satisfaction at the end of day d.
Input
Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A.
D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,... | ```python
D=int(input())
c=list(map(int, input().split()))
s=[list(map(int, input().split())) for i in range(D)]
t=[int(input()) for i in range(D)]
d=[0]*(26)
v=[0]*(D+1)
for i in range(D):
v[i]=s[i][t[i]-1]
d[t[i]-1]=-1
sb=0
for j in range(26):
d[j]+=1
sb+=d[j]*c[j]
... |
p02750 Social Infrastructure Information Systems Division Hitachi Programming Contest 2020 - Manga Market | There are N stores called Store 1, Store 2, \cdots, Store N. Takahashi, who is at his house at time 0, is planning to visit some of these stores.
It takes Takahashi one unit of time to travel from his house to one of the stores, or between any two stores.
If Takahashi reaches Store i at time t, he can do shopping the... | ```python
import sys
readline = sys.stdin.buffer.readline
INF = 10**18+3
N, T = map(int, readline().split())
AB = [tuple(map(int, readline().split())) for _ in range(N)]
ABzero = [b for a, b in AB if a == 0]
ABnonzero = [(a, b) for a, b in AB if a]
ABnonzero.sort(key = lambda x: (x[1]+1)/x[0])
dp = [0]
for a, b in ... |
p02885 AtCoder Beginner Contest 143 - Curtain | The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)
We will close the window so as to minimize the total horizontal length of the uncovered part of the window. Fin... | ```python
a,b=map(int,input().split())
print(a-2*b if a-2*b>=0 else 0)
``` |
p03020 AtCoder Grand Contest 034 - Manhattan Max Matching | Snuke is playing with red and blue balls, placing them on a two-dimensional plane.
First, he performed N operations to place red balls. In the i-th of these operations, he placed RC_i red balls at coordinates (RX_i,RY_i). Then, he performed another N operations to place blue balls. In the i-th of these operations, he ... | ```python
import sys
from collections import deque
def min_cost_flow(links, links_from, s, t, flow, n2):
remain = flow
result = 0
INF = 10 ** 12
predecessors = [0] * n2 # link_id
while remain:
# print(remain)
distances = [INF] * n2
updated = [False] * n2
distances... |
p03160 Educational DP Contest - Frog 1 | There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |... | ```python
N = int(input())
H = [0]+list(map(int, input().split()))
C = [10**10] + [0]*N
for i in range(2,N+1):
C[i] = min(C[i-1]+abs(H[i-1]-H[i]), C[i-2]+abs(H[i-2]-H[i]))
print(C[-1])
``` |
p03303 SoundHound Inc. Programming Contest 2018 -Masters Tournament- - Acrostic | You are given a string S consisting of lowercase English letters. We will write down this string, starting a new line after every w letters. Print the string obtained by concatenating the letters at the beginnings of these lines from top to bottom.
Constraints
* 1 \leq w \leq |S| \leq 1000
* S consists of lowercase E... | ```python
S = list(input())
w = int(input())
ans = S[::w]
for a in ans:
print(a, end="")
print()
``` |
p03463 AtCoder Grand Contest 020 - Move and Win | A game is played on a strip consisting of N cells consecutively numbered from 1 to N.
Alice has her token on cell A. Borys has his token on a different cell B.
Players take turns, Alice moves first. The moving player must shift his or her token from its current cell X to the neighboring cell on the left, cell X-1, or... | ```python
n, a, b = map(int, input().split())
print('Alice' if (a - b - 1) % 2 == 1 else 'Borys')
``` |
p03781 AtCoder Regular Contest 070 - Go Home | There is a kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0. During the period between time i-1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right. That is, if his coordinate at time i-1 is x, he can be a... | ```python
import math
X = int(input())
low_N = (-1 + (1 + 8 * X)**0.5) / 2
high_N = (1 + (1 + 8 * X)**0.5) / 2
if low_N % 1 == 0:
print(int(low_N))
else:
print(math.floor(high_N))
``` |
p03951 AtCoder Grand Contest 006 - Prefix and Suffix | Snuke is interested in strings that satisfy the following conditions:
* The length of the string is at least N.
* The first N characters equal to the string s.
* The last N characters equal to the string t.
Find the length of the shortest string that satisfies the conditions.
Constraints
* 1≤N≤100
* The lengths o... | ```python
N = int(input())
s = input()
t = input()
x = s+t
for i in range(N):
if (s[i:N] == t[0:N-i]):
x = s + t[N-i:N]
break
print(len(x))
``` |
p00041 Expression | Using the given four integers from 1 to 9, we create an expression that gives an answer of 10. When you enter four integers a, b, c, d, write a program that outputs an expression that gives an answer of 10 according to the following conditions. Also, if there are multiple answers, only the first answer found will be ou... | ```python
from itertools import permutations, product
import sys
readline = sys.stdin.readline
write = sys.stdout.write
P = [
"((%d %s %d) %s (%d %s %d))",
"(%d %s (%d %s (%d %s %d)))",
"(((%d %s %d) %s %d) %s %d)",
"((%d %s (%d %s %d)) %s %d)",
"(%d %s ((%d %s %d) %s %d))",
]
def solve():
*X, =... |
p00173 Haunted House | Aizu Gakuen High School holds a school festival every year. The most popular of these is the haunted house. The most popular reason is that 9 classes do haunted houses instead of 1 or 2 classes. Each one has its own unique haunted house. Therefore, many visitors come from the neighborhood these days.
Therefore, the sc... | ```python
while True:
try:a,b,c=input().split()
except:break
b,c=map(int,[b,c])
print(a,b+c,b*200+c*300)
``` |
p00502 Hot days | problem
During this time of winter in Japan, hot days continue in Australia in the Southern Hemisphere. IOI, who lives in Australia, decided to plan what clothes to wear based on the weather forecast for a certain D day. The maximum temperature on day i (1 ≤ i ≤ D) is predicted to be Ti degrees.
IOI has N kinds of cl... | ```python
def solve():
from sys import stdin
f_i = stdin
D, N = map(int, f_i.readline().split())
T = tuple(int(f_i.readline()) for i in range(D))
clothes = [tuple(map(int, f_i.readline().split())) for i in range(N)]
clothes.sort(key=lambda x: x[2])
candidate = []
for t in ... |
p00686 Where's Your Robot? | You have full control over a robot that walks around in a rectangular field paved with square tiles like a chessboard. There are m columns of tiles from west to east, and n rows of tiles from south to north (1 <= m, n <= 100). Each tile is given a pair of coordinates, such as (i, j), where 1 <= i <= m and 1 <= j <= n.
... | ```python
while True:
col, row = map(int, input().split())
if col == 0:
break
else:
robot = [1, 1]
direction = "up"
while True:
str = input()
if str == "STOP":
print(robot[0], robot[1])
break
elif str == "LEF... |
p00828 Make a Sequence | Your company’s next product will be a new game, which is a three-dimensional variant of the classic game “Tic-Tac-Toe”. Two players place balls in a three-dimensional space (board), and try to make a sequence of a certain length.
People believe that it is fun to play the game, but they still cannot fix the values of s... | ```python
import sys
sys.setrecursionlimit(1000000000)
input=lambda : sys.stdin.readline().rstrip()
dx=[1,1,0,-1,1,1,0,-1,-1,-1,0,1,0]
dy=[0,1,1,1,0,1,1,1,0,-1,-1,-1,0]
dz=[0,0,0,0,1,1,1,1,1,1,1,1,1]
while True:
n,m,q=map(int,input().split())
if n==m==q==0:
break
field=[[[-1 for i in range(n)]for ... |
p00959 Medical Checkup | Problem C Medical Checkup
Students of the university have to go for a medical checkup, consisting of lots of checkup items, numbered 1, 2, 3, and so on.
Students are now forming a long queue, waiting for the checkup to start. Students are also numbered 1, 2, 3, and so on, from the top of the queue. They have to under... | ```python
n, t = map(int, input().split())
s = x = y = 0
for i in range(n):
h = int(input())
s, x, y = s+x, h, max(h, y)
print(max((t-x-s)//y+2,1))
``` |
p01228 Rhythm Machine | Advanced Computer Music (ACM) sold a rhythm machine that plays music according to a pre-programmed rhythm. At one point, ACM was trying to develop and sell a new rhythm machine. While ACM's old product could only play one sound at a time, the new product was able to play up to eight sounds at the same time, which was t... | ```python
def shorten(s):
f = 1
while f:
l = len(s) // 2
while f:
f = 0
if l % 2 == 0:
for i in range(l):
if s[2 * i:2 * i + 2] != "00" and i % 2:break
else:
f = 1
t = ""
... |
p01362 Dice Room | You are playing a popular video game which is famous for its depthful story and interesting puzzles. In the game you were locked in a mysterious house alone and there is no way to call for help, so you have to escape on yours own. However, almost every room in the house has some kind of puzzles and you cannot move to n... | ```python
from collections import deque
def main():
I = {
1: ((6, 0), (2, 1), (5, 2), (4, 3)),
2: ((6, 3), (3, 1), (5, 3), (1, 3)),
3: ((6, 2), (4, 1), (5, 0), (2, 3)),
4: ((6, 1), (1, 1), (5, 1), (3, 3)),
5: ((1, 0), (2, 0), (3, 0), (4, 0)),
6: ((1, 2), (2, 2), (3, 2... |
p01844 Land Inheritance | F --Land inheritance
Problem Statement
One $ N $ brother was discussing the inheritance of his parents. The vast heritage left by their parents included vast lands. The land has a rectangular shape extending $ H $ km from north to south and $ W $ km from east to west. This land is managed in units of 1 km square, 1 k... | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def rotate(H, W, R0):
R1 = [[0]*H for i in range(W)]
for i in range(H):
for j in range(W):
R1[W-1-j][i] = R0[i][j]
return R1
def make(H, W, R0):
R1 = [[0]*(W+1) for i in range(H+1)]
for i in range(H):
... |
p02126 Ball | Problem
There are $ N $ balls, each with its own color and value.
There are $ C $ types of ball colors from $ 1 $ to $ C $, and each color has an upper limit on the number of balls that can be selected.
Maximize the total value you get when choosing at most $ M $ balls in total.
Constraints
The input satisfies the f... | ```python
# -*- coding: utf-8 -*-
def inpl(): return list(map(int, input().split()))
N, M, C = inpl()
L = {i+1:v for i, v in enumerate(inpl())}
balls = []
for _ in range(N):
c, w = inpl()
balls.append([w, c])
balls = sorted(balls, reverse=True)
i = 0
count = 0
ans = 0
for i in range(N):
w, c = balls[i]
... |
p02266 Areas on the Cross-Section Diagram | Areas on the Cross-Section Diagram
Your task is to simulate a flood damage.
For a given cross-section diagram, reports areas of flooded sections.
<image>
Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides. For example, for the abov... | ```python
def cross_section_diagram():
down = []
edge = []
pool = []
for i, c in enumerate(input()):
if c == '\\':
down.append(i)
elif c == '/' and down:
left = down.pop()
area = i - left
while edge:
if edge[-1] < left:
break
edge.pop()
area += pool.pop()
edge.append(left)
... |
p02414 Matrix Multiplication | Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula:
\\[ c_{ij} = \sum_{k=1}^m a_{ik}b_{kj} \\]
where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ res... | ```python
n,m,l = map(int,input().split())
A = [list(map(int,input().split())) for i in range(n)]
B = [list(map(int,input().split())) for j in range(m)]
C = [[0 for k in range(l)]for i in range(n)]
for i in range(n) :
for k in range(l) :
for j in range(m) :
C[i][k] = C[i][k] + A[i][j] * B[j][k]
for i in r... |
1042_D. Petya and Array | Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his arra... | ```python
maxn = 2*10**5 + 5
bit = [0]*(maxn)
def add(idx):
idx += 1
while idx < maxn:
bit[idx] += 1
idx += idx & -idx
def sm(idx):
idx += 1
tot = 0
while idx > 0:
tot += bit[idx]
idx -= idx & -idx
return tot
n,t = map(int,input().split())
a = list(map(int,in... |
1065_C. Make It Equal | There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i.
Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make towe... | ```python
#########################################################################################################\
#########################################################################################################
###################################The_Apurv_Rathore#############################################... |
1088_A. Ehab and another construction problem | Given an integer x, find 2 integers a and b such that:
* 1 ≤ a,b ≤ x
* b divides a (a is divisible by b).
* a ⋅ b>x.
* a/b<x.
Input
The only line contains the integer x (1 ≤ x ≤ 100).
Output
You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in... | ```python
n=int(input())
if n>=3 and n%2==1:
print(n-1,2)
elif n>=2 and n%2==0:
print(n,2)
else:
print(-1)
``` |
1107_A. Digits Sequence Dividing | You are given a sequence s consisting of n digits from 1 to 9.
You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the ... | ```python
for _ in range(int(input())):
n = int(input())
z = input()
if n==2 and z[0]>=z[1]:
print("NO")
else:
print("YES")
print(2)
print(z[0],z[1::])
``` |
1136_A. Nastya Is Reading a Book | After lessons Nastya decided to read a book. The book contains n chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.
Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number k as the fi... | ```python
n=int(input())
p=[]
for x in range(n):
a,b=list(map(int,input().split()))
sam=list(range(a,b+1))
p.append(sam)
kam=int(input())
for x in p:
if kam in x:
print(n-p.index(x))
break
``` |
1154_E. Two Teams | There are n students standing in a row. Two coaches are forming two teams — the first coach chooses the first team and the second coach chooses the second team.
The i-th student has integer programming skill a_i. All programming skills are distinct and between 1 and n, inclusive.
Firstly, the first coach will choose ... | ```python
import sys
input = sys.stdin.readline
def main():
n, k = map(int, input().split())
A = list(map(int, input().split()))
B = []
for i, a in enumerate(A):
B.append((a, i+1))
B.sort()
#print(B)
bit = [0]*(n+1)
def bit_query(i, bit):
res = 0
while i > 0:
... |
1176_C. Lose it! | You are given an array a consisting of n integers. Each a_i is one of the six following numbers: 4, 8, 15, 16, 23, 42.
Your task is to remove the minimum number of elements to make this array good.
An array of length k is called good if k is divisible by 6 and it is possible to split it into k/6 subsequences 4, 8, 15... | ```python
_=int(input())
a=list(map(int,input().split()))
b=[4,8,15,16,23,42]
c=[0]*6
for i in range(len(a)):
x = b.index(a[i])
if x == 0:
c[0] +=1
elif c[x-1]!=0:
c[x-1]-=1
c[x]+=1
print(len(a)-6*c[5])
``` |
1195_B. Sport Mafia | Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia.
For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs n actions. The first action performed is to put a single candy into the box. For each of the remainin... | ```python
n,x=map(int,input().split())
formula=0
i=0
if(n==1):
print(0)
else:
formula=1000000
while(abs(n-(i+formula))!=x):
i=i+1
formula=(i*(i+1))//2
print(abs(n-i))
``` |
1234_D. Distinct Characters Queries | You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
... | ```python
import sys
def upd(bit, idx, inc):
while idx < len(bit):
bit[idx] += inc
idx += idx & -idx
def query(bit, idx):
ret = 0
while idx > 0:
ret += bit[idx]
idx -= idx & -idx
return ret
if __name__ == '__main__':
input = sys.stdin.readline
inp = list(inp... |
1253_C. Sweets Eating | Tsumugi brought n delicious sweets to the Light Music Club. They are numbered from 1 to n, where the i-th sweet has a sugar concentration described by an integer a_i.
Yui loves sweets, but she can eat at most m sweets each day for health reasons.
Days are 1-indexed (numbered 1, 2, 3, …). Eating the sweet i at the d-t... | ```python
n,m = list(map(int,input().split()))
a = list(map(int,input().split()))
a.sort()
f = [0] * 1000000
sum = [0] * 1000000
for i in range(n):
sum[i] = sum[i - 1] + a[i]
for i in range(n):
f[i] = f[i - m] + sum[i]
print(f[i], end = " ")
``` |
1277_B. Make Them Odd | There are n positive integers a_1, a_2, ..., a_n. For the one move you can choose any even value c and divide by two all elements that equal c.
For example, if a=[6,8,12,6,3,12] and you choose c=6, and a is transformed into a=[3,8,12,3,3,12] after the move.
You need to find the minimal number of moves for transformin... | ```python
for _ in range(int(input())):
n=int(input())
a=[int(y) for y in input().split()]
a=sorted(a)
a=a[::-1]
d={}
count=0
for i in range(n):
d[a[i]]=0
for i in range(n):
if(d[a[i]] == 0):
s=a[i]
while(a[i]%2==0):
a[i]/=2
... |
1320_C. World of Darkraft: Battle for Azathoth | Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.
Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense... | ```python
# quick input by @c1729 and @pajenegod
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from bisect import bisect_right
from operator import itemgetter
class SegmTree:
'''
- increment on interval
- get max on interval
'''
def __init__(self, size):
N = 1
... |
133_A. HQ9+ | HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | ```python
s=input()
flag=0
for i in range(len(s)):
if(s[i]=='H' or s[i]=='Q' or s[i]=='9'):
print('YES')
flag=1
break
if flag==0:
print('NO')
``` |
1361_B. Johnny and Grandmaster | Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. ... | ```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.... |
1381_C. Mastermind | In the game of Mastermind, there are two players — Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.
When Bob guesses a code, Alice tells him some information about ... | ```python
from sys import stdin, stdout
from collections import defaultdict
from heapq import heapify, heappop, heappush
def solve():
n, s, y = map(int, stdin.readline().split())
a = stdin.readline().split()
d = defaultdict(list)
for i, x in enumerate(a):
d[x].append(i)
for i in range(1, n +... |
1401_D. Maximum Distributed Tree | You are given a tree that consists of n nodes. You should label each of its n-1 edges with an integer in such way that satisfies the following conditions:
* each integer must be greater than 0;
* the product of all n-1 numbers should be equal to k;
* the number of 1-s among all n-1 integers must be minimum po... | ```python
import sys
input=sys.stdin.readline
for _ in range(int(input())):
n=int(input())
dic={}
dico={}
for i in range(1,n+1):
dic[i]=[]
dico[i]=[]
for i in range(n-1):
x,y=map(int,input().split())
dic[x].append(y)
dic[y].append(x)
dico[x].append(y)
... |
1446_B. Catching Cheaters | You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the ... | ```python
n, m = map(int, input().split())
a = input()
b = input()
res = 0
dp = [[0 for _ in range(m + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 2)
dp[i][j] = max(dp[i][j], max(dp[i ... |
1470_B. Strange Definition | Let us call two integers x and y adjacent if (lcm(x, y))/(gcd(x, y)) is a perfect square. For example, 3 and 12 are adjacent, but 6 and 9 are not.
Here gcd(x, y) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x and y, and lcm(x, y) denotes the [least comm... | ```python
from sys import stdin
dct = {i:i for i in range(1000001)}
for i in range(2, 1001):
for j in range(1, (10 ** 6) // (i ** 2) + 1):
dct[(i ** 2) * j] = j
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
elements = map(int, stdin.readline().split())
q = int(stdin.readline())
dct2 = {}... |
1497_A. Meximization | You are given an integer n and an array a_1, a_2, …, a_n. You should reorder the elements of the array a in such way that the sum of MEX on prefixes (i-th prefix is a_1, a_2, …, a_i) is maximized.
Formally, you should find an array b_1, b_2, …, b_n, such that the sets of elements of arrays a and b are equal (it is equ... | ```python
#fi = open("task1.txt")
#def input():
# return fi.readline()
T = int(input())
for _ in range(T):
n = int(input())
a = [int(x) for x in input().split()]
nums = [0 for _ in range(101)]
for el in a:
nums[el] += 1
result = []
for i in range(101):
if nums[i] >= 1:
result += [str(i)]
nums[i] -= 1... |
174_B. File List | Eudokimus, a system administrator is in trouble again. As a result of an error in some script, a list of names of very important files has been damaged. Since they were files in the BerFS file system, it is known that each file name has a form "name.ext", where:
* name is a string consisting of lowercase Latin lett... | ```python
s=input()
n=len(s)
a=s.find('.')
b=s.rfind('.')
from sys import exit
if a==b==-1:print('NO');exit()
if a==0 or n-b-1==0:print('NO');exit()
if not 0<a<9 or not 0<n-b-1<4:print('NO');exit()
s2=s[a+1:b+1]
res=[s[:a+1]]
app=res.append
length,item=0,''
for i,x in enumerate(s2):
if x=='.':
if not 1<leng... |
194_C. Cutting Figure | You've gotten an n × m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two s... | ```python
n, m = map(int, input().split())
p, s = [], {}
x = 0
for i in range(n):
for j, q in enumerate(input()):
if q != '#': continue
s[(i, j)] = x
p.append([])
if (i, j - 1) in s:
p[x] += [x - 1]
p[x - 1] += [x]
if (i - 1, j) in s:
y = s... |
218_C. Ice Skating | Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves... | ```python
#start the code from here
n=int(input())
global parent
parent=[i for i in range(n)]
# n is total number of nodes
# finding parent of a node
def find(w):
global parent
if parent[w]==w:
return w
else:
return find(parent[w])
def union(a,b):
global parent
w=find(a)
y=find(b)
if w==y:
return
par... |
241_G. Challenging Balloons | Martha — as a professional problemsetter — proposed a problem for a world-class contest. This is the problem statement:
Tomorrow is Nadia's birthday, and Bardia (her brother) is assigned to make the balloons ready!
There are n balloons (initially empty) that are tied to a straight line on certain positions x1, x2, ..... | ```python
print(302)
print("0 1000000")
coord, rad = 17321*2, 300
for i in range(300):
print(coord, rad)
coord, rad = coord+600, rad-1
print("1000000 1000000")
``` |
267_A. Subtractions | You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).
You've got some num... | ```python
for i in range(int(input())):
a,b=map(int,input().split())
sm=0
while a and b:
sm+=a//b
t=b
b=a%b
a=t
print(sm)
``` |
290_A. Mysterious strings |
Input
The input contains a single integer a (1 ≤ a ≤ 40).
Output
Output a single string.
Examples
Input
2
Output
Adams
Input
8
Output
Van Buren
Input
29
Output
Harding | ```python
ans = [0, 1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51, 1, 2, 1, 14, 1, 2, 2, 14, 1, 6, 1, 4, 2, 2, 1, 52, 2, 5, 1, 5, 1, 15, 2, 13, 2, 2, 1, 13, 1, 2, 4, 267]
print(ans[int(input())])
``` |
316_A1. Special Task | Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get th... | ```python
hint = input()
seen = []
if 'A' <= hint[0] <= 'J':
num = 9
seen = [hint[0]]
elif '0' <= hint[0] <= '9':
num = 1
elif hint[0] == '?':
num = 9
for l in hint[1:]:
if 'A' <= l <= 'J':
if not l in seen:
num *= 10 - len(seen)
seen += [l]
elif l == '?':
... |
384_C. Milking cows | Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of mi... | ```python
n = int(input())
lis = list(map(int,input().split()))
ans=b=0
for i in range(n-1,-1,-1):
if lis[i]==1:
ans+=b
else:
b+=1
print(ans)
``` |
405_B. Domino Effect | Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".
Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes... | ```python
n = int(input())
s = input()+'R'
r = 0
flag = 'L'
a = 0
for _ in range(n+1):
if s[_] == '.':
a+=1
elif s[_] == 'L':
if flag =='L':
a = 0
else:
if a%2==1:
r+=1
a = 0
flag = 'L'
else:
if flag =='L':
... |
432_C. Prime Swaps | You have an array a[1], a[2], ..., a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times):
* choose two indexes, i and j (1 ≤ i < j ≤ n; (j - i + 1) is a prime number);
* swap the elements on positi... | ```python
def sieve(n):
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
n = int(input())
prime = [True for i in range(n+2)]
prime[0]=0
prime[1]=0
sieve(n+1)
aa=[0]*(n+1)
for i in range(n+1):
if prime[i]:... |
454_E. Little Pony and Summer Sun Celebration | Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration.
<im... | ```python
"""
Codeforces Contest 259 Div 1 Problem C
Author : chaotic_iak
Language: Python 3.3.4
"""
def main():
# Read N and M from problem statement.
n,m = read()
# Set up an adjacency list for each vertex.
edges = [[] for _ in range(n+1)]
for i in range(m):
a,b = read()
edges... |
477_C. Dreamoon and Strings | Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.
More formally... | ```python
s, p = input(), input()
n, m = len(s) + 1, len(p)
d = [[0] * n for t in range(n)]
for x in range(1, n):
i, j = x, m
while i and j:
j -= s[i - 1] == p[j - 1]
i -= 1
if not j:
for y in range(i + 1): d[x][y + x - i - m] = d[i][y] + 1
for y in range(x): d[x][y] = max(d[x][y... |
4_D. Mysterious Present | Peter decided to wish happy birthday to his friend from Australia and send him a card. To make his present more mysterious, he decided to make a chain. Chain here is such a sequence of envelopes A = {a1, a2, ..., an}, where the width and the height of the i-th envelope is strictly higher than the width and the height o... | ```python
inputi = [int(i) for i in input().split(" ")]
amt = inputi[0]
cardW = inputi[1]
cardH = inputi[2]
envelopes = []
cur_amt = 1
for i in range(amt):
inputi = [int(i) for i in input().split(" ")]
if inputi[0] > cardW and inputi[1] > cardH:
envelopes.append((inputi[0],inputi[1],inputi[0]*inputi[1],... |
525_C. Ilya and Sticks | In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of n sticks and an instrument. Each stick is characterized by its length li.
Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maxi... | ```python
n = int(input())
rects = [int(s) for s in input().split()]
rects.sort()
sumsquare = 0
stash = []
i = len(rects) - 1
while i > 0:
if rects[i] - rects[i-1] == 1 or rects[i] == rects[i-1]:
if len(stash) == 2:
sumsquare += stash[0]*stash[1]
stash.clear()
stash.append(rects[i-1])
rects.pop()
re... |
550_D. Regular Bridge | An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such gra... | ```python
def nextEdge():
global v
for i in range(1, v + 1):
for j in range(i + 1, v + 1):
yield (i, j)
k = int(input())
if k % 2 == 0:
print("NO")
elif k == 1:
print("YES", "2 1", "1 2", sep = "\n")
else:
n = 2 * k + 4
m = k * (k + 2)
print("YES")
print(n, m, sep =... |
59_C. Title | Vasya has recently finished writing a book. Now he faces the problem of giving it the title. Vasya wants the title to be vague and mysterious for his book to be noticeable among others. That's why the title should be represented by a single word containing at least once each of the first k Latin letters and not contain... | ```python
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
k = int(input())
a = list(input().rstrip())
n = len(a)
unused = [1] * k
def ng():
print('IMPOSSIBLE')
exit()
try:
for i in range(n):
if a[i] == '?' and a[n - i - 1] ... |
621_A. Wet Shark and Odd and Even | Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark.
Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.
Input
The first line of the ... | ```python
n=int(input())
l=list(map(int,input().split()))
s=sum(l)
ls=set(l)
lss=list(ls)
lss.sort()
c=0
for i in range(len(lss)):
if lss[i]%2!=0:
c=lss[i]
break
if s%2==0:
print(s)
else:
print(s-c)
``` |
66_D. Petya and His Friends | Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to n.
Let us remind you the definition of the greatest common divisor: GCD(a1, ..., ak) = d, where d represents such a maximal positive number that each ai (1 ≤ i ≤ k) is e... | ```python
import math
def checkprime(n):
if(n==1):
return 0
i=2
while(i*i<=n):
if(n%i==0):
return 0
i+=1
return 1
primes=[]
primes.append(0)
i=1
while(i<=1000):
if(checkprime(i)==1):
primes.append(i)
i+=1
n=int(input())
if(n==2):
print(-1)
exit(0)
res=[]
i=1
while(i<=n):
product=1
j=i
while(j<i+n-... |
691_A. Fashion in Berland | According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.
You are given a jacket with n buttons. Determine if it is fasten... | ```python
n = int(input())
a = list(map(int,input().split()))
c = a.count(0)
if (c>1 or c<1) and n>1 :
print('NO')
elif n==1 and c==1:
print('NO')
else:
print('YES')
``` |
716_A. Crazy Computer | ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear!
More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then ever... | ```python
"""
second a and then the next word at second b, then if b - a ≤ c,
just the new word is appended to other words on the screen.
If b - a > c, then everything on the screen disappears and after that the word
you have typed appears on the screen.
"""
num1 = input()
num2 = input()
a = []
b = []
def get_t... |
736_C. Ostap and Tree | Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no m... | ```python
def main():
n, k = map(int, input().split())
cnt = [[[0] * 21 for _ in (0, 1)] for _ in range(n + 1)]
edges, mod = [[] for _ in range(n + 1)], 1000000007
for _ in range(n - 1):
u, v = map(int, input().split())
edges[u].append(v)
edges[v].append(u)
def dfs(u, f):
... |
760_C. Pavel and barbecue | Pavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction.
Pavel has a plan: a permutation p and a sequence b1, b2, ... | ```python
n = int(input())
p = list(map(int, input().split()))
b = list(map(int, input().split()))
s = sum(b[i] for i in range(n))
if s % 2 == 0:
ans = 1
else:
ans = 0
visited = [0] * n
ptr = 0
start = 1
visited[0] = 1
q = 1
c = 1
while q < n:
start = p[start - 1]
if visited[start - 1] == 1:
c +... |
875_A. 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
n = int(input())
res = []
def sum_digits(x):
return sum([int(i) for i in x])
for i in range(max(0, n - 80), n):
# print(sum_digits(str(i)))
if i + sum_digits(str(i)) == n:
res.append(i)
print(len(res))
if len(res) != 0:
for r in sorted(res):
print(r)
``` |
899_F. Letters Removing | Petya has a string of length n consisting of small and large English letters and digits.
He performs m operations. Each operation is described with two integers l and r and a character c: Petya removes from the string all characters c on positions between l and r, inclusive. It's obvious that the length of the string ... | ```python
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
class FenwickTree:
def __init__(self, x):
"""transform list into BIT"""
self.bit = x
for i in range(len(x)):
j = i | (i + 1)
if j < len(x):
x[j] += x[i]
def updat... |
920_B. Tea Queue | Recently n students from city S moved to city P to attend a programming camp.
They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.
i-th stude... | ```python
if __name__ == '__main__':
cin = input
t = int(cin())
while t > 0:
n = int(cin())
a, cnt = [0] * n, 0
for i in range(n):
l, r = map(int, cin().split())
if r >= cnt + max(l - cnt, 1):
cnt += max(l - cnt, 1)
a[i] += cnt... |
976_E. Well played! | Recently Max has got himself into popular CCG "BrainStone". As "BrainStone" is a pretty intellectual game, Max has to solve numerous hard problems during the gameplay. Here is one of them:
Max owns n creatures, i-th of them can be described with two numbers — its health hpi and its damage dmgi. Max also has two types ... | ```python
import sys
read=lambda:map(int,sys.stdin.buffer.readline().split())
n,a,b=read()
v=[tuple(read()) for _ in range(n)]
ans=0
if b>0:
c=[v[x][0]-v[x][1] for x in range(n)]
w,r=list(range(n)),[0]*n
w.sort(key=lambda x:c[x],reverse=True)
for i in range(n): r[w[i]]=i
f=True;s=0;m=min(n,b)
for i in range(m):
... |
996_C. Tesla | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be repre... | ```python
n, k = list(map(int, input().split()))
table = []
for row in range(4):
table.append(list(map(int, input().split())))
moves = []
def make_move(start,finish):
moves.append((table[start[0]][start[1]], finish[0]+1, finish[1]+1))
table[finish[0]][finish[1]] = table[start[0]][start[1]]
table[start... |
p02649 Tokio Marine & Nichido Fire Insurance Programming Contest 2020 - O(rand) | Given are N pairwise distinct non-negative integers A_1,A_2,\ldots,A_N. Find the number of ways to choose a set of between 1 and K numbers (inclusive) from the given numbers so that the following two conditions are satisfied:
* The bitwise AND of the chosen numbers is S.
* The bitwise OR of the chosen numbers is T.
C... | ```python
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
cmb=[[0 for i in range(51)] for j in range(51)]
cmb[0][0]=1
for i in range(51):
for j in range(5... |
p02778 AtCoder Beginner Contest 154 - I miss you... | Given is a string S. Replace every character in S with `x` and print the result.
Constraints
* S is a string consisting of lowercase English letters.
* The length of S is between 1 and 100 (inclusive).
Input
Input is given from Standard Input in the following format:
S
Output
Replace every character in S with ... | ```python
s = input()
print('x' * (len(s)))
``` |
p02913 AtCoder Beginner Contest 141 - Who Says a Pun? | Given is a string S of length N.
Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.
More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:
... | ```python
n = int(input())
s = input()
l1 = l2 = length = 0
while l2 + length < n:
if s[l1 : l2] in s[l2:]:
length = l2 - l1
l2 += 1
else:
l1 += 1
l2 = l1 + length + 1
print(length)
``` |
p03049 diverta 2019 Programming Contest - AB Substrings | Snuke has N strings. The i-th string is s_i.
Let us concatenate these strings into one string after arranging them in some order. Find the maximum possible number of occurrences of `AB` in the resulting string.
Constraints
* 1 \leq N \leq 10^{4}
* 2 \leq |s_i| \leq 10
* s_i consists of uppercase English letters.
In... | ```python
import re
n = int(input())
a = 0
b = 0
ab = 0
cnt = 0
for i in range(n):
s = input()
tmp = re.findall(r'AB',s)
ab += len(tmp)
if s[0] == "B":
b += 1
if s[-1] == "A":
a += 1
if s[0] == "B" and s[-1] == "A":
cnt += 1
if a == b and a == cnt and a > 0:
print(... |
p03337 AtCoder Beginner Contest 098 - Add Sub Mul | You are given two integers A and B. Find the largest value among A+B, A-B and A \times B.
Constraints
* -1000 \leq A,B \leq 1000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B
Output
Print the largest value among A+B, A-B and A \times B.
Examples
Inp... | ```python
A, B = map(int, input().split())
M = max(A+B,A-B,A*B)
print(M)
``` |
p03499 AtCoder Regular Contest 086 - Smuggling Marbles | Snuke has a rooted tree with N+1 vertices. The vertices are numbered 0 through N, and Vertex 0 is the root of the tree. The parent of Vertex i (1 \leq i \leq N) is Vertex p_i.
Besides this tree, Snuke also has an box which is initially empty and many marbles, and playing with them. The play begins with placing one mar... | ```python
n, = map(int, input().split())
p = [-1] + [*map(int, input().split())]
MOD = 10**9+7
dp = [[] for _ in range(n+1)]
dep = [0]*(n+1)
nxt = [0]*(n+1)
for v in range(n,0,-1):
_,nxt[p[v]],dep[p[v]] = sorted([nxt[p[v]],dep[p[v]],dep[v]+1])
tot = [0]*(dep[0]+1)
for i in range(n+1): tot[dep[i]] += 1
def merge... |
p03658 AtCoder Beginner Contest 067 - Snake Toy | Snuke has N sticks. The length of the i-th stick is l_i.
Snuke is making a snake toy by joining K of the sticks together.
The length of the toy is represented by the sum of the individual sticks that compose it. Find the maximum possible length of the toy.
Constraints
* 1 \leq K \leq N \leq 50
* 1 \leq l_i \leq 50
... | ```python
N,K=map(int,input().split(' '))
print(sum(sorted(list(map(int,input().split(' '))))[::-1][:K]))
``` |
p03814 AtCoder Beginner Contest 053 - A to Z String | Snuke has decided to construct a string that starts with `A` and ends with `Z`, by taking out a substring of a string s (that is, a consecutive part of s).
Find the greatest length of the string Snuke can construct. Here, the test set guarantees that there always exists a substring of s that starts with `A` and ends w... | ```python
N = input()
a = N.find("A")
z = N.rfind("Z")
print(z - a + 1)
``` |
p00071 Bombs Chain | There is a plane like Figure 1 with 8 vertical and 8 horizontal squares. There are several bombs on that plane. Figure 2 shows an example (● = bomb).
| □ | □ | □ | □ | □ | □ | □ | □
--- | --- | --- | --- | --- | --- | --- | ---
□ | □ | □ | □ | □ | □ | □ | □
□ | □ | □ | □ | □ | □ | □ | □
□ | □ | □ | □ | □ | □ | □ | □
□... | ```python
def e(x,y):
A[y][x]='0'
for d in range(-3,4):
0<=x+d<8and'1'==A[y][x+d]and e(x+d,y)
0<=y+d<8and'1'==A[y+d][x]and e(x,y+d)
for i in range(int(input())):
print(f'Data {i+1}:');input()
A=[list(input())for _ in[0]*8]
e(int(input())-1,int(input())-1)
for r in A:print(*r,sep='')
``` |
p00203 A New Plan of Aizu Ski Resort | Yukiya, the owner of Aizuyama Ski Resort, has prepared a course for advanced skiers with obstacles and jumping hills. There are various ways to slide on the course, and users who can slide in all patterns during the season will be given a gift.
Let's create a program for the oil tree shop that outputs the number of pa... | ```python
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0203
"""
import sys
from sys import stdin
from collections import deque, defaultdict
input = stdin.readline
def solve(field):
BLANK, OBSTACLE, JUMP = 0, 1, 2
ans = 0 # ??????????????°??????????... |
p00359 Dungeon | Bob is playing a popular game called "Dungeon". The game is played on a rectangular board consisting of W × H squares. Each square is identified with its column and row number, thus the square located in the x-th column and the y-th row is represented as (x, y). The left-most square in the top row is (0, 0) and the rig... | ```python
w, h, n = map(int, input().split())
xys = sorted([list(map(int, input().split())) for _ in range(n)])
y_max = [0]
for _, y in reversed(xys):
y_max.append(max(y_max[-1], y))
xs = [0] + [x for x, _ in xys]
print(min([xs[i] + y_max[n - i] for i in range(n + 1)]))
``` |
p00570 Stove | JOI has a stove in your room. JOI himself is resistant to the cold, so he doesn't need to put on the stove when he is alone in the room, but he needs to put on the stove when there are visitors.
On this day, there are N guests under JOI. The ith (1 \ leq i \ leq N) visitor arrives at time T_i and leaves at time T_i + ... | ```python
n, k = map(int, input().split())
li = [int(input()) for i in range(n)]
diff = []
for j in range(n-1):
diff.append(li[j+1]-li[j]-1)
diff.sort(reverse=True)
print(n+sum(diff[k-1:]))
``` |
p00717 Polygonal Line Search | Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from th... | ```python
# -*- coding: utf-8 -*-
def main():
N = int(input())
while N:
lines = []
for _ in range(N+1):
tmp = []
M = int(input())
x0, y0 = map(int, input().split())
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
... |
p01120 Tally Counters | <!--
Problem D
-->
Tally Counters
A number of tally counters are placed in a row. Pushing the button on a counter will increment the displayed value by one, or, when the value is already the maximum, it goes down to one. All the counters are of the same model with the same maximum value.
<image> Fig. D-1 Tally Cou... | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve(C, N, M, range = range, min = min):
K = N // 4 + 1
S = [0]*K
T = [0]*K
U = [0]*(K+1)
for i in range(N-1):
U[0] = 10**18
for j in range(K):
U[j+1] = min(U[j], S[j])
k = K-1
... |
p01419 On or Off | Saving electricity is very important!
You are in the office represented as R \times C grid that consists of walls and rooms. It is guaranteed that, for any pair of rooms in the office, there exists exactly one route between the two rooms. It takes 1 unit of time for you to move to the next room (that is, the grid adja... | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in ... |
p01735 Optimal alpha beta pruning | Fox Ciel is developing an artificial intelligence (AI) for a game. This game is described as a game tree T with n vertices. Each node in the game has an evaluation value which shows how good a situation is. This value is the same as maximum value of child nodes’ values multiplied by -1. Values on leaf nodes are evaluat... | ```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
*P, = map(int, readline().split())
G = []
prt = [0]*N
for i in range(N):
k, *t = map(int, readline().split())
G.append([e-1 for e in t])
... |
p02295 Cross Point | For given two segments s1 and s2, print the coordinate of the cross point of them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
* The given segments have a cross point and are not in parallel.
Input
The... | ```python
def dot(a, b):
return a.real * b.real + a.imag * b.imag
def cross(a, b):
return a.real * b.imag - a.imag * b.real
def cross_point(p0,p1,p2,p3):
base=p3-p2
d1=abs(cross(base,p0-p2))
d2=abs(cross(base,p1-p2))
t=d1/(d1+d2)
ans= p0+(p1-p0)*t
return ans.real,ans.imag
n = int(input())
for i in ra... |
p02442 Lexicographical Comparison | Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The num... | ```python
input()
a = list(map(int, input().split(' ')))
input()
b = list(map(int, input().split(' ')))
print(1 if a<b else 0)
``` |
1015_C. Songs Compression | Ivan has n songs on his phone. The size of the i-th song is a_i bytes. Ivan also has a flash drive which can hold at most m bytes in total. Initially, his flash drive is empty.
Ivan wants to copy all n songs to the flash drive. He can compress the songs. If he compresses the i-th song, the size of the i-th song reduce... | ```python
n,m = input().split()
n=int(n)
m=int(m)
songs=list()
for i in range(n):
songs.append([int(c) for c in input().split()])
def sumList(lista,inx):
sum=0
for i in range(len(lista)):
sum+=lista[i][inx]
return sum
songs=sorted(songs,key=lambda x: x[1]-x[0])
suma = sumList(songs,0)
f... |
1039_A. Timetable | There are two bus stops denoted A and B, and there n buses that go from A to B every day. The shortest path from A to B takes t units of time but some buses might take longer paths. Moreover, buses are allowed to overtake each other during the route.
At each station one can find a sorted list of moments of time when a... | ```python
def read():
return list(map(int, input().split(' ')))
def fail():
print('No')
exit(0)
n, t = read()
aa = read()
xx = read()
res = [0] * n
prevX = 0
prevV = -10
for i in range(n):
x = xx[i] - 1
if x < prevX or x < i:
fail()
prevX = x
res[i] = prevV = max(aa[i + 1] + t if... |
1061_C. Multiplicity | You are given an integer array a_1, a_2, …, a_n.
The array b is called to be a subsequence of a if it is possible to remove some elements from a to get b.
Array b_1, b_2, …, b_k is called to be good if it is not empty and for every i (1 ≤ i ≤ k) b_i is divisible by i.
Find the number of good subsequences in a modulo... | ```python
import math
def nextDiv(a):
ret = []
i = 1;
while (i*i <= a):
if (a%i == 0):
ret.append(i)
j = a//i
if (i != j):
ret.append(j)
i += 1
return reversed(ret)
MOD = int(1e9+7)
def solve(n, lis):
dp = [0] * (max(lis)+1)
... |
1083_B. The Fair Nut and Strings | Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicog... | ```python
d = {'a': 0, 'b': 1}
def process(s, t, k):
n = len(s)
answer = 0
D = 0
final_i = n
for i in range(n):
d1 = d[s[i]]
d2 = d[t[i]]
D = 2*(D)+d2-d1
if D+1 < k:
answer+=(D+1)
else:
final_i = i
break
answer+=k*(n-fi... |
1102_D. Balanced Ternary String | You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string ... | ```python
from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
# from math import *
from collections import defaultdict as dd, deque
def data(): return sys.stdin.readline().strip()
def mdata(): return map(int, data().split())
# sys.setrecursionlimit(1000000)
mod = 998244353
n=int(da... |
1130_D1. Toy Train (Simplified) | This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at... | ```python
from collections import defaultdict as dd
n,m=[int(i) for i in input().split(' ')]
a=[]
b=[]
def fnx(i,j):
if i<j:
return(j-i)
else:
return(n-i+j)
def fnr(r):
if r%n==0:
return(n)
else:
return(r%n)
for i in range(m):
x,y=[int(i) for i in input().split(' '... |
1190_B. Tokitsukaze, CSL and Stone Game | Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if... | ```python
def find(A):
from collections import defaultdict
A=sorted(A)
N=len(A)
dic=defaultdict(int)
for i in range(N):
dic[A[i]]+=1
checked=[]
count=set([])
for x in A:
if dic[x]>2:
return "cslnb"
if dic[x]==2:
count.add(x)
... |
1228_E. Another Filling the Grid | You have n × n square grid and an integer k. Put an integer in each cell while satisfying the conditions below.
* All numbers in the grid should be between 1 and k inclusive.
* Minimum number of the i-th row is 1 (1 ≤ i ≤ n).
* Minimum number of the j-th column is 1 (1 ≤ j ≤ n).
Find the number of ways to ... | ```python
def Solve(n,k):
mod = 10**9+7
max_n = 10**4
#precalcular los factoriales
fac = [1] + [0] * max_n
fac_i = [1] + [0] * max_n
for i in range(1,n+1):
fac[i] = fac[i-1] * (i) % mod
fac_i[i] = fac_i[i- 1] * pow(i,mod-2,mod) % mod
#calculo de las combinaciones con factorial inver... |
1270_E. Divide Points | You are given a set of n≥ 2 pairwise different points with integer coordinates. Your task is to partition these points into two nonempty groups A and B, such that the following condition holds:
For every two points P and Q, write the [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance) between them o... | ```python
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
from typing import List
"""
created by shhuan at 2019/12/30 21:55
"""
N = int(input())
A = []
for i in range(N):
x, y = map(int, input().split())
A.append((x, y))... |
1293_C. NEKO's Maze Game | [3R2 as DJ Mashiro - Happiness Breeze](https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak)
[Ice - DJ Mashiro is dead or alive](https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive)
NEKO#ΦωΦ has just got a new maze game on her PC!
The game's main puzzle is a maze, in the forms of a 2 × n rectangle grid. NEKO... | ```python
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
n, q = [int(item) for item in input().split()]
block = [[0] * (n + 6) for _ in range(2)]
wall = 0
for _ in range(q):
x, y = [int(item) - 1 for item in input().split()]
y += 3
invx = (x + 1) % 2
if block[x][y]:
block[x][y] =... |
1313_C1. Skyscrapers (easy version) | This is an easier version of the problem. In this version n ≤ 1000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company ... | ```python
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import *
from collections import defaultdict, deque, Counter
import math, string
from heapq import *
from operator import add
from itertools import accumulate
BUFSIZE = 8192
sys.setrecursionlimit(10 ** 5)
class FastIO... |
1335_F. Robots on a Grid | There is a rectangular grid of size n × m. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell (i, j) is c_{i, j}. You are also given a map of directions: for each cell, there is a direction s_{i, j} which is one of the four characters 'U', 'R', 'D' and 'L'.
* If s_{i, j} is 'U' then t... | ```python
import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI():... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.