name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
525_B. Pasha and String | Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.
Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent ... | ```python
s = list(input())
m = int(input())
a = [int(x) for x in input().split()]
n = len(s) // 2
sums = [0] * (n+1)
for i in a:
sums[i-1] += 1
for i in range (1, len(sums)):
sums[i] += sums[i-1]
for i in range(n):
if sums[i] % 2 != 0:
s[i], s[len(s) - i - 1] = s[len(s) - i - 1], s[i]
print("".jo... |
550_C. Divisibility by Eight | You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes.
Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-... | ```python
from itertools import combinations
def solve():
n="00"+input()
for s in (int(n[i]+n[j]+n[k]) for i,j,k in combinations(range(len(n)),3)):
if s%8==0:
print("YES\n{}".format(s))
exit(0)
print("NO")
solve()
``` |
577_D. Invariance of Tree | A tree of size n is an undirected connected graph consisting of n vertices without cycles.
Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vert... | ```python
def main():
n = int(input())
a = list(map(lambda x: int(x) - 1, input().split()))
p = -1
q = -1
for i in range(n):
if a[a[i]] == i:
p, q = i, a[i]
if a[i] == i:
print('YES')
[print(i + 1, j + 1) for j in range(n) if i != j]
e... |
59_B. Fortune Telling | Marina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces a... | ```python
n = int(input())
l = list(map(int, input().split()))
r = 0
par = []
nep = []
for item in l:
if item % 2 == 0:
par.append(item)
else:
nep.append(item)
if len(nep) % 2 == 0 and nep != []:
nep.remove(min(nep))
r += sum(nep)
if r != 0:
r += sum(par)
print(r)
``` |
641_E. Little Artem and Time Machine | Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.
Artem wants to create a basic multiset of integers. He wants these structure to support operations of three typ... | ```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(... |
66_C. Petya and File System | Recently, on a programming lesson little Petya showed how quickly he can create files and folders on the computer. But he got soon fed up with this activity, and he decided to do a much more useful thing. He decided to calculate what folder contains most subfolders (including nested folders, nested folders of nested fo... | ```python
lines = []
from collections import defaultdict
d = {}
while True:
try:
x = input();
if len(x) == 0:
break
x = x.split("\\")
lines.append(x[1:])
curr_d = d
for i in range(0, len(x) - 1):
curr = x[i]
if curr in curr_d:
... |
736_B. Taxes | Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to n (n ≥ 2) burles and the amount of tax he has to pay is calculated as the maximum divisor of n (not equal to n, of course). For example, if n = 6 then Funt has to pay 3 burles, while for n = 25 he ne... | ```python
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
if __name__ == "__main__":
def prime(n):
if n == 1:
return False
i ... |
760_B. Frodo and pillows | n hobbits are planning to spend the night at Frodo's house. Frodo has n beds standing in a row and m pillows (n ≤ m). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if h... | ```python
n, m, k = map(int, input().split())
m -= n
d = 0
k -= 1
out = 1
while m > 1 and d != max(k, n - k - 1):
out += 1
m -= 1
left = min(d, k)
right = min(d, n - k - 1)
d += 1
m -= left
m -= right
out += m // n
print(out)
``` |
804_C. Ice cream coloring | Isart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: "Can you solve a problem I'm stuck at all day?"
We have a tree T with n vertices and m types of ice cream numerated from 1 to m. Each vertex i has a set of si types of ice cream. Vertices which have the i-t... | ```python
from collections import deque
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
src = 0
X = []
for u in range(n):
X.append(list(map(lambda x: int(x) - 1, input().split())))
X[u] = X[u][1:]
if len(X[u]) > len(X[src]):
src = u
E = [[] for u in range(n)]
for j in rang... |
82_B. Sets | Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.
One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible... | ```python
c, v = [[0] * 201 for i in range(201)], []
n = int(input())
for i in range(n * (n - 1) // 2):
a = list(map(int, input().split()))[1:]
for x in a:
for y in a:
c[x][y] += 1
for i, ci in enumerate(c):
if ci[i]:
a = [j for j, cij in enumerate(ci) if cij == n - 1]
v.... |
899_E. Segments Removal | Vasya has an array of integers of length n.
Vasya performs the following operations on the array: on each step he finds the longest segment of consecutive equal integers (the leftmost, if there are several such segments) and removes it. For example, if Vasya's array is [13, 13, 7, 7, 7, 2, 2, 2], then after one operat... | ```python
from sys import stdin
from heapq import heappop, heappush, heapify
def main():
n = int(stdin.readline())
a = stdin.readline().split()
q = []
p = 0
c = 0
l = [0] * (n + 1)
r = [0] * (n + 1)
k = [0] * (n + 1)
pa = [0] * (n + 1)
for i, x in enumerate(a):
if x == a[... |
920_A. Water The Garden | It is winter now, and Max decided it's about time he watered the garden.
The garden can be represented as n consecutive garden beds, numbered from 1 to n. k beds contain water taps (i-th tap is located in the bed xi), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed xi is turned ... | ```python
t=int(input())
for _ in range(t):
n,k=list(map(int,input().split()))
x=list(map(int,input().split()))
b=[]
for i in range(1,n+1):
a=[]
for j in range(k):
a.append(abs(x[j]-i))
b.append(min(a))
print(max(b)+1)
``` |
976_D. Degree Set | You are given a sequence of n positive integers d1, d2, ..., dn (d1 < d2 < ... < dn). Your task is to construct an undirected graph such that:
* there are exactly dn + 1 vertices;
* there are no self-loops;
* there are no multiple edges;
* there are no more than 106 edges;
* its degree set is equal to d.... | ```python
from sys import stdin
from sys import stdout
n = int(stdin.readline())
d = [0] + list(map(int, stdin.readline().split()))
e = []
for i in range(1, n+1):
for u in range(d[i-1]+1, d[i]+1):
for v in range(u+1, d[n-i+1]+2):
e.append([u,v])
stdout.write("{}\n".format(len(e)))
for ei in e: stdout.write("{} {... |
996_B. World Cup | Allen wants to enter a fan zone that occupies a round square and has n entrances.
There already is a queue of a_i people in front of the i-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.
Allen uses the following strategy to enter the fan zone:
* Initially he stands... | ```python
_ = input()
arr = list(map(int, input().split()))
best = None
for i in range(len(arr)):
pos_at_zero = arr[i] % len(arr)
if pos_at_zero > i:
extra = len(arr) - pos_at_zero + i
else:
extra = i - pos_at_zero
time_needed = arr[i] + extra
#print(i, time_needed, extra, arr[i])
... |
p02648 Tokio Marine & Nichido Fire Insurance Programming Contest 2020 - Knapsack Queries on a tree | We have a rooted binary tree with N vertices, where the vertices are numbered 1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex \left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a weight of W_i. Now, process the following query Q times:
... | ```python
import sys
MX = 10**5
def main():
data = map(int, sys.stdin.buffer.read().split())
N = next(data)
H = min(N + 1, 1 << 10)
dp = [None] * H
dp[0] = [0] * (MX + 1)
IV, IW = [], []
i = 1
for v, w in zip(data, data):
if i < H:
dpi = dp[i >> 1][:]
dp[... |
p02777 AtCoder Beginner Contest 154 - Remaining Balls | We have A balls with the string S written on each of them and B balls with the string T written on each of them.
From these balls, Takahashi chooses one with the string U written on it and throws it away.
Find the number of balls with the string S and balls with the string T that we have now.
Constraints
* S, T, and ... | ```python
S,T=input().split()
a,b=map(int,input().split())
n=input()
if S==n:
print(a-1,b)
else:
print(a,b-1)
``` |
p02912 AtCoder Beginner Contest 141 - Powerful Discount Tickets | Takahashi is going to buy N items one by one.
The price of the i-th item he buys is A_i yen (the currency of Japan).
He has M discount tickets, and he can use any number of them when buying an item.
If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nea... | ```python
n,m = map(int,input().split())
a = [-int(i) for i in input().split()]
import heapq
heapq.heapify(a)
for i in range(m):
x = heapq.heappop(a)
heapq.heappush(a,-(-x//2))
print(-sum(a))
``` |
p03048 diverta 2019 Programming Contest - RGB Boxes | Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:
* Red boxes, each containing R red balls
* Green boxes, each containing G green balls
* Blue boxes, each containing B blue balls
Snuke wants to get a total of exactly N balls by buying r red boxes, g gre... | ```python
R,G,B,N=map(int,input().split())
ans=0
for i in range(1+N//R):
r=R*i
for j in range(1+(N-r)//G):
g=G*j
if (N-r-g)%B==0:
ans+=1
print(ans)
``` |
p03189 AtCoder Grand Contest 030 - Inversion Sum | You are given an integer sequence of length N: A_1,A_2,...,A_N. Let us perform Q operations in order. The i-th operation is described by two integers X_i and Y_i. In this operation, we will choose one of the following two actions and perform it:
* Swap the values of A_{X_i} and A_{Y_i}
* Do nothing
There are 2^Q wa... | ```python
import sys
n, q = list(map(int, input().split()))
MOD = 10 ** 9 + 7
INV2 = (MOD + 1) // 2
lines = sys.stdin.readlines()
aaa = list(map(int, lines[:n]))
mat = [[0] * n for _ in [0] * n]
for i in range(n):
for j in range(n):
mat[i][j] = int(aaa[i] < aaa[j])
# print(*mat, sep='\n')
for line in lines... |
p03336 AtCoder Grand Contest 025 - Addition and Andition | Takahashi and Aoki love calculating things, so they will play with numbers now.
First, they came up with one positive integer each. Takahashi came up with X, and Aoki came up with Y. Then, they will enjoy themselves by repeating the following operation K times:
* Compute the bitwise AND of the number currently kept b... | ```python
def Z():
m=-1;I=input;N,M,K=map(int,I().split());W=2000000;s=[0]*W;t=[0]*W;L=max(N,M)-1;R=range;p=lambda x:print(*reversed(x),sep='')
for i,c in zip(R(N-1,m,m),I()):s[i]=int(c)
for i,c in zip(R(M-1,m,m),I()):t[i]=int(c)
for i in R(L,m,m):
j=i;z=K
while s[j]and t[j]and z:
s[j]=t[j]=0;s[j+1]+=1;t[j+1... |
p03497 AtCoder Regular Contest 086 - Not so Diverse | Takahashi has N balls. Initially, an integer A_i is written on the i-th ball.
He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls.
Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
Constraints
* 1 \leq K \leq N... | ```python
from collections import Counter
n, k = map(int, input().split())
xs = map(int, input().split())
ctr = Counter(xs)
cnts = sorted(ctr.values())
ans = n - sum(cnts[-k:])
print(ans)
``` |
p03657 AtCoder Beginner Contest 067 - Sharing Cookies | Snuke is giving cookies to his three goats.
He has two cookie tins. One contains A cookies, and the other contains B cookies. He can thus give A cookies, B cookies or A+B cookies to his goats (he cannot open the tins).
Your task is to determine whether Snuke can give cookies to his three goats so that each of them ca... | ```python
A,B=map(int,input().split())
b=A%3==0 or B%3==0 or (A+B)%3==0
print("Possible" if b else "Impossible")
``` |
p03813 AtCoder Beginner Contest 053 - ABC/ARC | Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.
You are given Smeke's current rating, x. Print `ABC` if Smeke will participate in ABC, and print `ARC` otherwise.
Constraints
* 1 ≦ x ≦ 3{,}000
* x i... | ```python
a= input()
if a<"1200":
print("ABC")
else:
print("ARC")
``` |
p00070 Combination of Number Sequences | Consider a sequence of n numbers using integers from 0 to 9 k1, k2, ..., kn. Read the positive integers n and s,
k1 + 2 x k2 + 3 x k3 + ... + n x kn = s
Create a program that outputs how many rows of n numbers such as. However, the same number does not appear more than once in one "n sequence of numbers".
Input
T... | ```python
from collections import defaultdict, Counter
import sys
# dp[n][使った数字(bit)][合計] = count
dp = [defaultdict(Counter) for _ in [0]*11]
dp[0][0][0] = 1
for i in range(1, 11):
for used, counter in dp[i-1].items():
for j in filter(lambda x: used & 2**x == 0, range(10)):
for total, count in... |
p00202 At Boss's Expense | Taro Aizu's company has a boss who hates being indivisible. When Taro goes out to eat with his boss, he pays by splitting the bill, but when the payment amount is not divisible by the number of participants, his boss always pays for it.
One day, Taro became the secretary of the dinner party. Mr. Taro, who has little m... | ```python
def solve(price, ps, is_prime):
dp = [0] * ((price >> 5) + 1)
for i in range(0, price + 1,ps[0]):
dp[i >> 5] |= 1 << (i & 31)
dp[0] = 1
for i in range(1, len(ps)):
cur_p = ps[i]
r = cur_p & 31
rest = 0
if cur_p >= 32:
for p in range(cur_p, p... |
p00357 Trampoline | A plurality of trampolines are arranged in a line at 10 m intervals. Each trampoline has its own maximum horizontal distance within which the jumper can jump safely. Starting from the left-most trampoline, the jumper jumps to another trampoline within the allowed jumping range. The jumper wants to repeat jumping until ... | ```python
n = 0
bounce = []
def IsReachable() :
current = 0
for i in range(n) :
if current < 10*i : return False
current = max( current, 10*i + bounce[i] )
if current >= 10*n : return True
return False
n = int(input())
for i in range(n) :
bounce.append( int(input()) )
if not I... |
p00716 Ohgas' Fortune | The Ohgas are a prestigious family based on Hachioji. The head of the family, Mr. Nemochi Ohga, a famous wealthy man, wishes to increase his fortune by depositing his money to an operation company. You are asked to help Mr. Ohga maximize his profit by operating the given money during a specified period.
From a given l... | ```python
def c(a):
global y,r,d
for _ in range(y):a+=int(a*r)-d
return a
def s(a):
global y,r,d
b=0
for _ in range(y):
b+=int(a*r)
a-=d
return a+b
for _ in range(int(input())):
m=0
a=int(input());y=int(input())
for _ in range(int(input())):
b,r,d=map(fl... |
p00856 Minimal Backgammon | Here is a very simple variation of the game backgammon, named “Minimal Backgammon”. The game is played by only one player, using only one of the dice and only one checker (the token used by the player).
The game board is a line of (N + 1) squares labeled as 0 (the start) to N (the goal). At the beginning, the checker ... | ```python
while True:
N, T, L, B = map(int, input().split())
if not (N | T | L | B):
break
Lose = [False for i in range(N + 1)]
Back = [False for i in range(N + 1)]
for i in range(L):
Lose[int(input())] = True
for j in range(B):
Back[int(input())] = True
dp = [[0.0... |
p01119 Balance Scale | <!--
Problem C
-->
Balance Scale
You, an experimental chemist, have a balance scale and a kit of weights for measuring weights of powder chemicals.
For work efficiency, a single use of the balance scale should be enough for measurement of each amount. You can use any number of weights at a time, placing them eithe... | ```python
def main():
n,m = map(int,input().split())
if n*m == 0: return False
a = list(map(int, input().split()))
w = list(map(int,input().split()))
d = {0:1}
for i in w:
new_d = dict(d)
for j in d.keys():
new_d[j+i] = 1
new_d[abs(j-i)] = 1
new_d[... |
p01418 Sleeping Time | Miki is a high school student. She has a part time job, so she cannot take enough sleep on weekdays. She wants to take good sleep on holidays, but she doesn't know the best length of sleeping time for her. She is now trying to figure that out with the following algorithm:
1. Begin with the numbers K, R and L.
2. She t... | ```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 ... |
p01873 Periodic Sequence | B: Periodic Sequence-
problem
Dr. Period, a professor at H University, is studying a property called the cycle that is supposed to be hidden in all things. As a generally known basic cycle, a cycle hidden in a sequence may be considered. That is, if the sequence S = S_1, S_2, ..., S_N of length N satisfies the follow... | ```python
n=int(input())
a=list(map(int,input().split()))
for i in range(1,n+1):
if n%i==0:
for j in range(n):
if j>=i and a[j]!=a[j-i]:break
else:print(n//i);exit()
print(1)
``` |
p02010 Additions | You are given an integer $N$ and a string consisting of '+' and digits. You are asked to transform the string into a valid formula whose calculation result is smaller than or equal to $N$ by modifying some characters. Here, you replace one character with another character any number of times, and the converted string s... | ```python
from heapq import heappush, heappop, heapify
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
S = readline().strip()
L = len(S)
S += "+"
if L % 2 == 0 and N < 10:
write("-1\n")
return
pw10 = [1]*11
for i in range(10)... |
p02294 Intersection | For given two segments s1 and s2, print "1" if they are intersect, "0" otherwise.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2n... | ```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
3
0 0 3 0 1 1 2 -1
0 0 3 0 3 1 3 -1
0 0 3 0 3 -2 5 0
output:
1
1
0
"""
import sys
EPS = 1e-9
def cross(a, b):
return a.real * b.imag - a.imag * b.real
def dot(a, b):
return a.real * b.real + a.imag * b.imag
def check_ccw(p0, p1, p2):
... |
p02441 Count | For a given sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$, perform the following operations.
* count($b, e, k$): print the number of the specific values $k$ in $a_b, a_{b+1}, ..., a_{e-1}$.
Constraints
* $1 \leq n \leq 1,000$
* $-1,000,000,000 \leq a_i, k_i \leq 1,000,000,000$
* $1 \leq q \leq 1,000$
* $0 ... | ```python
import sys
n = int(input())
a = list(map(int,input().split()))
q = int(input())
for q in (list(map(int,line.split())) for line in sys.stdin):
print(a[q[0]:q[1]].count(q[2]))
``` |
1056_E. Check Transcription | One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal s towards a faraway galaxy. Recently they've received a response t which they believe to be a response from aliens! The scientists now want to check if the signal t is similar to s.
The original signal s was a se... | ```python
import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def add(a,b):
return (a+b)%1000000007
def sub(a,b):
return (a+1000000007-b)%1000000007
def mul(a,b):
return (a*b)%1000000007
p = 102367
s = lis... |
107_A. Dorm Water Supply | The German University in Cairo (GUC) dorm houses are numbered from 1 to n. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).
For each house, the... | ```python
import sys
input = sys.stdin.readline
for _ in range(1):
n,m=[int(x) for x in input().split()]
g,v=[[] for i in range(n)],[False for i in range(n)]
s=[False for i in range(n)]
for i in range(m):
a,b,c=[int(x) for x in input().split()]
s[b-1]=True
g[a-1].append([b-1,c])
... |
1147_B. Chladni Figure | Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned ... | ```python
from math import gcd
def primes():
yield 2; yield 3; yield 5; yield 7;
bps = (p for p in primes()) # separate supply of "base" primes (b.p.)
p = next(bps) and next(bps) # discard 2, then get 3
q = p * p # 9 - square of next base prime to ke... |
1168_C. And Reachability | Toad Pimple has an array of integers a_1, a_2, …, a_n.
We say that y is reachable from x if x<y and there exists an integer array p such that x = p_1 < p_2 < … < p_k=y, and a_{p_i} \& a_{p_{i+1}} > 0 for all integers i such that 1 ≤ i < k.
Here \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bi... | ```python
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.read... |
1223_B. Strings Equalization | You are given two strings of equal length s and t consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.
... | ```python
for _ in range(int(input())):
s=input()
s1=input()
s=set(s)
s1=set(s1)
if s1&s:
print('YES')
else:
print('NO')
``` |
1248_E. 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... |
1267_D. DevOps Best Practices | Daisy is a senior software engineer at RainyDay, LLC. She has just implemented three new features in their product: the first feature makes their product work, the second one makes their product fast, and the third one makes their product correct. The company encourages at least some testing of new features, so Daisy a... | ```python
import sys
from functools import reduce
def impossible():
print("Impossible")
def main_proc():
res = []
cnt2resolve = 0
n = int(input()) # number of servers
# structure definition
target = [[[], []] for _ in range(8)] # target_id(equal to number of features) => [parent src_ids,t... |
1288_E. Messenger Simulator | Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented wit... | ```python
n,m=map(int,input().split())
a=[int(i)-1 for i in input().split()]
ans1=[i+1 for i in range(n)]
ans2=[-1 for i in range(n)]
for i in set(a):
ans1[i]=1
N=1
while N<n+m:N<<=1
st=[0 for i in range(N<<1)]
pos=[i+m for i in range(n)]
for i in range(n):
st[i+N+m]=1
for i in range(N-1,0,-1):
st[i]=st[i<<1]... |
1352_C. K-th Not Divisible by n | You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n.
For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the ... | ```python
t=int(input())
for _ in range(t):
n,k=map(int,input().split())
if k%(n-1)==0:
temp=k//(n-1)
print(n*(temp-1)+n-1)
else:
temp=k//(n-1)
print(n*temp+k%(n-1))
``` |
1372_A. Omkar and Completion | You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!
An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 ≤ x,y,z ≤ n), a_{x}+a_{y} ≠ a_{z} (not necessarily distinct).
You are given one integer ... | ```python
t=int(input())
for i in range(0,t):
n=int(input())
L=[1]*n
print(*L)
``` |
1419_C. Killjoy | A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).
Killjoy's account is already infected and has a rating equal to x. Its rating is constant. There are n accounts except hers, number... | ```python
for _ in range(int(input())):
n,x=map(int,input().split())
a=list(map(int,input().split()))
if len(set(a))==1 and list(set(a))[0]==x:
print(0)
elif sum(a)/n==x:
print(1)
elif x in a:
print(1)
else:
print(2)
``` |
1437_C. Chef Monocarp | Chef Monocarp has just put n dishes into an oven. He knows that the i-th dish has its optimal cooking time equal to t_i minutes.
At any positive integer minute T Monocarp can put no more than one dish out of the oven. If the i-th dish is put out at some minute T, then its unpleasant value is |T - t_i| — the absolute d... | ```python
from sys import stdin, stdout
t=int(stdin.readline())
for _ in range(t):
n=int(stdin.readline())
arr=list(map(int,stdin.readline().split()))
arr.sort()
dp=[[10**9 for _ in range(2*n)] for _ in range(n)]
for i in range(0,n):
for j in range(1,2*n):
if i==0:
dp[i][j]=min(dp[i][j-1],abs(arr[i]-j))
... |
1462_A. Favorite Sequence | Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible ... | ```python
import sys
from collections import deque
t = int(sys.stdin.readline())
for _ in range(t):
n = int(sys.stdin.readline())
nums = list(map(int, sys.stdin.readline().split()))
nums = deque(nums)
sw = 0
while nums:
if sw == 0:
print(nums.popleft(), end=" ")
sw ... |
1487_B. Cat Cycle | Suppose you are living with two cats: A and B. There are n napping spots where both cats usually sleep.
Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:
* Cat A changes its napping place in order: n, n - 1, n - 2, ..., 3, 2, 1, n, n - 1, ... In other words, a... | ```python
def main():
t = int(input())
for _ in range(t):
n, k = list(map(int, input().split()))
k -= 1
if n % 2 == 0:
print(k % n + 1)
else:
med = int(n*0.5)
print((k+int((k/med)))%n+1)
main()
``` |
1538_D. Another Problem About Dividing Numbers | You are given two integers a and b. In one turn, you can do one of the following operations:
* Take an integer c (c > 1 and a should be divisible by c) and replace a with a/c;
* Take an integer c (c > 1 and b should be divisible by c) and replace b with b/c.
Your goal is to make a equal to b using exactly k ... | ```python
import math
import sys
sys.setrecursionlimit(10000)
def prime_factors(n):
global gcdNM
count=0
while n%2==0:
gcdNM+=1
count+=1
n=n//2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
gcdNM+=1
count+=1
n=n//i
if ... |
232_A. Cycles | John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been pa... | ```python
import sys
import math
c=int(input())
Ans=[]
F=[1]
for i in range(1,101):
F.append(F[-1]*i)
for i in range(100):
Ans.append([0]*100)
print(100)
cycles=1
Ans[0][1]=1
Ans[1][0]=1
Ans[1][2]=1
Ans[2][1]=1
Ans[0][2]=1
Ans[2][0]=1
m=3
while(cycles<c):
Ans[0][m]=1
Ans[m][0]=1
inc=1
for j ... |
32_E. Hide-and-Seek | Victor and Peter are playing hide-and-seek. Peter has hidden, and Victor is to find him. In the room where they are playing, there is only one non-transparent wall and one double-sided mirror. Victor and Peter are points with coordinates (xv, yv) and (xp, yp) respectively. The wall is a segment joining points with coor... | ```python
xv,yv=list(map(int,input().split()))
xp,yp=list(map(int,input().split()))
xw1,yw1,xw2,yw2=list(map(int,input().split()))
xm1,ym1,xm2,ym2=list(map(int,input().split()))
def a(x1,y1,x2,y2,x3,y3,x4,y4):
if x1==x2:
if x3==x4:
return False
else:
k2=(y3-y4)/(x3-x4)
... |
398_A. Cards | User ainta loves to play with cards. He has a cards containing letter "o" and b cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below.
1. At first, the score is 0.
2. For each block of contiguous "o"s with length x the score increases by x2.
3. F... | ```python
a,b=[int(i) for i in input().split()]
if(a==0):
print(-b**2)
print('x'*b)
elif(b==0):
print(a**2)
print('o'*a)
elif(b==1):
print(a**2-1)
print('x'+'o'*a)
else:
ans=-float('inf')
gr_no=None
for i in range(2,min(a+2,b+1)):
v1=(a+2-i)**2 + i-2
quo=b//i
... |
420_B. Online Meeting | Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F ... | ```python
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
'''
Created on 13/09/2018
@author: ernesto
'''
n, m = [int(x) for x in input().strip().split(" ")]
posibles_jefes = set(range(1, n + 1))
anteriores = set()
posteriores = set()
continuos = [True] * (n + 1)
mencionados = set()
posibles_jefes_men... |
469_A. I Wanna Be the Guy | There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ... | ```python
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
d=[]
for i in range(1,p[0]+1):
d+=[p[i]]
for i in range(1,q[0]+1):
if(q[i] not in d):
d+=[q[i]]
if(len(d)==n):
print("I become the guy.")
else:
print("Oh, my keyboard!")
``` |
515_A. Drazil and Date | Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (... | ```python
a, b, s = map(int,input().split())
if (s - abs(a) - abs(b)) % 2 == 1 or s < abs(a) + abs(b):
print('NO')
else:
print('YES')
``` |
569_C. Primes or Palindromes? | Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this!
Let us remind you... | ```python
import sys
p,q = map(int,sys.stdin.readline().split())
def prime(n):
#print(int(n**0.5))
for div in range(2,int(n**0.5)+1):
if n%div==0:
return False
return True
def palindrom(n):
n = str(n)
for pos in range((len(n)+1)//2):
if n[pos]!=n[-1-pos]:
... |
590_A. Median Smoothing | A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practi... | ```python
import sys
lines = sys.stdin.readlines()
n = int(lines[0].strip())
arr = list(map(int, lines[1].strip().split(" ")))
arr.append(arr[-1])
res = []
maxChange = 0
left = 0
for i in range(1, n+1):
if arr[i] == arr[i-1]:
L = i - left
res += [arr[left]]*(L//2) + [arr[i-1]]*(L-L//2)
maxC... |
660_C. Hard Process | You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 ≤... | ```python
a,b=map(int,input().split())
z=list(map(int,input().split()))
ans=[]
for i in range(len(z)):
if(z[i]==0):
ans.append(i)
freq=[]
count=1
inde=0
if(len(ans)==0):
print(len(z))
print(*z)
exit()
pair=[[0,0] for i in range(len(ans))]
if(z[0]==0):
inde=1
for i in range(1,len(z)):
... |
707_A. Brain's Photos | Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a ... | ```python
n, m = [int(s) for s in input().split()]
for i in range(n):
a = [str(s) for s in input().split()]
if 'C' in a or 'Y' in a or 'M' in a:
m = -1
break
else:
pass
print('#Color') if m == -1 else print('#Black&White')
``` |
773_C. Prairie Partition | It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k ≥ 0, 0 < r ≤ 2k. Let's call that representation prairie partition of x.
For example, the prairie partitions of 12, 17, 7 and 1 are:
12 = 1 + 2 + 4 + 5,
17 = 1 + 2 + 4 + 8 + 2,
... | ```python
from collections import Counter
from math import log2
powers = [2 ** p for p in range(64)]
def can():
near = Counter()
for num in set(nums):
p = int(log2(num))
near[p] += nums[num]
seq_cp = seqs - Counter()
for num in set(near):
cnt = near[num]
while cnt != 0... |
798_B. Mike and strings | Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".
Now Mike asks himself: what... | ```python
def fn(s1,s2):
l1=list(s1)
l2=list(s2)
ans=0
for i in range(len(l1)):
if l1==l2:
break
l1=l1[1:]+[l1[0]]
ans+=1
if l1==l2:
return ans
else:
print(-1)
exit()
n1=int(input())
l=[]
if n1==1:
print(0)
exit()
for i in range... |
818_D. Multicolored Cars | Alice and Bob got very bored during a long car trip so they decided to play a game. From the window they can see cars of different colors running past them. Cars are going one after another.
The game rules are like this. Firstly Alice chooses some color A, then Bob chooses some color B (A ≠ B). After each car they upd... | ```python
n,A=map(int,input().split())
c=[]
c=list(map(int,input().split()))
if(A not in c):
print(c[0])
elif(c[0] == A):
print(-1)
else:
ind = c.index(A)
d={}
for i in range(ind):
if(c[i] in d.keys()):
d[c[i]] +=1
else:
d[c[i]] = 1
acar = 1
for i in r... |
864_C. Bus | A bus moves along the coordinate line Ox from the point x = 0 to the point x = a. After starting from the point x = 0, it reaches the point x = a, immediately turns back and then moves to the point x = 0. After returning to the point x = 0 it immediately goes back to the point x = a and so on. Thus, the bus moves from ... | ```python
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
"""
created by shhuan at 2017/10/4 19:43
"""
a, b, f, k = map(int, input().split())
if b < f or f+b < a:
print(-1)
exit(0)
r = a-f
res = 0
fuel = b
for i in range(k):
if i % 2 == 0:
... |
88_B. Keyboard | Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make ... | ```python
import math
def shift_key_test(arr, dictionary, distance, row, column):
arr_dict = {}
if dictionary.get("S") is not None:
for a, b in dictionary.get("S"):
upper_limit = b - distance
lower_limit = b + distance
if upper_limit < 0:
upper_limit... |
934_E. A Colourful Prospect | Firecrackers scare Nian the monster, but they're wayyyyy too noisy! Maybe fireworks make a nice complement.
Little Tommy is watching a firework show. As circular shapes spread across the sky, a splendid view unfolds on the night of Lunar New Year's eve.
A wonder strikes Tommy. How many regions are formed by the circl... | ```python
from math import sqrt
class vector:
def __init__(self, _x = 0, _y = 0):
self.x = _x
self.y = _y
def len(self):
return sqrt(self.x ** 2 + self.y ** 2)
def len_sq(self):
return self.x ** 2 + self.y ** 2
def __mul__(self, other):
if (type(self) == type(other)):
return self.x * other.x + self.y ... |
988_D. Points and Powers of Two | There are n distinct points on a coordinate line, the coordinate of i-th point equals to x_i. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset co... | ```python
n = int(input())
a = [int(i) for i in input().split()]
d = {}
power = [2**i for i in range(31)]
ans = []
for i in a:
d[i] = 0
for num in d.keys():
for p in power:
if num+p in d:
ans = [num, num+p]
if num+p+p in d:
print(3)
ans.append(nu... |
p02596 AtCoder Beginner Contest 174 - Repsept | Takahashi loves the number 7 and multiples of K.
Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.)
If the sequence contains no multiples of K, print `-1` instead.
Constraints
* 1 \leq K \leq 10^6
* K is an integer.
Input
Input is giv... | ```python
n=int(input())
f=0
for i in range(n):
f=f*10+7
f%=n
if f==0:
print(i+1)
break
else:print(-1)
``` |
p02727 AtCoder Beginner Contest 160 - Red and Green Apples | You are going to eat X red apples and Y green apples.
You have A red apples of deliciousness p_1,p_2, \dots, p_A, B green apples of deliciousness q_1,q_2, \dots, q_B, and C colorless apples of deliciousness r_1,r_2, \dots, r_C.
Before eating a colorless apple, you can paint it red or green, and it will count as a red o... | ```python
X, Y, A, B, C = map(int, input().split())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
r = list(map(int, input().split()))
p.sort()
p.reverse()
q.sort()
q.reverse()
new = p[0:X] + q[0:Y] + r
new.sort()
new.reverse()
print(sum(new[0:X+Y]))
``` |
p02858 DISCO Presents Discovery Channel Code Contest 2020 Qual - DISCOSMOS | In 2937, DISCO creates a new universe called DISCOSMOS to celebrate its 1000-th anniversary.
DISCOSMOS can be described as an H \times W grid. Let (i, j) (1 \leq i \leq H, 1 \leq j \leq W) denote the square at the i-th row from the top and the j-th column from the left.
At time 0, one robot will be placed onto each s... | ```python
def gcd(x,y):
if x<y:
x,y=y,x
if y==0:
return x
else:
return gcd(y,x%y)
H,W,T=map(int,input().split())
mod=10**9+7
h=gcd(H,T)
w=gcd(W,T)
H//=h
W//=w
ans=pow(2,H,mod)+pow(2,W,mod)+pow(2,gcd(H,W),mod)-3
print(pow(ans,h*w,mod))
``` |
p02994 AtCoder Beginner Contest 131 - Bite Eating | You have N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative.
You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.
You planned to make an apple pie using all of the apples, ... | ```python
n,l=map(int,input().split())
if l <= 0:
if -1 * l >= n:
n -= 1
else:
l += 1
n -= 1
print(int(n*(2*l+n-1)/2))
``` |
p03135 AtCoder Beginner Contest 117 - Entrance Examination | In order to pass the entrance examination tomorrow, Taro has to study for T more hours.
Fortunately, he can leap to World B where time passes X times as fast as it does in our world (World A).
While (X \times t) hours pass in World B, t hours pass in World A.
How many hours will pass in World A while Taro studies fo... | ```python
[a,b]=map(int, input().split())
print(a/b)
``` |
p03280 AtCoder Beginner Contest 106 - Garden | There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.)
What is the area of this yard excluding the roads? Find it.
Constraints
* A is an ... | ```python
a, b = map(int, input().split())
print(a*b - b - (a-1))
``` |
p03435 AtCoder Beginner Contest 088 - Takahashi's Information | We have a 3 \times 3 grid. A number c_{i, j} is written in the square (i, j), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.
According to Takahashi, there are six integers a_1, a_2, a_3, b_1, b_2, b_3 whose values are fixed, and the number written in the square (i, j) is... | ```python
c=[list(map(int,input().split()))for _ in range(3)]
a=c[0].copy()
b=[0]*3
for i in range(1,3):b[i]=c[i][0]-a[0]
ans="Yes"
for i in range(3):
for j in range(3):
if a[j]+b[i]!=c[i][j]:ans="No"
print(ans)
``` |
p03594 CODE FESTIVAL 2017 qual A - Four Coloring | We have a grid with H rows and W columns of squares. We will represent the square at the i-th row from the top and j-th column from the left as (i,\ j). Also, we will define the distance between the squares (i_1,\ j_1) and (i_2,\ j_2) as |i_1 - i_2| + |j_1 - j_2|.
Snuke is painting each square in red, yellow, green or... | ```python
H,W,D = map(int,input().split())
d = ['R','Y','G','B']
ans = [[] for i in range(H)]
for i in range(H):
for j in range(W):
x,y = i+j, i-j
k = (x % (2*D)) // D
k += ((y % (2*D)) // D) * 2
ans[i].append(d[k])
for row in ans:
print(''.join(row))
``` |
p03751 square869120Contest #4 - Atcoder Handles | Mr.X, who the handle name is T, looked at the list which written N handle names, S_1, S_2, ..., S_N.
But he couldn't see some parts of the list. Invisible part is denoted `?`.
Please calculate all possible index of the handle name of Mr.X when you sort N+1 handle names (S_1, S_2, ..., S_N and T) in lexicographical ord... | ```python
n=int(input());s=[input()for i in range(n)];b=input();ans=[]
def change(s,az):
ans=""
for i in s:ans+=i if i!="?"else az
return ans
a,z=[b],[b]
for i in s:
a.append(change(i,"a"))
z.append(change(i,"z"))
a.sort();z.sort()
for i in range(n+1):
if a[i]==b:ans.append(i+1);break
for i in range(1,n+2):... |
p03915 CODE FESTIVAL 2016 Final - Zigzag MST | We have a graph with N vertices, numbered 0 through N-1. Edges are yet to be added.
We will process Q queries to add edges. In the i-th (1≦i≦Q) query, three integers A_i, B_i and C_i will be given, and we will add infinitely many edges to the graph as follows:
* The two vertices numbered A_i and B_i will be connected... | ```python
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from operator import itemgetter
N,Q = map(int,readline().split())
m = map(int,read().split())
ABC = list(zip(m,m,m))
INF = 10 ** 18
cyclic_cost = [INF] * N
for a,b,c in ABC:
if cyclic_cos... |
p00017 Caesar Cipher | In cryptography, Caesar cipher is one of the simplest and most widely known encryption method. Caesar cipher is a type of substitution cipher in which each letter in the text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 1, 'a' would be replaced by 'b', 'b' would... | ```python
ca = ord('a')
def convert(s, d):
res = []
for c in s:
if c not in ' .':
c = chr(((ord(c) - ca + d) % 26) + ca)
res.append(c)
return "".join(res)
for line in open(0).readlines():
s = line.strip()
for d in range(26):
s0 = convert(s, d)
if "the" in ... |
p00149 Eye Test | Create a program that inputs the test result data of the visual acuity test and outputs the number of people who apply to each judgment based on the following visual acuity judgment table for each of the left and right eyesight.
Judgment | Sight
--- | ---
A | 1.1 or above
B | 0.6 or more and less than 1.1
C | 0.2 or m... | ```python
import sys
LA = RA = 0
LB = RB = 0
LC = RC = 0
LD = RD = 0
for i in sys.stdin:
l,r = map(float,i.split())
if l >= 1.1:
LA += 1
elif 0.6 <= l <1.1:
LB += 1
elif 0.2 <= l < 0.6:
LC += 1
else:
LD += 1
if r >= 1.1:
RA += 1
elif 0.6 <= r <1.1:
... |
p00301 Symmetric Ternary Number | It is known that each weight of 1 gram, 3 gram, 9 gram, and 27 gram can be weighed from 1 gram to 40 gram in 1 gram increments using a balance. For example, if you put a weight of 3 grams and a weight you want to weigh on one plate of the balance and a weight of 27 grams and 1 gram on the other plate, the weight of the... | ```python
#! /usr/bin/env python
from itertools import product, starmap, dropwhile
from math import log
n = int(input())
m = int(log(n, 3)) + 2
for a in product([-1, 0, 1], repeat=m):
if n == sum(starmap(lambda t, x: 3 ** t * x, zip(reversed(range(m)), a))):
print("".join(map(lambda x: "-0+"[x + 1], dropw... |
p00470 Commute routes | problem
A city in Canada where JOI lives is divided into a grid pattern by w roads that extend straight in the north-south direction and h roads that extend straight in the east-west direction.
The w roads in the north-south direction are numbered 1, 2, ..., w in order from the west. In addition, h roads in the east-... | ```python
for e in iter(input,'0 0'):
w,h=map(int,e.split())
M=[[[1,0]*2 for _ in[0]*h]for _ in[0]*w]
for i in range(1,w):
for j in range(1,h):
a,b,c,d=[*M[i-1][j][:2],*M[i][j-1][2:]]
M[i][j]=[d,a+b,b,c+d]
print((sum(M[w-2][h-1][:2])+sum(M[w-1][h-2][2:]))%10**5)
``` |
p00662 The Great Summer Contest | Currently, people's entertainment is limited to programming contests. The activity of the entertainment club of a junior high school to which she belongs is to plan and run a programming contest. Her job is not to create problems. It's a behind-the-scenes job of soliciting issues from many, organizing referees, and pro... | ```python
# AOJ 1077: The Great Summer Contest
# Python3 2018.7.10 bal4u
while True:
n, k, f = [0]*3, [0]*3, [0]*3
a = list(map(int, input().split()))
if sum(a) == 0: break
for i in range(3): n[i] += a[i]+a[3+i]
ans = 0
for i in range(3):
if n[i] >= 3: f[i] = 1
ans += n[i]//3
n[i] %= 3
k[n[i]] += 1
if k... |
p00936 Squeeze the Cylinders | Example
Input
2
10 10
Output
40.00000000 | ```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... |
p01339 Alien's Counting | Natsuki and her friends were taken to the space by an alien and made friends with a lot of aliens. During the space travel, she discovered that aliens’ hands were often very different from humans’. Generally speaking, in a kind of aliens, there are N fingers and M bend rules on a hand. Each bend rule describes that a f... | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
sys.setrecursionlimit(10**6)
def scc(N, G, RG):
order = []
used = [0]*N
group = [None]*N
def dfs(s):
used[s] = 1
for t in G[s]:
if not used[t]:
dfs(t)
order.append(s)
def r... |
p01677 Broken Audio Signal | Problem Statement
Nathan O. Davis is a student at the department of integrated systems.
Today's agenda in the class is audio signal processing. Nathan was given a lot of homework out. One of the homework was to write a program to process an audio signal. He copied the given audio signal to his USB memory and brought ... | ```python
INF = float('inf')
def judge(src):
x_max = INF
x_min = -INF
for i,(s1,s2) in enumerate(zip(src,src[1:])):
if s1 == s2:
return 'none'
if i%2:
s1,s2 = s2,s1
if s1 != 'x' and s2 != 'x':
if s1 < s2:
return 'none'
... |
p01821 Identity Function | Example
Input
3
Output
1 | ```python
N = int(input())
def gcd(m, n):
while n:
m, n = n, m % n
return m
def lcm(m, n):
return m // gcd(m, n) * n
def carmichael(x):
r = 1
b = 0
while x & 1 == 0:
b += 1
x >>= 1
if b > 1:
r = 2 if b == 2 else 2**(b-2)
y = 3
while y*y <= x:
... |
p01956 Window | In the building of Jewelry Art Gallery (JAG), there is a long corridor in the east-west direction. There is a window on the north side of the corridor, and $N$ windowpanes are attached to this window. The width of each windowpane is $W$, and the height is $H$. The $i$-th windowpane from the west covers the horizontal r... | ```python
n,h,w=map(int,input().split())
x=list(map(int,input().split()))
wide_total=n*w
wide_cover=[False]*wide_total
for i in range(n):
if (i+1)%2==1:
for j in range(i*w+x[i],i*w+x[i]+w):
wide_cover[j]=True
else:
for j in range(i*w-x[i],i*w-x[i]+w):
wide_cover[j]=True
... |
p02243 Single Source Shortest Path II | For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$.
Constraints
* $1 \leq n \leq 10,000$
* $0 \leq c_i \leq 100,000$
* $|E| < 500,000$
* All vertices are reachable from vertex $0... | ```python
import heapq
n = int(input())
C = [[] for _ in range(n)]
for _ in range(n):
tmp = list(map(int,input().split()))
for i in range(1,tmp[1]+1):
C[tmp[0]].append(tuple(tmp[2*i:2*i+2]))
q = []
def heap_dijkstra(start = 0):
visited = [False]*n
INF = 10000000000
d = [INF]*n
d[star... |
p02389 Rectangle | Write a program which calculates the area and perimeter of a given rectangle.
Constraints
* 1 ≤ a, b ≤ 100
Input
The length a and breadth b of the rectangle are given in a line separated by a single space.
Output
Print the area and perimeter of the rectangle in a line. The two integers should be separated by a si... | ```python
a, b = input().split()
print(int(a)*int(b),int(a)*2+int(b)*2)
``` |
1016_D. Vasya And The Matrix | Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!
Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1, a2, ..., an denote... | ```python
def sum(x):
ans = 0
for i in x:
ans ^= i
return ans
i = lambda: [*map(int, input().split())]
n, m = i()
a = i()
b = i()
if sum(a) != sum(b):
print("NO")
quit()
print("YES")
one = sum(a[1:]) ^ b[0]
print(one, end = " ")
for i in b[1:]:
print(i, end = " ")
print()
st = ""
for i ... |
1084_D. The Fair Nut and the Best Path | The Fair Nut is going to travel to the Tree Country, in which there are n cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city u and go by a simple path to city v. He hasn't determined the pat... | ```python
from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
from collections import deque
n=int(input())
l=list(map(int,input().split()))
visited=set()
graph={i:set() for i in range(1,n+1)}
d={}
papa=[0 for i in range(n+1)]
level=[[] for i in range(n+1)]
z=[[0] for i... |
1104_A. Splitting into digits | Vasya has his favourite number n. He wants to split it to some non-zero digits. It means, that he wants to choose some digits d_1, d_2, …, d_k, such that 1 ≤ d_i ≤ 9 for all i and d_1 + d_2 + … + d_k = n.
Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different d... | ```python
n = int(input())
f = 0
for i in range(9,0,-1):
if n%i==0:
f = 1
break
if f == 0:
print(1)
print(n)
else:
print(n//i)
print(*(n//i*str(i).split()))
``` |
1131_F. Asya And Kittens | Asya loves animals very much. Recently, she purchased n kittens, enumerated them from 1 and n and then put them into the cage. The cage consists of one row of n cells, enumerated with integers from 1 to n from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were n - 1 ... | ```python
class UnionFind:
def __init__(self, n):
self.parent = [i for i in range(n + 1)]
self.rank = [0 for _ in range(n + 1)]
self.size = [1] * (n + 1)
self.group = [[i] for i in range(n + 1)]
def find(self, x):
# If x is root
if self.parent[x] == x:
... |
1152_B. Neko Performs Cat Furrier Transform | Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.
Assume that we have a cat with a number x. A perfect longcat is a cat with a number equal 2^m - 1 for some non-ne... | ```python
from sys import stdin,stdout
from collections import Counter
def ai(): return list(map(int, stdin.readline().split()))
def ei(): return map(int, stdin.readline().split())
def ip(): return int(stdin.readline().strip())
def op(ans): return stdout.write(str(ans) + '\n')
import math
n = ip()
ans = 0
li = []
for... |
1191_D. Tokitsukaze, CSL and Stone Game | Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if... | ```python
import sys
n = int(input())
a = sorted([int(i) for i in input().split()])
t = 0
for i in range(1,n):
t += a[i]==a[i-1]
if t >= 2:
print("cslnb")
sys.exit(0)
if t:
for i in range(n):
if a[i]==a[i+1]:
if a[i] and a[i]!=a[i-1]+1:
a[i] -= 1
break
else:
print("cslnb")
sys.exit(0)
print(... |
1230_B. Ania and Minimizing | Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first... | ```python
n, k = [int(x) for x in input().strip().split()]
S = input().strip()
if n == 1 and k == 1:
res = '0'
elif k == 0:
res = S
else:
S = [c for c in S]
if S[0] != '1':
S[0] = '1'
k -= 1
i = 1
while k > 0:
if i >= n:
break
if S[i] == '0':
... |
1251_E2. Voting (Hard Version) | The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins.... | ```python
from sys import stdin, stdout
import heapq
class MyHeap(object):
def __init__(self, initial=None, key=lambda x:x):
self.key = key
if initial:
self._data = [(key(item), item) for item in initial]
heapq.heapify(self._data)
else:
self._data = []
def p... |
1271_D. Portals | You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, y... | ```python
import sys
input = sys.stdin.buffer.readline
N, M, K = map(int, input().split())
A = [0] * N
B = [0] * N
C_raw = [0] * N
for i in range(N):
A[i], B[i], C_raw[i] = map(int, input().split())
adj = [[] for _ in range(N+1)]
for _ in range(M):
u, v = map(int, input().split())
adj[v].append(u)
C = [[... |
1294_E. Obtain a Permutation | You are given a rectangular matrix of size n × m consisting of integers from 1 to 2 ⋅ 10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n ⋅ m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift belo... | ```python
from collections import Counter
from sys import stdin
def input():
return(next(stdin))
def main():
n, m = map(int, input().split())
aaa = []
for _ in range(n):
aaa.append([int(a) for a in input().split()])
aaar = list(zip(*aaa))
t = m * n
cost = 0
for i,aa in enumera... |
1337_A. Ichihime and Triangle | Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh... | ```python
"""
Author : thekushalghosh
Team : CodeDiggers
"""
import sys,math,cmath,time
start_time = time.time()
################# ---- USER DEFINED INPUT FUNCTIONS ---- #################
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
... |
1359_E. Modular Stability | We define x mod y as the remainder of division of x by y (\% operator in C++ or Java, mod operator in Pascal).
Let's call an array of positive integers [a_1, a_2, ..., a_k] stable if for every permutation p of integers from 1 to k, and for every non-negative integer x, the following condition is met:
(((x mod a_1) m... | ```python
import sys
import string
input = sys.stdin.readline
import math
#import numpy
#letters = list(string.ascii_lowercase)
from decimal import Decimal
n = list(map(int, input().split()))
n,k = n[0], n[1]
m = 998244353
fact = []
fac = 1
for i in range(1, n+2):
fac *= i
fac = fac % m
fact.append(fac)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.