name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
449_B. Jzzhu and Cities | Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One ... | ```python
import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
... |
493_D. Vasya and Chess | Vasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess.
The queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell cont... | ```python
n = int(input())
if n & 1 == 0:
print('white\n1 2')
else:
print('black')
``` |
518_C. Anya and Smartphone | Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th ... | ```python
'''input
5 4 2
3 1 5 2 4
4 4 4 4
'''
import math
from sys import stdin, stdout
def get_order(pemut):
order = dict()
for i in range(1, n + 1):
order[permut[i - 1]] = i
r_order = dict()
for i in order:
r_order[order[i]] = i
return order, r_order
# main starts
n, m, k = list(map(int, stdin.readli... |
544_C. Writing Code | Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes.
Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m... | ```python
a = list(map(int, input().split()))
n = a[0]
m = a[1]
b = a[2]
mod = a[3]
ac = list(map(int,input().split()))
ac = [0] + ac
dp = [[[0 for k in range(b+1)] for _ in range(m+1)] for z in range(2)]
for i in range(n+1) :
for x in range(b+1) :
dp[i%2][0][x] = 1
for i in range(1,n+1) :
for... |
592_C. The Big Race | Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today.
<image>
Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.
... | ```python
from sys import stdin
import math
# stdin = open('in.txt')
# t, w, b = map(int, stdin.readline().split())
t, w, b = map(int, input().split())
d = math.gcd(w, b)
l = (w*b)//d
add = min(w, b)
ans = add*(t//l)
m = t%l
ans += min(add, m+1)
ans -= 1
d = math.gcd(ans, t)
ans //= d
t //= d
print(ans, '/', t, sep... |
614_A. Link/Cut Tree | Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.
Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed... | ```python
#from math import pow
def pow(num, n):
ans = 1
while n>0:
ans*=num
n-=1
return ans
l,r,k = map(int, input().split())
i = 0;
while (pow(k,i)<l):
i+=1
count = 0
a = []
while (l<=pow(k,i)<=r):
a.append(int(pow(k,i)))
count += 1
i+=1
if count == 0:
print(-1)
e... |
709_C. Letters Cyclic Shift | You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' ... | ```python
s=input()
l=len(s)
a1=a2=1000000
q=[]
k=0
b=''
j=0
if 'a' in s:
for i in s:
if i=='a':
if len(q)>0 and j-q[-1]>1:
q.append(j)
k=j
break
q.append(j)
j+=1
if len(q)==l:
print('a'*(l-1)+'z')
exit()
... |
79_B. Colorful Field | Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes.
After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following... | ```python
n,m,k,t=map(int,input().split(" "))
field=[]
for _ in range(k):
a,b=map(int,input().split(" "))
field.append( (a-1)*m+(b-1) )
field.sort()
#print("field=",field)
dic={0:"Carrots",1:"Kiwis",2:"Grapes"}
for _ in range(t):
flag=0
x,y=map(int,input().split(" "))
value=(x-1)*m+(y-1)
for... |
867_B. Save the problem! | Attention: we lost all the test cases for this problem, so instead of solving the problem, we need you to generate test cases. We're going to give you the answer, and you need to print a test case that produces the given answer. The original problem is in the following paragraph.
People don't use cash as often as they... | ```python
a = int(input())
n = 2*(a-1)+1
m = 2
print(n, m)
print(1, 2)
``` |
892_D. Gluttony | You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e.
<image>
Input
The first line contains one integer n (1 ≤ n ≤ 22)... | ```python
n = int(input())
a = list(map(int, input().split()))
sorted_a = sorted(a)
shifted_sorted_a = [sorted_a[-1]] + sorted_a[:-1]
#print(sorted_a)
#print(shifted_sorted_a)
for i in range(len(a)):
pos_in_sorted = sorted_a.index(a[i])
print(shifted_sorted_a[pos_in_sorted], end=" ")
print()
``` |
914_D. Bash and a Tough Math Puzzle | Bash likes playing with arrays. He has an array a1, a2, ... an of n integers. He likes to guess the greatest common divisor (gcd) of different segments of the array. Of course, sometimes the guess is not correct. However, Bash will be satisfied if his guess is almost correct.
Suppose he guesses that the gcd of the ele... | ```python
#!/usr/bin/env python3
import os
import sys
from atexit import register
from io import StringIO
from math import gcd
sys.stdin = StringIO(os.read(0, os.fstat(0).st_size).decode())
sys.stdout = StringIO()
register(lambda: os.write(1, sys.stdout.getvalue().encode()))
input = lambda: sys.stdin.readline().rstri... |
937_B. Vile Grasshoppers | The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.
The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppe... | ```python
p,y = map(int,input().split())
for x in range(y,p,-1):
# print(x)
# check
flag = True
for i in range(2,min(p,int(x**0.5))+1):
if x%i == 0:
flag = False
break
if flag:
print(x)
exit()
print(-1)
``` |
962_D. Merge Equals | You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value x that occurs in the array 2 or more times. Take the first two occurrences of x in this array (the two leftmost occurrences). Remove the left of these two occur... | ```python
n = int(input())
d = {}
for i, x in enumerate(map(int, input().split())):
while x in d:
del d[x]
x *= 2
d[x] = i
print(len(d))
print(*d)
``` |
p02608 AIsing Programming Contest 2020 - XYZ Triplets | Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:
* 1 \leq x,y,z
* x^2 + y^2 + z^2 + xy + yz + zx = n
Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^4
Input
Input is given from Sta... | ```python
n=int(input())
import math
nn=int(math.sqrt(n))+1
a=[0]*(100*n)
for x in range(1,nn+1):
for y in range(1,nn+1):
for z in range(1,nn+1):
a[(x+y+z)**2-x*y-x*z-y*z]+=1
for i in range(1,n+1):
print(a[i])
``` |
p02739 AtCoder Grand Contest 043 - Topology | Given are a positive integer N and a sequence of length 2^N consisting of 0s and 1s: A_0,A_1,\ldots,A_{2^N-1}. Determine whether there exists a closed curve C that satisfies the condition below for all 2^N sets S \subseteq \\{0,1,\ldots,N-1 \\}. If the answer is yes, construct one such closed curve.
* Let x = \sum_{i ... | ```python
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
A = list(map(int,readline().rstrip().decode()))
minimal_sets = []
for n in range(1<<N):
s = n
is_min = (A[n] == 0)
while s:
s = (s - 1) & n
if A... |
p02874 AtCoder Grand Contest 040 - Two Contests | 10^9 contestants, numbered 1 to 10^9, will compete in a competition. There will be two contests in this competition.
The organizer prepared N problems, numbered 1 to N, to use in these contests. When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclus... | ```python
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
class SegmentTree():
'''
非再帰
segment tree
'''
def __init__(self, n, func, init=float('inf')):
'''
n->配列の長さ
func:func(a,b)->val, func=minだとRMQになる
木の高さhとすると,
... |
p03008 diverta 2019 Programming Contest 2 - Squirrel Merchant | The squirrel Chokudai has N acorns. One day, he decides to do some trades in multiple precious metal exchanges to make more acorns.
His plan is as follows:
1. Get out of the nest with N acorns in his hands.
2. Go to Exchange A and do some trades.
3. Go to Exchange B and do some trades.
4. Go to Exchange A and do some... | ```python
n = int(input())
A = [int(item) for item in input().split()]
B = [int(item) for item in input().split()]
dp = [0] * (n+1)
AB = []
for a, b in zip(A, B):
if b > a:
AB.append((a, b))
for i in range(n+1):
for a, b in AB:
if i - a >= 0:
y = dp[i-a] + b - a
if y >... |
p03148 AtCoder Beginner Contest 116 - Various Sushi | There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i. You are choosing K among these N pieces to eat. Your "satisfaction" here will be calculated as follows:
* The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".
* The base total de... | ```python
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**9)
n,k=map(int,input().split())
Sushi=[list(map(int,input().split())) for i in range(n)]
Sushi=sorted(Sushi,key=lambda x: x[1],reverse=True)
ans=0
A=[]
kind=set()
for t,d in Sushi[:k]:
ans+=d
if t in kind:
A.append(d)
else:
... |
p03292 AtCoder Beginner Contest 103 - Task Scheduling Problem | You have three tasks, all of which need to be completed.
First, you can complete any one task at cost 0.
Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.
Here, |x| denotes the absolute value of x.
Find the minimum total cost required to complete all the task.
Constrain... | ```python
a,b,c=sorted(map(int,input().split()))
print(abs(a-b)+abs(b-c))
``` |
p03448 AtCoder Beginner Contest 087 - Coins | You have A 500-yen coins, B 100-yen coins and C 50-yen coins (yen is the currency of Japan). In how many ways can we select some of these coins so that they are X yen in total?
Coins of the same kind cannot be distinguished. Two ways to select coins are distinguished when, for some kind of coin, the numbers of that co... | ```python
a = int(input())
b = int(input())
c = int(input())
x = int(input())
li = [[i, j, k] for i in range(a+1) for j in range(b+1) for k in range(c+1) if 500*i+100*j+50*k == x]
print(len(li))
``` |
p03608 AtCoder Beginner Contest 073 - joisino's travel | There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in this order).
She will fly to the first town she visits, and fly back from the last town she visi... | ```python
import itertools
N, M, R = map(int, input().split())
r = [int(x) - 1 for x in input().split()]
G = [[10 ** 7 for j in range(N)] for i in range(N)]
for i in range(N):
G[i][i] = 0
for i in range(M):
a, b, c = map(int, input().split())
G[a - 1][b - 1] = c
G[b - 1][a - 1] = c
def warshall_floyd(G):
for ... |
p03769 AtCoder Grand Contest 012 - Tautonym Puzzle | We will call a string x good if it satisfies the following condition:
* Condition: x can be represented as a concatenation of two copies of another string y of length at least 1.
For example, `aa` and `bubobubo` are good; an empty string, `a`, `abcabcabc` and `abba` are not good.
Eagle and Owl created a puzzle on ... | ```python
def test():
from itertools import combinations
s = '111223111223'
result = 0
for k in range(1, len(s) // 2 + 1):
for idx in combinations(range(len(s)), 2 * k):
success = True
for ii in range(k):
if s[idx[ii]] != s[idx[ii + k]]:
... |
p03938 AtCoder Grand Contest 007 - Construct Sequences | You are given a permutation p of the set {1, 2, ..., N}. Please construct two sequences of positive integers a_1, a_2, ..., a_N and b_1, b_2, ..., b_N satisfying the following conditions:
* 1 \leq a_i, b_i \leq 10^9 for all i
* a_1 < a_2 < ... < a_N
* b_1 > b_2 > ... > b_N
* a_{p_1}+b_{p_1} < a_{p_2}+b_{p_2} < ... < a... | ```python
n = int(input())
x = list(map(int, input().split()))
a = [20001*i for i in range(1,n+1)]
b = [20001*(n+1-i) for i in range(1,n+1)]
for i in range(n):
b[x[i]-1] += i
for x in a:print(x, end=' ')
print()
for x in b:print(x, end=' ')
``` |
p00030 Sum of Integers | Write a program that extracts n different numbers from the numbers 0 to 9 and outputs the number of combinations that add up to s. Each n number is from 0 to 9, and the same number cannot be used in one combination. For example, if n is 3 and s is 6, the combination of the three numbers totaling 6 is
1 + 2 + 3 = 6
0 +... | ```python
def dfs(depth,prev,sum):
if depth == n:
return sum == s
ret = 0
for i in range(prev + 1,10):
ret += dfs(depth + 1,i,sum + i)
return ret
while True:
n,s = map(int,input().split())
if n == 0:
break
print(dfs(0,-1,0))
``` |
p00161 Sport Meet | An autumn sports festival is held. There are four events: foot race, ball-carrying, obstacle race, and relay. There are n teams participating, and we would like to commend the team with the shortest total time in this 4th event as the "winner", the next smallest team as the "runner-up", and the second team from the bot... | ```python
# -*- coding: utf-8 -*-
import sys
import os
for s in sys.stdin:
N = int(s)
if N == 0:
break
A = []
for i in range(N):
lst = list(map(int, input().split()))
id = lst[0]
data = lst[1:]
time_sum = data[0] * 60 + data[1] + \
data[2] * ... |
p00488 Lunch | problem
At the JOI pasta shop, the recommended pasta for lunch and the set menu of freshly squeezed juice are popular. When ordering this set menu, choose one from each of the three pasta and two juices of the day. The price is the total price of pasta and juice minus 50 yen.
Given the price of pasta and juice for a ... | ```python
pasta = [int(input()) for i in range(3)]
juice = [int(input()) for j in range(2)]
print(min(pasta) + min(juice) - 50)
``` |
p00817 True Liars | After having drifted about in a small boat for a couple of days, Akira Crusoe Maeda was finally cast ashore on a foggy island. Though he was exhausted and despaired, he was still fortunate to remember a legend of the foggy island, which he had heard from patriarchs in his childhood. This must be the island in the legen... | ```python
from collections import defaultdict
class UnionFind():
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] == x:
return x
else:
self.parent[x] = self.find(self.parent[x])
ret... |
p00948 Distribution Center | Example
Input
4 3
1000 1
2000 2
3000 3
Output
2 3 4 4 | ```python
N,M = map(int,input().split())
XY = []
for _ in range(M):
x,y = map(int,input().split())
xy = (x,y)
XY.append(xy)
XY.sort(key = lambda x:x[0]) # x sort
*minY, = range(N)
*maxY, = range(N)
for _,y in XY:
y0,y1 = y-1, y
minY[y1] = minY[y0]
maxY[y0] = maxY[y1]
ans = [maxY[i] - minY[i]... |
p01533 Acrophobia | C: Acrophobia
Yayoi Takasugi is a super-selling idol. There is one thing she is not good at. It's a high place ... She is extremely afraid of heights. This time, due to the producer's inadequacy, she decided to take on the following challenges on a variety show.
This location will be held in a room in a ninja mansion... | ```python
from itertools import permutations
from collections import deque
w, h = map(int, input().split())
mp = ["X" * (w + 4)] * 2 + ["XX" + input() + "XX" for _ in range(h)] + ["X" * (w + 4)] * 2
m_lst = []
holes = []
for y in range(2, h + 2):
for x in range(2, w + 2):
if mp[y][x] == "S":
sx, sy = x, y
... |
p01689 Dowsing Machine | C --Dowsing Machine
Story
People make noise with X and Y, but the coming era will be "D". "Paklin Monster D" is a very popular game in which "D people" search for treasure using the "D machine" developed by the secret society "R team".
In this game, the person D in the square with the grid map repeatedly moves to th... | ```python
def bfs(start_y,start_x,goal_y,goal_x):
bfs_map = [[-1 for x in range(w)] for y in range(h)]
move_y = [1,-1,0,0]
move_x = [0,0,1,-1]
data_y = [start_y]
data_x = [start_x]
bfs_map[start_y][start_x] = 1
while len(data_x) != 0:
y = data_y.pop(0)
x = data_x.pop(0)
... |
p01833 Modern Announce Network | Example
Input
4 2 1 1
1 2
3
4
3
1 2
2 4
3 4
Output
2 1 | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
from collections import deque
INF = 10**9
def bfs(N, G, s):
dist = [INF]*N
*lb, = range(N)
dist[s] = 0
que = deque([s])
while que:
v = que.popleft()
d = dist[v] + 1
l = lb[v]
for w in G[v]:
... |
p01968 Hierarchical Calculator | B: 階層的計算機 (Hierarchical Calculator)
Problem
Ebi-chan has N formulae: y = a_i x for i =1, ..., N (inclusive). Now she considers a subsequence of indices with length k: s_1, s_2, ..., s_k. At first, let x_0 be 1 and evaluate s_1-th formulae with x = x_0. Next, let x_1 be the output of s_1 and evaluate s_2-th formulae w... | ```python
# -*- coding: utf-8 -*-
from collections import Counter
def inpl(): return tuple(map(int, input().split()))
N = int(input())
A = list(map(int, input().split()))
C = Counter(A)
if C[-2] % 2 == 0:
ans = [i+1 for i, a in enumerate(A) if abs(a) == 2]
print(len(ans))
if len(ans):
print(*ans, ... |
p02255 Insertion Sort | Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:
for i = 1 to A.length-1
key = A[i]
/* insert A[i] into the sorted sequence A[0,...,j-1] */
j = i - 1
while j >= 0 and A[j] > key
A[j+1] = A[j]
j--
A[j+1] = key
Note... | ```python
n = int(input())
a = list(map(int, input().split()))
print(*a, sep=' ')
for i in range(1, n):
v = a[i]
j = i - 1
while j >= 0 and a[j] > v:
a[j+1] = a[j]
a[j] = v
j -= 1
print(*a, sep=' ')
``` |
p02403 Print a Rectangle | Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'.
Constraints
* 1 ≤ H ≤ 300
* 1 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero)... | ```python
while True:
H,W = map(int,input().split())
if H == 0 and W == 0:
exit()
for i in range(H):
print("#"*W)
print()
``` |
1005_E2. Median on Segments (General Case Edition) | You are given an integer sequence a_1, a_2, ..., a_n.
Find the number of pairs of indices (l, r) (1 ≤ l ≤ r ≤ n) such that the value of median of a_l, a_{l+1}, ..., a_r is exactly the given number m.
The median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-dec... | ```python
def cv(r, n, d):
s = [0]*(2*n + 1)
q = n
ans = 0
s[q] = 1
z = 0
for i in range(n):
if d[i] < r:
q -= 1
z -= s[q]
else:
z += s[q]
q += 1
ans += z
s[q] += 1
return ans
n, r = map(int,input().split())
d =... |
1029_D. Concatenated Multiples | You are given an array a, consisting of n positive integers.
Let's call a concatenation of numbers x and y the number that is obtained by writing down numbers x and y one right after another without changing the order. For example, a concatenation of numbers 12 and 3456 is a number 123456.
Count the number of ordered... | ```python
import os
import sys
from io import BytesIO, IOBase
# import string
# characters = string.ascii_lowercase
# digits = string.digits
# sys.setrecursionlimit(int(1e6))
# dir = [-1,0,1,0,-1]
# moves = 'NESW'
inf = float('inf')
from functools import cmp_to_key
from collections import defaultdict as dd
from collec... |
104_C. Cthulhu | ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super... | ```python
n, m = [int(i) for i in input().split()]
adj = [[] for i in range(n+1)]
seen = [False for i in range(n+1)]
pai = [0 for i in range(n+1)]
ciclos = 0
def dfs (u):
seen[u] = True
global ciclos
for v in adj[u]:
if not seen[v]:
pai[v] = u
dfs(v)
elif v != pai[u]... |
1093_F. Vasya and Array | Vasya has got an array consisting of n integers, and two integers k and len in addition. All numbers in the array are either between 1 and k (inclusive), or equal to -1. The array is good if there is no segment of len consecutive equal numbers.
Vasya will replace each -1 with some number from 1 to k (inclusive) in suc... | ```python
def vasya_and_array():
n,k,leng = [int(x) for x in input().split()]
if(leng==1):
return 0
a = [int(x) for x in input().split()]
mod = 998244353
a.insert(0,0)
dp = [[0 for x in range((k+1))] for y in range(n+1)]
sumdp = [0 for _ in range(n+1)]
sumdp[0]=1
count = [0 f... |
1142_A. The Beatles | Recently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through n ⋅ k cities. The cities are numerated from 1 to n ⋅ k, the distance between the neighboring cities is exactly 1 km.
Sergey does not like beetles, he loves burgers. Fortunately for him, there are n fast food restaurants on... | ```python
from math import gcd
def lcm(a,b):
return a*b//gcd(a,b)
def mod(a,m):
a%=m
if a<0:
a+=m
return a
n,k=map(int, input().split())
a,b=map(int, input().split())
st,ed=[],[]
nk=n*k
for i in range(0,n):
st.append(mod(i*k-a,nk))
st.append(mod(i*k+a,nk))
ed.append(mod(i*k-b,nk))
ed.append(mod(i*k+b,nk))... |
1162_C. Hide and Seek | Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, …, x_k in order.... | ```python
def main():
n, k = map(int, input().split())
x = [int(i) for i in input().split()]
ans = 3 * n - 2
a, b = set(), set()
for val in x:
if val - 1 in a:
b.add((val, val - 1))
if val + 1 in a:
b.add((val, val + 1))
a.add(val)
ans -= len(a) +... |
1183_B. Equalize Prices | There are n products in the shop. The price of the i-th product is a_i. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.
In fact, the owner of the shop can change the price of some product i in such a way that the difference between the old price of this ... | ```python
q = int(input())
for qq in range(q):
n, k = map(int, input().split())
*a, = map(int, input().split())
m = 0
M = 1e9
for x in a:
M = min(M, x + k)
m = max(m, x - k)
if M >= m:
print(M)
else:
print(-1)
``` |
1200_C. Round Corridor | Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by n sectors, and the outer area is equally divided by m sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wa... | ```python
n,m,q = map(int,input().split())
s = []
for i in range(q):
s.append(list(map(int,input().split())))
def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(a,b):
return (a // gcd(a,b))*b
g = lcm(n,m)
a,b = g//m,g//n
for i in s:
s1,e1,s2,e2 = i
if s1==1:
s... |
1242_B. 0-1 MST | Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is conne... | ```python
import collections as cc
import sys
input=sys.stdin.readline
#sys.setrecursionlimit(10**9)
I=lambda:list(map(int,input().split()))
n,m=I()
g=[set() for i in range(n+1)]
xx=[0]*(n+1)
for i in range(m):
x,y=I()
g[x].add(y)
g[y].add(x)
parent=[i for i in range(n+1)]
def find(x):
while x!=parent[x]:
x=paren... |
1261_B2. Optimal Subsequences (Hard Version) | This is the harder version of the problem. In this version, 1 ≤ n, m ≤ 2⋅10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.
You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more e... | ```python
from bisect import bisect_left, bisect_right, insort_right
class SquareSkipList:
def __init__(self, values=None, sorted_=False, square=1000, seed=42):
inf = float("inf")
self.square = square
if values is None:
self.rand_y = seed
self.layer1 = [inf]
... |
1283_D. Christmas Trees | There are n Christmas trees on an infinite number line. The i-th tree grows at the position x_i. All x_i are guaranteed to be distinct.
Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.
There are m people who want t... | ```python
import heapq
n,m = map(int,input().split())
x = sorted(map(int,input().split()))
# (distance, position, direction, maxval)
pos = [(1,x[0]-1,-1,m), (1,x[-1]+1,1,m)]
for i in range(n-1):
left = (x[i+1]-x[i])//2
right = (x[i+1]-x[i]-1)//2
if left:
pos.append((1,x[i]+1,1,left))
if right:... |
1327_A. Sum of Odd Integers | You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases.
The next t lines... | ```python
import collections
class Solution:
def solve(self, n, k):
isKOdd = k & 1
isNOdd = n & 1
if isKOdd ^ isNOdd:
return False
return k**2 <= n
sol = Solution()
t = int(input().strip())
# [n,m] = list(map(int, input().strip().split()))
for i in range(t):
... |
1368_A. C+= | Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change).
In a prototype progr... | ```python
t=int(input())
c=[]
for i in range(t):
a,b,n=input().split()
a,b,n=int(a),int(b),int(n)
count=0
while True:
if a<b:
a=a+b
else:
b=a+b
count+=1
if max(a,b)>n:
break
c.append(count)
for j in c:
print(j)
``` |
1389_C. Good String | Let's call left cyclic shift of some string t_1 t_2 t_3 ... t_{n - 1} t_n as string t_2 t_3 ... t_{n - 1} t_n t_1.
Analogically, let's call right cyclic shift of string t as string t_n t_1 t_2 t_3 ... t_{n - 1}.
Let's say string t is good if its left cyclic shift is equal to its right cyclic shift.
You are given str... | ```python
t = int(input())
for i in range(t):
s=input()
ans=0
e=len(s)
qr=0
for j in range(10):
for q in range(10):
b=False
r=0
for i in range(len(s)):
if j!=q:
if (s[i]==str(j)) and (not b):
... |
1409_F. Subsequences of Length Two | You are given two strings s and t consisting of lowercase Latin letters. The length of t is 2 (i.e. this string consists only of two characters).
In one move, you can choose any character of s and replace it with any lowercase Latin letter. More formally, you choose some i and replace s_i (the character at the positio... | ```python
n,k = map(int, input().split())
s,p = input(), input()
a,b = p[0],p[1]
if a==b:
x = min(s.count(a)+k,n)
print(x*(x-1)>>1)
else:
dp = [[-10000]*(k+2) for _ in range(n+2)]
dp[1][1] = 0
for i in range(n):
for q in range(i+2,0,-1):
for t in range(min(k,i+1)+1,0,-1):
... |
1430_D. String Deletion | You have a string s consisting of n characters. Each character is either 0 or 1.
You can perform operations on the string. Each operation consists of two steps:
1. select an integer i from 1 to the length of the string s, then delete the character s_i (the string length gets reduced by 1, the indices of characters ... | ```python
'''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineering College
'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,i... |
1453_F. Even Harder | Gildong is now developing a puzzle game. The puzzle consists of n platforms numbered from 1 to n. The player plays the game as a character that can stand on each platform and the goal of the game is to move the character from the 1-st platform to the n-th platform.
The i-th platform is labeled with an integer a_i (0 ≤... | ```python
MAX_N = 3000
inf = MAX_N
def solve():
global inf
n = int(input())
a = [0] + list(map(int, input().split()))
dp = [[0] * (n + 1) for i in range(n + 1)]
for i in range(2, n + 1):
cnt = 0
for j in range(i, n + 1):
dp[i][j] = inf
for j in range(i - 1,... |
1504_B. Flip the Bits | There is a binary string a of length n. In one operation, you can select any prefix of a with an equal number of 0 and 1 symbols. Then all symbols in the prefix are inverted: each 0 becomes 1 and each 1 becomes 0.
For example, suppose a=0111010000.
* In the first operation, we can select the prefix of length 8 sin... | ```python
# from sys import stdin,stdout
# input=stdin.readline
import math
# t=int(input())
from collections import Counter
import bisect
for _ in range(int(input())):
n = int(input())
a = list(map(int,input()))
b = list(map(int,input()))
# print(a,b)
count = [0 for i in range(n)]
if a[0]:
... |
1528_A. Parsa's Humongous Tree | Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He de... | ```python
import sys
input = sys.stdin.buffer.readline
def main():
t = int(input()); INF = float("inf")
for _ in range(t):
n = int(input())
L = []; R = []
for i in range(n):
l,r = map(int,input().split())
L.append(l); R.append(r)
G = [[] for _ in range(n)... |
226_B. Naughty Stone Piles | There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.
During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of... | ```python
class CodeforcesTask226BSolution:
def __init__(self):
self.result = ''
self.n = 0
self.piles = []
self.q = 0
self.variants = []
def read_input(self):
self.n = int(input())
self.piles = [int(x) for x in input().split(" ")]
self.q = int(in... |
275_A. Lights Out | Lenny is playing a game on a 3 × 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be swit... | ```python
matrix=[[1]*3 for i in range(3)]
togg=[[0]*3 for i in range(3)]
for i in range(3):
togg[i]=list(map(int,input().split()))
for i in range(3):
for j in range(3):
if togg[i][j]%2!=0:
matrix[i][j]=int(not matrix[i][j])
if i-1>=0:
matrix[i-1][j]=int(not matr... |
298_C. Parity Game | You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a... | ```python
a=input()
b=input()
tot1=0
tot2=0
for i in a:
tot1+=int(i)
for i in b:
tot2+=int(i)
if tot1+tot1%2>=tot2:
print("YES")
else:
print("NO")
``` |
321_A. Ciel and Robot | Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all:
* 'U': go up, (x, y) → (x, y+1);
* 'D': go down, (x, y) → (x, y-1);
* 'L': go left... | ```python
#http://codeforces.com/problemset/problem/321/A
import logging as log
class Point(object):
def __init__(self, x,y):
self.x, self.y = x, y
def __str__(self):
return "({}, {})".format(self.x, self.y)
def __add__(self, other):
#add 2 points together
return Point(self.x + other.x, self.y + othe... |
369_C. Valera and Elections | The city Valera lives in is going to hold elections to the city Parliament.
The city has n districts and n - 1 bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from 1 to n, inclusive. Furthermore, for each r... | ```python
n = int(input())
white = []
g = [[] for _ in range(n)]
d = [0] * n
for i in range(n - 1):
x, y, t = list(map(int, input().strip().split()))
x -= 1;
y -= 1;
# print(x,y)
if x >= 0 and y >= 0 and x < n and y < n:
g[x].append(y)
g[y].append(x)
if t == 2:
white.appe... |
391_C2. The Tournament | This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points.
Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined,... | ```python
m = 301000
ns = [0] * m
es = [0] * m
c = [0] * m
b = [0] * m
t = [0] * m
P = 0
def add(b, k):
k = t[k]
while k:
e = es[k]
if b[-1] > e: b[-1] = e
b[e] += 1
k = ns[k]
def delete(b):
for i in range(b[m - 1], m + 1):
if b[i]:
b[i] -= 1
b[-... |
413_C. Jeopardy! | 'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2.
The finals will have n questions, m of them are auction quest... | ```python
n, m = tuple(map(int, str.split(input())))
a = tuple(map(int, str.split(input())))
mi = tuple(map(int, str.split(input())))
ms = sorted(map(lambda i: a[i - 1], mi), reverse=True)
points = 0
for i, ai in enumerate(a):
if i + 1 not in mi:
points += ai
for m in ms:
if m > points:
po... |
43_E. Race | Today s kilometer long auto race takes place in Berland. The track is represented by a straight line as long as s kilometers. There are n cars taking part in the race, all of them start simultaneously at the very beginning of the track. For every car is known its behavior — the system of segments on each of which the s... | ```python
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, s = map(int, input().split())
data = [dict() for _ in range(n)]
for i in range(n):
k, *a = map(int, input().split())
cur = 0
for j in range(0, 2 * k, 2):
data[i][cur... |
462_B. Appleman and Card Game | Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on i... | ```python
n,k=map(int,input().split())
s=input()
di=dict()
for i in s:di[i]=di.get(i,0)+1
ans=0
se=list(set(s))
se.sort(key=lambda x:di[x],reverse=1)
for i in se:
ans+=min(k,di[i])*min(di[i],k)
k-=min(di[i],k)
if not k:break
print(ans)
``` |
486_A. Calculating Function | For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 ≤ n ≤ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | ```python
if __name__=="__main__":
n=int(input())
if(n&1):
print(-1*(n+1)//2)
else:
print(n//2)
``` |
534_B. Covered Path | The on-board computer on Polycarp's car measured that the car speed at the beginning of some section of the path equals v1 meters per second, and in the end it is v2 meters per second. We know that this section of the route took exactly t seconds to pass.
Assuming that at each of the seconds the speed is constant, and... | ```python
from collections import Counter,defaultdict,deque
import heapq as hq
from itertools import count, islice
#alph = 'abcdefghijklmnopqrstuvwxyz'
#from math import factorial as fact
import math
import sys
input=sys.stdin.readline
#print=sys.stdout.write
#tt = int(input())
#total=0
#n = int(input())
#n,m,k = [int... |
559_B. Equivalent Strings | Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2... | ```python
def equal(s):
if len(s)%2==1 : return s
m = len(s)//2
a=equal(s[:m])
b=equal(s[m:])
return a+b if a<b else b+a
print("YES" if equal(input())==equal(input()) else 'NO')
``` |
584_E. Anton and Ira | Anton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible.
More formally, we have two permutations, p and s of numbers from 1 to n. We can swap pi and pj, by pay... | ```python
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = {}
for i in range(n):
c[b[i]] = i
b = []
for i in range(n):
a[i] = c[a[i]]
print(sum(abs(a[i] - i) for i in range(n)) >> 1)
while True:
for i in range(n):
if a[i] < i:
for j in range(a[... |
606_E. Freelancer's Dreams | Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site.
He has suggestions to wo... | ```python
from fractions import Fraction
def higher(x1, y1, x2, y2):
if x1 == 0:
if x2 == 0:
return
def min_days(p, q, pr):
ma = max(a for a, b in pr)
mb = max(b for a, b in pr)
pr.sort(key=lambda t: (t[0], -t[1]))
ch = [(0, mb)]
for a, b in pr:
if a == ch[-1][0]... |
678_D. Iterated Linear Function | Consider a linear function f(x) = Ax + B. Let's define g(0)(x) = x and g(n)(x) = f(g(n - 1)(x)) for n > 0. For the given integer values A, B, n and x find the value of g(n)(x) modulo 109 + 7.
Input
The only line contains four integers A, B, n and x (1 ≤ A, B, x ≤ 109, 1 ≤ n ≤ 1018) — the parameters from the problem s... | ```python
import sys
import bisect
from bisect import bisect_left as lb
input_=lambda: sys.stdin.readline().strip("\r\n")
from math import log
from math import gcd
from math import atan2,acos
from random import randint
sa=lambda :input_()
sb=lambda:int(input_())
sc=lambda:input_().split()
sd=lambda:list(map(int,input_(... |
768_A. Oath of the Night's Watch | "Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple... | ```python
nb_steward = int(input())
strengths = [int(x) for x in input().split()]
mins = strengths.count(min(strengths))
maxs = strengths.count(max(strengths))
print(max(0, nb_steward - mins - maxs))
``` |
791_E. Bear and Company | Bear Limak prepares problems for a programming competition. Of course, it would be unprofessional to mention the sponsor name in the statement. Limak takes it seriously and he is going to change some words. To make it still possible to read, he will try to modify each word as little as possible.
Limak has a string s t... | ```python
# http://codeforces.com/contest/771/problem/D
"""
DP-solution.
For each state (v, k, x, v_is_last_letter) we trial a step along the v, k and x
axes and check that
dp[future_state] = min(dp[future_state], dp[state] + cost_of_move)
Hence this implicitly reults in the one with least cost.
V, K, X are arrays th... |
812_B. Sagheer, the Hausmeister | Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.
The building consists of n floors with stairs at the left and the right sides... | ```python
n, m = list(map(int, input().split()))
m += 2
l = []
do = False
for i in range(n):
s = input().strip()
if s.find('1') != -1 or do:
do = True
l.append(s)
n = len(l)
if n == 0:
print(0)
exit()
dp = []
for i in range(n):
dp.append([None] * 2)
for i in range(n):
R = 0
for j in range(m):
if l[i][j]... |
858_E. Tests Renumeration | The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.
Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.
Vladimir wants to re... | ```python
import random
def genTemp():
sl = ""
firstTime = True
while firstTime or sl in pre or sl in post:
sl = ""
firstTime = False
for i in range(6):
sl += chr(random.randint(ord("a"), ord("z")))
return sl
n = int(input())
e = 0
pre = set()
post = set()
for i in... |
883_K. Road Widening | Mayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy!
The Mayor thinks that one of the main city streets could be considerably widened on account of lawn nobody needs anyway. Moreover, that might help reduce the car jams which happen from time to time o... | ```python
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n = int(input())
s = []
g = []
forwardBound = []
backwardBound = []
for _ in range(n):
sCur,gCur = map(int,input().split())
s.append(sCur)
g.append(gCur)
forwardBound.append(s[0] + g[0])
for i in range(1,n):
if forwardB... |
928_C. Dependency management | Polycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity.
A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with lengt... | ```python
def scan_project():
name, version_str = input().split()
return (name, int(version_str))
n = int(input())
projects, depends = [], {}
for i in range(n):
if i > 0:
input()
project = scan_project()
projects.append(project)
depends[project] = [scan_project() for j in range(int(inpu... |
982_E. Billiard | Consider a [billiard table](https://en.wikipedia.org/wiki/Billiard_table) of rectangular size n × m with four pockets. Let's introduce a coordinate system with the origin at the lower left corner (see the picture).
<image>
There is one ball at the point (x, y) currently. Max comes to the table and strikes the ball. ... | ```python
from functools import reduce
import math
def bezout(a, b):
if a == 0:
return (0, 1)
else:
x, y = bezout(b % a, a)
return y - (b//a) * x, x
def lcm(a, b):
return abs(a*b) // math.gcd(a, b)
def CRT(a1, m1, a2, m2):
g = math.gcd(m1, m2)
if (a1-a2) % g != 0:
... |
p02562 AtCoder Library Practice Contest - MinCostFlow | You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j). A nonnegative integer A_{i,j} is written for each square (i,j).
You choose some of the squares so that each row and column contains at most K chosen squares. Under this constraint, calculate the maximum v... | ```python
import heapq
class mcf_graph:
def __init__(self, n=0):
self._n = n
self.g = [[] for _ in range(n)]
self.pos = []
def add_edge(self, frm, to, cap, cost):
m = len(self.pos)
e1 = self._edge(to, cap, cost)
e2 = self._edge(frm, 0, -cost)
e1.rev =... |
p02693 AtCoder Beginner Contest 165 - We Love Golf | Takahashi the Jumbo will practice golf.
His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive).
If he can achieve the objective, print `OK`; if he cannot, print `NG`.
Constraints
* All values in input are integers.
* 1 \leq A \leq B \... | ```python
k=int(input())
a,b=map(int,input().split())
print('OK' if b//k > (a-1)//k else 'NG')
``` |
p02822 AtCoder Beginner Contest 149 - Surrounded Nodes | Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N).
Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all th... | ```python
import sys
sys.setrecursionlimit(10 ** 6)
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 MI1(): return map(int1, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readl... |
p02958 AtCoder Beginner Contest 135 - 0 or 1 Swap | We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.
You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.
Print `YES` if you can sort p in ascending order in th... | ```python
N=int(input())
p=list(map(int,input().split()))
a=0
for i in range(N):
if p[i]!=i+1:
a+=1
if a>=3:
print('NO')
else:
print('YES')
``` |
p03240 AtCoder Beginner Contest 112 - Pyramid | In the Ancient Kingdom of Snuke, there was a pyramid to strengthen the authority of Takahashi, the president of AtCoder Inc.
The pyramid had center coordinates (C_X, C_Y) and height H. The altitude of coordinates (X, Y) is max(H - |X - C_X| - |Y - C_Y|, 0).
Aoki, an explorer, conducted a survey to identify the center ... | ```python
N=int(input())
z=[]
for i in range(N):
z.append(list(map(int,input().split())))
h=max(zz[2] for zz in z)
while(1):
flag=1
for x in range(101):
for y in range(101):
for zz in z:
if max(h-abs(zz[0]-x)-abs(zz[1]-y),0) != zz[2]:
break
... |
p03393 AtCoder Grand Contest 022 - Diverse Word | Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.
A word is called diverse if and only if it is a nonempty string of English lowercase... | ```python
from string import*
from itertools import*
b = ascii_lowercase
s = input()
if len(s) < 26:
print(s + sorted(set(b) - set(s))[0])
else:
d = -[p*len(list(k)) for p, k in groupby([i < j for i, j in zip(s[-1::-1], s[-2::-1])])][0] - 2
print(-(d < -26) or s[:d] + sorted(set(s[d+1:]) - set(b[:ord(s[d]) ... |
p03556 AtCoder Beginner Contest 077 - Around Square | Find the largest square number not exceeding N. Here, a square number is an integer that can be represented as the square of an integer.
Constraints
* 1 \leq N \leq 10^9
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the largest square number not exceeding N... | ```python
import math;print(round((math.sqrt(int(input()))//1))**2)
``` |
p03711 AtCoder Beginner Contest 062 - Grouping | Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below. Given two integers x and y (1 ≤ x < y ≤ 12), determine whether they belong to the same group.
b4ab979900ed647703389d4349eb84ee.png
Constraints
* x and y are integers.
* 1 ≤ x < y ≤ 12
Input
Input i... | ```python
L=[1,0,1,2,1,2,1,1,2,1,2,1]
a,b=map(int,input().split())
if L[a-1]==L[b-1]:
print("Yes")
else:
print("No")
``` |
p03867 AtCoder Regular Contest 064 - Rotated Palindromes | Takahashi and Aoki are going to together construct a sequence of integers.
First, Takahashi will provide a sequence of integers a, satisfying all of the following conditions:
* The length of a is N.
* Each element in a is an integer between 1 and K, inclusive.
* a is a palindrome, that is, reversing the order of elem... | ```python
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
n,k = list(map(int, input().split()))
M = 10**9+7
### 約数列挙
def fs(n):
s = set()
for i in range(1,int(n**0.5)+2):
if n%i==0:
s.add(i)
... |
p04031 AtCoder Beginner Contest 043 - Be Together | Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.
He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See ... | ```python
n=int(input())
A=list(map(int,input().split()))
r=4*10**6
for i in range(min(A),max(A)+1):
d=0
for j in range(n):
d+=(A[j]-i)**2
r=min(r,d)
print(r)
``` |
p00115 Starship UAZ Advance | Stellar history 2005.11.5. You are about to engage an enemy spacecraft as the captain of the UAZ Advance spacecraft. Fortunately, the enemy spaceship is still unnoticed. In addition, the space coordinates of the enemy are already known, and the "feather cannon" that emits a powerful straight beam is ready to launch. Af... | ```python
# -*- coding: utf-8 -*-
import sys
import os
import math
import random
# refs
# https://shikousakugo.wordpress.com/2012/06/27/ray-intersection-2/
def det(a, b, c):
return + a[0] * b[1] * c[2] \
+ a[2] * b[0] * c[1] \
+ a[1] * b[2] * c[0] \
- a[2] * b[1] * c[0] \
... |
p00248 Magic Square | A witch named Marie lived deep in a remote forest. Since she is a witch, she magically covers everything she needs to live, such as food, water, and fuel.
Her magic is activated by drawing a magic circle using some magical stones and strings. This magic circle is drawn by placing stones and tying several pairs of ston... | ```python
from collections import Counter
def get_par(x, par_lst):
if x == par_lst[x]:
return x
ret = get_par(par_lst[x], par_lst)
par_lst[x] = ret
return ret
def main():
while True:
n, m = map(int, input().split())
if n == 0:
break
par_lst = [i for i in range(n)]
counter = [0] * n
... |
p00429 String | Given a string consisting of only numbers from 0 to 9, consider the operation of creating a new string from that string according to the following rules. Read the given string one character at a time from the left end. Go, if the same number a continues r, write the number r and the number a in this order without separ... | ```python
def change(x) :
i = 0
ans = []
while True :
if i >= len(x) : break
cnt = 1
j = 1
while True :
if i+j >= len(x) or x[i+j] != x[i] :
ans = ans + list(str(cnt))
ans.append(x[i])
i += cnt
break
... |
p00769 Hierarchical Democracy | Hierarchical Democracy
The presidential election in Republic of Democratia is carried out through multiple stages as follows.
1. There are exactly two presidential candidates.
2. At the first stage, eligible voters go to the polls of his/her electoral district. The winner of the district is the candidate who takes a ... | ```python
N = int(input())
def rec ():
global now,l
if s[now].isdigit():
res = 0
while (now < l and s[now].isdigit()):
res = ((10 * res) + int(s[now]))
now += 1
return (res+1)//2
else:
g = []
while(now < l and s[now] == '['):
now += 1
g.append(rec())
now += 1
g.sort()
return sum(g[:(len(... |
p01303 Petting Cats | Many cats live on the campus of a school. Natsume's daily routine is to pet those cats. However, the cats may be capricious and go for a walk off campus.
The campus site is a rectangle with each side parallel to the x-axis or y-axis and is surrounded by a fence except for the gate, but cats can freely enter and exit t... | ```python
for _ in range(int(input())):
x, y, w, h = map(int,input().split())
c = 0
for _ in range(int(input())):
a, b = map(int,input().split())
if x <= a and a <= x + w and y <= b and b <= y + h:c += 1
print(c)
``` |
p01784 Parentheses | Example
Input
3
()(()((
))()()(()
)())(())
Output
Yes | ```python
def solve():
N = int(input())
T0 = []
T1 = []
su = 0
for i in range(N):
s = input()
a = 0
for c in s:
if c == '(':
a += 1
elif a > 0:
a -= 1
b = 0
for c in reversed(s):
if c == ')':
... |
p01919 Country in Distortion | D: Country In Distortion-
story
Alice was completely bored. This is because the White Rabbit, who is always playing with him, is out to Trump Castle. (Ah, I wish I had gone out with him in this case.) Alice thought. However, this is a country of distortion. If you go out so easily, you will get very tired. What does ... | ```python
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
inf = float('inf')
n,m = map(int,input().split())
pathT = [{} for _ in range(n)]
for i in range(m):
x,y,t = map(int,input().split())
x -= 1
y -= 1
pathT[x][y] = t
pathT[y][x] = t
import heapq
def Dijkstra(edge,start):
... |
p02057 MOD Rush | F: MOD Rush
problem
Given a positive integer sequence A of length N and a positive integer sequence B of length M.
For all (i, j) (1 \ leq i \ leq N, 1 \ leq j \ leq M), find the remainder of A_i divided by B_j and output the sum of them.
Input format
N M
A_1 A_2 ... A_N
B_1 B_2 ... B_M
Constraint
* 1 \ leq N,... | ```python
from collections import Counter
from itertools import accumulate
N, M = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
K = max(A)
table = [0]*(K+1)
table[0] = M
for b, v in Counter(B).items():
for j in range(b, K+1, b):
table[j] -= b*v
for j... |
p02199 Run | Run, Twins
E869120 You started running from home to school at a speed of $ P $ meters per minute.
square1001 noticed E869120's forgotten thing $ A $ minutes after E869120 left home and chased at $ Q $ meters per minute.
Then E869120 noticed something left behind $ B $ minutes after E869120 left home and turned back ... | ```python
a,b = map(int,input().split())
p,q,r = map(int,input().split())
print((b*p+b*r+a*q)/(r+q))
``` |
p02353 RSQ and RUQ | Write a program which manipulates a sequence $A$ = {$a_0, a_1, ..., a_{n-1}$} with the following operations:
* $update(s, t, x)$: change $a_s, a_{s+1}, ..., a_t$ to $x$.
* $getSum(s, t)$: print the sum of $a_s, a_{s+1}, ..., a_t$.
Note that the initial values of $a_i ( i = 0, 1, ..., n-1 )$ are 0.
Constraints
* $... | ```python
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
INF = 10 ** 9 + 1 # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7
def debug(*x):
print(*x, file=sys.stderr)
def set_depth(depth):
global DEPTH, SEGTREE_SIZE, NONLEAF_SIZE
DEPTH = depth
SEGTREE_... |
1006_D. Two Strings Swaps | You are given two strings a and b consisting of lowercase English letters, both of length n. The characters of both strings have indices from 1 to n, inclusive.
You are allowed to do the following changes:
* Choose any index i (1 ≤ i ≤ n) and swap characters a_i and b_i;
* Choose any index i (1 ≤ i ≤ n) and sw... | ```python
n = int(input())
a = input()
b = input()
l = 0; r = n-1; ans = 0
while l < r:
x1 = a[l]; x2 = a[r]
y1 = b[l]; y2 = b[r]
if (x1 == y1 and x2 == y2) or (x1 == y2 and x2 == y1) or (x1 == x2 and y1 == y2):
ans += 0
elif (x1 == y1 or x2 == y2) or (x1 == y2 or x2 == y1) or (y1 == y2):
... |
102_C. Homework | Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to l... | ```python
import itertools
import math
import time
def timer(f):
def tmp(*args, **kwargs):
t = time.time()
res = f(*args, **kwargs)
print("Время выполнения функции: %f" % (time.time()-t))
return res
return tmp
#n = int(input())
s = input()
n = int(input())
array = [[0, chr(i... |
1051_C. Vasya and Multisets | Vasya has a multiset s consisting of n integer numbers. Vasya calls some number x nice if it appears in the multiset exactly once. For example, multiset \{1, 1, 2, 3, 3, 3, 4\} contains nice numbers 2 and 4.
Vasya wants to split multiset s into two multisets a and b (one of which may be empty) in such a way that the q... | ```python
n = int(input())
s = list(map(int, input().split()))
d = {}
mt = False
mti = -1
for i in range(len(s)):
if s[i] not in d:
d[s[i]] = 1
else:
d[s[i]] += 1
if d[s[i]] > 2:
mt = True
mti = i
good = []
for i in d.keys():
if d[i] == 1:
good.append(... |
1073_D. Berland Fair | XXI Berland Annual Fair is coming really soon! Traditionally fair consists of n booths, arranged in a circle. The booths are numbered 1 through n clockwise with n being adjacent to 1. The i-th booths sells some candies for the price of a_i burles per item. Each booth has an unlimited supply of candies.
Polycarp has de... | ```python
from sys import stdin
input = stdin.readline
n, t = map(int, input().split())
lst = list(map(int, input().split()))
s = sum(lst)
x = min(lst)
candy = n * (t // s)
t -= s * (t // s)
while t >= x:
s, c = 0, 0
for i in lst:
if i <= t - s:
c += 1
s += i
candy += c * (... |
1095_D. Circular Dance | There are n kids, numbered from 1 to n, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as p_1, p_2, ..., p_n (all these numbers are from 1 to n and are distinct, so p is a permutation). Let the next kid for a kid p_i be kid p_{i + 1} if i < n and p_1 otherwise. After the da... | ```python
n = int(input())
p = [(None, None)]
for _ in range(n):
p.append(list(map(int, input().split())))
if n==3:
print("1 2 3")
else:
for idx, (a, b) in enumerate(p[1:], 1):
if a in p[b]:
p[idx] = [b]
elif b in p[a]:
p[idx] = [a]
return_val = [p[1][0]]
n-=1
while n:
return_val.append(p[r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.