name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
p01811 ABC Gene | ABC Gene
There is a gene sequence represented by the string `ABC`. You can rewrite this gene sequence by performing the following operations several times.
* Choose one of the letters `A`,` B`, `C`. Let this be x. Replace all x in the gene sequence with `ABC` at the same time.
Given a string S consisting only of `... | ```python
# coding: utf-8
moto=input()
s=moto
gene='ABC'
f=True
log=[]
while len(s)>3 and f:
f=False
if s[:3]=='ABC':
s=s.replace('ABC','A')
log.append('A')
f=True
elif s[len(s)-3:]=='ABC':
s=s.replace('ABC','C')
log.append('C')
f=True
elif 'ABC' in s:
... |
p01946 Slimming Plan | Chokudai loves eating so much. However, his doctor Akensho told him that he was overweight, so he finally decided to lose his weight.
Chokudai made a slimming plan of a $D$-day cycle. It is represented by $D$ integers $w_0, ..., w_{D-1}$. His weight is $S$ on the 0-th day of the plan and he aims to reduce it to $T$ ($... | ```python
S, T, D = map(int, input().split())
S -= T
*W, = map(int, input().split())
F = sum(W)
if F >= 0:
su = S
for i, w in enumerate(W):
su += w
if su <= 0:
print(i+1)
break
else:
print(-1)
exit(0)
su = 0
mi = 0
for d in W:
su += d
mi = min(mi, ... |
p02233 Fibonacci Number | Write a program which prints $n$-th fibonacci number for a given integer $n$. The $n$-th fibonacci number is defined by the following recursive formula:
\begin{equation*} fib(n)= \left \\{ \begin{array}{ll} 1 & (n = 0) \\\ 1 & (n = 1) \\\ fib(n - 1) + fib(n - 2) & \\\ \end{array} \right. \end{equation*}
Constraints
... | ```python
n = int(input())
num = [1,1]
for i in range(2,45):
f = num[i - 1] + num[i - 2]
num.append(f)
print(num[n])
``` |
p02379 Distance | Write a program which calculates the distance between two points P1(x1, y1) and P2(x2, y2).
Input
Four real numbers x1, y1, x2 and y2 are given in a line.
Output
Print the distance in real number. The output should not contain an absolute error greater than 10-4.
Example
Input
0 0 1 1
Output
1.41421356 | ```python
x1,y1,x2,y2=map(float,input().split())
n=((x1-x2)**2+(y1-y2)**2)**(1/2)
print('{:.8f}'.format(n))
``` |
1019_B. The hat | This is an interactive problem.
Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered ... | ```python
# this sequence is a bit scary
# 8
# 1 2 3 2 3 2 1 0
import sys
#sys.stdin=open("data.txt")
#input=sys.stdin.readline
got=[10**18]*100005
def getnum(i):
if got[i]==10**18:
print("? %d"%i)
sys.stdout.flush()
got[i]=int(input())
return got[i]
n=int(input())
if n%4==2:
# ... |
1042_A. Benches | There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available.
Let k be the maximum number of people sitting on one bench after additional m people c... | ```python
import math
n=int(input())
m=int(input())
a=[]
for i in range(n):
a.append(int(input()))
maxa=max(a)+m
mina=max(max(a),math.ceil((sum(a)+m)/n))
print(str(mina)+" "+str(maxa))
``` |
1106_D. Lunar New Year and a Wander | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.
The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever ... | ```python
from heapq import heappush, heappop
n,m = map(int,input().split())
adj = [[] for _ in range(n)]
for _ in range(m):
a,b = map(int,input().split())
a-=1
b-=1
adj[a].append(b)
adj[b].append(a)
st = set()
hp = []
v = [False for _ in range(n)]
heappush(hp,0)
v[0] = True
ans = []
while hp:
... |
1133_E. K Balanced Teams | You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.
You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! ... | ```python
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
n,k= kk()
ls = sorted(ll())
vs,ne = [0]*n,[-1]*n
b = 0
for a in range(n):
while b < n and ls[b] - ls[a] < 6: b+=1
vs[a],ne[a] = b-a, b
curr = [0]*(n+1)
# print(vs)
for _ in range(k):
# print(curr)
prev = curr
curr = [0]*(n+1)
for i in range(n):
c... |
1154_B. Make Them Equal | You are given a sequence a_1, a_2, ..., a_n consisting of n integers.
You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can:
* add D (only once), i. e. perform a_i := a_i + D, or
* subtract D (only once), i. e. perform a_i := a_i - D, or
* leave the value of a_i unchanged.
It is... | ```python
n = int(input())
L = [int(i) for i in input().split()]
F = []
mi = 101
ma = 0
for i in L:
if i not in F:
F.append(i)
if len(F) > 3:
print(-1)
else:
F.sort()
if len(F) == 3:
D = F[1] - F[0]
if F[2] - F[1] == D:
print(D)
else:
print(-1)
... |
1194_F. Crossword Expert | Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming.
Fortunately, Adilbek can spend time witho... | ```python
mod = 10 ** 9 + 7
MAX = 2 * 10 ** 5+2
r = [1] * MAX
factorial = [1] * MAX
rfactorial = [1] * MAX
rp = [1] * MAX
#Permite precalcular factorial hasta "MAX", para evitar tener que calcularlo varias veces
#dentro de la ejecucion del programa.
for i in range(2, MAX):
factorial[i] = i * factorial[i - 1... |
1234_B1. Social Network (easy version) | The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0... | ```python
def line():
return map(int, input().split())
def num():
return int(input())
from collections import OrderedDict as od
n,k = line()
ids = list(line())
screen = od()
for id in ids:
if id not in screen:
if len(screen)==k:
screen.popitem(last=False)
screen[id]=None
print... |
1276_E. Four Stones | There are four stones on an infinite line in integer coordinates a_1, a_2, a_3, a_4. The goal is to have the stones in coordinates b_1, b_2, b_3, b_4. The order of the stones does not matter, that is, a stone from any position a_i can end up in at any position b_j, provided there is a required number of stones in each ... | ```python
def gcd(a, b):
while a and b:
a %= b
if a: b %= a
return a + b
def gcd2(A):
r = A[1] - A[0]
for i in (2, 3):
r = gcd(r, A[i] - A[0])
return r
def Mir(x, c): return c * 2 - x
def Solve(A):
A[0].sort()
A[1].sort()
gcds = [gcd2(A[0]), gcd2(A[1])]
I0,... |
1296_E2. String Coloring (hard version) | This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.
You are given a string s consisting of n lowercase Latin letters.
You have to color all its characters the minimum numb... | ```python
"""
4
9
abacbecfd
8
aaabbcbb
7
abcdedc
5
abcde
"""
"""
# This is brute force for understanding the logic
t=int(input())
for _ in range(t):
n=int(input())
s=input()
col=[1]*n
for i in range(0,len(s)):
c=col[i]
for j in range(i+1,len(s)):
if(ord(s[i])>ord(s[j]... |
1339_C. Powered Addition | You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:
* Select some distinct indices i_{1}, i_{2}, …, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{... | ```python
import math
n = int(input())
for i in range(n):
m = int(input())
nums = [int(i) for i in input().split()]
highest = nums[0]
mostDiff = 0
for j in range(len(nums)):
if highest - nums[j] > mostDiff:
mostDiff = highest - nums[j]
if nums[j] > highest:
hi... |
1360_G. A/B Matrix | You are given four positive integers n, m, a, b (1 ≤ b ≤ n ≤ 50; 1 ≤ a ≤ m ≤ 50). Find any such rectangular matrix of size n × m that satisfies all of the following conditions:
* each row of the matrix contains exactly a ones;
* each column of the matrix contains exactly b ones;
* all other elements are zeros.... | ```python
for q in range(int(input())):
n, m, a, b = map(int, input().split())
if n*a != m*b:
print('NO')
continue
print('YES')
t = '1'*a+'0'*(m-a)
for i in range(n):
print(t)
t = t[m-a:]+t[:m-a]
``` |
1381_A1. Prefix Flip (Easy Version) | This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | ```python
def swap(ind):
global a
for i in range(ind + 1):
a[i] = 1 - a[i]
for i in range(ind // 2 + 1):
a[i], a[ind - i] = a[ind - i], a[i]
for _ in range(int(input())):
n = int(input())
a = list(input())
b = list(input())
a = [int(i) for i in a]
b = [int(i) for i... |
1401_A. Distance and Axis | We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point ... | ```python
for _ in range(int(input())):
n, k = map(int, input().split())
if n<k:print(k-n)
elif n%2 == k%2: print(0)
else: print(1)
``` |
1445_D. Divide and Sum | You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, r... | ```python
def ncr(n, r, p):
# initialize numerator
# and denominator
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
n = int(input())
a = sorted(list(map(int, input().split())))
ans = 0
for i in ... |
146_D. Lucky Number 2 | Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meet... | ```python
from math import *
from fractions import *
from sys import *
def li():
return list(map(int, input().split(" ")))
a = li()
if abs(a[2]-a[3]) > 1:
print(-1)
exit()
if a[2] == a[3]:
ans = "47"*a[2]+"4"
elif a[2] > a[3]:
ans = "47"*a[2]
else:
ans = "74"*a[3]
f = a[0]-ans.count("4")
s = a[1]-ans.count(... |
1519_C. Berland Regional | Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now.... | ```python
for _ in range(int(input())):
n = int(input())
u = list(map(int, input().split()))
s = list(map(int, input().split()))
p = max(u)
l = [[] for i in range(p)]
for i in range(n):
l[u[i]-1].append(s[i])
l.sort(key = len, reverse = True)
for i in range(p):
l[i].sort(... |
1546_C. AquaMoon and Strange Sort | AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaM... | ```python
from math import *
from collections import defaultdict as dt
from sys import stdin
inp = lambda : stdin.readline().strip()
I = lambda : int(inp())
M = lambda : map(int,inp().split())
L = lambda : list(M())
mod = 1000000007
inf = 100000000000000000000
ss = "abcdefghijklmnopqrstuvwxyz"
############## Al... |
193_E. Fibonacci Number | John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when div... | ```python
low_n = 1000
high_m = 15000
limit = int(10 ** 13)
f = int(input())
inputList = []
def customFunction(i):
if i == 0:
return (0, 1)
a, b = customFunction(i >> 1)
a, b = ((2 * a * b - a * a) % low_n, (b * b + a * a) % low_n)
if i & 1:
a, b = (b % low_n, (a + b) % low_n)
ret... |
266_C. Below the Diagonal | You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can a... | ```python
import os
from io import BytesIO, IOBase
import sys
def main():
n = int(input())
row = [0] * n
col = [0] * n
a = [[0 for j in range(n)] for i in range(n)]
for i in range(n - 1):
x, y = map(int, input().split())
row[x - 1] += 1
col[y - 1] += 1
a[x - 1][y - 1... |
28_C. Bath Queue | There are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their ro... | ```python
import sys
MAX_N = 55
line = list(map(int, sys.stdin.readline().split(" ")))
studc = line[0]
roomc = line[1]
arr = list(map(int, sys.stdin.readline().split(" ")))
ncr = [[0 for i in range(MAX_N)] for j in range(MAX_N)]
ncr[0][0] = 1
for i in range(1, MAX_N):
ncr[i][0] = 1;
for j in range(1, MAX_N)... |
315_C. Sereja and Contest | During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the... | ```python
n, k = map(int, input().split())
arr = map(int, input().split())
s, j, all_res = 0, 0, []
for i, q in enumerate(arr, 1):
if s - j * (n - i) * q < k:
all_res.append(str(i))
else:
s += q * j
j += 1
print('\n'.join(all_res))
``` |
404_D. Minesweeper 1D | Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.
For example, the correct field to play looks ... | ```python
Mod=1000000007
s=input()
n=len(s)
a,b,c,d=1,0,0,0
for i in range(0,n):
if s[i]=='*':
t=0,a+b+d,0,0
elif s[i]=='?':
t=a+b+c,a+b+d,0,0
elif s[i]=='0':
t=0,0,a+c,0
elif s[i]=='1':
t=0,0,b,a+c
else:
t=0,0,0,b+d
a,b,c,d=map(lambda a:a%Mod,t)
print((a+... |
454_B. Little Pony and Sort by Shift | One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
a1, a2, ..., an → an, a1, a2, ..., an - 1.
Help Twi... | ```python
def us_num(nums):
where = None
for idx, (a, na) in enumerate(zip(nums[:-1], nums[1:])):
if a > na:
if where is None:
where = idx
else:
return -1
if where is None:
return 0
elif nums[-1] > nums[0]:
return -1
return len(nums) - 1 - where
n = int(input())
nums =... |
476_E. Dreamoon and Strings | Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.
More formally... | ```python
s, p = input(), input()
n, m = len(s) + 1, len(p)
d = [[0] * n for t in range(n)]
for x in range(1, n):
i, j = x, m
while i and j:
j -= s[i - 1] == p[j - 1]
i -= 1
if not j:
for y in range(i + 1): d[x][y + x - i - m] = d[i][y] + 1
for y in range(x): d[x][y] = max(d[x][y... |
4_A. Watermelon | One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | ```python
x=int(input())
y=x-2
if y%2==0 and y!=0:
print("YES")
else :
print("NO")
``` |
550_A. Two Substrings | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
Input
The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.
Output
Print "YES" (without the quot... | ```python
a = input()
b = a
f1=0
f2=0
if(a.find('AB')!=-1):
a = a.replace('AB', 'C', 1)
if(a.find('BA')!=-1):
f1=1
if(b.find('BA')!=-1):
b = b.replace('BA', 'C', 1)
if(b.find('AB')!=-1):
f2=1
if(f1==0 and f2==0):
print("NO")
else:
print("YES")
``` |
577_B. Modulo Sum | You are given a sequence of numbers a1, a2, ..., an, and a number m.
Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.
Input
The first line contains two numbers, n and m (1 ≤ n ≤ 106, 2 ≤ m ≤ 103) — the size of the original sequence and ... | ```python
n,x=map(int,input().split())
a=set()
for i in input().split():
i=int(i)
b=set()
for j in a: b.add((i+j)%x)
a|=b
a.add(i%x)
if 0 in a:
print("YES")
break
else:
print("NO")
``` |
620_D. Professor GukiZ and Two Arrays | Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a sa as close as possible to the sum of the elements in the array b sb. So he wants to minimize the value v = |sa - sb|.
In one operation professor can swap some element from the array a and some element f... | ```python
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
sum_a, sum_b = sum(a), sum(b)
delta = sum_b - sum_a
ans = abs(delta)
ans_swap = []
for i in range(n):
for j in range(m):
if abs((sum_a - a[i] + b[j]) - (sum_b ... |
641_C. Little Artem and Dance | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.
More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a g... | ```python
import io, os, sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, q = map(int, input().split())
pos = [i for i in range(n)]
cnt, temp, flag = 0, [0, 0], 0
for _ in range(q):
p = list(map(int, input().split()))
if p[0] == 1:
x = (n + p[1]) % n
cnt = cnt + x
... |
66_A. Petya and Java | Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But h... | ```python
n= int(input())
if(n<=127):
print("byte")
elif(n<=32767):
print("short")
elif(n<=2147483647):
print("int")
elif(n<=9223372036854775807):
print("long")
else:
print("BigInteger")
``` |
690_F1. Tree of Life (easy) | Heidi has finally found the mythical Tree of Life – a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies.
On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of n points (... | ```python
n = int(input())
a = [0]*(n+1)
for _ in range(n-1):
x, y = input().split(' ')
x, y = [int(x), int(y)]
a[x] += 1
a[y] += 1
too = 0
for x in a:
too += (x * (x-1))//2
print(too)
``` |
735_E. Ostap and Tree | Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no m... | ```python
def main():
n, k = map(int, input().split())
cnt = [[[0] * 21 for _ in (0, 1)] for _ in range(n + 1)]
edges, mod = [[] for _ in range(n + 1)], 1000000007
for _ in range(n - 1):
u, v = map(int, input().split())
edges[u].append(v)
edges[v].append(u)
def dfs(u, f):
... |
780_D. Innokenty and a Football League | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.
Each club's full name consist of two wo... | ```python
from collections import defaultdict
names = int(input())
inp = [input().split() for x in range(names)]
choice = []
res = defaultdict(lambda: [])
for x, word in enumerate(inp):
choice.append(False)
res[word[0][:3]].append(x)
while True:
changes = []
for key in res.keys():
if len(res[ke... |
804_A. Find Amir | A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j co... | ```python
n = int(input())
print(int((n + 1) / 2) - 1)
``` |
873_D. Merge Sort | Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array a with indices from [l, r) can be implemented as follows:
1. If the segment [l, r) is already sorted in non-descending order (that is, for any i such that l ≤ i < r - 1 a[i] ≤ a[i + 1]), then end the function call;
2.... | ```python
def fun(arr,l,r,cnt,k,flag):
if cnt[0]==k:
flag[0]+=1
return
if l==r-1:
return
m=(l+r)//2
arr[m],arr[m-1]=arr[m-1],arr[m]
if flag[0]==0:
cnt[0]+=2
fun(arr,l,m,cnt,k,flag)
if flag[0]==0:
fun(arr,m,r,cnt,k,flag)
n,k=list(map(i... |
899_C. Dividing the numbers | Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible.
Help Petya to split the integers. Each of n integers should be exactly in one group.
Input
The first line contains a s... | ```python
n = int(input())
if n == 3:
print(0)
print(2, 1, 2)
quit()
start = 1
if n % 2 != 0:
start = 2
end = n // 2
if end % 2 != 0:
end -= 1
a = [k for k in range(start, n + 1)]
b = a[::-1]
# print(a)
# print(b)
c = []
d = []
step = True
for k in range(end):
if step:
c.append(a[... |
948_B. Primal Sport | Alice and Bob begin their day with a quick game. They first choose a starting number X0 ≥ 3 and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and anno... | ```python
import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: li... |
976_B. Lara Croft and the New Game | You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy.
Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D e... | ```python
import sys
n,m,k=map(int,input().split())
if(k<n):
print(k+1,1)
sys.exit()
k-=n
x=n-(k)//(m-1)
if(x%2==0):
y=k%(m-1)+2
else:
y=m-k%(m-1)
print(x,y)
``` |
p02646 Tokio Marine & Nichido Fire Insurance Programming Contest 2020 - Tag | Two children are playing tag on a number line. (In the game of tag, the child called "it" tries to catch the other child.) The child who is "it" is now at coordinate A, and he can travel the distance of V per second. The other child is now at coordinate B, and she can travel the distance of W per second.
He can catch ... | ```python
a,v=map(int, input().split())
b,w=map(int, input().split())
t=int(input())
dist=abs(b-a)
dist2=(v-w)*t
if dist>dist2:
print("NO")
else:
print("YES")
``` |
p02775 AtCoder Beginner Contest 155 - Payment | In the Kingdom of AtCoder, only banknotes are used as currency. There are 10^{100}+1 kinds of banknotes, with the values of 1, 10, 10^2, 10^3, \dots, 10^{(10^{100})}. You have come shopping at a mall and are now buying a takoyaki machine with a value of N. (Takoyaki is the name of a Japanese snack.)
To make the paymen... | ```python
dp = [0, 2]
for d in map(int, reversed(input())):
dp = [min(d + dp[0], d + 1 + dp[1]), min(10 - d + dp[0], 9 - d + dp[1])]
print(min(dp[0], 1 + dp[1]))
``` |
p02910 AtCoder Beginner Contest 141 - Tap Dance | Takahashi will do a tap dance. The dance is described by a string S where each character is `L`, `R`, `U`, or `D`. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character.
S is said to be easily playable if and onl... | ```python
S = input()
print("No" if ("L" in S[0::2]) or ("R" in S[1::2]) else "Yes")
``` |
p03045 AtCoder Beginner Contest 126 - 1 or 2 | There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.
Let A_i be the integer written on the i-th card.
Your objective is to guess A_1, A_2, ..., A_N correctly.
You know the following facts:
* For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.
You ar... | ```python
N, M = map(int,input().split())
par = [i for i in range(N+1)]
size = [1 for _ in range(N+1)]
def find(x):
if par[x] == x:
return x
else:
par[x] = find(par[x])
return par[x]
def unite(x,y):
x = find(x)
y = find(y)
if x == y:
return 1
par[x] = y
size... |
p03187 AtCoder Grand Contest 030 - Tree Burning | Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi. Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distance from the Takahashi's residence, measured counter-clockwise.
There are N... | ```python
l, n = [int(item) for item in input().split()]
right = []
left = []
for i in range(n):
a = int(input())
right.append(a)
left.append(l - a)
left.reverse()
rsum = [0] * (n+1)
lsum = [0] * (n+1)
for i in range(n):
rsum[i+1] += rsum[i] + right[i]
lsum[i+1] += lsum[i] + left[i]
# Take all fro... |
p03334 AtCoder Grand Contest 025 - Choosing Points | Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions:
* The distance between any two points in S is not \sqrt{D_1}.
* The distance between any two points in S is not \sqrt{D_2}.
Here, D_1 ... | ```python
def judge(D):
n = 0
while D%4==0:
n += 1
D //= 4
return (lambda x,y: ~((x>>n)^(y>>n))&1) if D%2==1 else (lambda x,y: ~(x>>n)&1)
N,D1,D2 = map(int,input().split())
j1,j2 = judge(D1),judge(D2)
for _,(x,y) in zip(range(N*N),filter(lambda p: j1(*p) and j2(*p), ((x,y) for x in range(N*2) for y in r... |
p03494 AtCoder Beginner Contest 081 - Shift only | There are N positive integers written on a blackboard: A_1, ..., A_N.
Snuke can perform the following operation when all integers on the blackboard are even:
* Replace each integer X on the blackboard by X divided by 2.
Find the maximum possible number of operations that Snuke can perform.
Constraints
* 1 \leq N... | ```python
input()
a = list(map(int, input().split()))
ans = 0
while all(i%2 == 0 for i in a):
a = [n/2 for n in a]
ans += 1
print(ans)
``` |
p03811 AtCoder Grand Contest 010 - Rearranging | There are N integers written on a blackboard. The i-th integer is A_i.
Takahashi and Aoki will arrange these integers in a row, as follows:
* First, Takahashi will arrange the integers as he wishes.
* Then, Aoki will repeatedly swap two adjacent integers that are coprime, as many times as he wishes.
We will assume... | ```python
import sys
sys.setrecursionlimit(1000000000)
def gcd(a: int, b:int):
while b:
a,b=b,a%b
return a
def merge(a,us,vs):
i,j,res=0,0,[]
while i<len(us) and j<len(vs):
if a[us[i]]>=a[vs[j]]:
res.append(us[i])
i+=1
else:
res.append(vs[j])... |
p00068 Enclose Pins with a Rubber Band | Hit n nails one by one at the coordinates P1 (x1, y1), P2 (x2, y2), P3 (x3, y3), ..., Pn (xn, yn) on the flat plate, and put them on the rubber band ring. Surround it with a single rubber band so that all the nails fit inside. At this time, the rubber bands must not intersect.
Create a program that reads the coordinat... | ```python
# AOJ 0068 Enclose Pins with a Rubber Band
# Python3 2018.6.22 bal4u
def cross(a, b):
return a.real*b.imag - a.imag*b.real
# 凸包 入力: 座標リスト リターン:凸包を構成する座標リスト
def convex_hull(p):
pp = sorted(p, key=lambda x:(x.imag,x.real)) # y座標を優先して昇順、同じならx座標で昇順
n = len(pp)
ans, j = [0]*(n+1), 0
for i in range(n):
w... |
p00200 Traveling Alone: One-way Ticket of Youth | Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro'... | ```python
from heapq import heappop, heappush
class WeightedEdge:
"""Weighted edge."""
def __init__(self, a, b, weight):
self.a = a
self.b = b
self.weight = weight
def __repr__(self):
return "(%d - %d: %d)" % (self.a, self.b, self.weight)
def __lt__(self, other):
... |
p00355 Reservation System | The supercomputer system L in the PCK Research Institute performs a variety of calculations upon request from external institutes, companies, universities and other entities. To use the L system, you have to reserve operation time by specifying the start and end time. No two reservation periods are allowed to overlap e... | ```python
a,b=map(int,input().split())
N=int(input())
judge=0
for i in range(N):
rs,re=map(int,input().split())
if judge==0:
if a<=rs and b>rs:
judge=1
elif a>rs and a<re:
judge=1
print(judge)
``` |
p00714 Water Tank | Mr. Denjiro is a science teacher. Today he has just received a specially ordered water tank that will certainly be useful for his innovative experiments on water flow.
<image>
---
Figure 1: The water tank
The size of the tank is 100cm (Width) * 50cm (Height) * 30cm (Depth) (see Figure 1). For the experiments, he fits... | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
W = [(0, 50)]
for i in range(N):
b, h = map(int, readline().split())
W.append((b, h))
W.append((100, 50))
M = int(readline())
S = [0]*(N+1)
Q = []
for i in range(... |
p00854 And Then There Was One | Let’s play a stone removing game.
Initially, n stones are arranged on a circle and numbered 1, ... , n clockwise (Figure 1). You are also given two numbers k and m. From this state, remove stones one by one following the rules explained below, until only one remains. In step 1, remove stone m. In step 2, locate the k-... | ```python
while True :
n, k, m = map(int, input().split())
if n == 0 and k == 0 and m == 0 :
break
stone = []
for i in range(n) :
stone.append(i+1)
i = m-1
while True :
del stone[i]
if len(stone) == 1 :
break
i += k-1
if i... |
p01117 Scores of Final Examination | Scores of Final Examination
I am a junior high school teacher. The final examination has just finished, and I have all the students' scores of all the subjects. I want to know the highest total score among the students, but it is not an easy task as the student scores are listed separately for each subject. I would li... | ```python
while True:
n,m=map(int,input().split())
if n==0 and m==0:
break
p=[list(map(int,input().split())) for i in range(m)]
for i in range(1,m):
for j in range(n):
p[i][j]+=p[i-1][j]
print(max(p[m-1]))
``` |
p01416 Tiles are Colorful | Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well.
Today's training is to quickly solve popular puzzles and train your instantaneous power. Today's challenge is a puzzle of colorful tiles lined up and erasing them well.
In the initial st... | ```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 ... |
p02007 Prefix Suffix Search | As an English learner, sometimes you cannot remember the entire spelling of English words perfectly, but you can only remember their prefixes and suffixes. For example, you may want to use a word which begins with 'appr' and ends with 'iate', but forget the middle part of the word. It may be 'appreciate', 'appropriate'... | ```python
from bisect import bisect
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def construct(N, S, base, MOD):
L = 26
root = [0, 0, N-1, [None]*L]
nds = [root]
for i, s in enumerate(S):
node = root
for c in s:
h, a, b, nt = node
if nt[c] is... |
p02151 Phone Number | Problem
Den, the phone number of Ukunikia Co., Ltd., enters a very long phone number into the phone every day.
One day, too tired, Den came up with a surprising idea.
"Isn't it even a little easier if you rearrange the arrangement of the buttons on the phone ?!"
The phone has squares evenly spaced at $ 3 \ times 3 $,... | ```python
def inpl(): return list(map(int, input().split()))
from collections import defaultdict
from itertools import combinations, permutations
N = int(input())
S = list(map(int, input()))
move = defaultdict(int)
b = S[0]
for i in range(N-1):
a, b = S[i], S[i+1]
move[(a, b)] += 1
move[(b, a)] += 1
R = ... |
p02292 Counter-Clockwise | <image>
For given three points p0, p1, p2, print
COUNTER_CLOCKWISE
if p0, p1, p2 make a counterclockwise turn (1),
CLOCKWISE
if p0, p1, p2 make a clockwise turn (2),
ONLINE_BACK
if p2 is on a line p2, p0, p1 in this order (3),
ONLINE_FRONT
if p2 is on a line p0, p1, p2 in this order (4),
ON_SEGMENT
... | ```python
x0,y0,x1,y1 = map(int, input().split())
p0=complex(x0,y0)
p1=complex(x1,y1)
q = int(input())
CCW = {1: 'COUNTER_CLOCKWISE',
-1: 'CLOCKWISE',
2: 'ONLINE_BACK',
-2: 'ONLINE_FRONT',
0: 'ON_SEGMENT',}
def dot(a, b):
return a.real * b.real + a.imag * b.imag
def cross(a, b):
retur... |
p02439 Min-Max | For given three integers $a, b, c$, print the minimum value and the maximum value.
Constraints
* $-1,000,000,000 \leq a, b, c \leq 1,000,000,000$
Input
The input is given in the following format.
$a \; b \; c\;$
Three integers $a, b, c$ are given in a line.
Output
Print the minimum and maximum values separate... | ```python
if __name__ == "__main__":
param = input().split(" ")
seq = [ int(a) for a in param]
min = min(seq)
max = max(seq)
print(str(min) + " " + str(max))
``` |
1030_C. Vasya and Golden Ticket | Recently Vasya found a golden ticket — a sequence which consists of n digits a_1a_2... a_n. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket 350178 is lucky since it can be divided into three segments 350, 17 and 8: 3+5+0=1+7=8. No... | ```python
n = int(input())
s = input()
arr = list()
arr.append(int(s[0]))
summ = arr[0]
bigflg = False
for i in range(1,len(s)):
arr.append(int(s[i]))
summ+=arr[i]
for i in range(2,len(s)+1):
if summ % i == 0:
amount = summ / i
sm = 0
flg = True
for j in range(len(arr)):
... |
1053_A. Vasya and Triangle | Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutio... | ```python
from math import gcd
def tfit(n, m, No, Mo):
if (n < m) != (No < Mo):
n, m = m, n
if n > No or m > Mo:
return -1, -1
return n, m
def sv():
N, M, K = map(int, input().split())
No = N
Mo = M
x = gcd(N, K)
N //= x
K //= x
x = gcd(M, K)
M //= x
K //= x
if K > 2:
print('NO')
return
elif K == ... |
1075_B. Taxi drivers and Lyft | Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.
Lyft has become so popular so that it is now used by all m taxi drivers in the city, who every day transport the rest of the city residents — n riders.
Each resident (including taxi drivers) of Palo... | ```python
n, m = [int(i) for i in input().split()]
x = [int(i) for i in input().split()]
t = [int(i) for i in input().split()]
ti = [k for k in range(n + m) if t[k] == 1]
pi = [k for k in range(n + m) if t[k] == 0]
tc = [0] * (m + n)
tc[ti[0]] += ti[0]
tc[ti[m-1]] += m + n - 1 - ti[m-1]
for i in range(m-1):
ti1 = t... |
1096_C. Polygon for the Angle | You are given an angle ang.
The Jury asks You to find such regular n-gon (regular polygon with n vertices) that it has three vertices a, b and c (they can be non-consecutive) with \angle{abc} = ang or report that there is no such n-gon.
<image>
If there are several answers, print the minimal one. It is guarantied t... | ```python
import math
t=int(input())
for e in range(t):
n=int(input())
g=math.gcd(n,180)
p=n//g
q=180//g
if n==180 or n==0: print(-1)
else:
if p==q-1: print(2*q)
else: print(q)
``` |
1117_D. Magic Gems | Reziba has many magic gems. Each magic gem can be split into M normal gems. The amount of space each magic (and normal) gem takes is 1 unit. A normal gem cannot be split.
Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is N units. If a magic g... | ```python
import sys
MOD = 10**9+7
def mult(A,B):
n = len(A)
C = []
for x in range(n):
c = [0]*n
for z in range(n):
b = B[x][z]
a = A[z]
for y in range(n):
c[y] += a[y]*b
for y in range(n):
c[y]%=MOD
C.append(c... |
1143_F. U2 | Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one.
Vasya drew several distinct points with integer coordinates on a plane and then drew an... | ```python
import sys
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
N = int(input())
A = [None]*N
for i in range(N):
x, y = map(int, sys.stdin.readline().split())
A[i] = (x, y-x*x)
A.sort()
upper = []
for p in reversed(A):
while len(upper) >= 2 and cross(upper[... |
1163_E. Magical Permutation | Kuro has just learned about permutations and he is really excited to create a new permutation type. He has chosen n distinct positive integers and put all of them in a set S. Now he defines a magical permutation to be:
* A permutation of integers from 0 to 2^x - 1, where x is a non-negative integer.
* The [bitwis... | ```python
def size(k):
return int(math.log2(k))
def v2(k):
if k%2==1:
return 0
else:
return 1+v2(k//2)
n=int(input())
s=list(map(int,input().split()))
import math
s.sort()
used=[]
use=0
found={0:1}
good=0
for guy in s:
big=size(guy)
if guy not in found:
used.append(guy)
... |
1184_B1. The Doctor Meets Vader (Easy) | Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he und... | ```python
def bs(num):
low=0
high=b-1
while low<high:
mid=(low+high)//2
if bases[mid][0]<=num:low=mid+1
else:high=mid-1
if bases[low][0]<=num:return low
else:return low-1
n,b=map(int,input().split())
ar=list(map(int,input().split()))
bases=[];summ=0
for i in range(b):
bases.appen... |
1202_A. You Are Given Two Binary Strings... | You are given two binary strings x and y, which are binary representations of some two integers (let's denote these integers as f(x) and f(y)). You can choose any integer k ≥ 0, calculate the expression s_k = f(x) + f(y) ⋅ 2^k and write the binary representation of s_k in reverse order (let's denote it as rev_k). For e... | ```python
for _ in range(int(input())):
x=input()[::-1]
y=input()[::-1]
posy=y.index('1')
posx=x.index('1',posy)
print(posx-posy)
``` |
1244_A. Pens and Pencils | Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d... | ```python
import math
t=eval(input())
while t>0:
a,b,c,d,k=map(int,input().split())
x=math.ceil(a/c)
y=k-x
flag=0
if y*d<b or y<0:
flag=1
if flag==1:
print(-1)
else:
print(x,y)
t-=1
``` |
1263_E. Editor | The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text.
Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters)... | ```python
'''input
11
(R)R(R)Ra)c
'''
# MODIFIED SEGMENT TREE (MIN = MINIMUM PREFIX SUM instead of MINIMUM ELEMENT IN PREFIX)
class SegmentTree:
def __init__(self, n, arr=[]):
self.n = n
self.tsum = [0] * (2 * n)
self.tmin = [0] * (2 * n)
self.tmax = [0] * (2 * n)
if arr:
... |
1285_A. Mezo Playing Zoma | Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands:
* 'L' (Left) sets the position x: =x - 1;
* 'R' (Right) sets the position x: =x + 1.
Unfortunately, Mezo's controller malfunctions sometimes. ... | ```python
def func(n):
x = input()
ans = 0
l_counter = x.count('L')
r_counter = x.count('R')
y = 0 - l_counter
z = 0 + r_counter
for i in range(y,z+1):
ans += 1
print(ans)
n = int(input())
func(n)
``` |
1304_C. Air Conditioner | Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.
Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all custo... | ```python
for tc in range(int(input())):
n,m=map(int, input().split())
a=b=m
m=0
fl=1
for tccc in range(n):
t,l,h=map(int, input().split())
a-=(t-m)
b+=(t-m)
m=t
if a<l:
a=l
if b>h:
b=h
if a>b:
fl=0
prin... |
1328_D. Carousel | The round carousel consists of n figures of animals. Figures are numbered from 1 to n in order of the carousel moving. Thus, after the n-th figure the figure with the number 1 follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal... | ```python
for i in range(int(input())):
n = int(input())
kinds = [int(i) for i in input().split()]
id1 = 1
k = 1
answer = [1] * n
while id1 < n:
if kinds[id1] == kinds[id1 - 1]:
break
if answer[id1 - 1] == 1:
answer[id1] = 2
else:
answe... |
1348_D. Phoenix and Science | Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria.
Initially, on day 1, there is one bacterium with mass 1.
Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass m splits, it becomes two bacteria of mass m/2 each. For example, a ba... | ```python
import sys
stdin = sys.stdin
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))
def solve():
n = ni()
da = n.bit_length() - 1
print(da)
n -= da + 1
f = [... |
1369_B. AccurateLee | Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...
The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s).
In one move he can choose two consecutive characters s_i and s_{i... | ```python
for _ in range(int(input())):
n=int(input())
s=input()
stack=[]
for i in range(n-1,-1,-1):
num=s[i]
#print(num)
if num=='0':
stack.append(num)
else:
if len(stack)==0:
stack.append(num)
... |
1391_A. Suborrays | A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
For a positive integer n, we call a... | ```python
import sys
input = sys.stdin.readline
from collections import *
for _ in range(int(input())):
n = int(input())
print(*[i for i in range(1, n+1)])
``` |
1413_D. Shurikens | Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available... | ```python
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from itertools import permutations,combinations
def... |
1455_D. Sequence and Swaps | You are given a sequence a consisting of n integers a_1, a_2, ..., a_n, and an integer x. Your task is to make the sequence a sorted (it is considered sorted if the condition a_1 ≤ a_2 ≤ a_3 ≤ ... ≤ a_n holds).
To make the sequence sorted, you may perform the following operation any number of times you want (possibly ... | ```python
import math
for _ in range(int(input())):
n,k=map(int,input().split())
a=list(map(int,input().split()))
ans=0
prob=0
rang=0
for i in range(1,n):
if a[i]<a[i-1]:
prob=1
rang=i
for i in range(rang):
if a[i]>k:
a[i],k=k,a[i]
... |
1506_D. Epic Transformation | You are given an array a of length n consisting of integers. You can apply the following operation, consisting of several steps, on the array a zero or more times:
* you select two different numbers in the array a_i and a_j;
* you remove i-th and j-th elements from the array.
For example, if n=6 and a=[1, 6,... | ```python
import sys
input=sys.stdin.readline
t = int(input())
for i in range(t):
n=int(input())
a=[int(x) for x in input().split()]
a.sort()
temp=1
if n==1:
print(1)
continue
count=[]
for i in range(1,n):
if a[i]==a[i-1]:
temp+=1
if i==n... |
152_C. Pocket Book | One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.
As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, ... | ```python
mod=10**9+7
n,m=map(int,input().split())
mat=[]
for _ in range(n):
s=input()
mat.append(s)
b=ord("A")
s=[False]*255
res=1
for j in range(m):
for i in range(b,b+26):
s[i]=False
for i in range(n):
s[ord(mat[i][j])]=True
r=0
for i in range(b,b+26):
if(s[i]):r+=1
res*=r
print(res%mod)
``` |
180_B. Divisibility Rules | Vasya studies divisibility rules at school. Here are some of them:
* Divisibility by 2. A number is divisible by 2 if and only if its last digit is divisible by 2 or in other words, is even.
* Divisibility by 3. A number is divisible by 3 if and only if the sum of its digits is divisible by 3.
* Divisibility by ... | ```python
b, d = map(int, input().split())
for i in range(1, 10):
if (b**i) % d == 0:
print("2-type")
print(i)
exit()
if (b-1) % d == 0:
print("3-type")
exit()
if (b+1) % d == 0:
print("11-type")
exit()
for i in range(2, d+1):
if d % i == 0:
x = 1
while d ... |
203_C. Photographer | Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve.
The camera's memory is d megabytes. Valera's camera can take photos of high and l... | ```python
n, d = map(int, input().split())
d1, d2 = map(int, input().split())
arr = [0] * n
for i in range(n):
a, b = map(int, input().split())
arr[i] = [d1*a + d2*b, i+1]
arr.sort()
res, idx = 0, ''
for i in arr:
if d - i[0] < 0:
break
d -= i[0]
res += 1
idx += str(i[1]) + ' '
print(res... |
228_B. Two Tables | You've got two rectangular tables with sizes na × ma and nb × mb cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the i-th row and the j-th column, as ai, j; we w... | ```python
def mi():
return map(int, input().split())
def mi1():
return map(int, list(input()))
'''
3 2
01
10
00
2 3
001
111
'''
na, ma = mi()
a = [0]*na
for i in range(na):
a[i] = list(mi1())
nb, mb = mi()
b = [0]*nb
for i in range(nb):
b[i] = list(mi1())
ans = -10**10
ax, ay = 0, 0
n, m... |
277_A. Learning Languages | The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official language... | ```python
from sys import stdin,stdout
input = stdin.readline
def main():
n, m = map(int,input().split())
sets = list(range(n+1+m))
sizes = [1]*(n+1+m)
def get(a):
if sets[a] != a:
sets[a] = get(sets[a])
return sets[a]
def union(a, b):
a = get(a)
b = get... |
29_C. Mail Stamps | One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sen... | ```python
n=int(input())
d={}
for i in range(n):
a,b=map(int,input().split())
if a in d:
d[a].append(b)
else:
d[a]=[b]
if b in d:
d[b].append(a)
else:
d[b]=[a]
ans=[]
for el in d:
if len(d[el])==1:
ans.append(el)
root=el
break
cur=r... |
323_A. Black-and-White Cube | You are given a cube of size k × k × k, which consists of unit cubes. Two unit cubes are considered neighbouring, if they have common face.
Your task is to paint each of k3 unit cubes one of two colours (black or white), so that the following conditions must be satisfied:
* each white cube has exactly 2 neighbourin... | ```python
k=int(input())
if k%2==1:
print(-1)
else:
for i in range(k):
for j in range(k):
a=''
for l in range(k):
a+='bw'[(i//2+j+l//2)%2]
print(a)
if i<k-1:
print()
``` |
347_D. Lucky Common Subsequence | In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substri... | ```python
def Solve(x,y,c):
if(c==len(virus)):
return 0
if(x==len(s1) or y==len(s2)):
return ""
if((x,y,c) in Mem):
return Mem[(x,y,c)]
ans=""
if(s1[x]==s2[y]):
q=0
if(s1[x]==virus[c]):
q=Solve(x+1,y+1,c+1)
if(q!=0):
q=s... |
392_B. Tower of Hanoi | The Tower of Hanoi is a well-known mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the pu... | ```python
def play(price, n):
# dp[i][j][k] - naimen'shaya stoimost' peremeshcheniya i blinov so sterzhnya j => k
# U nas vsegda est' dva varianta dejstviya:
# 1. Peremeshchaem i - 1 blin na mesto 2. Dalee, peremeshchaem i - yj blin na mesto 3. I nakonec peremeshchaem i - 1 blin na mesto 3.
# 2. Pereme... |
415_C. Mashmokh and Numbers | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he rem... | ```python
n,k=map(int,input().split())
if n//2>k or (k!=0 and n==1):
print(-1)
exit(0)
ans=[0]*n
ans[0]=k-n//2+1
if n>1:
ans[1]=2*ans[0]
for i in range(2,n):
ans[i]=ans[i-1]+1
print(*ans)
``` |
442_A. Borya and Hanabi | Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game.
Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding n cards. The game is somewhat complicated by the fact that everybody sees Borya's cards excep... | ```python
input()
p = {(1 << 'RGBYW'.index(c)) + (1 << int(k) + 4) for c, k in input().split()}
print(min(bin(t).count('1') for t in range(1024) if len({t & q for q in p}) == len(p)))
# Made By Mostafa_Khaled
``` |
464_B. Restore Cube | Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — c... | ```python
from itertools import permutations as p
d = lambda a, b: sum((i - j) ** 2 for i, j in zip(a, b))
f = lambda a, b: [i + j - k for i, j, k in zip(a, b, q)]
g = lambda t: sorted(sorted(q) for q in t)
v = [sorted(map(int, input().split())) for i in range(8)]
q = v.pop()
u = g(v)
for a, b, c in p(v, 3):
for... |
488_A. Giga Tower | Giga Tower is the tallest and deepest building in Cyberland. There are 17 777 777 777 floors, numbered from - 8 888 888 888 to 8 888 888 888. In particular, there is floor 0 between floor - 1 and floor 1. Every day, thousands of tourists come to this place to enjoy the wonderful view.
In Cyberland, it is believed t... | ```python
n = int(input())+1
nword = str(n)
count = 1
while("8" not in nword):
n+=1
nword = str(n)
count += 1
print(count)
``` |
510_E. Fox And Dinner | Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.
They will have dinner around some round tables. You want to distribute foxes such that:
1. Each fox is sitting at some table.
2. Each table has at least 3 foxes sitting around it.
3... | ```python
from collections import deque
class Dinic():
def __init__(self, listEdge, s, t):
self.s = s
self.t = t
self.graph = {}
self.maxCap = 1000000
# dict các node lân cận
# e[0]: from, e[1]: to, e[2]: dung luong
for e in listEdge:
... |
536_A. Tavas and Karafs | Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.
<image>
Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is ... | ```python
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.... |
560_B. Gerald is into Art | Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an a1 × b1 rectangle, the paintings have shape of a a2 × b2 and a3 × b3 rectangles.
Since th... | ```python
check = lambda ax, ay, bx, by, cx, cy : bx + cx <= ax and max(by, cy) <= ay
inp = lambda : map(int, input().split())
x1, y1 = inp()
x2, y2 = inp()
x3, y3 = inp()
if check(x1, y1, x2, y2, x3, y3) or check(y1, x1, x2, y2, x3, y3) or check(x1, y1, y2, x2, x3, y3) or check(y1, x1, y2, x2, x3, y3) or check(x1, y1,... |
586_D. Phillip and Trains | The mobile application store has a new game called "Subway Roller".
The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmo... | ```python
T = int(input())
for t in range(T):
n, k = map(int, input().split(' ')[:2])
s = ["","",""]
for i in range(3):
s[i] = input()
s[0] += '.' * (n*3)
s[1] += '.' * (n*3)
s[2] += '.' * (n*3)
def top():
return [s[0][0] != '.', s[1][0] != '.', s[2][0] != '.']
def sh... |
608_E. Marbles | In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.
One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2... | ```python
def prefix(s):
v = [0]*len(s)
for i in range(1,len(s)):
k = v[i-1]
while k > 0 and s[k] != s[i]:
k = v[k-1]
if s[k] == s[i]:
k = k + 1
v[i] = k
return v
n = int(input())
n-=1
s1 = input()
s2 = input()
opos = {'W':'E', 'E':'W', 'N':'S', 'S':'... |
656_C. Without Text | <image>
You can preview the image in better quality by the link: [http://assets.codeforces.com/files/656/without-text.png](//assets.codeforces.com/files/656/without-text.png)
Input
The only line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be an alphanumeric character o... | ```python
s = input()
alpha = "abcdefghijklmnopqrstuvwxyz.0123456789"
res = 0
for c in s:
x1 = int('@' < c and '[' > c)
x2 = alpha.index(c.lower()) + 1
x3 = int('`' < c and '{' > c)
x4 = x1 * x2
x5 = x2 * x3
x6 = x4 - x5
res += x6
print(res)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.