name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
p02723 AtCoder Beginner Contest 160 - Coffee | A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.
Given a string S, determine whether it is coffee-like.
Constraints
* S is a string of length 6 consisting of lowercase English l... | ```python
a = input()
print('Yes') if (a[2] == a[3] and a[4] == a[5]) else print('No')
``` |
p02854 DISCO Presents Discovery Channel Code Contest 2020 Qual - Iron Bar Cutting | Takahashi, who works at DISCO, is standing before an iron bar. The bar has N-1 notches, which divide the bar into N sections. The i-th section from the left has a length of A_i millimeters.
Takahashi wanted to choose a notch and cut the bar at that point into two parts with the same length. However, this may not be po... | ```python
N = int(input())
A = list(map(int,input().split()))
sA = sum(A)
ans = sum(A)
L = 0
for i in A:
L += i
R = sA-L
ans = min(ans,abs(R-L))
print(ans)
``` |
p02990 AtCoder Beginner Contest 132 - Blue and Red Balls | There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.
First, Snuke will arrange the N balls in a row from left to right.
Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive ... | ```python
import math
def comb(n, r):
return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
n,k = map(int,input().split())
for i in range(1,k+1):
if n - k + 1 >= i:
print(comb(n - k + 1,i) * comb(k-1,i-1) % (10**9 + 7))
else:
print(0)
``` |
p03131 Yahoo Programming Contest 2019 - When I hit my pocket... | Snuke has one biscuit and zero Japanese yen (the currency) in his pocket. He will perform the following operations exactly K times in total, in the order he likes:
* Hit his pocket, which magically increases the number of biscuits by one.
* Exchange A biscuits to 1 yen.
* Exchange 1 yen to B biscuits.
Find the maxi... | ```python
k,a,b=map(int,input().split())
if b-a<=2:
print(k+1)
else:
kaisu=max(0,(k-a+1)//2)
print(k-kaisu*2+kaisu*(b-a)+1)
``` |
p03274 AtCoder Beginner Contest 107 - Candles | There are N candles placed on a number line. The i-th candle from the left is placed on coordinate x_i. Here, x_1 < x_2 < ... < x_N holds.
Initially, no candles are burning. Snuke decides to light K of the N candles.
Now, he is at coordinate 0. He can move left and right along the line with speed 1. He can also light... | ```python
n,k=map(int,input().split())
x=list(map(int,input().split()))
ans=10**18
for i in range(n-k+1):
temp=0
temp+=(min(abs(x[i]),abs(x[i+k-1]))+abs(x[i]-x[i+k-1]))
ans=min(ans,temp)
print(ans)
``` |
p03431 AtCoder Grand Contest 021 - Ball Eat Chameleons | In Republic of AtCoder, Snuke Chameleons (Family: Chamaeleonidae, Genus: Bartaberia) are very popular pets. Ringo keeps N Snuke Chameleons in a cage.
A Snuke Chameleon that has not eaten anything is blue. It changes its color according to the following rules:
* A Snuke Chameleon that is blue will change its color to ... | ```python
def solve(n, k):
MOD = 998244353
if n > k:
return 0
if n == 1:
return pow(2, k - 1, MOD)
pf, kf = 1, 1
for m in range(2, k + 1):
pf = kf
kf *= m
kf %= MOD
inv = pow(kf, MOD - 2, MOD)
invs = [1] * (k + 1)
invs[k] = inv
for m in range... |
p03590 Tenka1 Programmer Beginner Contest - IntegerotS | Seisu-ya, a store specializing in non-negative integers, sells N non-negative integers. The i-th integer is A_i and has a utility of B_i. There may be multiple equal integers with different utilities.
Takahashi will buy some integers in this store. He can buy a combination of integers whose bitwise OR is less than or ... | ```python
def solve(K, ABs):
if not ABs: return 0
ansK = sum(b for a, b in ABs if (K | a) == K)
pool = []
for i in range(30, -1, -1):
if (K & (1<<i)):
pool.append(i)
for p in pool:
v = 1 << p
KK = (K >> p) << p
KKK = (K >> p)
t = sum(b for a, b in ... |
p03747 AtCoder Grand Contest 013 - Ants on a Circle | There is a circle with a circumference of L. Each point on the circumference has a coordinate value, which represents the arc length from a certain reference point clockwise to the point. On this circumference, there are N ants. These ants are numbered 1 through N in order of increasing coordinate, and ant i is at coor... | ```python
N, L, T = map(int, input().split())
s = 0
X = [0] * N
for i in range(N):
x, w = map(int, input().split())
if w == 1:
x += T
else:
x -= T
# xが0点を通る回数を足す
s += x // L
X[i] = x % L
X.sort()
for i in range(N):
print(X[(i+s) % N])
``` |
p03909 CODE FESTIVAL 2016 Final - Where's Snuke? | There is a grid with H rows and W columns.
The square at the i-th row and j-th column contains a string S_{i,j} of length 5.
The rows are labeled with the numbers from 1 through H, and the columns are labeled with the uppercase English letters from `A` through the W-th letter of the alphabet.
<image>
Exactly one of... | ```python
H, W = map(int, input().split())
S = [input().split() for _ in range(H)]
for i in range(H):
for j in range(W):
if S[i][j] == "snuke":
print(chr(ord("A")+j)+str(i+1))
``` |
p00013 Switching Railroad Cars | <image>
This figure shows railway tracks for reshuffling cars. The rail tracks end in the bottom and the top-left rail track is used for the entrace and the top-right rail track is used for the exit. Ten cars, which have numbers from 1 to 10 respectively, use the rail tracks.
We can simulate the movement (comings an... | ```python
stack = []
while True:
try:
n = int(input())
except:
break
if n == 0:
print(stack.pop())
else:
stack.append(n)
``` |
p00145 Cards | There is a set of cards with positive integers written on them. Stack the cards to make several piles and arrange them side by side. Select two adjacent piles of cards from them, and stack the left pile on top of the right pile. Repeat this operation until there is only one pile of cards.
When stacking two piles of ca... | ```python
n=int(input())
cards=[]
for i in range(n):
a,b=map(int,input().split())
cards.append((a,b))
memo=[[-1 for i in range(n+1)]for j in range(n+1)]
def getans (l,r,cards):
if(memo[l][r]==-1):
if(l+1==r):
memo[l][r]=0
else:
ans=1<<32
for m in range(l+... |
p00278 Study Session | At Akabe High School, a programmer training school, there is a unique study session run by the students themselves. It is important for programmers to constantly adopt new technologies, so the aim of this activity is to develop the habit of self-study through this study session.
There are a total of N students, each w... | ```python
from bisect import bisect
import operator
import sys
from collections import defaultdict
readline = sys.stdin.readline
write = sys.stdout.write
N, Q = map(int, readline().split())
R = [int(readline()) for i in range(N)]
S = list(set(R))
S.sort()
mp = {e: i for i, e in enumerate(S)}
D = defaultdict(int)
T = ... |
p00466 Receipt | problem
Taro bought 10 books. Later, I tried to find out the price based on the receipt, but the receipt was dirty and I could not read the price of a book. We decided to calculate the price of the book from the total price of 10 books and the prices of the other 9 books.
Write a program that outputs the price of the... | ```python
while 1:
n=int(input())
if n==0:
break
else:
for i in range(9):
b=int(input())
n-=b
print(n)
``` |
p00657 Rearranging Seats | Haruna is a high school student. She must remember the seating arrangements in her class because she is a class president. It is too difficult task to remember if there are so many students.
That is the reason why seating rearrangement is depress task for her. But students have a complaint if seating is fixed.
One da... | ```python
while 1:
a,b=map(int,input().split())
if a==b==0: break
if a*b%2: print("no")
else: print("yes")
``` |
p01335 K Poker | Description
In 200X, the mysterious circle K, which operates at K University, announced K Poker, a new game they created on the 4th floor of K East during the university's cultural festival.
At first glance, this game is normal poker, but it is a deeper game of poker with the addition of basic points to the cards.
The... | ```python
from collections import Counter
def parse_card(card):
suit = card[-1]
num = card[:-1]
if num == "A":num = 1
elif num == "K":num = 13
elif num == "Q":num = 12
elif num == "J":num = 11
elif num == "T":num = 10
else:num = int(num)
return (num, suit)
def parse_hand(hand):
return sorted((map... |
p01502 Sightseeing Tour | Example
Input
3
0 2 7
2 0 4
5 8 0
Output
11 | ```python
import sys
def main():
n = int(input())
edges = []
for i in range(n):
edges.append( list(map(int, sys.stdin.readline().split())) )
# ?±?????????????????????????????????°??????
# ????????????????????°?????????????????????????????????????????¨????????????
# ????????????????... |
p01815 Escape | Escape
An undirected graph with positive values at the vertices is given. The vertices are numbered from 1 to N, and the i-th vertex has a value of w_i. You can start from the first vertex and move on the graph with the constraint that you cannot pass the edge that you just passed. At each vertex, you can get the sc... | ```python
def find(x):
if par[x] == x:
return x
else:
par[x] = find(par[x])
return par[x]
def union(x, y):
par_x = find(x)
par_y = find(y)
if rank[par_x] < rank[par_y]:
par[par_x] = par_y
w[par_y]+=w[par_x]
else:
par[par_y] = par_x
w[par_x]+=w[par_y]
if rank[par_x] == rank[p... |
p01950 Endless BFS | Mr. Endo wanted to write the code that performs breadth-first search (BFS), which is a search algorithm to explore all vertices on an undirected graph. An example of pseudo code of BFS is as follows:
1: $current \leftarrow \{start\_vertex\}$
2: $visited \leftarrow current$
3: while $visited \ne $ the set of all the v... | ```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, M = map(int, readline().split())
G = [[] for i in range(N)]
for i in range(M):
u, v = map(int, readline().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
cnts ... |
p02099 GPA JANKEN | Problem
GPA is an abbreviation for "Galaxy Point of Aizu" and takes real numbers from 0 to 4.
GPA rock-paper-scissors is a game played by two people. After each player gives a signal of "rock-paper-scissors, pon (hoi)" to each other's favorite move, goo, choki, or par, the person with the higher GPA becomes the winner... | ```python
import bisect
n = int(input())
a = []
for i in range(n):
a.append(float(input()))
a2 = sorted(a)
for i in a:
kati = bisect.bisect_left(a2, i)
hiki = bisect.bisect_right(a2, i) - kati - 1
print(kati*3 + hiki)
``` |
p02237 Graph | There are two standard ways to represent a graph $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges; Adjacency list representation and Adjacency matrix representation.
An adjacency-list representation consists of an array $Adj[|V|]$ of $|V|$ lists, one for each vertex in $V$. For each $u \in V$, th... | ```python
dat = []
n = int(input())
for i in range(n):
dat.append([0] * n)
for i in range(n):
s = list(map(int, input().split()))
for j in range(len(s) - 2):
dat[i][s[j + 2] - 1] = 1
for i in range(n):
l = list(map(str, dat[i]))
print(" ".join(l))
``` |
p02383 Dice I | Write a program to simulate rolling a dice, which can be constructed by the following net.
<image>
<image>
As shown in the figures, each face is identified by a different label from 1 to 6.
Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the d... | ```python
num=list(map(int,input().split()))
s=input()
for i in s:
if i=='E':
num=[num[3],num[1],num[0],num[5],num[4],num[2]]
if i=='W':
num=[num[2],num[1],num[5],num[0],num[4],num[3]]
if i=='S':
num=[num[4],num[0],num[2],num[3],num[5],num[1]]
if i=='N':
num=[num[1],n... |
1004_C. Sonya and Robots | Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers.
Sonya has drawn n numbers in a row, a_i is located in the i-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will giv... | ```python
n=int(input())
a=[int(i) for i in input().split()]
dic={}
dic1={}
arr=[0]*(n)
count1=0
#print(arr)
for i in range(n-1,0,-1):
if(a[i] not in dic.keys()):
dic[a[i]]=1
count1+=1
arr[i-1]=count1
#print(dic,count1)
count=0
#print(arr)
for i in range(n-1):
if(a[i] not in dic1.keys()):
dic1[a[i]]=1
count... |
1028_C. Rectangles | You are given n rectangles on a plane with coordinates of their bottom left and upper right points. Some (n-1) of the given n rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary.
Find any point with integer coordinates that belongs... | ```python
r=range(int(input()))
def s(a,b):
(c,d,e,f),(g,h,i,j)=a,b;return max(c,g),max(d,h),min(e,i),min(f,j)
def p(a):
b=[a[0]]
for i in range(1,len(a)):
b+=[s(b[i-1],a[i])]
return b
H=9**15
B=(-H,-H,H,H)
a=[B]+[tuple(map(int,input().split())) for i in r]+[B]
b=p(a)
c=p(a[::-1])[::-1]
for i in r:
I,J,K,L=s(b[i... |
1046_I. Say Hello | Two friends are travelling through Bubble galaxy. They say "Hello!" via signals to each other if their distance is smaller or equal than d_1 and
* it's the first time they speak to each other or
* at some point in time after their last talk their distance was greater than d_2.
We need to calculate how many t... | ```python
from sys import stdin
stdin = iter(stdin)
class Vector:
''''''
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __add__(self, other):
return Vector(self.x + other.x, self.y + othe... |
1070_H. BerOS File Suggestion | Polycarp is working on a new operating system called BerOS. He asks you to help with implementation of a file suggestion feature.
There are n files on hard drive and their names are f_1, f_2, ..., f_n. Any file name contains between 1 and 8 characters, inclusive. All file names are unique.
The file suggestion feature... | ```python
smpl = {}
cntr = {}
def handle(s):
cur = set()
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
cur.add(s[i:j])
# print(cur)
for c in cur:
if c not in cntr:
cntr[c] = 0
cntr[c] += 1
smpl[c] = s
n = int(input())
for i in range(n):
s = input()
handle(s)
q = int(input())
for i in ... |
1092_D1. Great Vova Wall (Version 1) | Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th par... | ```python
n = int(input())
a = list(map(int,input().split()))
for i in range(n) : a[i] &= 1
b = list(a)
for i in range(n) : b[i] = a[i]^1
def check(a):
n = len(a)
s1,s2 = 0,0
for i in range(n):
if(i&1 == 0): s1 += a[i]
else : s2 += a[i]
diff = abs(s1-s2)
if(diff%3 == 0): return True
return False
possible... |
1111_B. Average Superhero Gang Power | Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.
Initially, there are n superheroes in avengers team having powers a_1, a_2, …, a_n, respectively. In one operation, they can r... | ```python
def main():
n, k, m = map(int, input().split())
heroes = [x for x in map(int, input().split())]
heroes.sort()
cbk = min(m, n)
m -= cbk
for i in range(cbk):
heroes[i] += 1
heroes.reverse()
for i in range(n):
used = min(m, k - 1)
heroes[i] += used
... |
1159_E. Permutation recovery | Vasya has written some permutation p_1, p_2, …, p_n of integers from 1 to n, so for all 1 ≤ i ≤ n it is true that 1 ≤ p_i ≤ n and all p_1, p_2, …, p_n are different. After that he wrote n numbers next_1, next_2, …, next_n. The number next_i is equal to the minimal index i < j ≤ n, such that p_j > p_i. If there is no su... | ```python
import sys
from array import array # noqa: F401
from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def main():
t = int(input())
ans = ['-1'] * t
for ti in range(t):
n = int(input())
... |
1217_B. Zmei Gorynich | You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!
<image>
Initially Zmei Gorynich has x heads. You can deal n types of blows. If you deal a blow of the i-th type, you decrease the number of Gorynich's heads by min(d_i, curX), there curX is th... | ```python
#!/usr/bin/env python3
import sys
def rint():
return map(int, sys.stdin.readline().split())
#lines = stdin.readlines()
t = int(input())
for tt in range(t):
n, x = rint()
d_max = -1
diff_max = -1
for i in range(n):
dd, hh = rint()
d_max = max(d_max, dd)
diff_max ... |
1282_A. Temporarily unavailable | Polycarp lives on the coordinate axis Ox and travels from the point x=a to x=b. It moves uniformly rectilinearly at a speed of one unit of distance per minute.
On the axis Ox at the point x=c the base station of the mobile operator is placed. It is known that the radius of its coverage is r. Thus, if Polycarp is at a ... | ```python
kl=int(input())
for l in range(kl):
p=[int(i) for i in input().split()]
a=min(p[0], p[1])
b=max(p[0], p[1])
tn=p[2]-p[3]
tk=p[2]+p[3]
if tn>=b or tk<=a:
print(b-a)
else:
if tn>=a:
print((b-a) - (min(b, tk)-tn))
else:
print((b-a) -(min... |
1326_A. Bad Ugly Numbers | You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers:
In the decimal representation of s:
* s > 0,
* s consists of n digits,
* no digit in s equals 0,
* s is not divisible by any of it's digits.
Input
The input consists of mult... | ```python
t = int(input())
for i in range(t):
n = int(input())
if n == 1:
print(-1)
else:
base = int('2' * n) + 1
print(int('2' + '3' * (n - 1)))
``` |
1366_F. Jog Around The Graph | You are given a simple weighted connected undirected graph, consisting of n vertices and m edges.
A path in the graph of length k is a sequence of k+1 vertices v_1, v_2, ..., v_{k+1} such that for each i (1 ≤ i ≤ k) the edge (v_i, v_{i+1}) is present in the graph. A path from some vertex v also has vertex v_1=v. Note ... | ```python
import sys
n,m,q=map(int,input().split())
mod,mxw = 1000000007,0;wgts,neig=[0]*n,[0]*n
for i in range(n):
neig[i]=[0]
for i in range(m):
a,b,w=map(int,input().split())
a-=1;b-=1;neig[a][0]+=1;neig[b][0]+=1;neig[a].append([b,w]);neig[b].append([a,w])
mxw=max(mxw,w);wgts[a]=max(wgts[a],w);wgts[... |
1408_F. Two Different | You are given an integer n.
You should find a list of pairs (x_1, y_1), (x_2, y_2), ..., (x_q, y_q) (1 ≤ x_i, y_i ≤ n) satisfying the following condition.
Let's consider some function f: N × N → N (we define N as the set of positive integers). In other words, f is a function that returns a positive integer for a pair... | ```python
import sys
readline = sys.stdin.readline
N = int(readline())
if N == 1:
print(0)
else:
BN = 1
while BN*2 <= N:
BN*= 2
Ans = []
for i in range(BN.bit_length()):
d = 1<<i
for j in range(1, BN+1, 2*d):
if j+d > BN:
break
for k in... |
1428_H. Rotary Laser Lock | This is an interactive problem.
To prevent the mischievous rabbits from freely roaming around the zoo, Zookeeper has set up a special lock for the rabbit enclosure. This lock is called the Rotary Laser Lock.
The lock consists of n concentric rings numbered from 0 to n-1. The innermost ring is ring 0 and the outermos... | ```python
import sys;Z=sys.stdin.readline
def P(d=1,x=0):
print('?',x,2*d-1);sys.stdout.flush()
return int(Z())
def poke(n):
global K,S,C,L
h=len(S);l=0;D=[0]*h
while h-l>1:
m=(l+h)//2;d=1-D[l]
for i in range(m-l):
v=P(d,S[l+i]);D[l+i]=d
if v<P()+n:
if... |
1452_D. Radio Towers | There are n + 2 towns located on a coordinate line, numbered from 0 to n + 1. The i-th town is located at the point i.
You build a radio tower in each of the towns 1, 2, ..., n with probability 1/2 (these events are independent). After that, you want to set the signal power on each tower to some integer from 1 to n (s... | ```python
def power(a, b, mod):
res = 1
while b:
if b%2:
res = (res*a)%mod
b //= 2
a = (a*a)%mod
return res%mod
def divide(a, b, mod):
return (a * power(b, mod-2, mod)) % mod
n = int(input())
MOD = 998244353
fib = [0, 1]
for i in rang... |
1476_B. Inflation | You have a statistic of price changes for one product represented as an array of n positive integers p_0, p_1, ..., p_{n - 1}, where p_0 is the initial price of the product and p_i is how the price was increased during the i-th month.
Using these price changes you are asked to calculate the inflation coefficients for ... | ```python
T=int(input())
while(T):
T-=1
(n,k)=input().split()
n=int(n)
k=int(k)
a=[int(n) for n in input().split()]
s=0
for i in range(n):
s+=a[i]
ans=0
for i in range(n-1,0,-1):
s-=a[i]
t=int((a[i]*100-1)/k)+1
if s<t :
ans+=t-s
... |
1501_A. Alexey and Train | Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should!
Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment 0. Also, let's say that the train will visit n stations numbered from 1 to n along its way, and ... | ```python
import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range (int(input())):
n = int(input())
a = []
b = []
for i in range (n):
ai,bi =[int(i) for i in input().split()]
a.append(ai)
b.append(bi)
t = [int(i) for i in input().split()]
... |
1526_C2. Potions (Hard Version) | This is the hard version of the problem. The only difference is that in this version n ≤ 200000. You can make hacks only if both versions of the problem are solved.
There are n potions in a line, with potion 1 on the far left and potion n on the far right. Each potion will increase your health by a_i when drunk. a_i c... | ```python
#!/usr/bin/env pypy
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
from heapq import heappush, heappop
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
MOD = 10**... |
158_A. Next Round | "Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ... | ```python
x,y=map(int,input().split())
z = list(map(int,input().split()))
i=0
count=0
for i in range (0,x):
if z[i] > 0:
if z[i] >= z[y-1]:
count=count+1
print(count)
``` |
1_B. Spreadsheets | In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow th... | ```python
import re
def from_excel(item):
row = ''.join([s for s in item if s.isdigit()])
column = excel_to_column(item.replace(row, ''))
return 'R{0}C{1}'.format(row, column)
def to_excel(item):
row, column = item.split('C')
row, column = int(row.replace('R', '')), int(column)
column = colu... |
224_C. 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
s = input()
st, v, vi, vj, vc = [], [], 0, 0, 0
for i, c in enumerate(s):
if c in '[(':
st.append(i)
continue
if st and s[st[-1]] + c in ('()', '[]'):
b = (st[-1], i+1)
if v and v[-1][1] == i: v[-1] = b
else: v.append(b)
if len(v) >= 2 and v[-2][1] == v[... |
249_A. Robo-Footballer | It's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And ye... | ```python
y1, y2, w, x, y, r = map(int, input().strip().split())
w -= r
y1 = 2 * w - y1 - y - r
y2 = 2 * w - y2 - y
if x * x * (y2 - y1) * (y2 - y1) <= (y1 * y1 + x * x) * r * r:
print(-1)
else:
print(f"{x * (y1 + y - w) / y1:.10f}")
``` |
273_B. Dima and Two Sequences | Little Dima has two sequences of points with integer coordinates: sequence (a1, 1), (a2, 2), ..., (an, n) and sequence (b1, 1), (b2, 2), ..., (bn, n).
Now Dima wants to count the number of distinct sequences of points of length 2·n that can be assembled from these sequences, such that the x-coordinates of points in th... | ```python
from collections import defaultdict
def factorial(n, m, rep):
r = 1
for i in range(2, n + 1):
j = i
while j % 2 == 0 and rep > 0:
j = j// 2
rep -= 1
r *= j
r %= m
return r
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,in... |
296_D. 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
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def solve():
n = int(input())
matrix = [array('i', list(map(int, input().split()))) for _ in range(n)]
a = tuple(map(lambda x: int(x) - 1, input().split()))
ans = [''] * n
... |
31_B. Sysadmin Bob | Email address in Berland is a string of the form A@B, where A and B are arbitrary strings consisting of small Latin letters.
Bob is a system administrator in «Bersoft» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order... | ```python
def main():
string = input()
comps = string.split('@')
ans = []
if '@' not in string:
print("No solution")
return
for i in range(len(comps)):
if i == 0 or i == len(comps) - 1:
if len(comps[i]) < 1:
print("No solution")
ret... |
344_B. Simple Molecules | Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule.
A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number — the number of bonds the atom must form with other atoms. An atom can form one... | ```python
a,b,c=map(int,input().split())
s=(a+b+c)//2
if (a+b+c)%2!=0 or s-a<0 or s-b<0 or s-c<0:
print("Impossible")
else:
print(s-c,s-a,s-b)
``` |
411_B. Multi-core Processor | The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.
At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information ... | ```python
n,m,k=map(int,input().split())
L=[]
for i in range(n):
L.append(list(map(int,input().split())))
Locked=[-1]*n
Z={}
for i in range(m):
K={}
for j in range(n):
if(Locked[j]!=-1):
continue
if(L[j][i] in K):
K[L[j][i]].append(j)
else:
K[L[j]... |
439_A. Devu, the Singer and Churu, the Joker | Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi... | ```python
a,b=input().split()
a=int(a)
b=int(b)
clist=list(map(int,input().split()))
sumi=sum(clist)
d=b-sumi
if(d>=(a-1)*10):
print(d//5)
else:
print("-1")
``` |
460_C. Present | Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted n flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noti... | ```python
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.... |
484_B. Maximum Value | You are given a sequence a consisting of n integers. Find the maximum possible value of <image> (integer remainder of ai divided by aj), where 1 ≤ i, j ≤ n and ai ≥ aj.
Input
The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·105).
The second line contains n space-separated integers ai (1 ≤ a... | ```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
import bisect
from types import GeneratorType
BUFSIZE = 8192
class SortedList:
def __init__(self, iterable=[], _load=... |
508_B. Anton and currency you all know | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.
Reliable sources have informed the financier Anton of some information about the exchange rate of... | ```python
n=list(input())
k=int(n[-1])
m=0
for i in range(len(n)):
z=int(n[i])
if(z%2==0):
temp=i
m=1
if(z<k):
break
if(m==0):
print("-1")
else:
n[-1],n[temp]=n[temp],n[-1]
print("".join(n))
``` |
557_C. Arthur and Table | Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable.
In total the table Arthur bought has n legs, the length of the i-th leg is li.
Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number di — the a... | ```python
"""
Author : Arif Ahmad
Date :
Algo :
Difficulty :
"""
from sys import stdin, stdout
def main():
n = int(stdin.readline())
leg = [int(_) for _ in stdin.readline().split()]
d = [int(_) for _ in stdin.readline().split()]
pairedLD = []
for x, y in zip(leg, d):
pairedLD.append((x, y))
pa... |
583_A. Asphalting Roads | City X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.
Sand roads have long been recognized out of date, so the decision was made to asphal... | ```python
n=int(input( ))
s=[[0 for a in range(n)]for b in range(n)]
for i in range(n**2):
a,b=[int(i) for i in input( ).split( )]
ac=0
for j in range(n):
if s[a-1][j]!=0 or s[j][b-1]!=0:
ac+=1
if ac==0:
s[a-1][b-1]+=1
print(i+1,end=' ')
``` |
605_A. Sorting Railway Cars | An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it... | ```python
n = int(input())
cars = [int(x) for x in input().split()]
sorted_cars = sorted(enumerate(cars), key = lambda x : x[1])
max_sorted_length = 1
length = 1
for i in range(1, n):
if sorted_cars[i][0] > sorted_cars[i-1][0]:
length += 1
else:
if max_sorted_length < length:
max_sor... |
651_B. Beautiful Paintings | There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.
We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while pa... | ```python
import math, re, sys, string, operator, functools, fractions, collections
sys.setrecursionlimit(10**7)
RI=lambda x=' ': list(map(int,input().split(x)))
RS=lambda x=' ': input().rstrip().split(x)
dX= [-1, 1, 0, 0,-1, 1,-1, 1]
dY= [ 0, 0,-1, 1, 1,-1,-1, 1]
mod=int(1e9+7)
eps=1e-6
pi=math.acos(-1.0)
MAX=1010
###... |
676_E. The Last Fight Between Human and AI | 100 years have passed since the last victory of the man versus computer in Go. Technologies made a huge step forward and robots conquered the Earth! It's time for the final fight between human and robot that will decide the faith of the planet.
The following game was chosen for the fights: initially there is a polynom... | ```python
def main():
n, k = map(int, input().split())
aa = []
for i in range(n + 1):
s = input()
aa.append(None if s == '?' else int(s))
qm_cnt = aa.count(None)
if k:
if qm_cnt:
print('Yes' if n & 1 else 'No')
else:
x = 0
for a in ... |
69_E. Subsegments | Programmer Sasha has recently begun to study data structures. His coach Stas told him to solve the problem of finding a minimum on the segment of the array in <image>, which Sasha coped with. For Sasha not to think that he had learned all, Stas gave him a new task. For each segment of the fixed length Sasha must find t... | ```python
from typing import TypeVar, Generic, Callable, List
import sys
from array import array # noqa: F401
from collections import Counter
def input():
return sys.stdin.buffer.readline().decode('utf-8')
minf = -10**9 - 100
T = TypeVar('T')
class SegmentTree(Generic[T]):
__slots__ = ["size", "tree", ... |
721_B. Passwords | Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.
Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrar... | ```python
n,k=map(int,input().split())
l1=[0]*101
for i in range(0,n):
s=input()
l1[len(s)]+=1
pword=input()
x=len(pword)
best=0
worst=0
best+=sum(l1[:x])
best=best+(best//k)*5 +1
worst+=sum(l1[:x+1])-1
worst=worst+(worst//k)*5+1
print(best,worst)
``` |
742_E. 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
n = int(input())
A = [0]*(2*n)
B = []
for line in sys.stdin:
x, y = [int(x)-1 for x in line.split()]
A[x] = y
A[y] = x
B.append(x)
C = [0]*(2*n)
for i in range(2*n):
while not C[i]:
C[i] = 1
C[i^1] = 2
i = A[i^1]
for x in B:
print(C[x], C[A[x]])
`... |
766_B. Mahmoud and a Triangle | Mahmoud has n line segments, the i-th of them has length ai. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check ... | ```python
def main():
n = int(input())
a = list(map(int, input().split()))
a.sort()
works = False
for i in range(2, n):
if a[i - 2] + a[i - 1] > a[i]:
works = True
break
print('YES' if works else 'NO')
main()
``` |
78_A. Haiku | Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syll... | ```python
g = ['a', 'e', 'i', 'o', 'u']
ans = [0]*3
h = [5,7,5]
for i in range(3):
s = input()
for j in s:
if j in g:
ans[i] += 1
if ans == h:
print('YES')
else:
print('NO')
``` |
810_C. Do you want a date? | Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the... | ```python
mod = 10**9+7
n = int(input())
x = sorted(list(map(int, input().split())))
total = 0
for i, (a, b) in enumerate(zip(x, x[1:])):
diff = b-a
total += (pow(2,i+1,mod)-1)*(pow(2,n-i-1,mod)-1)*diff
total %= mod
print(total)
``` |
906_B. Seating of Students | Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."
The class can be represented as a matrix with n rows and m col... | ```python
def get_answer(m, n):
if (m, n) in [(1, 2), (2, 1), (1, 3), (3, 1), (2, 2), (2, 3), (3, 2)]:
return ("NO", [])
elif (m == 1):
mat = [[i for i in range(2, n+1, 2)] + [i for i in range(1, n+1, 2)]]
return ("YES", mat)
elif (n == 1):
mat = [[i] for i in range(2, m+1, 2)] + [[i] for i in range(1, m+1... |
926_D. Choose Place | A classroom in a school has six rows with 3 desks in each row. Two people can use the same desk: one sitting on the left and one sitting on the right.
Some places are already occupied, and some places are vacant. Petya has just entered the class and wants to occupy the most convenient place. The conveniences of the p... | ```python
#!/usr/bin/env python3
variants = []
price = (
(3,4,3),
(3,4,3),
(2,3,2),
(2,3,2),
(1,2,1),
(1,2,1)
)
max_price = (0, 0, 0, 0)
class_map = []
for i in range(6):
current_row = input().split('-')
class_map.append(current_row)
for j, parta in enumerate(current_row):
... |
955_B. Not simply beatiful strings | Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others — a gr... | ```python
def go(s):
d = {}
for c in s:
d[c] = d.get(c, 0) + 1
if len(d.keys()) > 4 or len(d.keys()) == 1:
return 'No'
if len(d.keys()) == 2:
if 1 in d.values():
return 'No'
else:
return 'Yes'
if len(d.keys()) == 3:
if sum(d.values()) >... |
981_D. Bookshelves | Mr Keks is a typical white-collar in Byteland.
He has a bookshelf in his office with some books on it, each book has an integer positive price.
Mr Keks defines the value of a shelf as the sum of books prices on it.
Miraculously, Mr Keks was promoted and now he is moving into a new office.
He learned that in the ne... | ```python
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(... |
p02553 AtCoder Beginner Contest 178 - Product Max | Given are integers a,b,c and d. If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?
Constraints
* -10^9 \leq a \leq b \leq 10^9
* -10^9 \leq c \leq d \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the follo... | ```python
lines = map(int,input().split())
a,b,c,d = lines
print(max(a*c,a*d,b*c,b*d))
``` |
p02684 AtCoder Beginner Contest 167 - Teleporter | The Kingdom of Takahashi has N towns, numbered 1 through N.
There is one teleporter in each town. The teleporter in Town i (1 \leq i \leq N) sends you to Town A_i.
Takahashi, the king, loves the positive integer K. The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K... | ```python
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = []
ord = [-1] * (n+1)
v = 1
while ord[v] == -1:
ord[v] = len(s)
s.append(v)
v = a[v-1]
c = len(s) - ord[v]
l = ord[v]
ans = 0
if k < l:
ans = s[k]
else:
k -= l
k %= c
ans = s[l+k]
print(ans)
``` |
p02812 AtCoder Beginner Contest 150 - Count ABC | We have a string S of length N consisting of uppercase English letters.
How many times does `ABC` occur in S as contiguous subsequences (see Sample Inputs and Outputs)?
Constraints
* 3 \leq N \leq 50
* S consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
... | ```python
n = input()
print(input().count('ABC'))
``` |
p02949 AtCoder Beginner Contest 137 - Coins Respawn | There is a directed graph with N vertices numbered 1 to N and M edges. The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge. Additionally, there is a button on Vertex N.
We will play a game on this graph. You start the game on Vertex 1 with zero coins, and head for V... | ```python
n,m,p = map(int, input().split())
edge = []
inv_link = [[] for _ in range(n)]
link = [[] for _ in range(n)]
for i in range(m):
a,b,cost = list(map(int,input().split()))
edge.append([a-1,b-1,p-cost])
link[a-1].append(b-1)
inv_link[b-1].append(a-1)
def bell(edges, start,num_v):
cost = [flo... |
p03085 AtCoder Beginner Contest 122 - Double Helix | On the Planet AtCoder, there are four types of bases: `A`, `C`, `G` and `T`. `A` bonds with `T`, and `C` bonds with `G`.
You are given a letter b as input, which is `A`, `C`, `G` or `T`. Write a program that prints the letter representing the base that bonds with the base b.
Constraints
* b is one of the letters `A`... | ```python
aT={'A':'T','T':'A','C':'G','G':'C'}
print(aT[input()])
``` |
p03230 Tenka1 Programmer Beginner Contest - Crossing | You are given an integer N. Determine if there exists a tuple of subsets of \\{1,2,...N\\}, (S_1,S_2,...,S_k), that satisfies the following conditions:
* Each of the integers 1,2,...,N is contained in exactly two of the sets S_1,S_2,...,S_k.
* Any two of the sets S_1,S_2,...,S_k have exactly one element in common.
... | ```python
N = int(input())
k = 1
n = 0
while n < N:
n += k
k += 1
if n!=N:
print('No')
exit()
print('Yes')
print(k)
ans = [[] for _ in range(k)]
v = 1
for i in range(k-1):
for j in range(i+1,k):
ans[i].append(v)
ans[j].append(v)
v += 1
for row in ans:
print(*([len(row)] +... |
p03380 AtCoder Beginner Contest 094 - Binomial Coefficients | Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order. From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized. If there are multiple pairs that maximize the value, any of them is accepted.
Constraints
* 2 ... | ```python
n = int(input())
a = list(map(int, input().split()))
ai = max(a)
aj = min(filter(lambda x: x!=ai, a), key=lambda x: abs(x-ai//2))
print("{} {}".format(ai, aj))
``` |
p03545 AtCoder Beginner Contest 079 - Train Ticket | Sitting in a station waiting room, Joisino is gazing at her train ticket.
The ticket is numbered with four digits A, B, C and D in this order, each between 0 and 9 (inclusive).
In the formula A op1 B op2 C op3 D = 7, replace each of the symbols op1, op2 and op3 with `+` or `-` so that the formula holds.
The given in... | ```python
s=input()
l=['+']*3+['']
for k in range(7):
a=''.join([i+j for i,j in zip(s,l)])
if eval(a)==7:
print(a+'=7')
break
l=list(bin(k+1)[2:].zfill(3).replace('0','+').replace('1','-'))+['']
``` |
p03699 AtCoder Beginner Contest 063 - Bugged | You are taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When... | ```python
n = int(input())
s = sorted([int(input()) for _ in range(n)])
a = sum(s)
if a %10:
print(a)
exit()
for i in range(n):
b = a - s[i]
if b%10:
print(b)
break
else:
print(0)
``` |
p03854 AtCoder Beginner Contest 049 - Daydream | You are given a string S consisting of lowercase English letters. Another string T is initially empty. Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times:
* Append one of the following at the end of T: `dream`, `dreamer`, `erase` and `eraser`.
Constrain... | ```python
import re
S = str(input())
print("YES" if re.match("^(dream|dreamer|erase|eraser)+$", S) else "NO")
``` |
p04021 AtCoder Grand Contest 003 - BBuBBBlesort! | Snuke got an integer sequence of length N from his mother, as a birthday present. The i-th (1 ≦ i ≦ N) element of the sequence is a_i. The elements are pairwise distinct. He is sorting this sequence in increasing order. With supernatural power, he can perform the following two operations on the sequence in any order:
... | ```python
n,*a=map(int,open(0))
print(len(set(a[::2])^set(sorted(a)[::2]))//2)
``` |
p00105 Book Index | Books are indexed. Write a program which reads a list of pairs of a word and a page number, and prints the word and a list of the corresponding page numbers.
You can assume that a word consists of at most 30 characters, and the page number is less than or equal to 1000. The number of pairs of a word and a page number ... | ```python
index = {}
while True:
try:
word,page = input().split()
page = int(page)
index[word].append(page)
except KeyError:
index[word] = [page]
except EOFError:
break
for (key,value) in sorted(index.items()):
print(key)
value = list(map(str,sorted(value)))
print(" ".join(value))
``` |
p00239 Calorie Counting | Food contains three nutrients called "protein", "fat" and "carbohydrate", which are called three major nutrients. It is calculated that protein and carbohydrate are 4 kcal (kilocalories) and fat is 9 kcal per 1 g (gram). For example, according to the table below, the number 1 cake contains 7 g of protein, 14 g of fat a... | ```python
ans = []
readline = open(0).readline
writelines = open(1, 'w').writelines
while 1:
N = int(readline())
if N == 0:
break
items = [map(int, readline().split()) for i in range(N)]
P, Q, R, C = map(int, readline().split())
c = 0
for s, p, q, r in items:
if p <= P and q <= ... |
p00615 Traffic Analysis | There are two cameras which observe the up line and the down line respectively on the double lane (please see the following figure). These cameras are located on a line perpendicular to the lane, and we call the line 'monitoring line.' (the red line in the figure)
<image>
Monitoring systems are connected to the cam... | ```python
# AOJ 1029: Traffic Analysis
# Python3 2018.7.6 bal4u
import sys
from sys import stdin
input = stdin.readline
while True:
n, m = map(int, input().split())
if n == 0 and m == 0: break
if n > 0: a = list(map(int, input().split()))
if m > 0: b = list(map(int, input().split()))
ans = i = j = 0
s, t = 0, -... |
p00754 The Balance of the World | The Balance of the World
The world should be finely balanced. Positive vs. negative, light vs. shadow, and left vs. right brackets. Your mission is to write a program that judges whether a string is balanced with respect to brackets so that we can observe the balance of the world.
A string that will be given to the p... | ```python
def is_balanced(s):
stack = []
for c in s:
if c == '(' or c == '[':
stack.append(c)
elif c == ')':
if not stack:
return "no"
elif stack[-1] == '(':
stack.pop()
else:
return "no"
elif... |
p00891 Where's Wally | Do you know the famous series of children's books named "Where's Wally"? Each of the books contains a variety of pictures of hundreds of people. Readers are challenged to find a person called Wally in the crowd.
We can consider "Where's Wally" as a kind of pattern matching of two-dimensional graphical images. Wally's ... | ```python
import string
import sys
S = string.ascii_uppercase + string.ascii_lowercase + string.digits + "+/"
mod = 10**9 + 9; p = 13; q = 19
L = 1000
p_table = [1]*(L+1); q_table = [1]*(L+1)
for i in range(L):
p_table[i+1] = p_table[i] * p % mod
q_table[i+1] = q_table[i] * q % mod
readline = sys.stdin.readli... |
p01023 Caterpillar | G, a college student living in a certain sky city, has a hornworm, Imotaro. He disciplined Imotaro to eat all the food in order with the shortest number of steps. You, his friend, decided to write a program because he asked me to find out if Imotaro was really disciplined.
Input
H W N
area
Input is given in H + ... | ```python
from collections import deque
def main():
h, w, n = map(int, input().split())
mp = [list("#" * (w + 2))] + [list("#" + input() + "#") for _ in range(h)] + [list("#") * (w + 2)]
init_body = [None] * 4
for y in range(1, h + 1):
for x in range(1, w + 1):
if mp[y][x] == "S":
... |
p01294 For the Peace | This is a story of a world somewhere far from the earth. In this world, the land is parted into a number of countries ruled by empires. This world is not very peaceful: they have been involved in army race.
They are competing in production of missiles in particular. Nevertheless, no countries have started wars for yea... | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in ... |
p01622 Twin book report | At the school where the twins Ami and Mami attend, the summer vacation has already begun, and a huge amount of homework has been given this year as well. However, the two of them were still trying to go out without doing any homework today. It is obvious that you will see crying on the last day of summer vacation as it... | ```python
while True:
n=int(input())
if n==0:
break
books=[]
read_t=0
write_t=0
for i in range(n):
r,w=map(int,input().split())
read_t+=r
write_t+=w
books.append((r,w))
books=sorted(books)
if books[-1][0]<=read_t//2:
print(read_t+write_t)
... |
p01775 Rescue a Postal Worker | D: Rescue a Postal Worker
story
You got a job at the post office, which you have long dreamed of this spring. I decided on the delivery area I was in charge of, and it was my first job with a feeling of excitement, but I didn't notice that there was a hole in the bag containing the mail because it was so floating tha... | ```python
from heapq import heappush, heappop
n, m, k, p = map(int, input().split())
p -= 1
edges = [[] for _ in range(n)]
for _ in range(m):
x, y, w = map(int, input().split())
x -= 1
y -= 1
edges[x].append((y, w))
edges[y].append((x, w))
point = []
for _ in range(k):
s, t = map(int, input().split())
s ... |
p01909 Graduation Ceremony | problem
The point $ P $ is placed at the origin on the coordinate plane. I want to move the point $ P $ to a position where the Manhattan distance from the origin is as far as possible.
First, the string $ S = s_1s_2 \ cdots s_ {| S |} $ ($ | S | $ is the number of characters in $ S $) is given. The point $ P $ is mo... | ```python
def main():
s = input()
k = int(input())
lrs = []
uds = []
for c in s:
if c == "R":
lrs.append(1)
if c == "L":
lrs.append(-1)
if c == "U":
uds.append(-1)
if c == "D":
uds.append(1)
lr_length = len(lrs)
ud_length = len(uds)
lr_dp1 = [0] * (lr_length + ... |
p02190 Set | Set
Given the sequence a_1, a_2, .., a_N.
How many values are there in this sequence?
input
N
a_1 a_2 ... a_N
output
Output the number of types of values in the sequence.
Constraint
* 1 \ leq N \ leq 10 ^ 5
* 1 \ leq a_i \ leq 10 ^ 9
Input example
6
8 6 9 1 2 1
Output example
Five
Example
... | ```python
n = int(input())
l = [int(i) for i in input().split()]
print(len(set(l)))
``` |
p02344 Weighted Union Find Trees | There is a sequence $A = a_0, a_1, ..., a_{n-1}$. You are given the following information and questions.
* relate$(x, y, z)$: $a_y$ is greater than $a_x$ by $z$
* diff$(x, y)$: report the difference between $a_x$ and $a_y$ $(a_y - a_x)$
Constraints
* $2 \leq n \leq 100,000$
* $1 \leq q \leq 200,000$
* $0 \leq x, y <... | ```python
line = input()
n, q = list(map(int, line.split()))
rel = {}
for i in range(0, n):
rel[i] = []
parent = [i for i in range(0, n)]
rank = [0] * n
weight = [0] * n
def find(x):
if parent[x] == x:
return x
else:
y = find(parent[x])
weight[x] += weight[parent[x]]
parent[... |
p02477 Multiplication of Big Integers II | Multiplication of Big Integers II
Given two integers $A$ and $B$, compute the product, $A \times B$.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the product in a line.
Constraints
* $-1 \times 10^{200000} \leq A, B \leq 10^{200000}$
Sample Input 1
5 8
Sa... | ```python
a,b=map(int,input().split())
ans=a*b
print(ans)
``` |
1009_A. Game Shopping | Maxim wants to buy some games at the local game shop. There are n games in the shop, the i-th game costs c_i.
Maxim has a wallet which can be represented as an array of integers. His wallet contains m bills, the j-th bill has value a_j.
Games in the shop are ordered from left to right, Maxim tries to buy every game i... | ```python
n, m = map(int, input().split())
a = list( map(int, input().split()) )
b = list( map(int, input().split()) )
i, j, counter = 0, 0, 0
while( i < int(n) and j < int(m) ):
if( a[i] <= b[j] ):
i += 1
j += 1
counter += 1
else:
i += 1
print(counter)
``` |
1031_D. Minimum path | You are given a matrix of size n × n filled with lowercase English letters. You can change no more than k letters in this matrix.
Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is f... | ```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... |
1054_D. Changing Array | At a break Vanya came to the class and saw an array of n k-bit integers a_1, a_2, …, a_n on the board. An integer x is called a k-bit integer if 0 ≤ x ≤ 2^k - 1.
Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himse... | ```python
n,k=list(map(int,input().split()))
arr=list(map(int,input().split()))
newarr=[0]
for num in arr:
newarr+=[newarr[-1]^num]
dic={}
for num in newarr:
x=(min(num,2**k-1-num),max(num,2**k-1-num))
if x in dic:
dic[x]+=1
else:
dic[x]=1
ans=0
for elem in dic:
m=dic[elem]
half=m//2
ans+=half*(h... |
1076_D. Edge Deletion | You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with l... | ```python
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n,m,k = map(int, input().split())
g = [[] for i in range(n)]
toid = {}
for i in range(m):
x,y,w = map(int, input().split())
x,y = x-1, y-1
g[x].append((w,y))
g[y].append((w,x))
toid[(x,y)] = i
toid[(y... |
1097_D. Makoto and a Blackboard | Makoto has a big blackboard with a positive integer n written on it. He will perform the following action exactly k times:
Suppose the number currently written on the blackboard is v. He will randomly pick one of the divisors of v (possibly 1 and v) and replace v with this divisor. As Makoto uses his famous random num... | ```python
import time
mod = int(1e9 + 7)
def fast_expo(x, k):
ans = 1
while k > 0:
if (k & 1) > 0:
ans = (ans * x) % mod
x = (x * x) % mod
k >>= 1
return ans
def inverse(x):
return fast_expo(x, mod - 2)
N, K = [int(_) for _ in input().split()]
start_time = time.ti... |
1118_D2. Coffee and Coursework (Hard Version) | The only difference between easy and hard versions is the constraints.
Polycarp has to write a coursework. The coursework consists of m pages.
Polycarp also has n cups of coffee. The coffee in the i-th cup Polycarp has a_i caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can dri... | ```python
import sys
n,m=map(int,input().split())
A=list(map(int,input().split()))
if sum(A)<m:
print(-1)
sys.exit()
A.sort(reverse=True)
MIN=1
MAX=n
while MIN!=MAX:
d=(MIN+MAX)//2
ANS=0
j=0
count=0
for a in A:
if a<=j:
continue
ANS+=(a-j)
... |
1145_A. Thanos Sort | [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process.
Given an input array, what i... | ```python
n = int(input())
a = list(map(int, input().split(' ')))
ans = 1
length = 2
while length <= n:
for i in range(0, n // length):
b = a[i * length: (i + 1) * length]
ok = True
for j in range(len(b) - 1):
if b[j] > b[j + 1]:
ok = False
break
... |
1165_F2. Microtransactions (hard version) | The only difference between easy and hard versions is constraints.
Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.
E... | ```python
import math
from collections import defaultdict
import sys
#input = sys.stdin.readline
def main():
n, m = map(int, input().split())
k = list(map(int, input().split()))
sales = [(0, 0)] * m
for i in range(m):
a, b = map(int, input().split())
sales[i] = (b, a)
def check(da... |
1184_E1. Daleks' Invasion (easy) | Heidi found out that the Daleks have created a network of bidirectional Time Corridors connecting different destinations (at different times!). She suspects that they are planning another invasion on the entire Space and Time. In order to counter the invasion, she plans to deploy a trap in the Time Vortex, along a care... | ```python
def naiveSolve():
return
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def find(self, a): #return parent of a. a and b are in same set if they have same parent
acopy = a
while a != self.parent[a]:
a = self.parent[a]
... |
1203_C. Common Divisors | You are given an array a consisting of n integers.
Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array.
For example, if the array a will be [2, 4, 6, 2, 10], then 1 and 2 ... | ```python
import math
n = int(input())
l=list(map(int,input().split()))
hcf = l[0]
for i in l[1:]:
hcf = math.gcd(hcf,i)
count = 0
for i in range(1, int(math.sqrt(hcf))+1):
if hcf % i == 0 : count += 2
if hcf == 1: print(count - 1)
else:
if int(math.sqrt(hcf)) * int(math.sqrt(hcf)) == hcf :
count -... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.