Unnamed: 0 int64 0 999 | name stringlengths 9 60 | description stringlengths 168 5.26k | solution stringlengths 38 20.8k |
|---|---|---|---|
700 | 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... | 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. Peremeshchaem i ... |
701 | 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... | 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) |
702 | 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... | 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 |
703 | 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... | 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 x in p(a)... |
704 | 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... | n = int(input())+1
nword = str(n)
count = 1
while("8" not in nword):
n+=1
nword = str(n)
count += 1
print(count)
|
705 | 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 ... | #------------------------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.txt', 'w')... |
706 | 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... | 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, x2, y2, y... |
707 | 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... | 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 shift():
... |
708 | 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... | 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':'N'}
s3 = '... |
709 | 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... | 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)
|
710 | 702_C. Cellular Network | You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from t... | import bisect
import sys
EPS = sys.float_info.epsilon
LENGTH = 10
matrix = [[] for i in range(LENGTH)]
array = [0] * LENGTH
if __name__ == "__main__":
n, m = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
b = list(map(int, sys.stdin.readline().split()))
answe... |
711 | 724_D. Dense Subsequence | You are given a string s, consisting of lowercase English letters, and the integer m.
One should choose some symbols from the given string so that any contiguous subsegment of length m has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves.
Then one uses the chosen... | from collections import Counter
from string import ascii_lowercase as asc
m, s = int(input()), input()
g = Counter(s)
def solve(c):
p = 0
for q in ''.join(x if x >= c else ' ' for x in s).split():
i, j = 0, -1
while j + m < len(q):
j = q.rfind(c, j + 1, j + m + 1)
if j ... |
712 | 746_D. Green and Black Tea | Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black.
Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing... | n,k,a,b = [int(i) for i in input().split()]
check = False
if (a>b):
a,b = b,a
check = True
res = ""
cr = 1
cA = True
while (a > 0 or b > 0):
if (a==b):
break
#print(a,b)
if (cr==1):
if a <= b:
u = min(k, b - a)
b -= u
res += u * '1'
else:... |
713 | 769_D. k-Interesting Pairs Of Integers | Vasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if k = 2, the pair of integers x = 5 and y = 3 is k-interesting, because their binary representation x=101 and y=011 differs ... | from collections import defaultdict
n, k = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]
A_dict = defaultdict(int)
for i in A:
A_dict[i] += 1
def bitCount(x):
cur = 0
while x > 0:
if x % 2:
cur += 1
x //= 2
return cur
mask = []
for i in range(2**1... |
714 | 793_D. Presents in Bankopolis | Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.
The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lan... | import sys
from functools import lru_cache
input = sys.stdin.readline
# sys.setrecursionlimit(2 * 10**6)
def inpl():
return list(map(int, input().split()))
@lru_cache(maxsize=None)
def recur(v, s, e, k):
"""
vから初めて[s, e]の都市をk個まわる最小値は?
"""
if k == 0:
return 0
elif k > e - s + 1:
... |
715 | 814_A. An abandoned sentiment from past | A few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. Ever since, she tried to avoid contact with others, for fear that this secret might be noticed.
To get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long t... | def checker(L):
return all(x<y for x, y in zip(L, L[1:]))
R = lambda: map(int,input().split())
n, k = R()
a = list(R())
b = list(R())
b.sort(reverse=True)
for i in range(n):
if a[i] in b:
exit(print('No'))
if a[i] == 0:
a[i] = b[0]
del b[0]
print('No' if checker(a) else 'Yes')
|
716 | 83_A. Magical Array | Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.
Valera absolutel... | from collections import defaultdict
n = int(input())
arr = list(map(int,input().split()))
cur = arr[0]
cnt = 1
d = defaultdict(int)
for i in range(1,n):
if arr[i]==cur:
cnt+=1
else:
d[cnt]+=1
cur = arr[i]
cnt = 1
if cnt!=0:
d[cnt]+=1
ans = 0
for i in d:
freq = d[i]
cnt = (i*(i+1))//2
cnt = cnt*freq
ans+=... |
717 | 85_B. Embassy Queue | In an embassy of a well-known kingdom an electronic queue is organised. Every person who comes to the embassy, needs to make the following three actions: show the ID, pay money to the cashier and be fingerprinted. Besides, the actions should be performed in the given order.
For each action several separate windows are... | q = zip(map(int, input().split()), map(int, input().split()))
n = int(input())
c = list(map(int, input().split()))
d = c[:]
for k, t in q:
for i in range(min(k, n)): c[i] += t
for i in range(k, n): c[i] = max(c[i], c[i - k]) + t
print(max(c[i] - d[i] for i in range(n))) |
718 | 886_B. Vlad and Cafes | Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes h... | from sys import stdin as fin
# fin = open("tc173b.in", "r")
n = int(fin.readline())
# n, k = map(int, fin.readline().split())
arr = list(map(int, fin.readline().split()))
# s = fin.readline().rstrip()
s = dict()
for i in range(n):
x = arr[i]
s[x] = (i, x)
# print(tuple(s.items()))
print(min(s.items(), key=lam... |
719 | 909_B. Segments | You are given an integer N. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and N, inclusive; there will be <image> of them.
You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endp... | n=int(input())
print(((n//2)+1)*(n-(n//2))) |
720 | 1041_C. Coffee Break | Recently Monocarp got a job. His working day lasts exactly m minutes. During work, Monocarp wants to drink coffee at certain moments: there are n minutes a_1, a_2, ..., a_n, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute).
... | #Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
... |
721 | 1064_B. Equations of Mathematical Magic | Colossal! — exclaimed Hawk-nose. — A programmer! That's exactly what we are looking for.
Arkadi and Boris Strugatsky. Monday starts on Saturday
Reading the book "Equations of Mathematical Magic" Roman Oira-Oira and Cristobal Junta found an interesting equation: a - (a ⊕ x) - x = 0 for some given a, where ⊕ stands for... | def countSetBits(n):
if(n==0):
return(0)
else:
return((n&1)+countSetBits(n>>1))
t=int(input())
for _ in range(0,t):
a=int(input())
x=countSetBits(a)
print(pow(2,x))
|
722 | 1105_E. Helping Hiasat | Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.
Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequen... | import time
def find_max_clique(remain, size, max_, index, maxs):
# print(remain, size, max_)
result = max_
if size + len(remain) <= result:
# print('pruning (1)...')
return result
if not remain:
# print('trivial')
return size
while remain:
candidate = max(re... |
723 | 1133_A. Middle of the Contest | Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha... | s=input()
h1=int(s[:2])
m1=int(s[3:])
s=input()
h2=int(s[:2])
m2=int(s[3:])
#print(h1,m1,h2,m2)
m=(m2-m1)+(h2-h1)*60;
ma=(m1+m/2)%60;
ha=(h1+(m1+m/2)/60);
print('0'*(2-len(str(int(ha))))+str(int(ha))+':'+'0'*(2-len(str(int(ma))))+str(int(ma))) |
724 | 1153_D. Serval and Rooted Tree | Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before.
As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree.
A tree is a connected graph without cycles. A rooted tree has a special vertex ca... | R = lambda: map(int, input().split())
n = int(input())
fcs = [0] + list(R())
ps = [0, 0] + list(R())
cs = [1] * (n + 1)
for i in range(2, n + 1):
cs[ps[i]] = 0
nc = sum(cs) - 1
for i in range(n, 1, -1):
if fcs[ps[i]] == 0:
cs[ps[i]] += cs[i]
else:
if not cs[ps[i]]:
cs[ps[i]] = cs... |
725 | 1175_C. Electrification | At first, there was a legend related to the name of the problem, but now it's just a formal statement.
You are given n points a_1, a_2, ..., a_n on the OX axis. Now you are asked to find such an integer point x on OX axis that f_k(x) is minimal possible.
The function f_k(x) can be described in the following way:
... | def main():
inp = readnumbers()
ii = 0
T = inp[ii]
ii += 1
for _ in range(T):
n = inp[ii]
ii += 1
k = inp[ii]
ii += 1
a = inp[ii:ii+n]
ii += n
ans = min((a[i] - a[i - k], a[i]) for i in range(k, n))
sys.stdout.buffer.write... |
726 | 1231_E. Middle-Out | The problem was inspired by Pied Piper story. After a challenge from Hooli's compression competitor Nucleus, Richard pulled an all-nighter to invent a new approach to compression: middle-out.
You are given two strings s and t of the same length n. Their characters are numbered from 1 to n from left to right (i.e. from... | # your code goes here
t =int(input())
for h in range(t):
ans = 1000000000
n = int(input())
a = str(input())
b = str(input())
if sorted(a) != sorted(b):
ans = -1
else:
ans = 10000000000000
for i in range(n):
... |
727 | 1276_A. As Simple as One and Two | You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ... | t=int(input())
for _ in range(t):
answer=[]
s=input()
n=len(s)
i=0
while i<(n-2):
if s[i:i+3]=='one':
answer.append(i+2)
i+=3
elif s[i:i+3]=="two":
if (i+4)<n and s[i:i+5]=="twone":
answer.append(i+3)
i+=5
... |
728 | 131_B. Opposites Attract | Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≤ ti ≤ 10). Of course, one number can be assigned to any number of cust... | c=[0]*50
n=int(input())
a=[0]*2000001
a=[int(i) for i in input().split()]
for i in range(n):
c[int(a[i]+10)]+=1;
r=0
for i in range(10):
r+=int(c[int(i)]*c[int(20-i)])
r+=(c[10]*(c[10]-1))//2;
r=int(r)
print(r) |
729 | 1338_D. Nested Rubber Bands | You have a tree of n vertices. You are going to convert this tree into n rubber bands on infinitely large plane. Conversion rule follows:
* For every pair of vertices a and b, rubber bands a and b should intersect if and only if there is an edge exists between a and b in the tree.
* Shape of rubber bands must be ... | import os
import sys
input = sys.stdin.buffer.readline
#sys.setrecursionlimit(int(3e5))
from collections import deque
from queue import PriorityQueue
import math
import copy
# list(map(int, input().split()))
#####################################################################################
class CF(object):
... |
730 | 1360_C. Similar Pairs | We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not.
You are given an array a of n (n is even) positive in... | for i in range(int(input())):
k=int(input())
a=list(map(int,input().split()))
a.sort()
c,d=0,0
i=1
e=0
for j in range(len(a)):
if(a[j]%2==0):
c+=1
else:
d+=1
if(c%2==0 and d%2==0):
print("YES")
else:
c,d=0,0
while(i<len(... |
731 | 1380_D. Berserk And Fireball | There are n warriors in a row. The power of the i-th warrior is a_i. All powers are pairwise distinct.
You have two types of spells which you may cast:
1. Fireball: you spend x mana and destroy exactly k consecutive warriors;
2. Berserk: you spend y mana, choose two consecutive warriors, and the warrior with gr... | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.wr... |
732 | 1469_F. Power Sockets | // We decided to drop the legend about the power sockets but feel free to come up with your own :^)
Define a chain:
* a chain of length 1 is a single vertex;
* a chain of length x is a chain of length x-1 with a new vertex connected to the end of it with a single edge.
You are given n chains of lengths l_1,... | import sys
input = sys.stdin.readline
import math
n, k = map(int, input().split())
B = sorted(map(int, input().split()), reverse=True)
N = 5 * (n + max(B))
A = [0] * N
A[0] = 1
A[1] = -1
ans = float("inf")
total = 0
j = 0
for i in range(N - 1):
total += A[i]
A[i + 1] += A[i]
if total + A[i + 1] >= k:
... |
733 | 1495_B. Let's Go Hiking | On a weekend, Qingshan suggests that she and her friend Daniel go hiking. Unfortunately, they are busy high school students, so they can only go hiking on scratch paper.
A permutation p is written from left to right on the paper. First Qingshan chooses an integer index x (1≤ x≤ n) and tells it to Daniel. After that, D... | def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
... |
734 | 1517_G. Starry Night Camping | At the foot of Liyushan Mountain, n tents will be carefully arranged to provide accommodation for those who are willing to experience the joy of approaching nature, the tranquility of the night, and the bright starry sky.
The i-th tent is located at the point of (x_i, y_i) and has a weight of w_i. A tent is important ... | import sys,io,os
try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
except:Z=lambda:sys.stdin.readline().encode()
Y=lambda:map(int,Z().split())
INF=float("inf");big=10**13
class D:
def __init__(self, n):
self.lvl = [0] * n
self.ptr = [0] * n
self.q = [0] * n
self.adj = [[] for... |
735 | 193_A. Cutting Figure | You've gotten an n × m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two s... | def add(vertex,neighbour):
if vertex in graph:
graph[vertex].append(neighbour)
else:
graph[vertex]=[neighbour]
if neighbour in graph: #####for undirected part remove to get directed
graph[neighbour].append(vertex)
else:
graph[neighbour]=[vertex]
def dfs(graph,n,currn... |
736 | 217_A. Ice Skating | Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves... | n = int(input())
g = []
for i in range(n):
t = input().split()
g.append([ int(t[0]), int(t[1]), False ])
def visita(i):
g[i][2] = True
for j in range(n):
if g[j][2] == False and (g[i][0] == g[j][0] or g[i][1] == g[j][1]):
visita(j)
cnt = -1
for i in range(n):
if g[i][2] == Fals... |
737 | 240_A. Cinema | Overall there are m actors in Berland. Each actor has a personal identifier — an integer from 1 to m (distinct actors have distinct identifiers). Vasya likes to watch Berland movies with Berland actors, and he has k favorite actors. He watched the movie trailers for the next month and wrote the following information fo... | import sys
try:
sys.stdin = open('input.txt')
sys.stdout = open('output.txt', 'w')
except:
pass
def compl(n, s):
return set(filter(lambda x: x not in s, range(1, n + 1)))
m, k = list(map(int, input().split()))
id = list(map(int, input().split()))
n = int(input())
favorite = set(id)
... |
738 | 265_D. Good Sequences | Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.
Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:
* The sequence is strictly increasing, i.e. xi < xi + 1 f... | # Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
def seieve_prime_factorisation(n):
p, i = [1] * (n + 1), 2
while i * i <= n:
if p[i] == 1:
for j in range(i * i, n + 1, i):
p[j]... |
739 | 289_D. Polo the Penguin and Houses | Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a hou... | MOD = 10 ** 9 + 7
n, k = map(int, input().split())
ans = pow(n - k, n - k, MOD) * pow(k, k - 1, MOD)
print(ans % MOD) |
740 | 337_A. Puzzles | The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | n,m = map(int,input().split())
f = list(map(int,input().split()))
f.sort()
a = []
for i in range(m-n+1):
a.append(f[i+n-1]-f[i])
print(min(a))
|
741 | 35_C. Fire Again | After a terrifying forest fire in Berland a forest rebirth program was carried out. Due to it N rows with M trees each were planted and the rows were so neat that one could map it on a system of coordinates so that the j-th tree in the i-th row would have the coordinates of (i, j). However a terrible thing happened and... | '''
___ ____
____ _____ _____/ (_)_ ______ ____ _____/ / /_ __ ______ ___ __
/ __ `/ __ `/ __ / / / / / __ \/ __ `/ __ / __ \/ / / / __ `/ / / /
/ /_/ / /_/ / /_/ / / /_/ / /_/ / /_/ / /_/ / / / / /_/ / /_/ / /_/ /
\__,_/\__,_/\__,_/_/\__,_/ .___/\__... |
742 | 383_A. Milking cows | Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of mi... | #! usr/bin/env python3
# coding:UTF-8
# wdnmd UKE
# wcnm UKE
ans = 0
cnt = 0
N = input()
t = input().split()
for i in t:
if(int(i) == 1):
cnt += 1
else:
ans += cnt
print(ans)
|
743 | 431_A. Black Square | Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | #!/usr/bin/env python3
a=list(map(int,input().split()))
s=input()
print(a[0]*s.count('1') + a[1]*s.count('2') + a[2]*s.count('3') + a[3]*s.count('4'))
|
744 | 453_C. Little Pony and Summer Sun Celebration | Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration.
<im... | import sys
readline = sys.stdin.readline
N, M = map(int, readline().split())
Edge = [[] for _ in range(N)]
for _ in range(M):
u, v = map(int, readline().split())
u -= 1
v -= 1
Edge[u].append(v)
Edge[v].append(u)
Pr = list(map(int, readline().split()))
Po = Pr[:]
if sum(Pr) == 0:
print(0)
else:... |
745 | 476_A. Dreamoon and Stairs | Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
Input
The single line contains two space separated i... | n,m = map(int, input().split())
if n < m:
print(-1)
else:
if n % 2 == 0:
b = n//2
else:
b = (n//2)+1
while b % m != 0:
b = b + 1
print(b) |
746 | 49_B. Sum | Vasya studies positional numeral systems. Unfortunately, he often forgets to write the base of notation in which the expression is written. Once he saw a note in his notebook saying a + b = ?, and that the base of the positional notation wasn’t written anywhere. Now Vasya has to choose a base p and regard the expressio... | a,b=list(map(int,input().split()))
k=int(max(str(a)+str(b)))+1
carry=0
l=max(len(str(a)),len(str(b)))
for itr in range(l):
if a%10+b%10+carry<k: carry=0
else: carry=1
a//=10
b//=10
#print(a,b)
if carry: print(l+1)
else: print(l) |
747 | 523_D. Statistics of Recompressing Videos | A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one ... | import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
def main():
import heapq
n, k = [int(i) for i in i... |
748 | 54_B. Cutting Jigsaw Puzzle | The Hedgehog recently remembered one of his favorite childhood activities, — solving puzzles, and got into it with new vigor. He would sit day in, day out with his friend buried into thousands of tiny pieces of the picture, looking for the required items one by one.
Soon the Hedgehog came up with a brilliant idea: ins... | def rotate(puzzle):
n_puzzle = []
for y in range(len(puzzle) - 1, -1, -1):
n_puzzle.append(puzzle[y])
result = []
for x in range(len(puzzle[0])):
col = []
for y in range(len(puzzle)):
col.append(n_puzzle[y][x])
result.append(col)
return result
def puzzle... |
749 | 599_A. Patrick and Shopping | Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ... | d=list(map(int,input().split()))
d.sort()
print(min(d[0]*2+d[1]*2,d[0]+d[1]+d[2])) |
750 | 61_E. Enemy is weak | The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep".
Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number.
In Shapur's opinion the weaknes... | from sys import stdin
class order_tree:
def __init__(self, n):
self.tree, self.n = [[0, 0] for _ in range(n << 1)], n
# get interval[l,r)
def query(self, r, col):
res = 0
l = self.n
r += self.n
while l < r:
if l & 1:
res += self.tree[l]... |
751 | 669_B. Little Artem and Grasshopper | Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grassh... | # python3
# utf-8
field_size = int(input())
field_idx___dir = input()
field_idx___jump_len = [int(x) for x in input().split()]
field_idx___was_visited = [False for x in range(field_size)]
curr_field_idx = 0
while 0 <= curr_field_idx < field_size:
if field_idx___was_visited[curr_field_idx]:
print('INFINIT... |
752 | 690_D2. The Wall (medium) | Heidi the Cow is aghast: cracks in the northern Wall? Zombies gathering outside, forming groups, preparing their assault? This must not happen! Quickly, she fetches her HC2 (Handbook of Crazy Constructions) and looks for the right chapter:
How to build a wall:
1. Take a set of bricks.
2. Select one of the possibl... | result=0
mod=10**6 +3
n,C=map(int,input().split()) #recibimos la entrada
#calc n!
def fact(n):
fact=1
for i in range(1,n+1): #1*2*3*...*n = n*(n-1)*(n-2)...*1
fact=(fact*i)%mod #
return fact
def pow(a,b): #Algoritmo de Exponenciacion binaria
exp=1 # Caso base a^1=a
x=a % mod
b=b%(mod-1... |
753 | 735_A. Ostap and Grasshopper | On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length n such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The gras... | n,k=[int(x) for x in input().split()]
s=input()
if s.index('G')>s.index('T'):s=s[::-1]
x=s.index('G')
for i in range(x,n):
x+=k
if x>n-1 or s[x]=='#':print("NO");break
elif s[x]=='T':print("YES");break |
754 | 75_A. Life Without Zeros | Can you imagine our life if we removed all zeros from it? For sure we will have many problems.
In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a... | a = input ()
b = input ()
c = str (int (a) + int (b))
a = a.replace ("0", "")
b = b.replace ("0", "")
c = c.replace ("0", "")
if int (a) + int (b) == int (c):
print ("YES")
else:
print ("NO") |
755 | 77_E. Martian Food | Have you ever tasted Martian food? Well, you should.
Their signature dish is served on a completely black plate with the radius of R, flat as a pancake.
First, they put a perfectly circular portion of the Golden Honduras on the plate. It has the radius of r and is located as close to the edge of the plate as possible... | #!/usr/bin/env python3
def solve(R,r,k):
# Thanks to Numberphile's "Epic circles" video
# Use the formula for radii of circles in Pappus chain
r = r / R
n = k
answer = ((1-r)*r)/(2*((n**2)*((1-r)**2)+r))
# Note that in a Pappus chain the diameter of the circle is 1, so we need to scale up:
answer = 2*R *... |
756 | 803_D. Magazine Ad | The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:
There are space-separated non-empty words of lowercase and uppercase Latin letters.
There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more th... | def f(r):
prev, ofs = -1, -1
s = list()
while True:
try:
ofs = r.index(' ', ofs + 1)
except ValueError:
s.append(len(r) - 1 - prev)
return s
s.append(ofs - prev)
prev = ofs
n = int(input())
s = f(input().replace('-', ' '))
def can(w):
c... |
757 | 828_B. Black Square | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.
You are to determine the minimum possible ... | h,l=[int(i) for i in input().split()]
a=[]
for i in range(h):
a.append(list(input()))
left,right,down,up=[l-1,0,0,h-1]
gg=True
for i in range(h):
for j in range(l):
if a[i][j]=='B':
gg=False
if i<up: up=i
if i>down: down=i
if j>right: right=j
i... |
758 | 84_C. Biathlon | Perhaps many have heard that the World Biathlon Championship has finished. Although our hero Valera was not present at this spectacular event himself and only watched it on TV, it excited him so much that he decided to enroll in a biathlon section.
Of course, biathlon as any sport, proved very difficult in practice. I... | def main():
from array import array
from bisect import bisect
from sys import stdin
input = stdin.readline
O = -1
n = int(input())
xr = []
for i in range(n):
xi, ri = map(int, input().split())
xr.append((xi, ri ** 2, i))
xr.sort()
cur = 1
res1 = 0
res2 = a... |
759 | 898_E. Squares and not squares | Ann and Borya have n piles with candies and n is even number. There are ai candies in pile with number i.
Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new ... | n=int(input())
p=[]
m=list(map(int,input().split()))
from math import floor,ceil
for i in m:
if i**0.5%1==0:
p.append(0)
else:
p.append(min(i-floor(i**0.5)**2,ceil(i**0.5)**2-i))
a=p.count(0)
am=m.count(0)
if n//2<=a:
x=a-n//2
dif=a-am
if dif >= x:
print(x)
else:
... |
760 | 946_E. Largest Beautiful Number | Yes, that's another problem with definition of "beautiful" numbers.
Let's call a positive integer x beautiful if its decimal representation without leading zeroes contains even number of digits, and there exists a permutation of this representation which is palindromic. For example, 4242 is a beautiful number, since i... | import sys
t = int(sys.stdin.buffer.readline().decode('utf-8'))
ans = ['']*t
for _ in range(t):
a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').rstrip()))
n = len(a)
parity = [0]*10
for x in a:
parity[x] ^= 1
psum = sum(parity)
for i, free in zip(range(n-1, -1, -1), rang... |
761 | 975_C. Valhalla Siege | Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.
Ivar has n warriors, he places them on a straight line in front of the main gate, in a way that the i-th warrior stands right after (i-1)-th warrior. The fir... | import bisect
n,q=map(int,input().split())
a=list(map(int,input().split()))
s=[0,]
for i in a:
s.append(s[-1]+i)
k=list(map(int,input().split()))
tb=0
for i in range(q):
tb+=k[i]
if tb>=s[-1]:
tb=0
print(n)
else:
ans=bisect.bisect_right(s,tb)
print(n-ans+1)
|
762 | 995_B. Suit and Tie | Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture m... | input()
a=list(map(int,input().split()))
cnt=0
while a:
i=a.index(a.pop(0))
cnt+=i
a.pop(i)
print(cnt) |
763 | 1009_D. Relatively Prime Graph | Let's call an undirected graph G = (V, E) relatively prime if and only if for each edge (v, u) ∈ E GCD(v, u) = 1 (the greatest common divisor of v and u is 1). If there is no edge between some pair of vertices v and u then the value of GCD(v, u) doesn't matter. The vertices are numbered from 1 to |V|.
Construct a rela... | from math import gcd
from itertools import islice
def get_all(n):
for i in range(1, n+1):
for j in range(i+1, n+1):
if gcd(i, j) == 1: yield i, j
def solve(n, m):
x = list(islice(get_all(n), m))
if len(x) == m >= n - 1:
return x
res = solve(*map(int, input().split()))
if res is... |
764 | 1032_A. Kitchen Utensils | The king's birthday dinner was attended by k guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.
All types of utensils in the kingdom are numbered from 1 to 100.... | import math
n, k = map(int, input().split())
a = [int(t) for t in input().split()]
d = {}
for i in a:
if d.get(i) is None:
d[i] = 0
d[i] += 1
print(math.ceil(max(d.values()) / k) * len(d.keys()) * k - n) |
765 | 1145_D. Pigeon d'Or | From "ftying rats" to urban saniwation workers - can synthetic biology tronsform how we think of pigeons?
The upiquitous pigeon has long been viewed as vermin - spleading disease, scavenging through trush, and defecating in populous urban spases. Yet they are product of selextive breeding for purposes as diverse as r... | n = int(input())
a = list(map(int, input().split()))
print(2+(min(a)^a[2])) |
766 | 1166_C. A Tale of Two Lands | The legend of the foundation of Vectorland talks of two integers x and y. Centuries ago, the array king placed two markers at points |x| and |y| on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at poin... | num = int(input())
data = [abs(int(i)) for i in input().split()]
data.sort()
def bins(a, b, n):
if a == b:
if data[a] <= n:
return a+1
else:
return a
else:
m = (a+b)//2
if data[m] <= n:
return bins(m+1,b,n)
else:
return bi... |
767 | 1185_A. Ropewalkers | Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad.
The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performa... | a, b, c, d = map(int, input().split())
a, b, c = sorted([a, b, c])
def solve1(a, b, c):
r1 = max(0, d-(b-a))
b += r1
r2 = max(0, d-(c-b))
return r1+r2
def solve2(a, b, c):
r1 = max(0, d-(c-b))
r2 = max(0, d-(b-a))
return r1+r2
def solve3(a, b, c):
r1 = max(0, d-(c-b))
b -= r1
r2... |
768 | 1203_E. Boxers | There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.
It is necessary to choose the largest boxing team in terms of the number o... | N = int(input())
A = sorted([int(a) for a in input().split()])
k = 0
ans = 0
for i in range(N):
if k > A[i]:
pass
elif k >= A[i] - 1:
ans += 1
k += 1
else:
ans += 1
k = A[i] - 1
print(ans)
|
769 | 1220_C. Substring Game in the Lesson | Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string s and a number k (0 ≤ k < |s|).
At the beginning of the game, players are given a substring of s with left border l and right border r, both equal to k ... | s = input().rstrip()
minimum = "z"
for ch in s:
if ch > minimum:
print("Ann")
else:
print("Mike")
minimum = ch |
770 | 1265_C. Beautiful Regional Contest | So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 ≥ p_2 ≥ ... ≥ p_n.
Help the jury distrib... | def func(a, total):
d = {}
temp = total
for no in a:
if total - 1 >= 0:
total -= 1
if no in d:
d[no] += 1
else:
d[no] = 1
else:
if no in d:
del d[no]
break
if len(d) < 3:
r... |
771 | 134_B. Pairs of Numbers | Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.
Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n... | import sys
def solve():
n = int(input())
if n == 1: return 0
res = 1000000
for other in range(n - 1, 0, -1):
pair = [n, other]
temp = 0
while (pair[0] > 1 or pair[1] > 1) and (pair[0] > 0 and pair[1] > 0):
pair.sort()
multiples = (pair[1] - 1) // pair[0]
... |
772 | 1417_C. k-Amazing Numbers | You are given an array a consisting of n integers numbered from 1 to n.
Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there i... | 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.write = self.buffer.write if self.wri... |
773 | 1434_A. Perform Easily | After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has 6 strings and an infinite number of frets numbered from 1. Fretting the fret number j on the i-th string produces the note a_{i} + j.
Tayuya wants to play a melody of n notes. Each note can be play... | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.wri... |
774 | 1485_A. Add and Divide | You have two positive integers a and b.
You can perform two kinds of operations:
* a = ⌊ a/b ⌋ (replace a with the integer part of the division between a and b)
* b=b+1 (increase b by 1)
Find the minimum number of operations required to make a=0.
Input
The first line contains a single integer t (1 ≤ t ≤ 10... | def incre(a,b):
flag=0
if a//b==0:
return 1
if b==1:
b+=1
flag=1
tb=b
ans=float("inf")
if a//b==0:
return 1+flag
while b<=a:
ta=a
cnt=b-tb
while ta:
ta//=b
cnt+=1
b+=1
if ans<cnt:
return ans+flag
ans=min(ans,cnt)
return ans+flag
for i in range(int(input())):
a,b=map(int,input().st... |
775 | 1535_C. Unstable String | You are given a string s consisting of the characters 0, 1, and ?.
Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...).
Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can... | for s in[*open(0)][1:]:
r=p=i=j=k=0
for x in s[:-1]:
i+=1;x=ord(x)^i&1
if x<50:k=(k,j)[p!=x];p=x;j=i
r+=i-k
print(r) |
776 | 182_B. Vasya's Calendar | Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present — the clock that shows not only the time, but also the date.
The clock's face can display any number from 1 to d. It is guaranteed that ai ≤ d for all i from 1 to n. The clock does not keep information ab... | d = int(input())
n = int(input())
months = list(map(int, input().split()))
changes = 0
for month in months[:-1]:
changes += d - month
print(changes)
|
777 | 205_D. Little Elephant and Cards | The Little Elephant loves to play with color cards.
He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks... | def solve():
n = int(input())
cards = []
cnt = {}
for i in range(n):
card = tuple(map(int, input().split(' ')))
cards.append(card)
cnt[card[0]] = [0, 0]
cnt[card[1]] = [0, 0]
for card in cards:
if card[0] != card[1]:
cnt[card[0]][0] += 1
... |
778 | 255_B. Code Parsing | Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime:
1. Find two consecutive characters in the string, such that the first of them equals "y", and the s... | from sys import stdin,stdout
import bisect as bs
nmbr = lambda: int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
for _ in range(1):#nmbr()):
s=input()
n=len(s)
x=s.count('x')
y=n-x
if y>=x:
for i in range(y-x):
stdout.write('y')
else:
for i ... |
779 | 279_B. Books | When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ... | import bisect
n,t=list(map(int,input().split()))
a=list(map(int,input().rstrip().split()))
b=[0]
sol=0
for i in range(n):
b.append(b[-1]+a[i])
b.pop(0)
for i in range(n):
sol=max(sol,bisect.bisect_right(b,t)-i)
t+=a[i]
print(sol)
|
780 | 301_A. Yaroslav and Sequence | Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.
Yaroslav is now wondering: what maximum sum of array elements c... | #!/usr/bin/python3
n = int(input())
data = list(map(int, input().split()))
negative, zero, positive = 0, 0, 0
for element in data:
if element < 0:
negative += 1
elif element == 0:
zero += 1
else:
positive += 1
seen = {}
min_negative = negative
def go(negative, positive):
glob... |
781 | 327_D. Block Tower | After too much playing on paper, Iahub has switched to computer games. The game he plays is called "Block Towers". It is played in a rectangular grid with n rows and m columns (it contains n × m cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build any bui... | #Connected component
import sys
from collections import deque
sys.setrecursionlimit(501 * 501)
n,m = [int(i) for i in input().split()]
a=[[0 for i in range(m)] for i in range(n)]
d=[(0,1),(0,-1),(1,0),(-1,0)]
q=deque()
def main():
global a
ans=[]
first=[]
q=deque()
for i in range(n):
l... |
782 | 373_A. Collecting Beats is Fun | Cucumber boy is fan of Kyubeat, a famous music game.
Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel.
Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his... | n = int(input())
memo = {}
for _ in range(4):
s = input()
for i in s:
if i != '.':
if i not in memo:
memo[i] = 1
else:
memo[i] += 1
res = True
for k, v in memo.items():
if v > n*2:
res = False
if res:
print("YES")
else:
pri... |
783 | 466_C. Number of Ways | You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.
More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that <image>... | def NoW(xs):
if sum(xs) % 3 != 0:
return 0
else:
part = sum(xs) // 3
ci = ret = 0
acum = xs[0]
for i, x in enumerate(xs[1:]):
if acum == 2*part:
# print("2. x=",x)
ret += ci
if acum == part:
# print("... |
784 | 48_A. Rock-paper-scissors | Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obvio... | I = lambda: int(input())
IL = lambda: list(map(int, input().split()))
L = [input()[0] for i in '123']
gt = {'r': 'rp', 'p': 'ps', 's': 'sr'}
print('F' if L[1] not in gt[L[0]] and L[2] not in gt[L[0]] else
'M' if L[0] not in gt[L[1]] and L[2] not in gt[L[1]] else
'S' if L[0] not in gt[L[2]] and L[1] not in... |
785 | 567_A. Lineland Mail | All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec... | n = int(input())
a = [int(i) for i in input().split()]
for i in range(n):
print(min(abs(a[i]-a[(i+1)%n]), abs(a[i]-a[i-1])), max(abs(a[i]-a[0]), abs(a[i]-a[-1]))) |
786 | 588_C. Duff and Weight Lifting | Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimi... | from collections import *
import sys
import math
from functools import reduce
def factors(n):
return set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
def li():return [int(i) for i in input().rstrip('\n').split(' ')]
def st():return input().rstrip('\n')
def val():return i... |
787 | 60_E. Mushroom Gnomes | Once upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighbori... | #!/usr/bin/pypy3
from sys import stdin, stdout
input, print = stdin.readline, stdout.write
p = 0
def readints():
return list(map(int, input().split()))
def writeln(x):
print(str(x) + '\n')
def mod(x):
return (x % p + p) % p
def matmul(a, b):
n = len(a)
c = [[0 for x in range(n)] for y in range(n... |
788 | 681_D. Gifts by the List | Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.
Each man has at most one father but may have arbitrary number of sons.
Man number A is considered to b... | # [https://codeforces.com/contest/681/submission/37694242 <- https://codeforces.com/contest/681/status/D <- https://codeforces.com/contest/681 <- https://codeforces.com/blog/entry/45425 <- https://codeforces.com/problemset/problem/681/D <- https://algoprog.ru/material/pc681pD]
(n, m) = map(int, input().split())
adj = ... |
789 | 727_A. Transformation: from A to B | Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations:
* multiply the current number by 2 (that is, replace the number x by 2·x);
* append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1).
You need to help Vasil... | n, target = map(int, input().split())
def keep(target, ans):
#print(target)
while target % 2 == 0:
target = target // 2
ans = [target]+ans
if str(target).endswith("1") and target != 1:
return keep((target-1) // 10, [(target-1) // 10]+ans)
else:
return target, ans
next,... |
790 | 771_A. Bear and Friendship Condition | Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that membe... | n,m = map(int,input().split())
dic = {}
edges = []
from collections import Counter
def find(node):
tmp = node
while node!=dic[node]:
node = dic[node]
while tmp!=dic[tmp]:
dic[tmp],tmp=node,dic[tmp]
return node
for _ in range(m):
p1,p2 = map(int,input().split())
dic.setdefault(p1,... |
791 | 796_A. Buying A House | Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us.
<image>
The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: hou... | def main():
n, m, k = map(int, input().split())
m -= 1
a = list(map(int, input().split()))
min_dist = n
for i, ai in enumerate(a):
if ai != 0 and ai <= k:
min_dist = min(min_dist, abs(i - m))
print(min_dist * 10)
if __name__ == '__main__':
# import sys
# sys.stdin... |
792 | 816_B. Karen and Coffee | To stay woke and attentive during classes, Karen needs some coffee!
<image>
Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".
She knows n ... | ranges, maps, strs = range, map, str
fout = ""
count = 0
n, k, q = maps(int, input().split())
rangeArr = []
for i in ranges(200002):
rangeArr.append(0)
for recipe in ranges(n):
left, right = maps(int, input().split())
rangeArr[left] += 1
rangeArr[right + 1] -= 1
for recipe in ranges(1, len(rangeArr)):
rangeA... |
793 | 841_B. Godsend | Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts a... | input()
for t in input().split():
if int(t) % 2:
print("First")
break
else:
print("Second") |
794 | 862_C. Mahmoud and Ehab and the xor | Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to f... | n, x = map(int, input().split())
if (n == 2 and x == 0):
print("NO")
quit()
a = 2**17
b = 2**18
ans = 0
print("YES")
if(n == 1):
print(x)
quit()
if (n == 2):
print(x, 0)
quit()
for i in range(n-3):
print(i+1, end = " ")
ans = (ans ^ (i+1))
if (ans == x):
print(b, a, a+b)
else:
pr... |
795 | 888_A. Local Extrema | You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have ... | n = int(input())
arr = [int(x) for x in input().split()]
cnt = 0
for i in range(1,n-1):
if arr[i]< arr[i-1] and arr[i] < arr[i+1]:cnt += 1
else:
if arr[i]> arr[i-1] and arr[i] > arr[i+ 1]:
cnt += 1
print(cnt) |
796 | 910_B. Door Frames | Petya has equal wooden bars of length n. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length a and one top side of length b. A solid (i.e. continuous without breaks) piece of bar is needed for each side.
Determine a minimal number of wooden bars which are needed t... | n = int(input())
a = int(input())
b = int(input())
ans = 6
cnt = 0
cur = 2
cnt += 2 * ((n - b) // a)
while cnt < 4:
cur += 1
cnt += (n // a)
ans = min(ans, cur)
if b * 2 <= n:
cur, cnt = 0, 0
cur = 1
cnt += ((n - 2 * b) // a)
while cnt < 4:
cur += 1
cnt += (n // a)
ans = min(... |
797 | 959_E. Mahmoud and Ehab and the xor-MST | Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of n vertices numbered from 0 to n - 1. For all 0 ≤ u < v < n, vertex u and vertex v are connected with an undirected edge that has weight <image> (where <image> is t... | import math
n = int(input())
ans = 0
cur = 1
while cur < n:
cnt = math.ceil((n-cur)/(cur << 1))
ans += cnt*cur
cur <<= 1
print(ans)
|
798 | 986_C. AND Graph | You are given a set of size m with integer elements between 0 and 2^{n}-1 inclusive. Let's build an undirected graph on these integers in the following way: connect two integers x and y with an edge if and only if x \& y = 0. Here \& is the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). C... | n, m = map(int, input().split())
a = set(map(int, input().split()))
y = 2 ** n
mk = [0] * (2 * y)
cur = 0
for x in a:
if mk[x]: continue
mk[x] = 1
st = [x]
def push(v):
if not mk[v]: mk[v] = 1; st.append(v)
while st:
u = st.pop()
if u < y:
push(y + u)
els... |
799 | 1006_F. Xor-Paths | There is a rectangular grid of size n × m. Each cell has a number written on it; the number on the cell (i, j) is a_{i, j}. Your task is to calculate the number of paths from the upper-left cell (1, 1) to the bottom-right cell (n, m) meeting the following constraints:
* You can move to the right or to the bottom onl... | from collections import*
n, m, k = map(int, input().split())
b = [[int(v) for v in input().split()] for _ in range(n)]
if m < n:
a = [[b[j][i] for j in range(n)] for i in range(m)]
b = a
m, n = n, m
cntrs = [Counter() for _ in range(n)]
d = (n + m-1) // 2
for i in range(1<<d):
ones = bin(i).count('1')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.