name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
p02407 Reversing Numbers | Write a program which reads a sequence and prints it in the reverse order.
Note
解説
Constraints
* n ≤ 100
* 0 ≤ ai < 1000
Input
The input is given in the following format:
n
a1 a2 . . . an
n is the size of the sequence and ai is the ith element of the sequence.
Output
Print the reversed sequence in a line. P... | ```python
input()
nums=input().split()
nums.reverse()
print(' '.join(nums))
``` |
1005_B. Delete from the Left | You are given two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty.
For example:
* by applying a move to the string "where", the result is the s... | ```python
a = str(input())
b = str(input())
a = a[::-1]
b = b[::-1]
na = len(a)
nb = len(b)
d = abs(na-nb)
l = min(na,nb)
k = 0
for i in range(0,l):
if a[i] != b[i]:
k = (l - i)*2
break
print(d+k)
``` |
1047_D. Little C Loves 3 II | Little C loves number «3» very much. He loves all things about it.
Now he is playing a game on a chessboard of size n × m. The cell in the x-th row and in the y-th column is called (x,y). Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between ... | ```python
n, m = map(int, input().split())
if n > m:
n, m = m, n
if n == 1:
ans = (m//6)*6+2*max(m%6-3, 0)
print(ans)
elif n == 2:
if m == 2:
print(0)
elif m == 3:
print(4)
elif m == 7:
print(12)
else:
print(n*m)
else:
ans = ((n*m)//2)*2
print(ans)... |
1093_B. Letters Rearranging | You are given a string s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is... | ```python
def good_string(string):
if string[::-1] != string:
return string
else:
string = string[-1] + string[:-1]
try:
return good_string(string)
except:
return -1
if __name__ == "__main__":
queries = int(input())
for _ in range(queries):
string = input()
print(good_string(string))
``` |
1113_B. Sasha and Magnetic Machines | One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by n machines, and the power of the i-th machine is a_i.
This year 2D decided to cultivate a new culture, but what exactly he d... | ```python
"""""""""""""""""""""""""""""""""""""""""""""
| author: mr.math - Hakimov Rahimjon |
| e-mail: mr.math0777@gmail.com |
"""""""""""""""""""""""""""""""""""""""""""""
#inp = open("spaceship.in", "r"); input = inp.readline; out = open("spaceship.out", "w"); print = out.write
TN = 1
# =======... |
1141_E. Superhero Battle | A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly n minutes. After a round ends, the next round starts immediately. This is repeated over and over again.
Each round has the same scenario. It is described by a sequence of n numbers: d_1, d_2, ..., d_n (-10^6 ≤ d_i ≤ 10^6). Th... | ```python
INF = 10 ** 13
h, n = map(int, input().split())
a = list(map(int, input().split()))
b = a[:]
for i in range(1, n):
b[i] += b[i - 1]
low = min(b)
tot = b[-1]
if h + low <= 0:
lo = 0
else:
lo, hi = 0, INF
while lo < hi:
mid = (lo + hi) // 2
cur = h + mid * tot + low
if ... |
1182_D. Complete Mirror | You have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below.
* For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means... | ```python
from collections import deque
n = int(input())
e = [[] for i in range(n+1)]
for i in range(n - 1):
u, v = map(int, input().split())
e[u].append(v)
e[v].append(u)
dep = [-1] * (n + 1)
dep[1] = 0
q = deque([1])
cur = 1
while q:
cur = q.popleft()
for to in e[cur]:
if dep[to] == -1:
dep[to] = dep[cu... |
1260_E. Tournament | You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j.
The tournament will be organized as follows: n boxers will be d... | ```python
import sys
from array import array # noqa: F401
import typing as Tp # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def main():
from itertools import accumulate
n = int(input())
log = len(bin(n)) - 3
cnt = list(accumulate([0] + [n >> i for i in range(1, l... |
1282_E. The Cake Is a Lie | We are committed to the well being of all participants. Therefore, instead of the problem, we suggest you enjoy a piece of cake.
Uh oh. Somebody cut the cake. We told them to wait for you, but they did it anyway. There is still some left, though, if you hurry back. Of course, before you taste the cake, you thought abo... | ```python
def get_edge(vertex1, vertex2):
return (vertex1, vertex2) if vertex1 < vertex2 else (vertex2, vertex1)
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
if __name__ == '__main__':
T = int(input())
for t in range(T):
n = int(input())
pieces = []
... |
1326_E. Bombs | You are given a permutation, p_1, p_2, …, p_n.
Imagine that some positions of the permutation contain bombs, such that there exists at least one position without a bomb.
For some fixed configuration of bombs, consider the following process. Initially, there is an empty set, A.
For each i from 1 to n:
* Add p_i to... | ```python
import sys
input = sys.stdin.readline
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
seg_el=1<<(N.bit_length()) # Segment treeの台の要素数
SEG=[0]*(2*seg_el) # 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化
LAZY=[0]*(2*seg_el) # 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化
def i... |
1345_E. Quantifier Question | Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal (∀) and existential (∃). You can read more about them here.
The universa... | ```python
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input().strip()
return(list(s[:len(s)]))
def invr():
return(map(int,input().split()))
def from_fi... |
1367_D. Task On The Board | Polycarp wrote on the board a string s containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.
After that, he erased some letters from the string s, and he rewrote the remaining letters in any order. As a result, he got some new string t. You have to find it with some ad... | ```python
t=int(input())
for i in range(t):
s=input()
b=[]
d=dict()
for j in s:
if j in d.keys():
d[j]+=1
else:
b.append(j)
d[j]=1
b.sort(reverse=True)
n=int(input())
a=list(map(int,input().split()))
c=["a"]*(n)
m=1
f=dict()
... |
1388_D. Captain Flint and Treasure | Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like t... | ```python
from sys import stdin
from collections import deque
n = int(stdin.readline())
a = list(map(int,stdin.readline().split()))
p = list(map(int,stdin.readline().split()))
chnum = [0] * n
for i in range(n):
if p[i]-1 >= 0:
chnum[p[i]-1] += 1
q = deque([])
for i in range(n):
if chnum[i] == 0:
... |
1409_B. Minimum Product | You are given four integers a, b, x and y. Initially, a ≥ x and b ≥ y. You can do the following operation no more than n times:
* Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y.
Your task is to fi... | ```python
for _ in range(int(input())):
a,b,x,y,n=map(int,input().split())
if n>=((a-x)+(b-y)):
print(x*y)
else:
if a>=b and n<=(b-y):
print(a*(b-n))
elif b>a and n<=(a-x):
print((a-n)*b)
elif n<=(a-x) and n<=(b-y):
print(min((a-n)*b,a*(b-n)))
else:
if n>(a-x)... |
142_E. Help Greg the Dwarf 2 | Greg the Dwarf has been really busy recently with excavations by the Neverland Mountain. However for the well-known reasons (as you probably remember he is a very unusual dwarf and he cannot stand sunlight) Greg can only excavate at night. And in the morning he should be in his crypt before the first sun ray strikes. T... | ```python
import math
mas = list(map(int, input().split()))
r = mas[0]
h = mas[1]
l = (r ** 2 + h ** 2) ** 0.5#2 * math.pi * r
mas = list(map(float, input().split()))
x1 = mas[0]
y1 = mas[1]
z1 = mas[2]
mas = list(map(float, input().split()))
x2 = mas[0]
y2 = mas[1]
z2 = mas[2]
s = 0
if ((z1 == 0) and (z2 == 0)):
s... |
1453_B. Suffix Operations | Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. I... | ```python
T = int(input())
for _ in range(T):
N = int(input())
A = list(map(int,input().split()))
d = sum(abs(a-b) for a,b in zip(A,A[1:]))
ans = d
for a,b,c in zip(A,A[1:],A[2:]):
p = abs(a-b) + abs(b-c)
q = abs(a-c)
ans = min(ans, d - (p-q))
ans = min(ans, d - abs(A[0] ... |
1503_D. Flip the Cards | There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i... | ```python
import sys
input = sys.stdin.readline
n = int(input())
front = [-1] * n
back = [-1] * n
rev = [-1] * (2 * n)
used = [False] * n
opp = [-1] * (2 * n)
for c in range(n):
a, b = map(lambda x: int(x) - 1, input().split())
front[c] = a
back[c] = b
rev[a] = c
rev[b] = c
opp[a] = b
opp... |
1527_B2. Palindrome Game (hard version) | The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is n... | ```python
# from __future__ import print_function,division
# range = xrange
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(10**9)
from sys import stdin, stdout
from collections import defaultdict, Counter
M = 10**9+7
def main():
for _ in range(int(input())):
n = int(input())
s = inpu... |
159_A. Friends or Not | Polycarpus has a hobby — he develops an unusual social network. His work is almost completed, and there is only one more module to implement — the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that ... | ```python
import re
from collections import Counter
class Task:
data = []
delta = 0
friends = set()
def getData(self):
n, self.delta = [int(x) for x in input().split(" ")]
for i in range(0, n):
self.data += [input()]
def solve(self):
messages = dict()
... |
178_D2. Magic Squares | The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.
The magic square is a matrix of size n × n. The elements of this matrix are integers.... | ```python
import sys, random
def f(b):
global a
a = [[0] * n for o in range(n)]
for i in range(n):
for j in range(n):
a[i][j] = b[i * n + j]
rez = 0
for i in range(n):
ns = 0
for j in range(n):
ns += a[i][j]
rez += abs(su - ns)
for j in ... |
200_D. Programming Language | Recently, Valery have come across an entirely new programming language. Most of all the language attracted him with template functions and procedures. Let us remind you that templates are tools of a language, designed to encode generic algorithms, without reference to some parameters (e.g., data types, buffer sizes, de... | ```python
def main():
from collections import defaultdict
import sys
strings = sys.stdin.read().split('\n')
strings.reverse()
f = defaultdict(lambda: defaultdict(int))
n = int(strings.pop())
for i in range(n):
s = strings.pop().replace('(', ' ').replace(')', ' ').repla... |
225_C. Barcode | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.
A picture is a barcode if the following conditions are fulfilled:
* All pixels in each column are of the same color.
* The width of each monochrome ver... | ```python
def main():
n, m, x, y = map(int, input().split())
col = [0] * m
for i in range(n):
row = input()
for j in range(m):
if row[j] == '.':
col[j] += 1
acc = [0]
for j in range(m):
acc.append(acc[-1] + col[j])
dp = [[0]*(m+1), [0]*(m+1)... |
24_A. Ring road | Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two ot... | ```python
n = int(input())
g=[]
d=[]
cost=[]
for i in range(n+1):
g.append([])
d.append([])
for j in range(n+1):
g[i].append(0)
d[i].append(0)
x,y=[],[]
for i in range(n):
a,b,c = tuple([int(x) for x in input().split()])
g[a][b]=c
g[b][a]=c
d[a][b]=c
d[b][a]=-c
ans = 0
tot=0
stack=[1]
visited=[1]
while ... |
274_B. Zero Tree | A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.
A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.
You're given a tr... | ```python
n = int(input())
r = [[] for i in range(n + 1)]
r[1] = [0]
for i in range(n - 1):
a, b = map(int, input().split())
r[a].append(b)
r[b].append(a)
t = list(map(int, input().split()))
u, v = [0] * (n + 1), [0] * (n + 1)
for i, j in enumerate(t, 1):
if j < 0: u[i] = - j
else: v[i] = j
# print(... |
320_B. Ping-Pong (Easy Version) | In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so ... | ```python
def main():
intervals = []
visited = []
for _ in range(int(input())):
read_input(intervals, visited)
def read_input(intervals: list, visited: list) -> None:
command, x, y = [int(x) for x in input().split(" ")]
if (command == 1):
intervals.append((x, y))
visited.a... |
368_D. Sereja ans Anagrams | Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained... | ```python
from sys import stdin, stdout
from math import log, sqrt
lines = stdin.readlines()
n = int(lines[0].split()[0])
m = int(lines[0].split()[1])
p = int(lines[0].split()[2])
a = [int(x) for x in lines[1].split()]
b = [int(x) for x in lines[2].split()]
hash_map = {}
def hash_elem(elem):
if hash_map.get(el... |
412_D. Giving Awards | The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.
Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one ... | ```python
n,m = map(int,input().split())
g = [set() for i in range(n)]
for i in range(m):
a,b = map(int,input().split())
g[a-1].add(b-1)
c = [0]*n
for i in range(n):
c[i]=i
for i in range(n):
j=i
while j>0 and c[j] in g[c[j-1]]:
c[j],c[j-1]=c[j-1],c[j]
j-=1
for i in c:
print(i+1,... |
43_A. Football | One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve... | ```python
n=int(input())
a,b=input(),""
x,y=1,0
for i in range(n-1):
s=input()
if a==s:
x+=1
else:
b=s
y+=1
print([b,a][x>y])
``` |
461_C. Appleman and a Sheet of Paper | Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types:
1. Fold the sheet of paper at position pi. After this query the leftmost... | ```python
from itertools import starmap
def main():
n, q = map(int, input().split())
a = list(range(n + 1))
flipped = False
start = 0
end = n
for _ in range(q):
cmd, *args = map(int, input().split())
if cmd == 1:
p = args[0]
if p > end-start-p:
... |
485_B. Valuable Resources | Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems.
Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes.... | ```python
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
mx = -10 ** 10
mix = 10 ** 10
my = mx
miy = mix
for _ in range(int(input())):
a, b = map(int, input().split())... |
509_B. Painting Pebbles | There are n piles of pebbles on the table, the i-th pile contains ai pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.
... | ```python
import sys,math,bisect
from random import randint
inf = float('inf')
mod = 998244353
"========================================"
def lcm(a,b):
return int((a/math.gcd(a,b))*b)
def gcd(a,b):
return int(math.gcd(a,b))
def tobinary(n):
return bin(n)[2:]
def binarySearch(a,x):
i = bisect.bisect_left... |
558_C. Amr and Chemistry | Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.
Amr has n different types of chemicals. Each chemical i has an initial volume of ai liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his t... | ```python
from collections import Counter
def main():
input()
aa = list(map(int, input().split()))
le, l = max(aa).bit_length(), []
for i, a in enumerate(aa):
j = le - a.bit_length()
aa[i] = a << j
l.append(j)
mi, ma = min(aa), max(aa)
a = mask = (1 << le) - 1
if mi... |
584_A. Olesya and Rodion | Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them.
Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1.
Input
T... | ```python
n, t = input().split(' ')
n = int(n)
t = int(t)
a = 10 ** (n-1)
b = 10 ** (n)
for i in range(a, b):
if i == b-1:
if i%t ==0:
print(i)
break
else:
print(-1)
break
else:
if i%t == 0:
print(i)
break
i... |
606_A. Magic Spheres | Carl is a beginner magician. He has a blue, b violet and c orange magic spheres. In one move he can transform two spheres of the same color into one sphere of any other color. To make a spell that has never been seen before, he needs at least x blue, y violet and z orange spheres. Can he get them (possible, in multiple... | ```python
have = list(map(int, input().split()))
goal = list(map(int, input().split()))
deficit = 0
makeable = 0
for i in range(3):
if have[i] < goal[i]:
deficit += goal[i] - have[i]
else:
makeable += (have[i] - goal[i]) // 2
print('Yes' if makeable >= deficit else 'No')
``` |
628_A. Tennis Tournament | A tennis tournament with n participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out.
The tournament takes place in the following way (below, m is the number of the participants of the current round):
* let k be the maximal power of the number 2 such ... | ```python
n, b, p = map(int, input().split())
ansb = 0
anst = n*p
while n > 1:
x = n//2
y = n % 2
n -= x
ansb += b*x*2 + x
print(ansb, anst)
``` |
652_B. z-sort | A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:
1. ai ≥ ai - 1 for all even i,
2. ai ≤ ai - 1 for all odd i > 1.
For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.
Can you make the... | ```python
n = int(input())
a = [int(x) for x in input().split(" ")]
a.sort()
for i in range(n):
if i%2 == 0:
firval = a[i]
secval = a[i-1]
if i == 0:
continue
elif firval > secval:
a[i],a[i-1] = a[i-1],a[i]
elif secval >= firval:
continue
... |
6_E. Exposition | There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were pub... | ```python
from collections import deque
def mini_in_window(A, n, k):
d = deque()
res = []
for i in range(n):
if i >= k and d[0] == i - k:
d.popleft()
while len(d) and A[d[-1]] >= A[i]:
d.pop()
d.append(i)
if i >= k - 1:
res.append(d[0])
... |
722_B. Verse Pattern | You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.
We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels:... | ```python
n = int(input())
p = input().split()
r = 'YES'
for i in range(n):
s = input()
if(r!='NO' and s.count('a')+s.count('e')+s.count('i')+s.count('o')+s.count('u')+s.count('y')!=int(p[i])):
r = 'NO'
print(r)
``` |
743_E. Vladik and cards | Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions:
* the number of occ... | ```python
import copy
def solve():
n = int(input())
a = [int(c)-1 for c in input().split(' ')]
nextcard = [[-1 for i in range(8)] for j in range(n)]
for i in range(n-2, -1, -1):
nextcard[i] = copy.copy(nextcard[i+1])
nextcard[i][a[i+1]] = i+1
jump = [[-1 for i in range(n+1)] for j... |
767_B. The Queue | Finally! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow.
He know... | ```python
##n = int(input())
##a = list(map(int, input().split()))
##print(' '.join(map(str, res)))
[ts , tf, t] = list(map(int, input().split()))
n = int(input())
if n == 0:
print(ts)
exit(0)
a = list(map(int, input().split()))
if a[0] > ts:
print(ts)
exit(0)
min_wait = 1e18
tbest = a[0]-1
tnow = t... |
791_A. Bear and Big Brother | Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | ```python
def banyak_tahun(a,b, count):
c = a*3
d = b*2
if c <= d:
banyak_tahun(c,d, count+1)
else:
print(count)
a, b = list(map(int, input().split()))
banyak_tahun(a,b,1)
``` |
811_C. Vladik and Memorable Trip | Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is know... | ```python
"""
from
http://codeforces.com/contest/811/problem/C
"""
length = int(input())
array = [0] + [int(x) for x in input().split()]
dp = [0]*(length+1)
end = [0]*5001
start = [5001]*5001
vis = [0]*5001
for i in range(1,length+1):
start[array[i]] = min(start[array[i]],i)
end[array[i]] = max(end[array[i]],i... |
837_E. Vasya's Function | Vasya is studying number theory. He has denoted a function f(a, b) such that:
* f(a, 0) = 0;
* f(a, b) = 1 + f(a, b - gcd(a, b)), where gcd(a, b) is the greatest common divisor of a and b.
Vasya has two numbers x and y, and he wants to calculate f(x, y). He tried to do it by himself, but found out that calcul... | ```python
def bgcd(a,b):
d=0
while a%2==0 and b%2==0:
a=a//2
b=b//2
d+=1
while a!=b:
if a%2==0:
a=a//2
elif b%2==0:
b=b//2
else:
if a>b:
a=(a-b)//2
else:
b=(b-a)//2
g=a
ret... |
858_A. k-rounding | For a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n.
For example, 4-rounding of 375 is 375·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program... | ```python
def nok(a, b):
c = a*b
while (a!=0) and (b!=0):
if a>b: a%=b;
else: b%=a;
return c//(a+b);
nk = input().split()
n, k = int(nk[0]), int(nk[1])
print (nok(10**k, n))
``` |
883_G. Orientation of Edges | Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices.
Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans:
1. to orient each undirected edge in one of two possible directions to maximize... | ```python
from collections import defaultdict
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
... |
907_B. Tic-Tac-Toe | Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.
The game is played on the following field.
<image>
Players are making moves by turns. At first move a player can put his chip in any cell of any sm... | ```python
import sys
#f = open('input', 'r')
f = sys.stdin
m = []
for t in range(3):
ml = [[] for _ in range(3)]
for _ in range(3):
map_line = f.readline().split()
for i, x in enumerate(map_line):
ml[i].append(list(x))
m.append(ml)
if t < 2:
f.readline()
x,y = map(int, f.readline().split())
... |
926_I. A Vital Problem | Polycarp has a strict daily schedule. He has n alarms set for each day, and the i-th alarm rings each day at the same time during exactly one minute.
Determine the longest time segment when Polycarp can sleep, i. e. no alarm rings in that period. It is possible that Polycarp begins to sleep in one day, and wakes up in... | ```python
n = int(input())
a = []
for i in range(n):
str = input()
h = int(str[0:2]) * 60
m = int(str[3:5])
a.append(h + m)
a.sort()
mx = 0
for i in range(n - 1):
if mx < ((-a[i] + a[i + 1]) - 1):
mx = ((-a[i] + a[i + 1]) - 1)
if mx < (1440 + a[0] - a[n - 1] - 1):
mx = 1440 + a[0] - ... |
957_A. Tritonic Iridescence | Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas.
Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into n consecutive segments, each segment needs to be painted in one of the colo... | ```python
def complete_canvas(s):
double = False
res = ""
for i,c in enumerate(s):
if i>0 and i<len(s)-1 and c=='?' and s[i-1] in colors and s[i+1] in colors:
#and s[i-1]!=s[i+1]
col = list(colors)
col.remove(s[i-1])
if s[i-1]!=s[i+1]:
... |
982_A. Row | You're given a row with n chairs. We call a seating of people "maximal" if the two following conditions hold:
1. There are no neighbors adjacent to anyone seated.
2. It's impossible to seat one more person without violating the first rule.
The seating is given as a string consisting of zeros and ones (0 means... | ```python
n = int(input())
l = '0' + input() +'0'
o = 0
z = 0
flag = True
for i in l:
if i == "0" and z < 2:
z += 1
o = 0
elif i == "1" and o != 1:
o = 1
z = 0
else:
flag = False
break
if flag:
print("Yes")
else:
print("No")
``` |
p02558 AtCoder Library Practice Contest - Disjoint Set Union | You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.
* `0 u v`: Add an edge (u, v).
* `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise.
Constraints
* 1 \leq N \leq 200,000
* 1 \leq Q \leq 200,000
* 0 \leq u_i, v_i \lt N
Input
Input is ... | ```python
import sys
input = sys.stdin.readline
class DSU:
def __init__(self, n):
self._n = n
self.parent_or_size = [-1] * n
def merge(self, a, b):
x, y = self.leader(a), self.leader(b)
if x == y:
return x
if -self.parent_or_size[x] < -self.parent_or_size[y]... |
p02689 AtCoder Beginner Contest 166 - Peaks | There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i. There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j.
Obs. i is said to be good when its elevation is higher than those of all observatories that can be r... | ```python
n,m=map(int,input().split())
h=list(map(int,input().split()))
ans=[1]*n
for i in range(m):
a,b=map(int,input().split())
if h[a-1]<=h[b-1]:
ans[a-1]=0
if h[a-1]>=h[b-1]:
ans[b-1]=0
print(ans.count(1))
``` |
p02818 AtCoder Beginner Contest 149 - Greedy Takahashi | Takahashi has A cookies, and Aoki has B cookies. Takahashi will do the following action K times:
* If Takahashi has one or more cookies, eat one of his cookies.
* Otherwise, if Aoki has one or more cookies, eat one of Aoki's cookies.
* If they both have no cookies, do nothing.
In the end, how many cookies will Taka... | ```python
A, B, K = map(int, input().split())
print(max(0, A - K), max(0, min(A + B -K, B)))
``` |
p02954 AtCoder Beginner Contest 136 - Gathering Children | Given is a string S consisting of `L` and `R`.
Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left.
The character written on the leftmost square is always `R`, and the character written on the rightmost square... | ```python
S = input()
N = len(S)
child = [1] * N
for i in range(N - 2):
if 'R' == S[i] and 'R' == S[i + 1]:
child[i + 2] += child[i]
child[i] = 0
if 'L' == S[N - i - 1] and 'L' == S[N -i - 2]:
child[N - i - 3] += child[N - i - 1]
child[N - i - 1] = 0
print(*child)
``` |
p03090 AtCoder Grand Contest 032 - Balanced Neighbors | You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved t... | ```python
N = int(input())
M = N*(N-1)//2-N//2
print(M)
if N%2 ==0:
rem = N+1
else:
rem = N
#print(rem)
for i in range(N):
i +=1 #1index
for j in range(i,N):
j +=1 #1index
temp = [i,j]
if i+j != rem:
print(*temp)
``` |
p03386 AtCoder Beginner Contest 093 - Small and Large Integers | Print all the integers that satisfies the following in ascending order:
* Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.
Constraints
* 1 \leq A \leq B \leq 10^9
* 1 \leq K \leq 100
* All values in input are integers.
Input
Input is give... | ```python
A,B,K = map(int, input().split())
X = range(A,B+1)
for _ in sorted(set(X[:K]) | set(X[-K:])):
print(_)
``` |
p03552 AtCoder Regular Contest 085 - ABS | We have a deck consisting of N cards. Each card has an integer written on it. The integer on the i-th card from the top is a_i.
Two people X and Y will play a game using this deck. Initially, X has a card with Z written on it in his hand, and Y has a card with W written on it in his hand. Then, starting from X, they w... | ```python
import sys
n,z,w=map(int,input().split())
a=list(map(int,input().split()))
if n==1: print(abs(a[0]-w));sys.exit()
x,y=[-1]*n,[-1]*n
x[n-1]=abs(a[n-1]-w)
y[n-2]=abs(a[n-1]-a[n-2])
for i in range(n-2,-1,-1):
x[i]=abs(a[i]-a[n-1])
for j in range(i+1,n-1):
x[i]=min(x[i],y[j])
y[i]=abs(a[n-1]... |
p03707 AtCoder Grand Contest 015 - Nuske vs Phantom Thnook | Nuske has a grid with N rows and M columns of squares. The rows are numbered 1 through N from top to bottom, and the columns are numbered 1 through M from left to right. Each square in the grid is painted in either blue or white. If S_{i,j} is 1, the square at the i-th row and j-th column is blue; if S_{i,j} is 0, the ... | ```python
def main():
import sys
input = sys.stdin.readline
H, W, Q = map(int, input().split())
S = [list(map(lambda x: x=="1", input())) for _ in range(H)]
#XYXY = zip(*[iter(map(int, sys.stdin.read().split()))]*4)
M, L, R, U, D = [], [], [], [], []
for x, s in enumerate(S):
M_, L_... |
p03861 AtCoder Beginner Contest 048 - Between a and b ... | You are given nonnegative integers a and b (a ≤ b), and a positive integer x. Among the integers between a and b, inclusive, how many are divisible by x?
Constraints
* 0 ≤ a ≤ b ≤ 10^{18}
* 1 ≤ x ≤ 10^{18}
Input
The input is given from Standard Input in the following format:
a b x
Output
Print the number of th... | ```python
a, b, x = map(int, input().split())
c = b//x - (a-1)//x
print(c)
``` |
p04027 AtCoder Regular Contest 059 - Children and Candies | 12:17 (UTC): The sample input 1 and 2 were swapped. The error is now fixed. We are very sorry for your inconvenience.
There are N children in AtCoder Kindergarten, conveniently numbered 1 through N. Mr. Evi will distribute C indistinguishable candies to the children.
If child i is given a candies, the child's happine... | ```python
n, c = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
MOD = 10 ** 9 + 7
dp = [[0] * (c + 1) for i in range(n + 1)]
dp[0][0] = 1
ru = [[0] * 410 for i in range(410)]
for cnt in range(410):
for x in range(409):
ru[cnt][x + 1] += ru[cnt][x] + pow(x... |
p00110 Alphametic | The problem of hiding a part of a formula and searching for the hidden number is called verbal arithmetic. This time, I'm dealing with an expression in which some numbers in the expression are hidden by X. Enter the following formula and create a program that outputs the result.
Formula
* A simple one-line addition e... | ```python
import sys,re
for e in sys.stdin:
s=any([len(x)>1 and x[0]=='X' for x in re.split('[+=]',e.strip())])
for i in '0123456789'[s:]:
if eval(e.replace('X',i).replace('=','==')):print(i);break
else:print('NA')
``` |
p00244 Hot Spring Trip | Takeshi, who loves hot springs, is planning a trip to a hot spring resort on his next long vacation. I would like to travel by connecting to a long-distance bus and reach my destination with as little money as possible. Takeshi, who has savings but is unwilling to pay, decided to consult with his grandfather. The grand... | ```python
MAX_V = 999999999999999999999
while 1:
n,m = list(map(int,input().split()))
if n == 0:break
costs = {x:[] for x in range(1,n+1)}
passed = [[False for x in range(2)] for y in range(n+1)]
result = [MAX_V,MAX_V]
for i in range(m):
a,b,c = list(map(int,input().split()))
cos... |
p00425 Dice | The dice are placed in the orientation shown in the figure below.
<image>
As shown in this figure, the dice used here have 1 on the upper side and 2 on the south side, and 3 on the east side. Since the sum of the facing faces of the dice is always 7, the invisible faces are 5 on the north side, 4 on the west side, a... | ```python
class Dice(object):
"""
6??¢???????????????
?????¢???top, ?????¢???bottom???????????\??????4??¢??????????????? north, south, east, west ??¨?????¶???
"""
def __init__(self, faces):
# faces???????????????????????¨?????????????????????????????????
# ???????????? top, south, ea... |
p00620 Line Puzzle | Let's solve the puzzle by programming.
The numbers n x n are arranged in a grid pattern. Some of the numbers are circled and we will call them the starting point. The rules of the puzzle are as follows:
* Draw one line that goes vertically and horizontally from each starting point (cannot be drawn diagonally).
* Exte... | ```python
while True:
n = int(input())
if n == 0:break
mp = [list(map(int, input().split())) for _ in range(n)]
used = [[False] * n for _ in range(n)]
inits = []
for y in range(n):
for x in range(n):
if mp[y][x] < 0:
inits.append((x, y, mp[y][x]))
used[y][x] = True
vec = ((... |
p00764 Chain-Confined Path | There is a chain consisting of multiple circles on a plane. The first (last) circle of the chain only intersects with the next (previous) circle, and each intermediate circle intersects only with the two neighboring circles.
Your task is to find the shortest path that satisfies the following conditions.
* The path co... | ```python
def solve():
from math import acos
from cmath import phase, rect, pi
from sys import stdin
file_input = stdin
while True:
n = int(file_input.readline())
if n == 0:
break
C = (map(int, file_input.readline().split()) for i in range(n))
... |
p00896 Weaker than Planned | The committee members of the Kitoshima programming contest had decided to use crypto-graphic software for their secret communication. They had asked a company, Kodai Software, to develop cryptographic software that employed a cipher based on highly sophisticated mathematics.
According to reports on IT projects, many p... | ```python
from string import ascii_uppercase
import sys
readline = sys.stdin.readline
write = sys.stdout.write
conv = ascii_uppercase.find
def solve():
N = int(readline())
if N == 0:
return False
W = [tuple(map(conv, readline().strip())) for i in range(N)]
S = []
T = set()
for s in rea... |
p01029 Yu-kun Likes Letters in the English Alphabet | Background
The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves lowercase letters as much as programming. Yu-kun decided to write a scoring program for a new play that uses paper, circles, lines, and lowercase lett... | ```python
v, e = map(int, input().split())
a_lst = input().split()
edges = [[] for _ in range(v)]
for _ in range(e):
s, t = map(int, input().split())
edges[s].append(t)
edges[t].append(s)
for i in range(v):
if "a" <= a_lst[i] <= "z": continue
lst = {i for i in range(26)}
for fr in edges[i]:
... |
p01299 Neko's Treasure | Maki is a house cat. One day she fortunately came at a wonderful-looking dried fish. Since she felt not hungry on that day, she put it up in her bed. However there was a problem; a rat was living in her house, and he was watching for a chance to steal her food. To secure the fish during the time she is asleep, she deci... | ```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
if N == 0:
return False
sx, sy, tx, ty = map(int, readline().split())
C = []
G = [[] for i in range(N+2)]
L = 0
for i in range(N):
xi, y... |
p01628 Amidakuji | Problem Statement
Mr. Takatsuki, who is planning to participate in the Aizu training camp, has a poor house and always tries to save as much paper as possible. She decided to play a ghost leg with other participants to decide the team for the Aizu training camp.
How to make Amidakuji for this training camp is as foll... | ```python
from itertools import permutations
N,M=map(int,input().split())
k=[int(input())-1 for i in range(M)]
g=[i for i in range(N)]
for i in range(N):
for j in k:
if g[i]==j:
g[i]=j+1
elif g[i]==j+1:
g[i]=j
s=10
for K in permutations(k):
G=[i for i in range(N)]
for... |
p01780 Breadth-First Search by Foxpower | Example
Input
4
1 1 2
Output
6 | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in ... |
p02053 Hokkaido University Hard | B: Hokkaido University Hard
Note
Please note that the question settings are the same as question A, except for the constraints.
story
Homura-chan, who passed Hokkaido University and is excited about the beginning of a new life. But in front of her, a huge campus awaits ...
"Eh ... I'm not in time for the next clas... | ```python
#!/usr/bin/python3
# -*- coding: utf-8 -*-
H,W = map(int, input().split())
builds = []
for h in range(H):
l = str(input())
for w in range(W):
if l[w] == "B":
builds.append([h,w])
# [min,max]
lu = [H+W,0]
ld = [H+W,0]
for h,w in builds:
lu = [min(lu[0],h+w),max(lu[1],h+w)]
ld = [min(ld[0]... |
p02349 Range Add Query (RAQ) | Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* get(i): output the value of ai.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 1 ≤ i ≤... | ```python
# -*- coding: utf-8 -*-
"""
Range Add Query (RAQ)
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_E&lang=ja
"""
import sys
def main(args):
def add(b, k, x):
while k <= n:
b[k] += x
k += k & -k
def get(b, k):
s = 0
while k > 0:
... |
1042_C. Array Product | You are given an array a consisting of n integers. You can perform the following operations with it:
1. Choose some positions i and j (1 ≤ i, j ≤ n, i ≠ j), write the value of a_i ⋅ a_j into the j-th cell and remove the number from the i-th cell;
2. Choose some position i and remove the number from the i-th cell... | ```python
n = int(input())
vector = [int(i) for i in input().split()]
usado = []
nusado = []
pos = -1
cn = 0
cz = 0
resp = []
i = 0
while i < n:
v = vector[i]
if v < 0:
cn+=1
if pos == -1 or (vector[pos] < v):
pos = i
nusado.append(i)
elif v == 0:
cz+=1
us... |
1065_B. Vasya and Isolated Vertices | Vasya has got an undirected graph consisting of n vertices and m edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edges (... | ```python
n, m = map(int, input().split())
print(max(n-2*m, 0), end=' ')
for i in range(0, n+1):
if i*(i-1)/2>=m: break
print(n-i)
``` |
1106_F. Lunar New Year and a Recursive Sequence | Lunar New Year is approaching, and Bob received a gift from his friend recently — a recursive sequence! He loves this sequence very much and wants to play with it.
Let f_1, f_2, …, f_i, … be an infinite sequence of positive integers. Bob knows that for i > k, f_i can be obtained by the following recursive equation:
$... | ```python
from math import ceil, sqrt
p = 998244353
def bsgs(g, h):
'''
Solve for x in h = g^x mod p given a prime p.
'''
N = ceil(sqrt(p - 1)) # phi(p) is p-1 if p is prime
# Store hashmap of g^{1...m} (mod p). Baby step.
tbl = {pow(g, i, p): i for i in range(N)}
# Precompute via Ferma... |
1133_F2. Spanning Tree with One Fixed Degree | You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to find any spanning tree of this graph such that the degree of the first vertex (vertex with label 1 on it) is equal to D (or sa... | ```python
import sys
from collections import Counter, defaultdict
def i_ints():
return map(int, sys.stdin.readline().split())
n, m, D = i_ints()
E = defaultdict(set)
for i in range(m):
u, v = i_ints()
E[u].add(v)
E[v].add(u)
def append_edge(u, v):
E[u].discard(v)
E[v].discard(u)
t... |
1154_D. Walking Robot | There is a robot staying at X=0 on the Ox axis. He has to walk to X=n. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.
The i-th segment of the path (from X=i-1 to X=i) can be exposed to sunlight or not. The array s denotes which segments are ex... | ```python
n,b,a=map(int,input().split())
s=list(map(int,input().split()))
maxa=a
cnt=0
for i in range(n):
if(s[i]==0):
if(a>0):
a-=1
cnt+=1
elif(b>0):
b-=1
cnt+=1
else:
if(a<maxa and b>0):
b-=1
a+=1
cnt+=1
elif(a>0):
a-=1
cnt+=1
if(b==0 and a==0):
break
print(cnt)
``` |
1176_B. Merge it! | You are given an array a consisting of n integers a_1, a_2, ... , a_n.
In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4],... | ```python
for _ in range(int(input())):
a=int(input())
b=list(map(int,input().split()))
k1=0
k2=0
k3=0
for i in b:
if i%3==0:
k3+=1
elif i%3==1:
k1+=1
else:
k2+=1
l=min(k1,k2)
m=(k1-l)//3
n=(k2-l)//3
print(k3+l+m+n)
``` |
1195_A. Drinks Choosing | Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?
There are n students living in a building, and for each of them the favorite drink a_i is known. So you know n integer... | ```python
from math import ceil
n, k = map(int, input().split())
bev = [0] * k
for i in range(n):
x = int(input())
bev[x-1] += 1
bad = 0
good = 0
for i in range(k):
bad += bev[i] & 1
good += bev[i] - (bev[i] & 1)
# print(good, bad)
bad = ceil(bad / 2)
print(good + bad)
``` |
1234_C. Pipes | You are given a system of pipes. It consists of two rows, each row consists of n pipes. The top left pipe has the coordinates (1, 1) and the bottom right — (2, n).
There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types:
<image> Types of pipes
... | ```python
input = __import__('sys').stdin.readline
print = __import__('sys').stdout.write
thres = 3
for _ in range(int(input())):
current = False
N = int(input())
tmp = [list(map(int, list(input()[:-1]))), list(map(int, list(input()[:-1])))]
for i in range(N):
if tmp[current][i] < thres:
... |
1253_B. Silly Mistake | The Central Company has an office with a sophisticated security system. There are 10^6 employees, numbered from 1 to 10^6.
The security system logs entrances and departures. The entrance of the i-th employee is denoted by the integer i, while the departure of the i-th employee is denoted by the integer -i.
The compan... | ```python
input()
t={0}
i=s=0
r=[0]
for x in map(int, input().split()):
if(x<0)!=(-abs(x)in t)or x>0 and abs(x)in t:r=-1,;break
if x>0:t|={x,-x}
else:t-={x}
i+=1;s+=x
if s==0:r[0]+=1;r+=i,;t={0};i=0
if s:r=-1,
print(r[0])
print(*r[1:])
``` |
1277_A. Happy Birthday, Polycarp! | Hooray! Polycarp turned n years old! The Technocup Team sincerely congratulates Polycarp!
Polycarp celebrated all of his n birthdays: from the 1-th to the n-th. At the moment, he is wondering: how many times he turned beautiful number of years?
According to Polycarp, a positive integer is beautiful if it consists of ... | ```python
for _ in range(int(input())):
x = input()
now = len(x)
ans = (now-1) * 9
ans += (int(x[0]))
flag = 0
for j in range(1,len(x)):
if(x[j] > x[j-1]):
break
elif(x[j] < x[j-1]):
flag = 1
break
ans -= flag
print(ans)
``` |
1320_B. Navigation System | The map of Bertown can be represented as a set of n intersections, numbered from 1 to n and connected by m one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along... | ```python
n, m = map(int, input().split())
Q = [[]for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
Q[v].append(u)
k = int(input())
p = [int(T) - 1 for T in input().split()]
W = [-1] * n
E = [0] * n
q = [(p[-1], 0)]
for u, d in q:
if W[u] < 0:
W[u] = d
... |
1339_E. Perfect Triples | Consider the infinite sequence s of positive integers, created by repeating the following steps:
1. Find the lexicographically smallest triple of positive integers (a, b, c) such that
* a ⊕ b ⊕ c = 0, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
* a, b, ... | ```python
memo=[(0,0,0)]
def new_find_pair(n):
stack=[]
while n>=len(memo):
N=n.bit_length()-1
if N%2==0:
i=N//2
stack.append((n,1,i))
n-=4**i
else:
i=N//2
if n>>(2*i)&1==0:
#type2
stack.append((... |
1361_A. Johnny and Contribution | Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers ... | ```python
import sys
readline = sys.stdin.buffer.readline
N, M = map(int, readline().split())
Edge = [[] for _ in range(N)]
for _ in range(M):
a, b = map(int, readline().split())
a -= 1
b -= 1
Edge[a].append(b)
Edge[b].append(a)
topic = list(map(int, readline().split()))
maxi = [0]*N
L = list(r... |
1381_B. Unmerge | Let a and b be two arrays of lengths n and m, respectively, with no elements in common. We can define a new array merge(a,b) of length n+m recursively as follows:
* If one of the arrays is empty, the result is the other array. That is, merge(∅,b)=b and merge(a,∅)=a. In particular, merge(∅,∅)=∅.
* If both arrays a... | ```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.readl... |
1401_C. Mere Array | You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0.
In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](... | ```python
for i in range(int(input())):
n=int(input())
a = [int(x ) for x in input().split()]
b= a[::-1]
b.sort()
z=min(a)
p=True
for j in range(n):
if a[j]!=b[j] :
if a[j]%z>0:
p=False
break
if p :
print("YES")
else:print(... |
1424_J. Lonely Numbers | In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b... | ```python
from math import sqrt
from sys import stdin, stdout
from time import time
start = time()
t = int(stdin.readline().strip())
tests = list(map(int, stdin.readline().split()))
def gen_primes(n):
sieve = [True] * (n//2)
for i in range(3,int(n**0.5)+1,2):
if sieve[i//2]:
sieve[i*i//2:... |
1446_A. Knapsack | You have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i.
You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: ⌈ W/2⌉ ≤ C ≤ W.
Output the list... | ```python
import sys
def run(use_file_io):
if use_file_io:
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
try:
solve()
finally:
sys.stdin.close()
sys.stdout.close()
else:
solve()
def getnums():
return map(i... |
1470_A. Strange Birthday Party | Petya organized a strange birthday party. He invited n friends and assigned an integer k_i to the i-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are m unique presents available, the j-th present costs c_j dollars (1 ≤ c_1 ≤ c_2 ≤ … ≤ c_m). It's not allowed to buy a single... | ```python
import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(99999)
t, = map(int, sys.stdin.readline().split())
for _ in range(t):
n, m = map(int, sys.stdi... |
1496_B. Max and Mex | You are given a multiset S initially consisting of n distinct non-negative integers. A multiset is a set, that can contain some elements multiple times.
You will perform the following operation k times:
* Add the element ⌈(a+b)/(2)⌉ (rounded up) into S, where a = \operatorname{mex}(S) and b = max(S). If this numbe... | ```python
import math
import bisect
tests = int(input().strip())
while tests:
tests -= 1
n, k = map(int, input().strip().split())
array = list(set(map(int, input().strip().split())))
n = len(array)
array.sort()
max_member = array[-1]
mex = n if max_member == n - 1 else None
if mex is No... |
1519_E. Off by One | There are n points on an infinite plane. The i-th point has coordinates (x_i, y_i) such that x_i > 0 and y_i > 0. The coordinates are not necessarily integer.
In one move you perform the following operations:
* choose two points a and b (a ≠ b);
* move point a from (x_a, y_a) to either (x_a + 1, y_a) or (x_a, y... | ```python
import sys
from sys import stdin
import math
from collections import deque
n = int(stdin.readline())
dic = {}
lis = []
for i in range(n):
a,b,c,d = map(int,stdin.readline().split())
A,B,C,D = a+b,b,c,d
siA = C * B
boA = D * A
g = math.gcd(siA,boA)
siA //= g
boA //= g
if (siA,... |
174_A. Problem About Equation | A group of n merry programmers celebrate Robert Floyd's birthday. Polucarpus has got an honourable task of pouring Ber-Cola to everybody. Pouring the same amount of Ber-Cola to everybody is really important. In other words, the drink's volume in each of the n mugs must be the same.
Polycarpus has already began the pro... | ```python
a,b=map(int,input().split())
l=list(map(int,input().split()))
if (max(l)*a)-sum(l)>b:
print(-1)
else:
for i in l:
print((sum(l)+b)/a-i)
``` |
194_B. Square | There is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downward... | ```python
i = int(input())
x = list(map(int, input().split(' ')))
for i in x:
print([4*i+1, 2*i+1, 4*i+1, i+1][i%4])
``` |
218_B. Airport | Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:
* it is up to a passenger to choose a plane to fly on;
* if the chosen plane has x (x > 0) empty seats at the given moment, then the ticket for such a plane costs ... | ```python
n,m=list(map(int,input().split()))
L=list(map(int,input().split()))
P=list(map(int,L))
mi=0
ma=0
for i in range(n):
x=max(L)
ma+=x
L[L.index(x)]-=1
#print(P)
for i in range(n):
x=min(P)
if x==0:
P.remove(x)
x=min(P)
mi+=x
P[P.index(x)]-=1
print(ma,mi)
``` |
338_B. Book of Evil | Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to r... | ```python
import heapq
def dfs(graph, start):
n = len(graph)
dist = [-0 for i in range(n + 1)]
visited = [False for i in range(n + 1)]
visited[start] = True
stack = []
dist[start] = 0
heapq.heappush(stack, start)
while stack:
u = heapq.heappop(stack)
for v in graph[... |
384_B. Multitasking | Iahub wants to enhance his multitasking abilities. In order to do this, he wants to sort n arrays simultaneously, each array consisting of m integers.
Iahub can choose a pair of distinct indices i and j (1 ≤ i, j ≤ m, i ≠ j). Then in each array the values at positions i and j are swapped only if the value at position ... | ```python
n,m,k = map(int,input().split())
for i in range(n):
a = [int(x) for x in input().split()]
d = []
for i in range(1,m):
for j in range(i+1,m+1):
if k == 0:
d.append((i,j))
else:
d.append((j,i))
print(len(d))
for i in d:
print(*i)
``` |
405_A. Gravity Flip | Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | ```python
cols = int(input(""))
inputs = input("")
inputList = inputs.split(' ')
inputList.sort(key=int)
for i in inputList:
print(i, end=" ")
``` |
432_B. Football Kit | Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi ≠ yi).
In the tournament, each team plays exactly one home game and exactly one aw... | ```python
n = int(input())
a = [0]*(10**5 + 1)
c = []
for i in range(n):
x,y = map(int, input().split())
c.append([x,y])
a[x]+=1
ans = n - 1
for i in range(n):
d = ans + a[c[i][1]]
print(d,2*(n - 1) - d)
``` |
477_B. Dreamoon and Sets | Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dream... | ```python
a, b = map(int, input().split(' '))
print((6*a-1)*b)
for i in range(a):
print((6*i+1)*b, (6*i+2)*b, (6*i+3)*b, (6*i+5)*b)
# Made By Mostafa_Khaled
``` |
4_C. Registration system | A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | ```python
users = {}
for x in range (0, int(input())):
want = input()
if want in users:
print(want + str(users[want]))
users[want] += 1
else:
print("OK")
users[want] = 1
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.