name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
p03289 AtCoder Beginner Contest 104 - AcCepted | You are given a string S. Each character of S is uppercase or lowercase English letter. Determine if S satisfies all of the following conditions:
* The initial character of S is an uppercase `A`.
* There is exactly one occurrence of `C` between the third character from the beginning and the second to last character (i... | ```python
S = input()
if S[0]=='A' and S[2:-1].count('C')==1 and (S[1:S.find('C')]+S[S.find('C')+1:]).islower():
print('AC')
else:
print('WA')
``` |
p03445 AtCoder Petrozavodsk Contest 001 - Simple APSP Problem | You are given an H \times W grid. The square at the top-left corner will be represented by (0, 0), and the square at the bottom-right corner will be represented by (H-1, W-1).
Of those squares, N squares (x_1, y_1), (x_2, y_2), ..., (x_N, y_N) are painted black, and the other squares are painted white.
Let the shorte... | ```python
from collections import deque, Counter
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
mod = 10**9 + 7
h, w = map(int, input().split())
n = int(input())
ans = 0
black = []
row = Counter()
column = Counter()
for _ in range(n):
x, y = map(int, input().split())
row[x] += 1
col... |
p03605 AtCoder Beginner Contest 073 - September 9 | It is September 9 in Japan now.
You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N?
Constraints
* 10≤N≤99
Input
Input is given from Standard Input in the following format:
N
Output
If 9 is contained in the decimal notation of N, print `Yes`; if not, print `No... | ```python
n = input()
ans = 'Yes' if '9' in n else 'No'
print(ans)
``` |
p03766 AtCoder Regular Contest 071 - Infinite Sequence | How many infinite sequences a_1, a_2, ... consisting of {{1, ... ,n}} satisfy the following conditions?
* The n-th and subsequent elements are all equal. That is, if n \leq i,j, a_i = a_j.
* For every integer i, the a_i elements immediately following the i-th element are all equal. That is, if i < j < k\leq i+a_i, a_j... | ```python
n = int(input())
dp = [0] * (n+1)
mod = 10**9+7
dp[0] = n
dp[1] = n*n
SUM = n+n*n
for i in range(2,n):
dp[i] = (n-1)*(n-1) + n-i+1+SUM-dp[i-2]
dp[i] %= mod
SUM += dp[i]
SUM %= mod
print(dp[n-1])
``` |
p00027 What day is today? | Your task is to write a program which reads a date (from 2004/1/1 to 2004/12/31) and prints the day of the date. Jan. 1, 2004, is Thursday. Note that 2004 is a leap year and we have Feb. 29.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset cons... | ```python
days = [31,29,31,30,31,30,31,31,30,31,30,31]
ans = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
while True:
idx = 3
m,d = map(int, input().split())
if m==0: break
print(ans[(idx+sum(days[:m-1])+d-1)%7])
``` |
p00158 Collatz's Problem | For a positive integer n
* If n is even, divide by 2.
* If n is odd, multiply by 3 and add 1.
If you repeat the above operation, the result will be 1. A problem called "Colatz conjecture" is that repeating this operation for any positive integer n will always result in 1. This problem is an unsolved problem, also k... | ```python
while 1:
n = int(input())
if n == 0:
break
cnt = 0
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = n * 3 + 1
cnt += 1
print(cnt)
``` |
p00315 Quality Management | The cloth coasters produced and sold by Aizu Takada City are known for their symmetrical design and great beauty. As part of quality control, Aizu Takada City has installed cameras on the production line to automatically verify that the images obtained by shooting each coaster are symmetrical. Each coaster is represent... | ```python
def next(N, i):
return ((N-i-1)+N)%N
def getState(N, G, i, j):
return G[i][j] == G[i][next(N, j)] and G[i][j] == G[next(N, i)][j] and G[i][j] == G[next(N, i)][next(N, j)]
def getInit(N, G):
dcnt = 0
for i in range(N//2):
for j in range(N//2):
if not getState(N, G, i, j)... |
p00485 Shopping in JOI Kingdom | There are N towns in JOI, which are connected by M bidirectional roads. There are shopping malls in K towns, and the people go to one of those towns through the road to shop.
Depending on the location of your home, you may have to travel long distances to go shopping, which is very inconvenient. To understand this sit... | ```python
from heapq import heappop as pop
from heapq import heappush as push
INF = 10 ** 18
class edge:
def __init__(self, to, cost):
self.to = to
self.cost = cost
#V, E, r = map(int,input().split())
N, M, K = map(int,input().split())
G = [[] for i in range(N)]
#G[i]...頂点iからの辺list、(行き先、コスト)
d = [INF for... |
p00671 Live Schedule | YOKARI TAMURA is a nationally famous artist. This month YOKARI will be touring live for D days. Divide this country into C different regions when deciding on a tour schedule. YOKARI benefits from performing live in an area, which is represented by a positive integer. As a general rule, YOKARI will perform up to one liv... | ```python
from itertools import accumulate
def main():
while True:
c, d, w, x = map(int, input().split())
if c == 0:
break
es = [[] for _ in range(d)]
for _ in range(c):
lst = list(map(int, input().split()))
for i in range(d):
es[i].append(lst[i])
fs = [[] for _ in r... |
p00814 Life Line | Let's play a new board game ``Life Line''.
The number of the players is greater than 1 and less than 10.
In this game, the board is a regular triangle in which many small regular triangles are arranged (See Figure l). The edges of each small triangle are of the same length.
<image>
Figure 1: The board
The size of ... | ```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 ... |
p01078 Star | Problem
Find the area of a regular N / K polygon inscribed in a circle with a radius of 1.
However, a regular N / K polygon is defined as "the outermost figure that takes N points on the circumference at equal intervals and connects each point every K-1".
For example, a 5/2 polygon can be drawn as follows. First, ... | ```python
# AOJ 1593: Star
# Python3 2018.7.13 bal4u
import math
PI = 3.1415926535897932384626433832795
# area = n*r^2*sin(180/n)*cos(180k/n)*sec(180(k-1)/n), for n/k star
N, K = map(int, input().split())
print(N*math.sin(PI/N)*math.cos(K*PI/N)/math.cos((K-1)*PI/N))
``` |
p01830 Delete Files | Example
Input
3
y 7
y 6
n 5
Output
1 | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
L = [0]*N; D = [0]*N
for i in range(N):
l, d = readline().split()
L[i] = +(l == 'y')
D[i] = int(d)
ans = 0
*I, = range(N)
I.sort(key = D.__getitem__)
U = [0]*N... |
p02112 Hating Crowd | Problem
Neat lives on the world line for a total of 360 days until the 30th of every month for 1 year and 12 months. In that world, N consecutive holidays with the same schedule were applied to people all over the world every year. Consecutive holidays i are consecutive Vi days starting from Mi month Di day.
NEET is ... | ```python
N = input()
N = int(N)+1
X = [0]
C = [0]*360
for i in range(1,N):
x = input()
X.append(x.split())
i_start = (int(X[i][0])-1)*30+int(X[i][1])-1
i_end = i_start+int(X[i][2])-1
for j in range(i_start,i_end+1):
C[j%360] = max(C[j%360],int(X[i][3]))
for k in range(1,int(X[i][3])... |
p02252 Fractional Knapsack Problem | You have $N$ items that you want to put them into a knapsack of capacity $W$. Item $i$ ($1 \le i \le N$) has weight $w_i$ and value $v_i$ for the weight.
When you put some items into the knapsack, the following conditions must be satisfied:
* The total value of the items is as large as possible.
* The total weight of... | ```python
N, W = map(int, input().split())
W_calc = W
ans = 0
items = []
for _ in range(N):
v, w = map(int, input().split())
density = v / w
items.append([density, v, w])
items.sort(reverse=True)
for density, v, w in items:
if w < W_calc:
W_calc -= w
ans += v
else:
ans +... |
p02400 Circle | Write a program which calculates the area and circumference of a circle for given radius r.
Constraints
* 0 < r < 10000
Input
A real number r is given.
Output
Print the area and circumference of the circle in a line. Put a single space between them. The output should not contain an absolute error greater than 10-... | ```python
pi=3.141592653589
r=float(input())
print(f'{r*r*pi:7f} {2*r*pi}')
``` |
1003_B. Binary String Constructing | You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≤ i < n) such that s_i ≠ s_{i + 1}. It is guaranteed that the answer always exists.
For example, for the string "01010" there ar... | ```python
a,b,x=map(int,input().split())
x+=1
y=x//2
c=0
if x%2:
if a>b:
a-=1;c=1
else:
b-=1;c=2
s=(a-y)*'0'+y*'01'+(b-y)*'1'
if c:s=s+'0'if c==1 else '1'+s
print(s)
``` |
1027_C. Minimum Value Rectangle | You have n sticks of the given lengths.
Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose suc... | ```python
super_ans = []
for i in range(int(input())):
n = input()
if n == '4':
super_ans.append(input())
continue
elif n == '5':
a = sorted(map(int, input().split()))
if a[0] == a[1] and a[2] == a[3]:
super_ans.append(' '.join([str(a[0]), str(a[0]), str(a[2]), s... |
1070_A. Find a Number | You are given two positive integers d and s. Find minimal positive integer n which is divisible by d and has sum of digits equal to s.
Input
The first line contains two positive integers d and s (1 ≤ d ≤ 500, 1 ≤ s ≤ 5000) separated by space.
Output
Print the required number or -1 if it doesn't exist.
Examples
In... | ```python
import os
import sys
from io import BytesIO, IOBase
_print = print
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... |
1091_E. New Year and the Acquaintance Estimation | Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if a is a friend of b, then b is also a friend of a. Each user thus has a non-negative amount of friends.
This morning, somebody anonymously sent Bob the following link: [graph realization ... | ```python
def main():
n=int(input())
a=list(map(int,input().split()))
a.sort(reverse=True)
mod=sum(a)%2
counts=[0]*(n+1)
for guy in a:
counts[guy]+=1
cumcounts=[counts[0]]
for i in range(n):
cumcounts.append(cumcounts[-1]+counts[i+1])
partialsums=[0]
curr=0
fo... |
1110_C. Meaningless Operations | Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.
Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_commo... | ```python
import math
from sys import stdin
q = int(input())
l = stdin.read().splitlines()
for i in l:
n = int(i)
k = int(math.log2(n + 1))
if (1 << k) < n + 1:
print((1 << (k + 1)) - 1)
continue
else:
found = False
for j in range(2, int(math.sqrt(n)) + 1):
i... |
1180_C. Valeriy and Deque | Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A >... | ```python
import sys
n,q=list(map(int,input().split()))
a=list(map(int,input().split()))
mx1=max(a)
a1=[]
dp={}
for i in range(q):
a1.append(int(input()))
if a1==[]:
mx=0
else:
mx=max(a1)
count=0
while(1):
count+=1
val1=a[0]
val2=a[1]
if val1==mx1:
break
if val1>val2:
a.... |
1199_C. MP3 | One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers.
If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} ... | ```python
from collections import *
from math import *
n,k = map(int,input().split())
a = list(map(int,input().split()))
d = Counter(a)
a.sort()
val = [0 for i in range(400005)]
a = list(set(a))
a.sort()
n1 = len(a)
val[0] = d[a[0]]
for i in range(1,n1):
val[i] = val[i-1] + d[a[i]]
m = n1
#print(n1)
for m in range(... |
1216_B. Shooting | Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he wi... | ```python
n = map(int, input().split())
A = list(map(int, input().split()))
la = []
ind = 1
for a in A:
la.append((a, ind))
ind += 1
la.sort(key=lambda x: x[0], reverse=True)
# print(la)
x = 0
sm = 0
li = []
for tp in la:
a = tp[0]
sm += (a * x + 1)
x += 1
li.append(tp[1])
print(sm)
print(" ".join(str(i) fo... |
1239_C. Queue in the Train | There are n seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from 1 to n from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat i (1 ≤ i ≤ n) will decid... | ```python
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
from heapq import heappop, heappush, heapify
from collections import deque
class SWAG_Stack():
def __init__(self, F):
self.stack1 = deque()
self.stack2 = deque()
self.F = F
self.len = 0
def pu... |
1257_E. The Contest | A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of... | ```python
x,y,z=map(int,input().split())
d=[[],[],[]]
d[0]=list(map(int,input().split()))
d[1]=list(map(int,input().split()))
d[2]=list(map(int,input().split()))
dicto=[dict(),dict(),dict()]
dp=[[float("inf")]*(x+y+z+1) for i in range(3)]
for i in range(3):
for j in d[i]:
dicto[i][j]=1
dp[0][0]=0
mini=99999... |
1280_F. Intergalactic Sliding Puzzle | You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a 2 × (2k + 1) rectangular grid. The alien has 4k + 1 distinct organs, numbered 1 to 4k + 1.
In healthy such aliens, the organs are arranged in a particular way. For exam... | ```python
def solve(k, grid):
seek = *range(2*k + 2), *range(4*k + 1, 2*k + 1, -1)
flat = [seek[v] for v in grid[0] + grid[1][::-1] if v]
m = {
'L': 'l'*2*k + 'u' + 'r'*2*k + 'd',
'R': 'u' + 'l'*2*k + 'd' + 'r'*2*k,
'C': 'l'*k + 'u' + 'r'*k + 'd',
'D': 'CC' + 'R'*(2*k + 1) +... |
1300_E. Water Balance | There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right.
You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1},... | ```python
def main():
from sys import stdin,stdout
ans = []
stdin.readline()
for ai in map(int, map(int, stdin.readline().split())):
cnt=1
while ans and ai*ans[-1][0]<=ans[-1][1]*cnt:
c, r = ans.pop()
ai+=r
cnt+=c
ans.append((cnt, ai))
for... |
1324_F. Maximum White Subtree | You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black).
You have to solve the following problem for each vertex v: what is the maximum difference betwee... | ```python
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.m... |
1343_E. Weights Distributing | You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts).
Mike has planned a trip from the vertex (district) a to the vertex (district) b... | ```python
import collections
tests = int(input())
def bfs(start, edges):
q = collections.deque([start])
dist = [-1]*(n+1)
dist[start] = 0
while(len(q) > 0):
curr_node = q.popleft()
for idx, neighbour in enumerate(edges[curr_node]):
if dist[neighbour] == -1:
... |
1365_F. Swaps Again | Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid.
Each test case consists of an integer n and two arrays a and b, of size n. If after some (possibly zero) operations described below, array a can be transformed into array b, the ... | ```python
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
pair = dict()
possible = 1
if n % 2 == 1:
if a[n//2] != b[n//2]:
possible = 0
for i in range(n//2):
M, m = max(a[i], a[n- i - 1])... |
1385_F. Removing Leaves | You are given a tree (connected graph without cycles) consisting of n vertices. The tree is unrooted — it is just a connected undirected graph without cycles.
In one move, you can choose exactly k leaves (leaf is such a vertex that is connected to only one another vertex) connected to the same vertex and remove them w... | ```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... |
1407_D. Discrete Centrifugal Jumps | There are n beautiful skyscrapers in New York, the height of the i-th one is h_i. Today some villains have set on fire first n - 1 of them, and now the only safety building is n-th skyscraper.
Let's call a jump from i-th skyscraper to j-th (i < j) discrete, if all skyscrapers between are strictly lower or higher than ... | ```python
n = int(input())
a = list(map(int, input().split()))
dp = [10**9]*n
dp[0] = 0
s1 = [0]
s2 = [0]
for i in range(1, n):
dp[i] = dp[i-1] + 1
f1, f2 = True, True
while s1 and a[i] >= a[s1[-1]]:
if a[i] == a[s1[-1]]:
f1 = False
dp[i] = min(dp[i], dp[s1[-1]] + 1)
s... |
1428_B. Belted Rooms | In the snake exhibition, there are n rooms (numbered 0 to n - 1) arranged in a circle, with a snake in each room. The rooms are connected by n conveyor belts, and the i-th conveyor belt connects the rooms i and (i+1) mod n. In the other words, rooms 0 and 1, 1 and 2, …, n-2 and n-1, n-1 and 0 are connected with conveyo... | ```python
from sys import stdin
import sys
tt = int(stdin.readline())
for loop in range(tt):
n = int(stdin.readline())
s = stdin.readline()[:-1]
if ("<" not in s) or (">" not in s):
print (n)
continue
ans = 0
for i in range(n):
if s[(i-1)%n] == "-" or s[i] == "-":
... |
1451_B. Non-Substring Subsequence | Hr0d1y has q queries on a binary string s of length n. A binary string is a string containing only characters '0' and '1'.
A query is described by a pair of integers l_i, r_i (1 ≤ l_i < r_i ≤ n).
For each query, he has to determine whether there exists a good subsequence in s that is equal to the substring s[l_i… r_... | ```python
# Problem: B. Non-Substring Subsequence
# Contest: Codeforces - Codeforces Round #685 (Div. 2)
# URL: https://codeforces.com/contest/1451/problem/B
# Memory Limit: 256 MB
# Time Limit: 1000 ms
#
# KAPOOR'S
from sys import stdin, stdout
def INI():
return int(stdin.readline())
def INL():
return [int(_) ... |
1475_B. New Year's Number | Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021.
For example, if:
* n=4041, then the number n can be represented as the s... | ```python
t=int(input())
for T in range(t):
n=int(input())
x=n//2020
if (n-x*2020)<=x:
print('YES')
else:
print('NO')
``` |
14_E. Camels | Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with t humps, representing them as polylines in the plane. Each polyline consists of n vertices with coordinates (x1, y1), (x2, y2), ..., (xn, yn). The first ve... | ```python
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, t = map(int, input().split())
dp = [[[0] * 5 for _ in range(2 * t + 1)] for _ in range(n)]
dp[0][0] = [0] + [1] * 4
for i in range(n - 1):
for j in range(min(2 * t, i + 1)):
... |
1525_B. Permutation Sort | You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once).
You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation canno... | ```python
k = int(input())
a = []
import math
def nhap():
r = input()
r = r.split()
r =[int(i) for i in r]
return r
def kq(a):
minn = min(a)
maxx = max(a)
b = sorted(a)
if(b == a): return 0
if(a[0]== maxx and a[-1]== minn): return 3
if(a[0]== minn or a[-1]== maxx): return 1
return 2
for i in range(k):
num =... |
156_D. Clues | As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more ... | ```python
def dfs(node, my_cc):
vis[node] = True
acc[my_cc]+=1
for i in adj[node]:
if not vis[i]:
dfs(i, my_cc)
def ittDfs(node):
queue = [node]
curr = 0
while(queue):
node = queue.pop()
if vis[node]:
continue
vis[node] = True
acc[... |
177_G1. Fibonacci Strings | Fibonacci strings are defined as follows:
* f1 = «a»
* f2 = «b»
* fn = fn - 1 fn - 2, n > 2
Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba".
You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as... | ```python
F = ['', 'a', 'b', 'ba', 'bab', 'babba', 'babbabab', 'babbababbabba', 'babbababbabbababbabab', 'babbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbab... |
223_A. Bracket Sequence | A bracket sequence is a string, containing only characters "(", ")", "[" and "]".
A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([... | ```python
import sys
from math import gcd,sqrt,ceil,log2
from collections import defaultdict,Counter,deque
from bisect import bisect_left,bisect_right
import math
import heapq
from itertools import permutations
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
# sys.stdin = open('input.tx... |
246_D. Colorful Graph | You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci.
Let's consider all vertices of the graph, that are painted some color k. Let's denote a se... | ```python
from collections import defaultdict
l=lambda :map(int,input().split())
n,m=l()
c=list(l())
graph=defaultdict(set)
for i in range(m):
a,b=l()
if c[a-1]==c[b-1]:
continue
graph[c[a-1]].add(c[b-1])
graph[c[b - 1]].add(c[a - 1])
d,f=min(c),0
for i in sorted(graph):
h=len(graph[i])
... |
271_E. Three Horses | There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top an... | ```python
# written with help of editorial
n, m = map(int, input().split())
a = list(map(int, input().split()))
def gcd(x, y):
while y:
x, y = y, x % y
return x
g = 0
for x in a:
g = gcd(g, x - 1)
answer = 0
def process(x):
global answer
if x % 2 == 0:
return 0
for i in range... |
295_B. Greg and Graph | Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game:
* The game consists of n steps.
* On the i-th step Greg removes vertex number xi from the grap... | ```python
#!/usr/bin/env python3
# from typing import *
import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq
from array import array
def input():
return sys.stdin.readline()[:-1]
# sys.setrecursionlimit(1000000)
# _INPUT = """4
# 0 57148 51001 13357
# ... |
342_E. Xenia and Tree | Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue.
The distance between two tree nodes v and u is the number of edges in the shortest path between v and u... | ```python
class CentroidDecomposition():
def __init__(self, g):
self.g = g
self.n = len(g)
self.parent = [-1]*self.n
self.size = [1]*self.n
self.cdparent = [-1]*self.n
self.cddepth = [0]*self.n
self.cdorder = [-1]*self.n
self.cdused = [0]*self.n
... |
366_B. Dima and To-do List | You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.
Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in ... | ```python
n,k = map(int, input().split())
t = list(map(int, input().split()))
current_sum = None
flag = 1
for i in range(k):
if current_sum == None or sum(t[i :: k]) < current_sum:
current_sum = sum(t[i :: k])
flag = i+1
print(flag)
#print(min((sum(t[i :: k]), i) for i in range(k))[1] + 1)
``` |
38_A. Army | The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.
One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.
Vasya ha... | ```python
#!/usr/bin/python3
def readln(): return tuple(map(int, input().split()))
n, = readln()
d = readln()
a, b = readln()
print(sum(d[a - 1:b - 1]))
``` |
409_I. Feed the Golorp | Golorps are mysterious creatures who feed on variables. Golorp's name is a program in some programming language. Some scientists believe that this language is Befunge; golorps are tantalizingly silent.
Variables consumed by golorps can take values from 0 to 9, inclusive. For each golorp its daily diet is defined by it... | ```python
"""
Codeforces April Fools Contest 2014 Problem I
Author : chaotic_iak
Language: Python 3.3.4
"""
class InputHandlerObject(object):
inputs = []
def getInput(self, n = 0):
res = ""
inputs = self.inputs
if not inputs: inputs.extend(input().split(" "))
if n == 0:
... |
437_D. The Child and Zoo | Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.... | ```python
R = lambda:map(int, input().split())
n, m = R()
a = list(R())
p, f, sz =[], [], []
e = [[] for i in range(n)]
vis = [0] * n
ans = 0
def find(u):
if f[u] != u:
f[u] = find(f[u])
return f[u]
for i in range(n):
p.append([a[i], i])
f.append(i)
sz.append(1)
p.sort()
p.reverse()
for i i... |
506_E. Mr. Kitayuta's Gift | Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly n lowercase English letters into s to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" a... | ```python
palindrom = lambda s: s == s[::-1]
printans = lambda l: print(''.join(l))
s = list(input())
for i in range(len(s)+1):
for letter in 'abcdefghijklmnopqrstvwuxyz':
tmp = s[:]
tmp.insert(i,letter)
if palindrom(tmp):
printans(tmp)
exit()
print('NA')
``` |
556_A. Case of the Zeros and Ones | Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ... | ```python
n = int(input())
s = input()
x = s.count('0')
y = s.count('1')
print(abs(x-y))
``` |
581_E. Kojiro and Furrari | Motorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her.
Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is... | ```python
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
e,s,n,m=map(int,input().split())
fuel1=[]
fuel2=[]
fuel3=[]
keymoments=[]
for i in range(n):
t,x=map(int,input().split())
if t==1:
fuel1.append(x)
if t==2:
fuel2.append(x)
if t==3:
fuel3.append(x)
keymoments.append(x)... |
626_B. Cards | Catherine has a deck of n cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions:
* take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color;
* take any two (not necessarily adj... | ```python
'''
Author : Md. Rezwanul Haque
Email : r.haque.249.rh@gmail.com
'''
import sys
from sys import stdout,stdin
input = lambda : sys.stdin.readline()
if __name__ == '__main__':
n = int(input())
s = input()
s = (s.count('B'), s.count('G'), s.count('R'))
if s[0] > 0 and s[1] > 0 and s[2] > 0:
... |
675_C. Money Transfers | There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning V... | ```python
n = int(input())
b = list(map(int, input().split()))
from collections import Counter
from itertools import accumulate
cum = list(accumulate(b))
cnt = Counter(cum)
print (n - cnt.most_common(1)[0][1])
``` |
699_D. Fix a Tree | A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is cons... | ```python
input()
A = list(map(int, input().split(' ')))
root=-1
for i,a in enumerate(A) :
if i == a-1 :
root = i
break
v = [False]*len(A)
if root>-1 :
v[root]=True
ans= 0
for i,a in enumerate(A) :
if v[i] :
continue
v[i]= True
l=[i]
a-=1
while not v[a] :
l.ap... |
741_C. Arpa’s overnight party and Mehrdad’s silent entering | Note that girls in Arpa’s land are really attractive.
Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs wer... | ```python
import sys
def solve():
n = int(input())
partner = [0]*(2*n)
pacani = []
for line in sys.stdin:
pacan, telka = [int(x) - 1 for x in line.split()]
partner[pacan] = telka
partner[telka] = pacan
pacani.append(pacan)
khavka = [None]*(2*n)
for i in range(2*... |
765_B. Code obfuscation | Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and rep... | ```python
Alphabet = "abcdefghijklmnopqrstuvwxyz"
X = input()
Checked = []
i, Index = 0, 0
while i < len(X):
if X[i] not in Checked and X[i] == Alphabet[Index]:
Checked.append(Alphabet[Index])
Index += 1
elif X[i] not in Checked and X[i] != Alphabet[Index]:
print("NO")
exit()
... |
80_A. Panoramix's Prediction | A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ... | ```python
from math import ceil, sqrt
def array(arr, struc):
return (list(map(struc, arr.split())))
def isPrime(x):
for i in range(2, ceil(sqrt(x))+1):
if x % i == 0:
return False
return True
arr = array(input(), int)
prime1 = arr[0]
prime2 = arr[1]
counter = 0
tmp = prime1 + 1
... |
855_B. Marvolo Gaunt's Ring | Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he... | ```python
cin=lambda:map(int,input().split())
n,p,q,r=cin()
A=cin()
tp,tq,tr=-1e20,-1e20,-1e20
for a in A:
tp=max(tp,p*a)
tq=max(tq,tp+q*a)
tr=max(tr,tq+r*a)
print(tr)
# Made By Mostafa_Khaled
``` |
903_B. The Modcrab | Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has... | ```python
class Character:
def __init__(self, hPoints, attPoints, healPoints):
self.hPoints = hPoints
self.attPoints = attPoints
self.healPoints = healPoints
def attack(self, boss):
boss.setHP(boss.getHP() - self.attPoints)
def recAttack(self, boss):
self.hPoints -= b... |
925_C. Big Secret | Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer 54 42, but an increasing integer sequence a_1, …, a_n. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence b_1, …, b_n using the following rules:
... | ```python
n=int(input())
s=[[] for i in range(60)]
for b in list(map(int,input().split())):
for i in range(59,-1,-1):
if b>>i&1:
s[i].append(b)
break
ans=[]
cur=0
for i in range(n):
fl=False
for j in range(60):
if s[j]!=[] and cur>>j&1==0:
ans.append(s[j][-1])
cur^=s[j][-1]
s[j].pop()
fl=True
... |
954_D. Fight Against Traffic | Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible num... | ```python
from collections import deque
def bfs(s, graph):
q = deque()
d = [0] * len(graph)
used = [False] * len(graph)
used[s] = True
q.append(s)
while len(q):
cur = q[0]
q.popleft()
for to in graph[cur]:
if not used[to]:
used[to] = True
... |
980_C. Posterized | Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.
Their algorithm will be tested on an array of integers, where the i-th integer represents the color of the i-th pixel in the image. The image is in black and white, therefore ... | ```python
R = lambda: map(int, input().split())
n, k = R()
a = list(range(0, 257)); v = [1]*257
for p in R():
if v[p]:
t = p
while t >= 0 and p-a[t]<=k-1: t -= 1
t += 1
for i in range(t, p+1): a[i] = a[t]; v[i] = 0
print(a[p], end=' ')
``` |
9_C. Hexadecimal's Numbers | One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy.
But his plan failed. The reason for this w... | ```python
n=int(input())
a=[]
c=int
for i in range(515):
a.append(c(bin(i)[2:]))
a.remove(0)
ans=0
for i in a:
if i<=n:
ans+=1
print(ans)
``` |
p02546 AtCoder Beginner Contest 179 - Plural Form | In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.
In Taknese, the plural form of a noun is spelled based on the following rules:
* If a noun's singular form does not end with `s`, append `s` to the end of the singular form.
* If a noun's singular form ends with `s`... | ```python
n=input()
if( n[-1]=='s'):
n+='es'
else:
n+='s'
print(n)
``` |
p02677 AtCoder Beginner Contest 168 - : (Colon) | Consider an analog clock whose hour and minute hands are A and B centimeters long, respectively.
An endpoint of the hour hand and an endpoint of the minute hand are fixed at the same point, around which each hand rotates clockwise at constant angular velocity. It takes the hour and minute hands 12 hours and 1 hour to ... | ```python
from math import *
a,b,h,m = map(int, input().split())
d = radians(fabs(((11*m)/2) - (30 * h)))
print(sqrt(a**2 + b**2 - 2*a*b*cos(d)))
``` |
p02805 AtCoder Beginner Contest 151 - Enclose All | Given are N points (x_i, y_i) in a two-dimensional plane.
Find the minimum radius of a circle such that all the points are inside or on it.
Constraints
* 2 \leq N \leq 50
* 0 \leq x_i \leq 1000
* 0 \leq y_i \leq 1000
* The given N points are all different.
* The values in input are all integers.
Input
Input is giv... | ```python
n = int(input())
xy=[list(map(int,input().split())) for i in range(n)]
import math
def calc(x1, y1, x2, y2, x3, y3):
try:
d = 2 * ((y1 - y3) * (x1 - x2) - (y1 - y2) * (x1 - x3))
x = ((y1 - y3) * (y1 ** 2 - y2 ** 2 + x1 ** 2 - x2 ** 2) - (y1 - y2) * (y1 ** 2 - y3 ** 2 + x1 ** 2 - x3 ** 2)) ... |
p02941 AtCoder Grand Contest 037 - Numbers on a Circle | There are N positive integers arranged in a circle.
Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For this objective, he will repeatedly perform the following operation:
* Choose an integer i such that 1 \leq i \leq N.
* Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. ... | ```python
n,*t=map(int,open(0).read().split());A=t[:n];B=t[n:];r=0
while 1:
c=0
for i in range(n):
b=B[~-i%n]+B[-~i%n]
if A[i]<B[i]>b:t=(B[i]-A[i])//b;c+=t;B[i]-=t*b
r+=c
if c==0:break
print([-1,r][A==B])
``` |
p03078 AtCoder Beginner Contest 123 - Cake 123 | The Patisserie AtCoder sells cakes with number-shaped candles. There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively. Each cake has an integer value called deliciousness, as follows:
* The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.
* The deliciousn... | ```python
from heapq import nlargest
x,y,z,k=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=list(map(int,input().split()))
ab=nlargest(k,(x+y for x in a for y in b))
abc=nlargest(k,(xy+z for xy in ab for z in c))
for i in abc:
print(i)
``` |
p03221 AtCoder Beginner Contest 113 - ID | In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each ci... | ```python
from collections import defaultdict
(n, m), *q = [[*map(int, i.split())] for i in open(0)]
d = defaultdict(list)
for k, v in q:
d[k].append(v)
c = defaultdict(dict)
for k, v in d.items():
for i, j in enumerate(sorted(v)):
c[k][j] = i + 1
for p, y in q:
print("{:0>6}{:0>6}".format(p, c[p][y... |
p03369 AtCoder Beginner Contest 095 - Something on It | In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).
A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is ... | ```python
s = input().count('o')
print(700 + s*100)
``` |
p03845 AtCoder Beginner Contest 050 - Contest with Drinks Easy | Joisino is about to compete in the final round of a certain programming competition. In this contest, there are N problems, numbered 1 through N. Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N).
Also, there are M kinds of drinks offered to the contestants, numbered 1 through M. If Joisino takes d... | ```python
N = int(input())
T = list(map(int,input().split()))
M = int(input())
sumT = sum(T)
for _ in range(M):
p,x = map(int,input().split())
print(sumT+x-T[p-1])
``` |
p04012 AtCoder Beginner Contest 044 - Beautiful Strings | Let w be a string consisting of lowercase letters. We will call w beautiful if the following condition is satisfied:
* Each lowercase letter of the English alphabet occurs even number of times in w.
You are given the string w. Determine if w is beautiful.
Constraints
* 1 \leq |w| \leq 100
* w consists of lowercas... | ```python
s=input()
for k in s:
if s.count(k)%2!=0:
print('No')
break
else:
print('Yes')
``` |
p00098 Maximum Sum Sequence II | Matrix of given integers
a1,1 a1,2 ... a1, n
a2,1 a2,2 ... a2, n
::
an, 1 an, 2 ... an, n
Then, create a program that outputs the maximum value of the sum of one or more consecutive terms (submatrix) in the vertical and horizontal directions and ends.
Input
The input data is given in the following format.
n
a... | ```python
n = int(input())
s = [[0 for i in range(n + 1)] for j in range(n + 1)]
for r in range(n):
inp = list(map(int, input().split()))
for c in range(n):
s[r + 1][c + 1] = inp[c] + s[r][c + 1]
ans = -10001
for r_end in range(1, n + 1):
for r_start in range(r_end):
dp = [-10001]
... |
p00230 Ninja Climbing | Ninja Atsushi guards the town from the roof of the Ninja Building from early morning to late night every day. This Ninja Building is two adjacent buildings of the same floor, and Atsushi's daily routine is to jump between buildings and head to the rooftop for security.
Because these two buildings are cleaned frequentl... | ```python
def bfs(b):
mem=[[False for i in range(n)]for j in range(2)]
st=[0,0]
for i in range(2):
if b[i][0]!=1:continue
while st[i]<n-1 and b[i][st[i]+1]==1:
st[i]+=1
if st[i]==n-1:return 0
mem[0][st[0]]=True
mem[1][st[1]]=True
que=[[0,st[0],0],[1,st[1],0]]
... |
p00392 Common-Prime Sort | You are now examining a unique method to sort a sequence of numbers in increasing order. The method only allows swapping of two numbers that have a common prime factor. For example, a sequence [6, 4, 2, 3, 7] can be sorted using the following steps.
Step 0: 6 4 2 3 7 (given sequence)
Step 1: 2 4 6 3 7 (elements 6 and 2... | ```python
from collections import defaultdict
def main():
def primes(n):
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
for i in range(2, int(n ** (1 / 2)) + 1):
if is_prime[i]:
for j in range(i * i, n + 1, i):
is_prime[j] = False
return [i for i in range(n + 1) ... |
p00884 Membership Management | Peter is a senior manager of Agile Change Management (ACM) Inc., where each employee is a member of one or more task groups. Since ACM is agile, task groups are often reorganized and their members frequently change, so membership management is his constant headache.
Peter updates the membership information whenever an... | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]
def LI(): return [int(x) for x i... |
p01287 Colored Octahedra | A young boy John is playing with eight triangular panels. These panels are all regular triangles of the same size, each painted in a single color; John is forming various octahedra with them.
While he enjoys his playing, his father is wondering how many octahedra can be made of these panels since he is a pseudo-mathem... | ```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 ... |
p01768 Shopping | Problem statement
2D, who is good at cooking, is trying to make lunch. Cooking requires all N ingredients a_ {0}, a_ {1},…, a_ {N−1}.
Now, 2D's refrigerator doesn't contain any ingredients, so I have to go to the supermarket to buy it. At the supermarket, you can buy the material a_ {i} for the price x_ {i} yen.
2D ... | ```python
n = int(input())
dic = {}
price = []
for i in range(n):
a, x = input().split()
dic[a] = i
price.append(int(x))
parent = [i for i in range(n)]
def find(x):
if parent[x] == x:return x
parent[x] = find(parent[x])
return parent[x]
m = int(input())
for _ in range(m):
s, t = input().split()
si, t... |
p02039 Othello | problem
Prepare the Othello board. The upper left is $ (1,1) $ and the lower right is $ (8,8) $. The board to be prepared here is $ (5,4) as follows. ) There is no $ black stone.
........
........
........
... ox ...
.... o ...
........
........
........
Kuroishi: x Shiraishi: o
8x8 board
From this state, Black st... | ```python
q = int(input())
li = [input().split() for i in range(q)]
for i in li:
a, b, c, d = map(int, i)
ans = 0
for j in range(a, c+1):
for k in range(b, d+1):
ans += 0 if j%2 == 1 and k%2 == 0 else 1
print(ans)
``` |
p02325 Bitonic Traveling Salesman Problem | For given $N$ points in the 2D Euclidean plane, find the distance of the shortest tour that meets the following criteria:
* Visit the points according to the following steps:
1. It starts from the leftmost point (starting point), goes strictly from left to right, and then visits the rightmost point (turn-around point)... | ```python
import math
pts = []
line = input()
N = int(line)
for _ in range(0, N):
line = input()
x, y = list(map(int, line.split()))
pts += [[x, y]]
def dist(i, j):
x1, y1 = pts[i]
x2, y2 = pts[j]
return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
def btsp():
dp = [ [0] * N for _ in range(... |
p02470 Euler's Phi Function | For given integer n, count the totatives of n, that is, the positive integers less than or equal to n that are relatively prime to n.
Input
n
An integer n (1 ≤ n ≤ 1000000000).
Output
The number of totatives in a line.
Examples
Input
6
Output
2
Input
1000000
Output
400000 | ```python
# https://tjkendev.github.io/procon-library/python/prime/eulers-totient-function.html
# https://qiita.com/drken/items/a14e9af0ca2d857dad23#%E5%95%8F%E9%A1%8C-6-%E3%82%AA%E3%82%A4%E3%83%A9%E3%83%BC%E9%96%A2%E6%95%B0
# オイラー関数
# 1,2,...,NのうちNと互いに素であるものの個数
# Python3 program to calculate
# Euler's Totient Functio... |
1019_A. Elections | As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.
Elections are coming. You know the number of voters and the number of parties — n and m respectively. For each vote... | ```python
n, m = map(int, input().split())
pc = [(0, 0) for _ in range(n)]
party_votes = [0 for _ in range(m)]
for i in range(n):
p, c = map(int, input().split())
pc[i] = (p - 1, c)
party_votes[p - 1] += 1
pc.sort(key=lambda x: x[1])
min_cost = 10**20
for votes in range(n + 1):
_party_votes = part... |
1041_F. Ray in the tube | You are given a tube which is reflective inside represented as two non-coinciding, but parallel to Ox lines. Each line has some special integer points — positions of sensors on sides of the tube.
You are going to emit a laser ray in the tube. To do so, you have to choose two integer points A and B on the first and the... | ```python
n, y1 = map(int, input().split())
a = list(map(int, input().split()))
m, y2 = map(int, input().split())
b = list(map(int, input().split()))
a_st, b_st = dict(), dict()
osn = 2 ** 30
k_a, k_b = set(), set()
for el in a:
try:
a_st[el % osn] += 1
except KeyError:
a_st[el % osn] = 1... |
1106_C. Lunar New Year and Number Division | Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.
There are n positive integers a_1, a_2, …, a_n on Bob's homework paper, where n is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least 2 numbers. Suppose the n... | ```python
n = int(input())
a = [int(s) for s in input().split(" ")]
a.sort()
ans = 0
for i in range(n//2):
ans += (a[i]+a[n-i-1])**2
print(ans)
``` |
1133_D. Zero Quantity Maximization | You are given two arrays a and b, each contains n integers.
You want to create a new array c as follows: choose some real (i.e. not necessarily integer) number d, and then for every i ∈ [1, n] let c_i := d ⋅ a_i + b_i.
Your goal is to maximize the number of zeroes in array c. What is the largest possible answer, if y... | ```python
from fractions import Fraction
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
count = {}
ans = 0
zeros = 0
for i in range(n):
if A[i] == 0 and B[i] != 0:
continue
elif A[i] == 0 and B[i] == 0:
zeros += 1
else:
temp = Fraction(abs... |
1154_A. Restoring Three Numbers | Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | ```python
x,y,z,w = (int(i) for i in input().split())
s = (x+y+z+w)//3
for i in x,y,z,w:
temp = s - i
if s - i > 0:
print(s-i, end=' ')
``` |
1175_F. The Number of Subpermutations | You have an array a_1, a_2, ..., a_n.
Let's call some subarray a_l, a_{l + 1}, ... , a_r of this array a subpermutation if it contains all integers from 1 to r-l+1 exactly once. For example, array a = [2, 2, 1, 3, 2, 3, 1] contains 6 subarrays which are subpermutations: [a_2 ... a_3], [a_2 ... a_4], [a_3 ... a_3], [a... | ```python
#import sys
import math
#input=sys.stdin.readline
#sys.setrecursionlimit(1000000)
mod=int(1000000007)
i=lambda :map(int,input().split())
n=int(input())
a=[int(x) for x in input().split()]
t=[[0]*21 for i in range(300005)]
for i in range(n):
t[i][0]=a[i]
def build(n):
for j in range(1,20):
f... |
1234_A. Equalize Prices Again | You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.
... | ```python
import math
for _ in range(int(input())):
k=int(input())
l=list(map(int,input().split()))
k=sum(l)/k
print(math.ceil(k))
``` |
1296_E1. String Coloring (easy version) | This is an easy version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.
You are given a string s consisting of n lowercase Latin letters.
You have to color all its characters one of the two ... | ```python
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in... |
131_E. Yet Another Task with Queens | A queen is the strongest chess piece. In modern chess the queen can move any number of squares in any horizontal, vertical or diagonal direction (considering that there're no other pieces on its way). The queen combines the options given to the rook and the bishop.
There are m queens on a square n × n chessboard. You ... | ```python
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
impo... |
1339_B. Sorted Adjacent Differences | You have array of n numbers a_{1}, a_{2}, …, a_{n}.
Rearrange these numbers to satisfy |a_{1} - a_{2}| ≤ |a_{2} - a_{3}| ≤ … ≤ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement.
Note that all numbers in a are not necessarily different. In other words, some numb... | ```python
for _ in range(int(input())):
n = int(input())
ls = sorted(list(map(int, input().split())))
mid = n // 2
if n % 2 == 0:
mid -= 1
i = mid - 1
turn = True
j = mid + 1
ar = []
ar.append(ls[mid])
while i >= 0 or j < n:
if turn and j < n:
ar.append(ls[j])
j += 1
elif not turn and i >= 0:
a... |
1360_F. Spy-string | You are given n strings a_1, a_2, …, a_n: all of them have the same length m. The strings consist of lowercase English letters.
Find any string s of length m such that each of the given n strings differs from s in at most one position. Formally, for each given string a_i, there is no more than one position j such that... | ```python
# cook your dish here
#code
import math
import collections
from sys import stdin,stdout,setrecursionlimit
from bisect import bisect_left as bsl
from bisect import bisect_right as bsr
import heapq as hq
setrecursionlimit(2**20)
def strcmp(s1,s2,m):
cnt = 0
for i in range(m):
if(s1[i]!=s2[i]... |
1380_G. Circular Dungeon | You are creating a level for a video game. The level consists of n rooms placed in a circle. The rooms are numbered 1 through n. Each room contains exactly one exit: completing the j-th room allows you to go the (j+1)-th room (and completing the n-th room allows you to go the 1-st room).
You are given the description ... | ```python
import sys
sys.setrecursionlimit(10 ** 5)
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 _ i... |
1424_G. Years | During one of the space missions, humans have found an evidence of previous life at one of the planets. They were lucky enough to find a book with birth and death years of each individual that had been living at this planet. What's interesting is that these years are in the range (1, 10^9)! Therefore, the planet was na... | ```python
dct = {}
for i in range(int(input())):
a,b = map(int,input().split())
dct[a] = dct.get(a,0)+1
dct[b] = dct.get(b,0)-1
cnt = curr = y = 0
for i in sorted(dct.keys()):
curr += dct[i]
if curr > cnt :
cnt = curr
y = i
print(y,cnt)
``` |
1445_C. Division | Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division.
To improve his division skills, Oleg came up with t pairs of integers p_i and q_i and for each pair decided to find the greatest integer x_i, such that:
* p_i is divisible by x_i;
* x_i is not divisible by q_i.
... | ```python
"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlin... |
146_C. Lucky Conversion | Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Pety... | ```python
a=input()
b=input()
da={'4':0,'7':0}
db={'4':0,'7':0}
for i in a:
da[i]+=1
for i in b:
db[i]+=1
dif=0
for i in range(len(a)):
if(a[i]!=b[i]):
dif+=1
ans=0
if(da==db):
ans=dif//2
else:
x=abs(da['4']-db['4'])
ans+=x
dif-=x
ans+=(dif//2)
print(ans)
``` |
1519_B. The Cake Is a Lie | There is a n × m grid. You are standing at cell (1, 1) and your goal is to finish at cell (n, m).
You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell (x, y). You can:
* move right to the cell (x, y + 1) — it costs x burles;
* move down to the cell (x + 1,... | ```python
t = int(input())
while t > 0:
n, m, k = map(int, input().split())
if k == n * m - 1:
print('Yes')
else:
print('No')
t -= 1
``` |
1546_B. AquaMoon and Stolen String | AquaMoon had n strings of length m each. n is an odd number.
When AquaMoon was gone, Cirno tried to pair these n strings together. After making (n-1)/(2) pairs, she found out that there was exactly one string without the pair!
In her rage, she disrupted each pair of strings. For each pair, she selected some positions... | ```python
import sys
input = sys.stdin.readline
def solve():
n, m = map(int, input().split())
original = [input() for _ in range(n)]
modified = [input() for _ in range(n-1)]
stolen_chars = []
for j in range(m):
chars_available = 0
for i in range(n):
chars_available += o... |
266_B. Queue at the School | During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | ```python
n, t = map(int, input().split())
a = list(input())
for i in range(t):
j = 0
while j < n:
while j < n and a[j] == 'G':
j += 1
while j < n and a[j] == 'B':
j += 1
if j < n:
a[j - 1], a[j] = 'G', 'B'
j += 1
for i in a:
... |
28_B. pSort | One day n cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i - j| = di, where ... | ```python
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=[[] for i in range(n)]
for i in range(n):
if i-b[i]>=0:
c[i].append(i-b[i])
c[i-b[i]].append(i)
if i+b[i]<n:
c[i].append(i+b[i])
c[i+b[i]].append(i)
v=[1]*n
def dfs(u):
global v,c
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.