name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
p01940 Unique Subsequence | C: Only one subsequence --Unique Subsequence-
problem
One day Ebi-chan noticed that a text string T of length n and a pattern string P (m \ leq n) of length m were placed on the desk. Ebi-chan loves the "only one subsequence" that appears in strings, so she immediately began investigating whether P was the only subse... | ```python
t=input()
p=input()
mae=[0]*len(p)
cnt=0
for i in range(len(t)):
if t[i]==p[cnt]:
mae[cnt]=i
cnt+=1
if cnt==len(p):
break
if cnt!=len(p):print("no");exit()
cnt-=1
for j in range(len(t)-1,-1,-1):
if t[j]==p[cnt]:
if mae[cnt]!=j:print("no");exit()
cnt-... |
p02089 AddMulSubDiv | B: AddMulSubDiv
Problem Statement
You have an array A of N integers. A_i denotes the i-th element of A.
You have to process one of the following queries Q times:
* Query 1: The query consists of non-negative integer x, and two positive integers s, t. For all the elements greater than or equal to x in A, you have to... | ```python
import bisect
n,Q,L,R = map(int,input().split())
a = list(map(int,input().split()))
a.sort()
p = []
for i in range(Q):
p.append(tuple(map(int,input().split())))
def f(z):
for q,x,s,t in p:
if q == 1:
if z >= x:
z = t*(z+s)
else:
if z <= x:
... |
p02221 Tournament | Problem statement
A $ 2 $ human-player match-up game tournament is about to take place in front of Kyoto University Camphor Tree.
There are $ 2 ^ N $ participants in this tournament, numbered from $ 1 $ to $ 2 ^ N $.
Winning or losing when $ 2 $ of participants fight is represented by the $ 2 ^ N-1 $ string $ S $ co... | ```python
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [li... |
p02373 Lowest Common Ancestor | For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The f... | ```python
class Lca:
def __init__(self, E, root):
import sys
sys.setrecursionlimit(500000)
self.root = root
self.E = E # V<V>
self.n = len(E) # 頂点数
self.logn = 1 # n < 1<<logn ぴったりはだめ
while self.n >= (1<<self.logn):
self.logn += 1
# pa... |
1036_A. Function Height | You are given a set of 2n+1 integer points on a Cartesian plane. Points are numbered from 0 to 2n inclusive. Let P_i be the i-th point. The x-coordinate of the point P_i equals i. The y-coordinate of the point P_i equals zero (initially). Thus, initially P_i=(i,0).
The given points are vertices of a plot of a piecewis... | ```python
from math import ceil
from sys import stdin, stdout
n, k = [int(i) for i in stdin.readline().rstrip().split()]
stdout.write(str((n+k-1)//n)+'\n')
``` |
1057_C. Tanya and Colored Candies | There are n candy boxes in front of Tania. The boxes are arranged in a row from left to right, numbered from 1 to n. The i-th box contains r_i candies, candies have the color c_i (the color can take one of three values — red, green, or blue). All candies inside a single box have the same color (and it is equal to c_i... | ```python
INF = 10e9
n,s,k = map(int, input().split())
r = list(map(int, input().split()))
r.append(0)
col = input()
mat = []
for i in range(n+1):
adj = {}
for j in range(n):
if i == n:
adj[j] = abs((s-1)-j)
else:
if col[i] != col[j] and r[i] < r[j]:
adj[j... |
1080_B. Margarite and the best present | Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.
Recently, she was presented with an array a of the size of 10^9 elements that is filled as follows:
* a_1 = -1
* a_2 = 2
* a_3 = -3
* a_4 = 4
* a_5 = -5
* And so on ...
... | ```python
for i in range(int(input())):
a,b=map(int,input().split())
if (b-a)%2!=0:
if a%2==0:
print(-(b-a+1)//2)
else:
print((b-a+1)//2)
else:
if a%2!=0:
print((b-a)//2 - b)
else:
print(-(b-a)//2 + b)
``` |
10_A. Power Consumption Calculation | Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes P1 watt per minute. T1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to P2 watt per minute. Finally, after T2 minut... | ```python
n,p1,p2,p3,t1,t2 = map(int,input().split())
p=[]
c=0
for j in range(n):
l,r = map(int,input().split())
if j==0:
c+= (r-l)*p1
p.append(r)
else:
if l-p[-1]>0:
if l-p[-1]<=t1:
c+=(l-p[-1])*p1
else:
if t1+t2>=l-p[-1]>... |
1148_B. Born This Way | Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.
There are n flights from A to B, they depart at time moments a_1, a_2, a_3, ..., a_n and arrive at B t_a moments later.
There are m flights from B to C... | ```python
from collections import *
from math import *
import array
import bisect
cin = lambda : [*map(int, input().split())]
def upper_bound(a, x):
l = 0
r = len(a) - 1
while l < r:
m = int((l + r + 1) / 2)
if a[m] <= x:
l = m
else:
r = m - 1
return l
... |
1169_D. Good Triple | Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 ≤ l ≤ r ≤ n and there is at least one pair of integers x, k such that 1 ≤ x, k ≤ n, l ≤ x < x + 2k ≤ r, and s_x = s_{x+k} = s_{x+2k}.
Find th... | ```python
from sys import stdin
s=stdin.readline().strip()
x=-1
ans=0
for i in range(len(s)):
for j in range(1,10):
if (i-2*j)>=0 and s[i]==s[i-j] and s[i-j]==s[i-2*j]:
if (i-2*j)>x:
ans+=(i-2*j-x)*(len(s)-i)
x=i-2*j
print(ans)
``` |
1187_F. Expected Square Beauty | Let x be an array of integers x = [x_1, x_2, ..., x_n]. Let's define B(x) as a minimal size of a partition of x into subsegments such that all elements in each subsegment are equal. For example, B([3, 3, 6, 1, 6, 6, 6]) = 4 using next partition: [3, 3\ |\ 6\ |\ 1\ |\ 6, 6, 6].
Now you don't have any exact values of x,... | ```python
mod = 10 ** 9 + 7
def pow_(x, y, p) :
res = 1
x = x % p
if x == 0:
return 0
while y > 0:
if (y & 1) == 1:
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
def reverse(x, mod):
return pow... |
1206_E. Palindromic Paths | This is an interactive problem
You are given a grid n× n, where n is odd. Rows are enumerated from 1 to n from up to down, columns are enumerated from 1 to n from left to right. Cell, standing on the intersection of row x and column y, is denoted by (x, y).
Every cell contains 0 or 1. It is known that the top-left ce... | ```python
from sys import stdout
# matrix="""
# 101110111011101110111
# 011101110111011101110
# 111011101110111011101
# 110111011101110111011
# 101110111011101110111
# 011101110111011101110
# 111011101110111011101
# 110111011101110111011
# 101110111011101110111
# 011101110111011101110
# 111011101110111011100
# 1101... |
1225_A. Forgetting Things | Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b.
Can you reconst... | ```python
a,b = map(int,input().split())
if(b == a+1):
print(str(a)+"9 "+str(b)+"0")
elif(b == a):
print(str(a)+"0 "+str(a)+"1")
elif(b == 1 and a == 9):
print("99 100")
else:
print(-1)
``` |
1249_C2. Good Numbers (hard version) | The only difference between easy and hard versions is the maximum value of n.
You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n.
The positive integer is called good if it can be represented as a sum of distinct powers of 3 (... | ```python
for _ in range(int(input())):
n=int(input())
a=[]
b=[0]
for i in range(50):
a.append(3**i)
b.append(b[-1]+a[-1])
if b[-1]> n:
break
s=b[i+1]
a=a[::-1]
# print(s,a)
for j in a:
if s-j>=n:
s-=j
print(s)
``` |
1267_K. Key Storage | Karl is developing a key storage service. Each user has a positive integer key.
Karl knows that storing keys in plain text is bad practice. So, instead of storing a key, he decided to store a fingerprint of a key. However, using some existing fingerprint algorithm looked too boring to him, so he invented his own one.
... | ```python
import math as m
import collections
IP = lambda: list(map(int, input().split()))
INF = 1e9
f = [1]
for i in range(1, 22):
f.append(f[-1]*i)
def solve(arr, n):
d = collections.Counter(arr)
tu = 1; mau = 1
a = [0]*22
for i in arr:
# print(i, n)
a[i] += 1
for i in range... |
1310_A. Recommendations | VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively ... | ```python
import heapq
n = int(input())
*a, = map(int, input().split())
*t, = map(int, input().split())
i = 0
sorted_idxs = sorted(range(n), key=lambda o: (a[o], -t[o]))
cur_val = a[sorted_idxs[0]]
dupls = []
ans = 0
s = 0
for i, idx in enumerate(sorted_idxs):
cur_val = a[idx]
heapq.heappush(dupls, (-t[idx],... |
1332_F. Independent Set | Eric is the teacher of graph theory class. Today, Eric teaches independent set and edge-induced subgraph.
Given a graph G=(V,E), an independent set is a subset of vertices V' ⊂ V such that for every pair u,v ∈ V', (u,v) not ∈ E (i.e. no edge in E connects two vertices from V').
An edge-induced subgraph consists of a ... | ```python
import sys
readline = sys.stdin.readline
def parorder(Edge, p):
N = len(Edge)
par = [0]*N
par[p] = -1
stack = [p]
order = []
visited = set([p])
ast = stack.append
apo = order.append
while stack:
vn = stack.pop()
apo(vn)
for vf in Edge[vn]:
... |
1353_B. Two Arrays And Swaps | You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | ```python
def swap_sum(a,b,cnt,k):
if cnt==k or min(a)>=max(b):
return sum(a)
else:
i=a.index(min(a))
j=b.index(max(b))
a[i],b[j]=b[j],a[i]
#print(a)
#print(b)
return swap_sum(a,b,cnt+1,k)
for ii in range(int(input())):
n,k=map(int,... |
1373_A. Donut Shops | There are two rival donut shops.
The first shop sells donuts at retail: each donut costs a dollars.
The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them ... | ```python
import sys
input = sys.stdin.readline
def main():
t = int(input())
for _ in range(t):
A, B, C = [int(x) for x in input().split()]
ans1 = -1
ans2 = -1
if A < C:
ans1 = 1
if A * B > C:
ans2 = B
print(ans1, ans2)
if __n... |
141_B. Hopscotch | So nearly half of the winter is over and Maria is dreaming about summer. She's fed up with skates and sleds, she was dreaming about Hopscotch all night long. It's a very popular children's game. The game field, the court, looks as is shown in the figure (all blocks are square and are numbered from bottom to top, blocks... | ```python
a, x, y = map(int, input().split())
h = a / 2
if y % a == 0:
print('-1')
exit()
y //= a
y += 1
if y == 1:
if x > -h and x < h:
print('1')
else:
print('-1')
else:
if y % 2 == 0:
if x > -h and x < h:
print(y + (y // 2) - 1)
else:
print(... |
1438_B. Valerii Against Everyone | You're given an array b of length n. Let's define another array a, also of length n, for which a_i = 2^{b_i} (1 ≤ i ≤ n).
Valerii says that every two non-intersecting subarrays of a have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers... | ```python
import sys
#from collections import deque
#from functools import *
#from fractions import Fraction as f
from copy import *
from bisect import *
#from heapq import *
from math import gcd,ceil,sqrt
from itertools import permutations as prm,product
def eprint(*args):
print(*args, file=sys.stderr)
zz=1
#... |
1463_A. Dungeon | You are playing a new computer game in which you have to fight monsters. In a dungeon you are trying to clear, you met three monsters; the first of them has a health points, the second has b health points, and the third has c.
To kill the monsters, you can use a cannon that, when fired, deals 1 damage to the selected ... | ```python
def zip_sorted(a,b):
# sorted by a
a,b = zip(*sorted(zip(a,b)))
# sorted by b
sorted(zip(a, b), key=lambda x: x[1])
return a,b
import sys
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))
S = lambda : list(map(str,input()))
t,=I()
for t1 in range(t):
a = I()
if sum(a)%9==0:... |
148_A. Insomnia cure | «One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | ```python
kill=[]
for i in range(4):
a=int(input())
kill.append(a)
d=int(input())
count=0
for i in range(1,d+1):
for j in kill:
if i%j==0:
count+=1
break
else:
count+=0
print(count)
``` |
1511_E. Colorings and Dominoes | You have a large rectangular board which is divided into n × m cells (the board has n rows and m columns). Each cell is either white or black.
You paint each white cell either red or blue. Obviously, the number of different ways to paint them is 2^w, where w is the number of white cells.
After painting the white cell... | ```python
mod = 998244353
m,n = map(int,input().split())
mat = [[0]*n for _ in range(m)]
t = 0
res = 0
com = [0] * (max(m,n) + 2)
com[2] = 1
pow2 = 1
for i in range(3,max(m,n)+1):
pow2 = (pow2 << 1) % mod
com[i] = (com[i-1] + 2*com[i-2] + pow2) % mod
for i in range(m):
s = input()
for j in range(n)... |
1539_C. Stable Groups | There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x.
For example, if x = 4, then the group with levels [1, 10, ... | ```python
n,k,x =list(map(int ,input().split()))
arr = list(map(int ,input().split()))
arr.sort()
groups =1
re = []
for i in range(n-1):
diff = arr[i+1]-arr[i]
if diff>x :
if x==0:
groups+=1
continue
if diff%x==0:
diff = diff//x -1
else:
diff =diff//x
re... |
187_A. Permutations | Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.
One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the perm... | ```python
import sys
input = sys.stdin.readline
from math import *
import bisect as bs
n=int(input())
a=[int(x) for x in input().split()]
b= [int(x) for x in input().split()]
d={}
for i in range(n):
d[b[i]]=i
c=0
ans=0
u=[0 for i in range(n)]
for i in range(n):
u[i]=d[a[i]]
#print(u)
for i in range(1,n):
... |
233_B. Non-square Equation | Let's consider equation:
x2 + s(x)·x - n = 0,
where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.
You are given an integer n, find the smallest positive integer root of equation x, or else determine that there are no such roots.
Input
A sing... | ```python
# your code goes here
n=int(input())
def s(x):
return sum(int(i) for i in str(x))
x=int(n**0.5)
d=0
while x>=0 and d<=50:
if(x*x+s(x)*x==n):
# print(x)
break
d+=1
x-=1
if d>50:
x=-1
print(x)
``` |
259_A. Little Elephant and Chess | The Little Elephant loves chess very much.
One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an 8 × 8 checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard doe... | ```python
flag=True
for i in range(8):
k=input()
if k!='BWBWBWBW' and k!='WBWBWBWB':
flag=False
if (flag):
print ("YES")
else:
print ("NO")
``` |
282_A. Bit++ | The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | ```python
n = int(input())
counter= 0
for i in range(n):
if input().find('+') > -1:
counter = counter + 1
else:
counter = counter - 1
print(counter)
``` |
331_A1. Oh Sweet Beaverette | — Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcomin... | ```python
from collections import defaultdict
n = int(input())
a = list(map(int,input().split()))
same = defaultdict(list)
only_positive = [max(0,x) for x in a]
partial_sum = [0 for i in range(n+1)]
for i in range(1,n+1):
partial_sum[i] = partial_sum[i-1]+only_positive[i-1]
for i in range(n):
same[a[i]].append(... |
352_D. Jeff and Furik | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.
At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjace... | ```python
n = int(input())
A = [int(i) for i in input().split()]
def mergesort(l):
l = list(l)
if len(l) <= 1:
return l,0
left,linv = mergesort(l[:len(l) // 2])
right,rinv = mergesort(l[len(l) // 2:])
lefti = 0
righti = 0
i = 0
numinversions = 0
while True:
if i >= len(l):
break
if lefti >= len(left)... |
399_B. Red and Blue Balls | User ainta has a stack of n red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack.
* While the top ball inside the stack is red, pop the ball from the top of the stack.
* Then replace the blue ball on the top with a red ball.
* And finally push some blue ba... | ```python
n = int(input())
s = list(input())
o = 0
#s.reverse()
# while s.count("B") > 0:
# while s[-1] == "R":
# s.pop()
# s[-1] = "R"
# while len(s) < n:
# s.append("B")
# o += 1
# print(s)
try:
index = s.index("B")
o += pow(2, index)
while True:
index = s.index("B", index + 1)
o += ... |
421_C. Online Meeting | Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F ... | ```python
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
'''
Created on 13/09/2018
@author: ernesto
'''
n, m = [int(x) for x in input().strip().split(" ")]
posibles_jefes = set(range(1, n + 1))
anteriores = set()
posteriores = set()
continuos = [True] * (n + 1)
mencionados = set()
posibles_jefes_men... |
448_A. Rewards | Bizon the Champion is called the Champion for a reason.
Bizon the Champion has recently got a present — a new glass cupboard with n shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has a1 first prize cups, a2 second prize cups an... | ```python
import math
a1,a2,a3 = list(map(int,input().split()))
b1,b2,b3 = list(map(int,input().split()))
n = int(input())
s1 = a1+a2+a3
s2 = b1+b2+b3
s3 = math.ceil(s1/5)+math.ceil(s2/10)
if s3 <= n:
print("YES")
else :
print("NO")
``` |
46_B. T-shirts from Sponsor | One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not ... | ```python
i=input
g=range
l=list(map(int,i().split()))
d={'S':0,'M':1,'L':2,'XL':3,'XXL':4}
r={0:'S',1:'M',2:'L',3:'XL',4:'XXL'}
n=int(i())
for x in g(n):
s=i()
if(l[d[s]]):
l[d[s]]-=1
res=s
else:
f=0
for _ in g(5):
if(d[s]+_<5 and l[d[s]+_]):
f=_
break
elif(d[s]-_>-1 and l[d[s]-_]):
f=-_
... |
492_C. Vanya and Exams | Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi es... | ```python
"""*There is no salvation without suffering*"""
"""* Read the damn question carefully*"""
n, r, avg = map(int, input().split())
needed = n * avg
current = 0
ammo = []
for i in range(n):
a, b = map(int, input().split())
current += a
if a < r:
ammo.append([b, r - a])
needed -= current
wr... |
543_B. Destroying Roads | In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any ... | ```python
from itertools import combinations_with_replacement
from collections import deque
#sys.stdin = open("input_py.txt","r")
n, m = map(int, input().split())
G = [ [] for i in range(n)]
for i in range(m):
x, y = map(int, input().split())
x-=1; y-=1
G[x].append(y)
G[y].append(x)
def BFS(s):
... |
56_D. Changing a String | There is a string s, consisting of capital Latin letters. Let's denote its current length as |s|. During one move it is allowed to apply one of the following operations to it:
* INSERT pos ch — insert a letter ch in the string s in the position pos (1 ≤ pos ≤ |s| + 1, A ≤ ch ≤ Z). The letter ch becomes the pos-th s... | ```python
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
s, t = input().rstrip(), input().rstrip()
n, m = len(s), len(t)
dp = [[10**9] * (m + 2) for _ in range(n + 2)]
dp[n][m] = 0
prev = [[(-1, -1)] * (m + 2) for _ in range(n + 2)]
for i in ra... |
591_B. Rebranding | The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan... | ```python
import string
N, M = map(int, input().split())
S = input()
dic = string.ascii_lowercase
for _ in range(M):
x, y = input().split()
dic = dic.translate(str.maketrans(x+y, y+x))
print(S.translate(str.maketrans(string.ascii_lowercase, dic)))
``` |
708_B. Recover the String | For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}.
In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matc... | ```python
import sys
def BS(x):
l = 1
r = 1000000
while (r-l) > 1:
m = (l+r)//2
if m*(m-1)//2 > x:
r = m
else:
l = m
if l*(l-1)//2 != x:
print("Impossible")
sys.exit()
return l
a00,a01,a10,a11=map(int,input().split())
if (a00 + a01 +... |
774_C. Maximum Number | Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below.
<image>
So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be high... | ```python
n = input()
n = int(n)
ans = ""
if(n % 2 == 1):
ans += "7"
n -= 3
while(n > 0):
ans += "1"
n -= 2
print(ans)
``` |
799_C. Fountains | Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allow... | ```python
import operator
fc = []
fd = []
n, c, d = map(int, input().split())
for _ in range(n):
b, p, m = input().split()
b, p = int(b), int(p)
if m == 'C':
if p <= c:
fc.append((b, p))
else:
if p <= d:
fd.append((b, p))
fc.sort(key=operator.itemgetter(0), re... |
845_A. Chess Tourney | Berland annual chess tournament is coming!
Organizers have gathered 2·n chess players who should be divided into two teams with n people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil.
Thus, organizers sh... | ```python
n = int(input())
a = sorted(map(int, input().split()))
print('YES' if a[n] > a[n-1] else 'NO')
# Made By Mostafa_Khaled
``` |
961_E. Tufurama | One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the ... | ```python
from sys import stdin
from sys import setrecursionlimit as SRL; SRL(10**7)
rd = stdin.readline
rrd = lambda: map(int, rd().strip().split())
n = int(input())
a = list(rrd())
bit = [0]*(n+100)
def ins(x):
while x<=n:
bit[x] += 1
x += x&(-x)
def get(l):
tot = 0
while l:
to... |
989_D. A Shade of Moonlight | Gathering darkness shrouds the woods and the world. The moon sheds its light on the boat and the river.
"To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino.
"See? The clouds are coming." Kanno gazes into the distance.
"That can't be better... | ```python
# Codeforces Round #487 (Div. 2)import collections
from functools import cmp_to_key
#key=cmp_to_key(lambda x,y: 1 if x not in y else -1 )
import sys
def getIntList():
return list(map(int, input().split()))
import bisect
N,L,WM = getIntList()
z = {}
z[-1] = {1:[], -1:[]}
z[0... |
p02602 M-SOLUTIONS Programming Contest 2020 - Marks | M-kun is a student in Aoki High School, where a year is divided into N terms.
There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:
* For the first through (K-1)-th terms: not given.
* For each of the K-th through N-th terms: the multipl... | ```python
N, K = map(int, input().split())
A = list(map(int, input().split()))
for i in range(N-K):
print('Yes' if A[i+K]>A[i] else 'No')
``` |
p02733 AtCoder Beginner Contest 159 - Dividing Chocolate | We have a chocolate bar partitioned into H horizontal rows and W vertical columns of squares.
The square (i, j) at the i-th row from the top and the j-th column from the left is dark if S_{i,j} is `0`, and white if S_{i,j} is `1`.
We will cut the bar some number of times to divide it into some number of blocks. In ea... | ```python
H, W, K = map(int, input().split())
S = [list(input()) for _ in range(H)]
res = float('inf')
for i in range(2**(H-1)):
c = bin(i).count('1')
cnt = c
sum_l = [0] * (c+1)
j = 0
flag = True
while j < W:
tmp = sum_l.copy()
pos = 0
for k in range(H):
if ... |
p02867 NIKKEI Programming Contest 2019-2 - Swaps | Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N. Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N, A_i \leq B_i holds:
* Choose two distinct integers x and y between 1 and N (inclusive), and swap the val... | ```python
from heapq import heappush, heappop
from collections import deque
import re
import math
import functools
def sRaw():
return input().rstrip("\r")
def iRaw():
return int(input())
def ssRaw():
return input().split()
def isRaw():
return list(map(int, ssRaw()))
INF = 1 << 29
def make1d_arr... |
p03001 AtCoder Beginner Contest 130 - Rectangle Cutting | There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H). You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the p... | ```python
w,h,x,y = map(int,input().split())
print(w*h/2)
print((x==w/2)*(y==h/2))
``` |
p03142 NIKKEI Programming Contest 2019 - Restore the Tree | There is a rooted tree (see Notes) with N vertices numbered 1 to N. Each of the vertices, except the root, has a directed edge coming from its parent. Note that the root may not be Vertex 1.
Takahashi has added M new directed edges to this graph. Each of these M edges, u \rightarrow v, extends from some vertex u to it... | ```python
n, m = map(int, input().split())
inc = [0]*n
out = [[] for _ in range(n)]
parent = [[] for _ in range(n)]
for _ in range(n-1+m):
a, b = map(int, input().split())
a -= 1
b -= 1
out[a].append(b)
parent[b].append(a)
inc[b] += 1
S = {i for i, c in enumerate(inc) if c == 0}
L = []
while S:
k = S... |
p03286 AtCoder Beginner Contest 105 - Base -2 Number | Given an integer N, find the base -2 representation of N.
Here, S is the base -2 representation of N when the following are all satisfied:
* S is a string consisting of `0` and `1`.
* Unless S = `0`, the initial character of S is `1`.
* Let S = S_k S_{k-1} ... S_0, then S_0 \times (-2)^0 + S_1 \times (-2)^1 + ... + S... | ```python
n = int(input())
s = ""
while n!=0:
s = str(n%2)+s
n = -(n//2)
#print(s, n)
print(0 if s=="" else s)
``` |
p03442 AtCoder Petrozavodsk Contest 001 - XOR Tree | You are given a tree with N vertices. The vertices are numbered 0 through N-1, and the edges are numbered 1 through N-1. Edge i connects Vertex x_i and y_i, and has a value a_i. You can perform the following operation any number of times:
* Choose a simple path and a non-negative integer x, then for each edge e that b... | ```python
from collections import Counter
from functools import reduce
from itertools import combinations
from operator import xor
n = int(input())
nodes = [0] * n
for _ in range(n - 1):
x, y, a = map(int, input().split())
nodes[x] ^= a
nodes[y] ^= a
c = Counter(nodes)
ans = 0
remains = set()
for i, v in ... |
p03600 AtCoder Beginner Contest 074 - Restoring Road Network | In Takahashi Kingdom, which once existed, there are N cities, and some pairs of cities are connected bidirectionally by roads. The following are known about the road network:
* People traveled between cities only through roads. It was possible to reach any city from any other city, via intermediate cities if necessary... | ```python
import copy
N = int(input())
A = []
for i in range(N):
A.append(list(map(int, input().split())))
B = copy.deepcopy(A)
for i in range(N):
for j in range(N):
if i == j:
continue
for k in range(N):
if j == k:
continue
if k == i:
... |
p03761 AtCoder Beginner Contest 058 - Dubious Document | Snuke loves "paper cutting": he cuts out characters from a newspaper headline and rearranges them to form another string.
He will receive a headline which contains one of the strings S_1,...,S_n tomorrow. He is excited and already thinking of what string he will create. Since he does not know the string on the headlin... | ```python
n = int(input())
l = []
for i in range(n):
l.append(input())
l_sorted = sorted(list(set(l[0])))
ans =''
for ch in l_sorted:
cnt = min(l[i].count(ch) for i in range(n))
ans += ch * cnt
print(ans)
``` |
p03931 square869120Contest #3 - Solving XOR-Puzzles | Sample testcase 3 has a mistake, so we erased this case and rejudged all solutions of this problem. (21:01)
Snuke got a sequence $a$ of length $n$ from AtCoder company. All elements in $a$ are distinct.
He made a sequence $b$, but actually, he is not remembered it.
However, he is remembered a few things about sequence... | ```python
n, k = map(int, input().split())
*A, = map(int, input().split())
MOD = 10**9 + 7
C = {a for a in A}
n = len(C)
m = [[0]*256 for i in range(n+1)]
m[0][0] = 1
for c in C:
for i in range(n-1, -1, -1):
s = m[i]; t = m[i+1]
for j in range(256):
t[c^j] += s[j]
ans = 0
r = 1
for i ... |
p00024 Physical Experiments | Ignoring the air resistance, velocity of a freely falling object $v$ after $t$ seconds and its drop $y$ in $t$ seconds are represented by the following formulas:
$ v = 9.8 t $
$ y = 4.9 t^2 $
A person is trying to drop down a glass ball and check whether it will crack. Your task is to write a program to help this ex... | ```python
import math
while 1:
try:
print(math.ceil(float(input())**2/98)+1)
except:break
``` |
p00155 Spider Jin | The hero of justice, the Spider, can pull a rope out of his arm and jump from building to building. However, due to the short rope, you can only move to buildings that are less than 50 distances from you. To move to a building farther away, you have to jump to another building.
<image>
Create a program that inputs... | ```python
import heapq
def dijkstra(G, s, g, n):
cost = [10**9] * n
cost[s] = 0
pre = [-1] * n
q = []
heapq.heappush(q, (0, s))
while q:
d, to = heapq.heappop(q)
if to == g:
break
if cost[to] < d:
continue
for n, dist in G[to]:
... |
p00312 Frog Going Straight | A frog is about to return to the burrow. The burrow is D centimeters ahead of the frog, and the frog goes straight toward the burrow. There are only two actions that a frog can do:
* Large jump (go forward L centimeters)
* Small jump (go 1 cm forward)
The frog aims to just land in the burrow without jumping over it... | ```python
D,L = map(int,input().split())
print(D//L + D%L)
``` |
p00811 Calling Extraterrestrial Intelligence Again | A message from humans to extraterrestrial intelligence was sent through the Arecibo radio telescope in Puerto Rico on the afternoon of Saturday November l6, l974. The message consisted of l679 bits and was meant to be translated to a rectangular picture with 23 × 73 pixels. Since both 23 and 73 are prime numbers, 23 × ... | ```python
answer = []
def prime(n):
prime_flag = [0 for i in range(n + 1)]
prime_list = []
for i in range(2, n + 1):
if prime_flag[i] == 0:
prime_list.append(i)
temp = 1
while temp * i <= n:
prime_flag[temp * i] = 1
temp += 1
... |
p01075 One-Time Path | Problem
There are N islands and M bridges. Numbers from 1 to N are assigned to each of the N islands. Numbers from 1 to M are also assigned to each of the M bridges.
Gaccho is currently on the first island (at time 0). Gaccho can move from the ai-th island to the bi-th island in one direction by using the i-th bridge... | ```python
# AOJ 590: One-Time Path
# Python3 2018.7.13 bal4u
INF = 0x7fffffff
import heapq
def dijkstra(V, to, start):
dist = [INF]*V
Q = []
dist[start] = 0
heapq.heappush(Q, (0, start))
while Q:
t, s = heapq.heappop(Q)
if dist[s] < t: continue
for e, cost in to[s]:
if t <= cost and cost < dist[e]:
d... |
p01827 Black Company | Example
Input
3
1 3 3
2
1 2
1 3
Output
5 | ```python
from collections import deque
import sys
def main():
readline = sys.stdin.readline
write = sys.stdout.write
def root(x):
if x == p[x]:
return x
p[x] = y = root(p[x])
return y
def unite(x, y):
px = root(x)
py = root(y)
if px < py:
... |
p02249 Pattern Search | Find places where a R × C pattern is found within a H × W region. Print top-left coordinates (i, j) of sub-regions where the pattern found. The top-left and bottom-right coordinates of the region is (0, 0) and (H-1, W-1) respectively.
Constraints
* 1 ≤ H, W ≤ 1000
* 1 ≤ R, C ≤ 1000
* The input consists of alphabetica... | ```python
from typing import List
def calc_hash(tab: List[List[int]], row_num: int, col_num: int) -> None:
global hash_table, R, C, baes1, base2, mask
tmp_table = [[0] * col_num for _ in range(row_num)]
diff_row, diff_col = row_num - R, col_num - C
bit_mask = 1
for _ in range(C):
bit_mask... |
p02397 Swapping Two Numbers | Write a program which reads two integers x and y, and prints them in ascending order.
Constraints
* 0 ≤ x, y ≤ 10000
* the number of datasets ≤ 3000
Input
The input consists of multiple datasets. Each dataset consists of two integers x and y separated by a single space.
The input ends with two 0 (when both x and y... | ```python
while True:
ans = list(map(int, input().split()))
if ans[0] ==0 and ans[1] ==0:
break
print(*sorted(ans))
``` |
1038_C. Gambling | Two players A and B have a list of n integers each. They both want to maximize the subtraction between their score and their opponent's score.
In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an elem... | ```python
N = int(input())
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
arr1.sort()
arr2.sort()
max1 = N-1
max2 = N-1
A = 0
B = 0
turn = 0
while(max1>=0 or max2>=0):
if turn == 0:
if arr1[max1]>=arr2[max2]:
if max1>=0:
A+=arr1[max1]
max1-=1
else:
... |
1082_E. Increasing Frequency | You are given array a of length n. You can choose one segment [l, r] (1 ≤ l ≤ r ≤ n) and integer value k (positive, negative or even zero) and change a_l, a_{l + 1}, ..., a_r by k each (i.e. a_i := a_i + k for each l ≤ i ≤ r).
What is the maximum possible number of elements with value c that can be obtained after one ... | ```python
import sys
input=sys.stdin.readline
n,c=map(int,input().split())
ar=list(map(int,input().split()))
br=[]
count=0
for i in range(n):
if(ar[i]==c):
count+=1
br.append(count)
dic={}
for i in range(n):
if(ar[i]!=c):
if(ar[i] in dic):
dic[ar[i]].append(i)
else:
... |
1101_G. (Zero XOR Subset)-less | You are given an array a_1, a_2, ..., a_n of integer numbers.
Your task is to divide the array into the maximum number of segments in such a way that:
* each element is contained in exactly one segment;
* each segment contains at least one element;
* there doesn't exist a non-empty subset of segments such tha... | ```python
import sys
from math import *
from fractions import gcd
readints=lambda:map(int, input().strip('\n').split())
n=int(input())
arr = list(readints())
arr.sort()
pref=0
basis=[]
for v in arr:
pref = pref^v
for b in basis:
v = min(v, v^b)
if v>0:
basis.append(v)
if pref==0:
pr... |
1150_A. Stock Arbitraging | Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market!
In the morning, there are n opportunities to buy shares. The i-th of them allows to buy as many shares as you want, each at the price o... | ```python
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=list(map(int,input().split()))
m=a[2]//(min(b))
p=m*max(c)+a[2]%min(b)
if(p>=a[2]):
print(p)
else:
print(a[2])
``` |
1172_B. Nauuo and Circle | Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points o... | ```python
from math import *
from collections import *
import sys
sys.setrecursionlimit(10**9)
mod = 998244353
n = int(input())
a = [0 for i in range(n+1)]
ans = n
for i in range(n-1):
u,v = map(int,input().split())
a[u] += 1
a[v] += 1
ans *= a[u]
ans %= mod
ans *= a[v]
ans %= mod
print(ans%mod)
``` |
118_C. Fancy Number | A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old d... | ```python
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt'... |
1209_B. Koala and Lights | It is a holiday season, and Koala is decorating his house with cool lights! He owns n lights, all of which flash periodically.
After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters a_i and b_i. Light with parameters a_i and b_i will toggle (on to off, or off t... | ```python
import sys
input = sys.stdin.readline
n=int(input())
s=input().strip()
AB=[tuple(map(int,input().split())) for i in range(n)]
ANS=[[0]*n for i in range(3000)]
for i in range(n):
k=int(s[i])
a,b=AB[i]
t=0
while t<3000:
if t>=b and (t-b)%a==0:
k=1-k
... |
1228_A. Distinct Digits | You have two integers l and r. Find an integer x which satisfies the conditions below:
* l ≤ x ≤ r.
* All digits of x are different.
If there are multiple answers, print any of them.
Input
The first line contains two integers l and r (1 ≤ l ≤ r ≤ 10^{5}).
Output
If an answer exists, print any of them. Oth... | ```python
l, r =map(int, input().split())
for i in range(l,r+1):
n = 0
a = str(i)
for j in a:
if a.count(j) == 1:
n = n+1
else:
pass
if n == len(a):
break
if n == len(a):
print(a)
else:
print('-1')
``` |
1270_A. Card Game | Two players decided to play one interesting card game.
There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a... | ```python
T = int(input())
for _ in range(T) :
in_li = list(map(int,input().split()))
n = in_li[0]
k1 = in_li[1]
k2 = in_li[2]
one = list(map(int,input().split()))
two = list(map(int,input().split()))
max1 = max(one)
max2 = max(two)
count1 = 0
count2 = 0
for num in one :
... |
1312_F. Attack on Red Kingdom | The Red Kingdom is attacked by the White King and the Black King!
The Kingdom is guarded by n castles, the i-th castle is defended by a_i soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders.
Each day the White King launches an attack on one of the castles. Then, at night, the forces o... | ```python
T = int(input())
def findPeriod(DP):
for offset in range(0, len(DP)):
for period in range(1, 500):
is_period = True
for j in range(offset, len(DP) - period):
if (DP[j][0] == DP[j + period][0] and DP[j][1] == DP[j + period][1] and DP[j][2] == DP[j + period]... |
1335_C. Two Teams Composing | You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills).
So, about the teams. Firstly, these two teams should have the s... | ```python
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
d = {}
maxd = 0
for x in a:
d[x] = d.get(x, 0) + 1
if d[x] > maxd:
maxd = d[x]
print(max(min(len(d)-1, maxd), min(len(d), maxd-1)))
``` |
1355_E. Restorer Distance | You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pill... | ```python
#!/usr/bin/env python3
import io
import os
from bisect import bisect
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def get_str():
return input().decode().strip()
def rint():
return map(int, input().split())
def oint():
return int(input())
def find_lu_value(th):
hi = bisect(h, t... |
1375_D. Replace by MEX | You're given an array of n integers between 0 and n inclusive.
In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).
For example, if the current array is [0, 2, 2, 1, 4], you can choose the second element and replace it... | ```python
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" no... |
1422_C. Bargain | Sometimes it is not easy to come to an agreement in a bargain. Right now Sasha and Vova can't come to an agreement: Sasha names a price as high as possible, then Vova wants to remove as many digits from the price as possible. In more details, Sasha names some integer price n, Vova removes a non-empty substring of (cons... | ```python
s = [int(c) for c in input()][::-1]
n = len(s)
mod = 1000000007
def inv(x):
return pow(x, mod - 2, mod)
teninv = inv(10)
P = [0]
p = 1
for x in s:
P.append((P[-1] + x*p) % mod)
p = p*10 % mod
Q = [0]
for i in range(n+1):
Q.append((Q[-1] + P[i]*pow(teninv, i, mod))%mod)
s = 0
for l in rang... |
1440_B. Sum of Medians | A median of an array of integers of length n is the number standing on the ⌈ {n/2} ⌉ (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with 1. For example, a median of the array [2, 6, 4, 1, 3, 5] is equal to 3. There exist some other definitions of the median, but i... | ```python
for _ in range(int(input())):
n, k = map(int, input().split())
a = list(map(int, input().split()))
total = 0
a.reverse()
t=n-(n+1)//2+1
for i in range(1, k+1):
total += a[t*i-1]
print(total)
``` |
1467_C. Three Bags | You are given three bags. Each bag contains a non-empty multiset of numbers. You can perform a number of operations on these bags. In one operation, you can choose any two non-empty bags, and choose one number from each of the bags. Let's say that you choose number a from the first bag and number b from the second bag.... | ```python
n1,n2,n3=map(int,input().split())
val=[]
def func(a,b,c,d,e,f):
dd=d-a[0]
v1=b[0]-dd
ff=f-c[-1]
v2=a[0]-ff-(e-b[0])
if v1<0:
return (c[-1]-v1)-v2
else:
v2-=v1
return (c[-1]-v2)
one=(list(map(int,input().split())))
two=(list(map(int,input().split())))
three=(l... |
1514_C. Product 1 Modulo N | Now you get Baby Ehab's first words: "Given an integer n, find the longest subsequence of [1,2, …, n-1] whose product is 1 modulo n." Please solve the problem.
A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly all) elements. The product of an empty subsequence is equal ... | ```python
import math
n=int(input())
ans=[]
prod=1
count=0
for i in range(1,n-1):
if math.gcd(n,i)==1:
ans.append(str(i))
prod=(prod*i)%n
count+=1
if n==2:
print(1)
print(1)
else:
if prod % n == 1:
print(count)
print(" ".join(ans))
else:
print(count+1)
print(" ".join(ans),n-1)
``` |
1541_C. Great Graphs | Farmer John has a farm that consists of n pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is... | ```python
for _ in range(int(input())):
n=int(input())
d=list(map(int,input().split()))
d=sorted(d)
if(n==1):
print(d[n-1])
continue
l=[0]
for i in range(n-2,-1,-1):
l.append(d[i]-d[n-1])
c=n-1
S=sum(l)
ans=S
for i in range(n-2,0,-1):
dis=(d[i]-d[i... |
169_B. Replacing Digits | You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≤ j ≤ m) of sequence s means that you can choose an arbitrary position i (1 ≤ i ≤ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can par... | ```python
n = str(input())
s = str(input())
ref = 10 * [0]
for j in range(len(s)):
index = ord(s[j]) - 48
ref[index] += 1
for j in range(len(n)):
output = n[j]
num = ord(n[j]) - 48
for k in range(9, num, -1):
if ref[k] > 0:
output = str(k)
ref[k] -= 1
brea... |
212_E. IT Restaurants | Сity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right — the road network forms an undirected... | ```python
from sys import stdin
n=int(stdin.readline())
g=[[] for i in range(n)]
for _ in range(n-1):
x,y=map(int,stdin.readline().split())
x-=1
y-=1
g[x].append(y)
g[y].append(x)
subtree_size=[0]*n
stack=[[-1,0,0]]
ans=[]
while stack:
par,ver,state=stack.pop()
if state==0:
stack.append([par,ver,1])
... |
261_C. Maxim and Matrix | Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size (m + 1) × (m + 1):
<image>
Maxim asks you to count, how many numbers m (1 ≤ m ≤ n) are there, such that the sum of values in the cells in the row number m + 1 of the resulting matrix equals t.
Expression (x xor y... | ```python
n, t = map(int, input().split())
s = bin(n + 2)[2:]
l = len(s)
if t & (t - 1):
ans = 0
else:
t = t.bit_length()
f = [[0] * (l + 1) for i in range(l + 1)]
for i in range(l + 1):
f[i][0] = f[i][i] = 1
for j in range(1, i):
f[i][j] = f[i - 1][j - 1] + f[i - 1][j]
... |
285_C. Building Permutation | Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.
You have a sequence of integers a1, a2, ..., an. In on... | ```python
n = int(input())
nums = sorted(list(map(int, input().split())))
score = 0
for i in range(n):
score+=abs(nums[i]-i-1)
print(score)
``` |
30_C. Shooting Gallery | One warm and sunny day king Copa decided to visit the shooting gallery, located at the Central Park, and try to win the main prize — big pink plush panda. The king is not good at shooting, so he invited you to help him.
The shooting gallery is an infinite vertical plane with Cartesian coordinate system on it. The targ... | ```python
##########################################################
from collections import Counter
def nCk(n, k):
res = 1
for i in range(1, k + 1):
res = res * (n - i + 1) // i
return res
import math
inf=10**20
n=int(input())
c=[]
dp=[0]*(n+1)
for i in range(n):
x,y, t,p = map(float, input().s... |
333_A. Secrets | Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of oth... | ```python
import math
n = int(input())
a=1
while n%a==0:
a*=3
print(n//a +1)
``` |
356_A. Knight Tournament | Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tourname... | ```python
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.writ... |
3_C. Tic-tac-toe | Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3 × 3 grid (one player always draws crosses, the other — noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the g... | ```python
first_row = input()
second_row = input()
third_row = input()
c = 0
o = 0
for i in range(0,3):
if first_row[i] == 'X':
c = c + 1
elif first_row[i] == '0':
o = o + 1
for i in range(0,3):
if second_row[i] == 'X':
c = c + 1
elif second_row[i] == '0':
o = o + 1
for i... |
44_H. Phone Number | Alas, finding one's true love is not easy. Masha has been unsuccessful in that yet. Her friend Dasha told Masha about a way to determine the phone number of one's Prince Charming through arithmancy.
The phone number is divined like that. First one needs to write down one's own phone numbers. For example, let's suppos... | ```python
# import sys
# input=sys.stdin.readline
a=input()
dp=[]
for i in range(len(a)):
dp.append([0]*10)
for i in range(10):
dp[0][i]=1
for i in range(len(a)-1):
for j in range(10):
if dp[i][j]!=0:
c=(int(a[i+1])+j)//2
d=(int(a[i+1])+j+1)//2
if c!=d:
... |
471_D. MUH and Cube Walls | Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of di... | ```python
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
def main():
n,w=map(int,input().split())
if n<w:
print(0)
exit()
if w==1:
print(n)
exit()
arr=list(map(int,input().split()))
for i in range(n-1,0,-1):... |
51_C. Three Base Stations | The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point — the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to l... | ```python
n = int(input())
houses = sorted(set(map(int, input().split())))
if len(houses) <= 3:
print(0)
result = houses[:]
while len(result) < 3:
result.append(result[-1])
print('%.6f %.6f %.6f' % tuple(result))
import sys; sys.exit()
span = 0
left = 1
right = len(houses) - 2
#print(house... |
573_A. Bear and Poker | Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.
Each player can double his bid any number of times and triple his bid any number of ... | ```python
import sys
import math
import collections
import bisect
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
def get_string(): return sys.stdin.readline().strip()
for t in range(1):
n=int(input())
arr=get_list... |
616_B. Dinner with Emma | Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.
Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets a... | ```python
print(max([min(elm) for elm in [map(int, input().split()) for _ in range(int(input().split()[0]))]]))
``` |
635_C. XOR Equation | Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)?
Input
The first line of the input contains two integers s and x (2 ≤ s ≤ 1012, 0 ≤ x ≤ 1012), the sum and bitwise xor of the pair of positive integers, respectively.
Output
Print a s... | ```python
def solve(s, x):
d = (s - x)
if x << 1 & d or d%2 or d<0: return 0
return 2 ** (bin(x).count('1')) - (0 if d else 2)
s, x = map(int, input().split())
print(solve(s, x))
``` |
664_B. Rebus | You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds.
Input
The only line of the input contains a re... | ```python
s = input().split("=")
v = int(s[1])
qs = s[0].split()
pos =0
neg =0
if len(qs) > 0:
pos += 1
signs = []
for i in qs:
if i == '+':
pos+=1
signs.append(1)
else:
if i == '-':
neg +=1
signs.append(0)
if pos == 0 and neg == 0 and v == 0:
print("Possi... |
688_E. The Values You Can Make | Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is ci. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya.
Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Ar... | ```python
from sys import stdin,stdout
n,m=map(int,input().split())
s=[0]+list(map(int,stdin.readline().strip().split()))
dp=[[[False for i in range(m+1)] for j in range(m+1)] for k in range(2)]
dp[0][0][0]=True
cur=0
for i in range(1,n+1):
cur+=1
cur%=2
last=(cur+1)%2
for j in range(m+1):
for k... |
710_D. Two Arithmetic Progressions | You are given two arithmetic progressions: a1k + b1 and a2l + b2. Find the number of integers x such that L ≤ x ≤ R and x = a1k' + b1 = a2l' + b2, for some integers k', l' ≥ 0.
Input
The only line contains six integers a1, b1, a2, b2, L, R (0 < a1, a2 ≤ 2·109, - 2·109 ≤ b1, b2, L, R ≤ 2·109, L ≤ R).
Output
Print th... | ```python
import sys
import bisect
from bisect import bisect_left as lb
input_=lambda: sys.stdin.readline().strip("\r\n")
from math import log
from math import gcd
from math import atan2,acos
from random import randint
sa=lambda :input_()
sb=lambda:int(input_())
sc=lambda:input_().split()
sd=lambda:list(map(int,input_(... |
801_C. Voltage Keepsake | You have n devices that you want to use simultaneously.
The i-th device uses ai units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.
You have a si... | ```python
#!/usr/bin/env python3
from sys import stdin,stdout
from decimal import *
def ri():
return map(int, input().split())
#getcontext().prec = 100
n, p = ri()
p = Decimal(p)
a = [Decimal(0) for i in range(n)]
b = [Decimal(0) for i in range(n)]
ab = [[Decimal(0), Decimal(0)] for i in range(n)]
A = [Decimal(... |
847_E. Packmen | A game field is a strip of 1 × n square cells. In some cells there are Packmen, in some cells — asterisks, other cells are empty.
Packman can move to neighboring cell in 1 time unit. If there is an asterisk in the target cell then Packman eats it. Packman doesn't spend any time to eat an asterisk.
In the initial mome... | ```python
import bisect
n = int(input())
s = input()
packmans = []
stars = []
for i in range(n):
if s[i] == '*':
stars.append(i)
elif s[i] == 'P':
packmans.append(i)
if len(stars) == 0:
print(0)
exit()
def check(t):
first_to_eat = 0
for i in range(len(packmans)):
x = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.