Unnamed: 0 int64 0 999 | name stringlengths 9 60 | description stringlengths 168 5.26k | solution stringlengths 38 20.8k |
|---|---|---|---|
600 | 1538_C. Number of Pairs | You are given an array a of n integers. Find the number of pairs (i, j) (1 β€ i < j β€ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l β€ a_i + a_j β€ r).
For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable:
* i=1 and j=2 (4 β€ 5 + 1 β€ 7... | # Author: Javier BΓ³rquez
import os
import sys
import bisect
def main():
fastReadInt = sys.stdin.buffer.readline
def fastReadStr(): return sys.stdin.buffer.readline().decode('utf-8').strip()
def fastWrite(ans): return sys.stdout.buffer.write(str(str(ans) + "\n").encode('utf-8'))
def fastWriteList(ans): return ... |
601 | 231_E. Cactus | A connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle.
A simple cycle in a undirected graph is a sequence of distinct vertices v1, v2, ..., vt (t > 2), such that for any i (1 β€ i < t) exists an edge between vertices vi and vi + 1, and also exists an ed... | from collections import defaultdict
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self... |
602 | 257_D. Sum | Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai β€ ai + 1 β€ 2Β·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will ge... | #!/usr/bin/python3
n = int(input())
a = list(map(int, input().split()))
s = a[-1]
ans = ['+']
for v in reversed(a[:-1]):
if s > 0:
s -= v
ans.append('-')
else:
s += v
ans.append('+')
if 0 <= s <= a[-1]:
print(''.join(reversed(ans)))
else:
s = -a[-1]
ans = ['-']
f... |
603 | 32_D. Constellation | A star map in Berland is a checked field n Γ m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is t... | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, m, k = map(int, input().split())
a = [tuple(map(lambda c: c == '*', input().rstrip())) for _ in range(n)]
cnt = [0] * 400
for i in range(1, n - 1):
for j in range(1, m - 1):
if not a[... |
604 | 351_B. 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... | from sys import *
n=int(stdin.readline().strip())
s1=stdin.readline().strip()
a=list(map(int,s1.split()))
if n==1:
print('0')
else:
x=0
n0=1
while n0<n:
n0=n0*2
b=[0]*(2*n0+10)
'''for i in range (n-1):
for j in range (i+1,n):
if a[i]>a[j]:
x+=1'''
... |
605 | 420_A. Start Up | Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?
The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out... | '''input
XO
'''
s = input()
if all(s[x] == s[~x] for x in range(len(s)//2)):
if any(y not in "AHIMOTUVWXY" for y in s[:len(s)//2+1]):
print("NO")
else:
print("YES")
else:
print("NO") |
606 | 490_E. Restoring Increasing Sequence | Peter wrote on the board a strictly increasing sequence of positive integers a1, a2, ..., an. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit.
Restore the the original sequence knowing digits remaining on the board.
Inpu... | def solve(s, t, i, l):
if i == l:
return False
if s[i] == "?":
if solve(s, t, i + 1, l):
s[i] = t[i]
return True
elif t[i] == "9":
return False
s[i] = nxt[t[i]]
for j in range(i, l):
if s[j] == "?":
s[j] = "0... |
607 | 514_E. Darth Vader and Tree | When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most... | # fast io
from sys import stdin
_data = iter(stdin.read().split('\n'))
input = lambda: next(_data)
N = 101
MOD = 1000000007
def mul_vec_mat(v, a):
c = [0] * N
for i in range(N):
c[i] = sum(a[j][i] * v[j] % MOD for j in range(N)) % MOD
return c
def mul_vec_sparse_mat(v, a):
c = [0] * N
for... |
608 | 569_B. Inventory | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.
During an audit, you were surprised to find out that the... | n = int(input())
fix = list()
factors = set(range(1, n + 1))
for i in map(int, input().split()):
if i in factors:
factors.remove(i)
fix.append(i)
else:
fix.append(None)
print(' '.join(str(factors.pop()) if i is None else str(i) for i in fix)) |
609 | 631_D. Messenger | Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature ... | def ziped(a):
p = []
for i in a:
x = int(i.split('-')[0])
y = i.split('-')[1]
if len(p) > 0 and p[-1][1] == y:
p[-1][0] += x
else:
p.append([x, y])
return p
def solve(a, b , c):
ans = 0
if len(b) == 1:
for token in a:
... |
610 | 660_B. Seating On Bus | Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.
Consider that m (m β€ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order... |
n,m = map(int,input().split())
for k in range(1,2*n +1):
num = 2 *n +k
if num <= m:
print(num, end=" ")
num = k
if num <= m:
print(num, end=" ")
|
611 | 74_C. Chessboard Billiard | Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.
More formally, first one of four diagonal directions is chosen and the billiard ball moves ... | import math
n,m=map(int,input().split())
print(math.gcd(n-1,m-1)+1)
|
612 | 773_B. Dynamic Problem Scoring | Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.
For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends... | import sys
inf = 10**9 + 7
def solve():
n = int(sys.stdin.readline())
v = [int(vi) for vi in sys.stdin.readline().split()] # Vesya
p = [int(pi) for pi in sys.stdin.readline().split()] # Petya
cnt = [0]*5
for i in range(5):
if v[i] != -1:
cnt[i] += 1
if p[i] != -1:
... |
613 | 798_A. Mike and palindrome | Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.
A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforc... | import sys
import math
import itertools
import collections
def getdict(n):
d = {}
if type(n) is list or type(n) is str:
for i in n:
if i in d:
d[i] += 1
else:
d[i] = 1
else:
for i in range(n):
t = ii()
if t in d... |
614 | 818_C. Sofa Thief | Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss?
Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs ... | import sys
from collections import defaultdict as dd
from collections import deque
pl=1
from math import *
import copy
#sys.setrecursionlimit(10**6)
if pl:
input=sys.stdin.readline
def li():
return [int(xxx) for xxx in input().split()]
def fi():
return int(input())
def si():
return list(input().rstrip())
def mi(... |
615 | 864_B. Polycarp and Letters | Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string s consisting only of lowercase and uppercase Latin letters.
Let A be a set of positions in the string. Let's call it pretty if following conditions are met:
* letters on positions from A in the string are all distinct and lowercase; ... | import re
input()
print(max(map(lambda s: len(set(s)), re.split('[A-Z]', input())))) |
616 | 88_A. Chord | Vasya studies music.
He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note aft... | # Problem: 88A
# Time Created: August 10(Monday) 2020 || 11:37:58
#>-------------------------<#
import sys
input = sys.stdin.readline
#>-------------------------<#
from itertools import permutations
# Helper Functions. -> Don't cluster your code.
def check_chord(tup):
notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F... |
617 | 934_D. A Determined Cleanup | In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.
Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...
Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients stric... | p, k = input().split()
p, k = int(p), int(k)
s = k - 1
ls = [0]
while s < p:
ls.append(0)
ls.append(0)
s = s * k * k + k - 1
n = len(ls)
for i in range(n):
if (i & 1) == 0:
ls[i] = k - 1
res = s - p
for i in range(n):
t = res % k
if i & 1:
ls[i] += t
else:
ls[i] -= t
... |
618 | 1077_E. Thematic Contests | Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the ... | # from collections import Counter as C
# n, k_ = map(int, input().split())
# l = [*map(int, input().split())]
# c = C(l)
# d = {}
# for k, v in c.items():
# d[v] = d.get(v, []) + [str(k)]
# ld = sorted([(k, v) for k, v in d.items()], reverse = True)
# res = []
# # print(ld)
# for e in ld:
# res += [e[1]]
# ... |
619 | 1119_E. Pavel and Triangles | Pavel has several sticks with lengths equal to powers of two.
He has a_0 sticks of length 2^0 = 1, a_1 sticks of length 2^1 = 2, ..., a_{n-1} sticks of length 2^{n-1}.
Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be ... | n = int(input())
a = list(map(int, input().split()))
ans = 0
last = 0
for q in range(len(a)):
while last > 0 and a[q] >= 2:
ans += 1
a[q] -= 2
last -= 1
ans += a[q]//3
last += a[q] % 3
print(ans)
|
620 | 1146_B. Hate "A" | Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example).
You are given a string... | s = input()
s1 = ""
a = 0
for i in s:
if i == 'a':
a -= -1
else:
s1 += i
if len(s1) % 2:
print(":(")
exit()
t = len(s1) // 2
ch = 1
x = len(s) - 1
for i in range(t - 1, -1, -1):
if s1[i] != s[x]:
ch = 0
break
x += -1
if ch:
for i in range(len(s) - t): print(... |
621 | 1185_E. Polycarp and Snakes | After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n Γ m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. ... |
def naiveSolve():
return
from collections import defaultdict
def charToInt(c): #'a'->0
if c=='.':
return -1
return ord(c)-ord('a')
def main():
t=int(input())
allans=[]
for _ in range(t):
n,m=readIntArr()
grid=[] # convert all chars to int
fo... |
622 | 1204_C. Anna, Svyatoslav and Maps | The main characters have been omitted to be short.
You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, β¦, p_m of m vertexes; for each 1 β€ i < m there is an arc from p_i to p_{i+1}.
Define the sequence v_1, v_2, β¦, v... | from collections import deque
n = int(input())
graph = [list(map(lambda bit: bit == '1', list(input()))) for _ in range(n)]
m = int(input())
way = list(map(lambda i: int(i) - 1, input().split()))
#print(graph)
def dfs(start):
queue = deque([start])
d = [-1] * n
d[start] = 0
while len(queue) != 0:
... |
623 | 1287_D. Numbers on Tree | Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i β the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first... | import sys
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n = int(input())
cs = [0] * (n + 1)
ps = [0] * (n + 1)
children = [[] for _ in range(n+1)]
for i in range(1, n+1):
p, c = map(int, input().split())
ps[i] ... |
624 | 1307_D. Cow and Fields | Bessie is out grazing on the farm, which consists of n fields connected by m bidirectional roads. She is currently at field 1, and will return to her home at field n at the end of the day.
The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has k special fields and he h... | import sys
from collections import deque
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
# v(G), e(G), special v
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
# adjacency lists
g = [[] for _ in range(n + 1)]
for _ in range(m):
v, to = map(int, input().split(... |
625 | 1350_D. Orac and Medians | Slime has a sequence of positive integers a_1, a_2, β¦, a_n.
In one operation Orac can choose an arbitrary subsegment [l β¦ r] of this sequence and replace all values a_l, a_{l + 1}, β¦, a_r to the value of median of \\{a_l, a_{l + 1}, β¦, a_r\}.
In this problem, for the integer multiset s, the median of s is equal to th... | # Template 1.0
import sys, re, math
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): retur... |
626 | 1393_C. Pinkie Pie Eats Patty-cakes | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.
Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat t... | def solve(n,ar):
freq = [0] * 200000
for i in range(n):
freq[ar[i]] += 1
maxi = 0
max_freq = 0
for i in range(len(freq)):
if maxi < freq[i]:
maxi = max(maxi,freq[i])
max_freq = 1
elif freq[i] == maxi:
max_freq += 1
print((n-max_fr... |
627 | 1418_B. Negative Prefixes | You are given an array a, consisting of n integers.
Each position i (1 β€ i β€ n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearra... | import sys
from sys import stdin
import math
import fractions
#Find Set LSB = (x&(-x)), isPowerOfTwo = (x & (x-1))
def iinput():
return int(input())
def minput():
return map(int,input().split())
def linput():
return list(map(int,input().split()))
def fiinput():
return int(stdin.readline())
def fminput(... |
628 | 1436_A. Reorder | For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that β_{i=1}^{n}{β_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl... | #import numpy as np
#import collections
#import sys
# =============================================================================
#def get_primeFactor(n):
# res=[1]
# x=2
# while x*x<=n:
# while n%x==0:
# res.append(x)
# n//=x
# x+=1
# if n>1:res.append(n)
# return r... |
629 | 1536_B. Prinzessin der Verurteilung | I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an β Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.
It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret h... | # abc = 'abcdefghijklmnopqrstuvwxy'
# test1_previous = [x + y for x in abc for y in abc if x!='m']
def nextchr(c):
return chr(ord(c)+1)
def next(s):
if s == '':
ans = '.'
elif s[-1] == 'z':
ans = next(s[:-1]) + 'a'
else:
ans = s[:-1] + nextchr(s[-1])
return ans
t = int(in... |
630 | 163_A. Substring and Subsequence | One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the s... | from sys import stdin
s=[ord(i)-97 for i in stdin.readline().strip()]
s1=[ord(i)-97 for i in stdin.readline().strip()]
n=len(s)
m=len(s1)
mod=1000000007
dp=[[0 for i in range(n)] for j in range(26)]
for i in range(m):
arr=[0 for j in range(n)]
for j in range(n):
if s1[i]==s[j] :
arr[j]=1
... |
631 | 183_B. Zoo | The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has n observation binoculars located at the OX axis. For each i between 1 and n, inclusive, there exists a single binocular located at the point with coordinates (i, 0). There are m flamingos in the Zoo, located at points with positive coordinates.... | def gcd(a,b):
if b == 0:
return a
return gcd(b, a % b)
def normalize_rational(num,den):
#associate the -ve with the num or cancel -ve sign when both are -ve
if num ^ den < 0 and num > 0 or num ^ den > 0 and num < 0:
num = -num; den = -den
#put it in its simplest form
g = gcd... |
632 | 230_C. Shifts | You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.
To cyclically shift a table row one cell to the right means to move the valu... | def solve(rows):
all_dists = [0 for _ in range(len(rows[0]))]
for r in rows:
dists = [len(r) for _ in r]
if '1' not in r:
return -1
start = r.index('1')
for i in range(len(r)):
right = (i+start)%len(r) # going right
left = (start+2*len(r)-i)%le... |
633 | 256_B. Mr. Bender and Square | Mr. Bender has a digital table of size n Γ n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy.
We'll consider the table rows numbered from top to bottom from 1 to n, and the columns β numbered from left to right f... | x, y, n, c = 0, 0, 0, 0
def suma_impares(m):
return m * m
def suma_n(m):
return m * (m - 1) // 2
def cnt(t):
u, d, l, r = x + t, x - t, y - t, y + t
suma = t ** 2 + (t + 1) ** 2
if u > n: suma -= suma_impares(u - n)
if d < 1: suma -= suma_impares(1 - d)
if l < 1: suma -= suma_impares(1 - l)
if r > n: suma -= su... |
634 | 374_A. Inna and Pink Pony | Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n Γ m chessboard, a very tasty candy and two numbers a and b.
Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the board. The boy said h... | n, m, i, j, a, b = map(int, input().split())
corners = [(1, 1), (1, m), (n, 1), (n, m)]
result = False
ans = -1
for cnt in corners:
if (abs(cnt[0] - i) % a == 0) and (abs(cnt[1] - j) % b == 0):
result = True
t1, t2 = abs(cnt[0] - i) // a, abs(cnt[1] - j) // b
if (t1 + t2) % 2 == 0:
... |
635 | 445_B. DZY Loves Chemistry | DZY loves chemistry, and he enjoys mixing chemicals.
DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.
Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pour... | def iterative_dfs(graph, start, path=[]):
visited = {}
for i in graph:
visited[i] = []
q=[start]
while q:
v=q.pop(0)
if not visited[v]:
visited[v] = True
path=path+[v]
q=graph[v]+q
return path
nodes, edges = map(int, input().split(' ')... |
636 | 467_C. George and Job | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.
Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers:
[l1, r1], [l2... | n, m, k = list(map(int, input().split()))
a = list(map(int, input().split()))
p_a = [0 for _ in range(n)]
p_a[0] = a[0]
for i in range(1, n):
p_a[i] = p_a[i - 1] + a[i]
INF = -1e10
# print(p_a)
dp = {}
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if st... |
637 | 53_D. Physical Education | Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line... | import sys
n = int(sys.stdin.readline ())
a= [int (x) for x in sys.stdin.readline ().split ()]
assert len(a) == n
b = [int (x) for x in sys.stdin.readline ().split ()]
assert len(b) == n
ans = []
for i in range (n):
j = i;
while b[j] != a[i] :
j += 1
while j > i:
ans += [(j, j + 1)]
... |
638 | 567_F. Mausoleum | King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.
The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has th... | n,k = map(int,input().split())
n*=2
n+=2
l,le,e = [[] for i in range(n)],[[] for i in range(n)],[0]*n
ok = 1
for i in range(k):
a,c,b = input().split()
a,b = int(a), int(b)
if c=="=":
if a==b:
continue
if (e[a] and e[a]!=b) or (e[b] and e[b]!=a):
ok = 0
e[a],... |
639 | 659_G. Fence Divercity | Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi.
Today Vasily de... | mod = 10 ** 9 + 7
n = int(input())
h = list(map(lambda x: int(x) - 1, input().split()))
ans = x = 0
for i in range(n):
ans += h[i] + min(h[i], h[i - 1]) * x
if i < n - 1:
x *= min(h[i - 1], h[i], h[i + 1])
x += min(h[i], h[i + 1])
ans %= mod
x %= mod
print(ans)
|
640 | 682_D. Alyona and Strings | After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar.
Alyona has her favourite positive integer k and because she is to... | n, m, k = map(int, input().split())
s, t = input(), input()
n += 1
m += 1
p = [i for i in range(n * m - n) if (i + 1) % n]
r = p[::-1]
d = [0] * n * m
for i in p:
if s[i % n] == t[i // n]: d[i] = d[i - n - 1] + 1
f = d[:]
for y in range(k - 1):
for i in p: f[i] = max(f[i], f[i - 1], f[i - n])
for i in... |
641 | 705_C. Thor | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).
q events are abou... | import collections
import copy
n, q = map(int, input().split())
Q = collections.deque()
A = n * [0]
B = copy.copy(A)
L = []
s = n = 0
for _ in range(q):
y, x = map(int, input().split())
if 2 > y:
x -= 1
Q.append(x)
B[x] += 1
A[x] += 1
s += 1
elif 3 > y:
x -= ... |
642 | 749_A. Bachgold Problem | Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi... | n=int(input())
c=0
if(n%2==1):
n-=3
l=[2]*(n//2)
l.append(3)
print(len(l))
print(*l)
else:
l=[2]*(n//2)
print(len(l))
print(*l) |
643 | 817_B. Makes And The Product | After returning from the army Makes received a gift β an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that aiΒ·ajΒ·ak is minimum possible, are there in the... | n=int(input())
a=list(map(int,(input().split(' '))))
a=sorted(a)
a.append(0)
ans=1
t=0
while a[3+t]==a[2]:t=t+1
if a[3]==a[0]:ans=(t+3)*(t+2)*(t+1)/6
elif a[3]==a[1]:ans=(t+2)*(t+1)/2
elif a[3]==a[2]:ans=t+1
print(int(ans))
|
644 | 842_B. Gleb And Pizza | Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.
The pizza is a circle of radius r and center at the origin. Pizza consists of the main part β circle of radius r - d with center at the origin, an... | '''input
8 4
7
7 8 1
-7 3 2
0 2 1
0 -2 2
-3 -3 1
0 6 2
5 3 1
'''
r, d = map(int, input().split())
n = int(input())
c = 0
for _ in range(n):
x, y, r1 = map(int, input().split())
s = (x**2 + y**2)**0.5
if r-d <= s-r1 and s+r1 <= r:
c += 1
print(c)
|
645 | 863_B. Kayaking | Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2Β·n people in the group (including Vadim), and they have exactly... | n = int(input())
n = 2*n
w = [int(i) for i in input().split()]
w.sort()
import math
res = math.inf
for x in range(n):
for y in range(x+1, n):
wc = w[:]
wc.pop(y); wc.pop(x)
# print(wc)
s = 0
for i in range(0, n-3, 2):
s += wc[i+1]-wc[i]
res = min(s, res)
print(res) |
646 | 888_F. Connecting Vertices | There are n points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw n - 1 segments, each connecting any two marked points, in such a way that all points have to be connected with e... | import sys
from array import array
n = int(input())
edge = [list(map(int, input().split())) for _ in range(n)]
mod = 10**9 + 7
dp_f = [array('i', [-1])*n for _ in range(n)]
dp_g = [array('i', [-1])*n for _ in range(n)]
for i in range(n):
dp_f[i][i] = dp_g[i][i] = 1
for i in range(n-1):
dp_f[i][i+1] = dp_g[i... |
647 | 911_D. Inversion Counting | A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a per... | def solve():
n=int(input())
a=list(map(int,input().split()))
cl=['odd','even']
m=int(input())
ans=True
b=[]
ap=b.append
for i in range(n):
for j in range(i):
if a[j]>a[i]:
ans=not ans
for i in range(m):
left,right=map(int,input().split())
... |
648 | 933_B. A Determined Cleanup | In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.
Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...
Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients stric... | s = input()
# s = '46 2'
p, k = list(map(int, s.split()))
res = []
f = True
while p != 0:
if f:
n = p % k
m = (p - n) // k
f = False
else:
n = (-p) % k
m = (p + n) // k
f = True
res.append(n)
p = m
print(len(res))
print(' '.join(list(map(str, res)))) |
649 | 987_B. High School: Become Human | Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.
It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-cl... | import math
x,y=map(lambda x:math.log(int(x))/int(x),input().split())
print('<=>'[(x>=y)+(x>y)]) |
650 | 1019_B. The hat | This is an interactive problem.
Imur Ishakov decided to organize a club for people who love to play the famous game Β«The hatΒ». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered ... |
# this sequence is a bit scary
# 8
# 1 2 3 2 3 2 1 0
import sys
#sys.stdin=open("data.txt")
#input=sys.stdin.readline
got=[10**18]*100005
def getnum(i):
if got[i]==10**18:
print("? %d"%i)
sys.stdout.flush()
got[i]=int(input())
return got[i]
n=int(input())
if n%4==2:
# the opposi... |
651 | 1042_A. Benches | There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available.
Let k be the maximum number of people sitting on one bench after additional m people c... | import math
n=int(input())
m=int(input())
a=[]
for i in range(n):
a.append(int(input()))
maxa=max(a)+m
mina=max(max(a),math.ceil((sum(a)+m)/n))
print(str(mina)+" "+str(maxa))
|
652 | 1106_D. Lunar New Year and a Wander | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.
The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever ... | from heapq import heappush, heappop
n,m = map(int,input().split())
adj = [[] for _ in range(n)]
for _ in range(m):
a,b = map(int,input().split())
a-=1
b-=1
adj[a].append(b)
adj[b].append(a)
st = set()
hp = []
v = [False for _ in range(n)]
heappush(hp,0)
v[0] = True
ans = []
while hp:
x = hea... |
653 | 1133_E. K Balanced Teams | You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.
You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! ... | kk=lambda:map(int,input().split())
ll=lambda:list(kk())
n,k= kk()
ls = sorted(ll())
vs,ne = [0]*n,[-1]*n
b = 0
for a in range(n):
while b < n and ls[b] - ls[a] < 6: b+=1
vs[a],ne[a] = b-a, b
curr = [0]*(n+1)
# print(vs)
for _ in range(k):
# print(curr)
prev = curr
curr = [0]*(n+1)
for i in range(n):
curr[i] = v... |
654 | 1154_B. Make Them Equal | You are given a sequence a_1, a_2, ..., a_n consisting of n integers.
You can choose any non-negative integer D (i.e. D β₯ 0), and for each a_i you can:
* add D (only once), i. e. perform a_i := a_i + D, or
* subtract D (only once), i. e. perform a_i := a_i - D, or
* leave the value of a_i unchanged.
It is... | n = int(input())
L = [int(i) for i in input().split()]
F = []
mi = 101
ma = 0
for i in L:
if i not in F:
F.append(i)
if len(F) > 3:
print(-1)
else:
F.sort()
if len(F) == 3:
D = F[1] - F[0]
if F[2] - F[1] == D:
print(D)
else:
print(-1)
elif len(... |
655 | 1194_F. Crossword Expert | Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming.
Fortunately, Adilbek can spend time witho... | mod = 10 ** 9 + 7
MAX = 2 * 10 ** 5+2
r = [1] * MAX
factorial = [1] * MAX
rfactorial = [1] * MAX
rp = [1] * MAX
#Permite precalcular factorial hasta "MAX", para evitar tener que calcularlo varias veces
#dentro de la ejecucion del programa.
for i in range(2, MAX):
factorial[i] = i * factorial[i - 1] % mod
... |
656 | 1234_B1. Social Network (easy version) | The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0... | def line():
return map(int, input().split())
def num():
return int(input())
from collections import OrderedDict as od
n,k = line()
ids = list(line())
screen = od()
for id in ids:
if id not in screen:
if len(screen)==k:
screen.popitem(last=False)
screen[id]=None
print(len(scree... |
657 | 1296_E2. String Coloring (hard version) | This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.
You are given a string s consisting of n lowercase Latin letters.
You have to color all its characters the minimum numb... | """
4
9
abacbecfd
8
aaabbcbb
7
abcdedc
5
abcde
"""
"""
# This is brute force for understanding the logic
t=int(input())
for _ in range(t):
n=int(input())
s=input()
col=[1]*n
for i in range(0,len(s)):
c=col[i]
for j in range(i+1,len(s)):
if(ord(s[i])>ord(s[j])):
... |
658 | 1339_C. Powered Addition | You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:
* Select some distinct indices i_{1}, i_{2}, β¦, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{... | import math
n = int(input())
for i in range(n):
m = int(input())
nums = [int(i) for i in input().split()]
highest = nums[0]
mostDiff = 0
for j in range(len(nums)):
if highest - nums[j] > mostDiff:
mostDiff = highest - nums[j]
if nums[j] > highest:
highest = nu... |
659 | 1360_G. A/B Matrix | You are given four positive integers n, m, a, b (1 β€ b β€ n β€ 50; 1 β€ a β€ m β€ 50). Find any such rectangular matrix of size n Γ m that satisfies all of the following conditions:
* each row of the matrix contains exactly a ones;
* each column of the matrix contains exactly b ones;
* all other elements are zeros.... | for q in range(int(input())):
n, m, a, b = map(int, input().split())
if n*a != m*b:
print('NO')
continue
print('YES')
t = '1'*a+'0'*(m-a)
for i in range(n):
print(t)
t = t[m-a:]+t[:m-a] |
660 | 1401_A. Distance and Axis | We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point ... | for _ in range(int(input())):
n, k = map(int, input().split())
if n<k:print(k-n)
elif n%2 == k%2: print(0)
else: print(1) |
661 | 1445_D. Divide and Sum | You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, r... | def ncr(n, r, p):
# initialize numerator
# and denominator
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
n = int(input())
a = sorted(list(map(int, input().split())))
ans = 0
for i in range(n):
... |
662 | 146_D. Lucky Number 2 | Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meet... | from math import *
from fractions import *
from sys import *
def li():
return list(map(int, input().split(" ")))
a = li()
if abs(a[2]-a[3]) > 1:
print(-1)
exit()
if a[2] == a[3]:
ans = "47"*a[2]+"4"
elif a[2] > a[3]:
ans = "47"*a[2]
else:
ans = "74"*a[3]
f = a[0]-ans.count("4")
s = a[1]-ans.count("7")
shit ... |
663 | 1546_C. AquaMoon and Strange Sort | AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaM... | from math import *
from collections import defaultdict as dt
from sys import stdin
inp = lambda : stdin.readline().strip()
I = lambda : int(inp())
M = lambda : map(int,inp().split())
L = lambda : list(M())
mod = 1000000007
inf = 100000000000000000000
ss = "abcdefghijklmnopqrstuvwxyz"
############## All the best... |
664 | 193_E. Fibonacci Number | John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when div... | low_n = 1000
high_m = 15000
limit = int(10 ** 13)
f = int(input())
inputList = []
def customFunction(i):
if i == 0:
return (0, 1)
a, b = customFunction(i >> 1)
a, b = ((2 * a * b - a * a) % low_n, (b * b + a * a) % low_n)
if i & 1:
a, b = (b % low_n, (a + b) % low_n)
return (a, b)... |
665 | 404_D. Minesweeper 1D | Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 β the total number of bombs in adjacent squares.
For example, the correct field to play looks ... | Mod=1000000007
s=input()
n=len(s)
a,b,c,d=1,0,0,0
for i in range(0,n):
if s[i]=='*':
t=0,a+b+d,0,0
elif s[i]=='?':
t=a+b+c,a+b+d,0,0
elif s[i]=='0':
t=0,0,a+c,0
elif s[i]=='1':
t=0,0,b,a+c
else:
t=0,0,0,b+d
a,b,c,d=map(lambda a:a%Mod,t)
print((a+b+c)%Mod)
|
666 | 454_B. Little Pony and Sort by Shift | One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
a1, a2, ..., an β an, a1, a2, ..., an - 1.
Help Twi... | def us_num(nums):
where = None
for idx, (a, na) in enumerate(zip(nums[:-1], nums[1:])):
if a > na:
if where is None:
where = idx
else:
return -1
if where is None:
return 0
elif nums[-1] > nums[0]:
return -1
return len(nums) - 1 - where
n = int(input())
nums = list(map(... |
667 | 476_E. Dreamoon and Strings | Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.
More formally... | s, p = input(), input()
n, m = len(s) + 1, len(p)
d = [[0] * n for t in range(n)]
for x in range(1, n):
i, j = x, m
while i and j:
j -= s[i - 1] == p[j - 1]
i -= 1
if not j:
for y in range(i + 1): d[x][y + x - i - m] = d[i][y] + 1
for y in range(x): d[x][y] = max(d[x][y], d[x - 1... |
668 | 4_A. Watermelon | One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | x=int(input())
y=x-2
if y%2==0 and y!=0:
print("YES")
else :
print("NO") |
669 | 550_A. Two Substrings | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
Input
The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.
Output
Print "YES" (without the quot... | a = input()
b = a
f1=0
f2=0
if(a.find('AB')!=-1):
a = a.replace('AB', 'C', 1)
if(a.find('BA')!=-1):
f1=1
if(b.find('BA')!=-1):
b = b.replace('BA', 'C', 1)
if(b.find('AB')!=-1):
f2=1
if(f1==0 and f2==0):
print("NO")
else:
print("YES") |
670 | 577_B. Modulo Sum | You are given a sequence of numbers a1, a2, ..., an, and a number m.
Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.
Input
The first line contains two numbers, n and m (1 β€ n β€ 106, 2 β€ m β€ 103) β the size of the original sequence and ... | n,x=map(int,input().split())
a=set()
for i in input().split():
i=int(i)
b=set()
for j in a: b.add((i+j)%x)
a|=b
a.add(i%x)
if 0 in a:
print("YES")
break
else:
print("NO") |
671 | 620_D. Professor GukiZ and Two Arrays | Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a sa as close as possible to the sum of the elements in the array b sb. So he wants to minimize the value v = |sa - sb|.
In one operation professor can swap some element from the array a and some element f... | from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
sum_a, sum_b = sum(a), sum(b)
delta = sum_b - sum_a
ans = abs(delta)
ans_swap = []
for i in range(n):
for j in range(m):
if abs((sum_a - a[i] + b[j]) - (sum_b + a[i] - b... |
672 | 641_C. Little Artem and Dance | Little Artem is fond of dancing. Most of all dances Artem likes rueda β Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.
More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a g... | import io, os, sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, q = map(int, input().split())
pos = [i for i in range(n)]
cnt, temp, flag = 0, [0, 0], 0
for _ in range(q):
p = list(map(int, input().split()))
if p[0] == 1:
x = (n + p[1]) % n
cnt = cnt + x
... |
673 | 66_A. Petya and Java | Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But h... | n= int(input())
if(n<=127):
print("byte")
elif(n<=32767):
print("short")
elif(n<=2147483647):
print("int")
elif(n<=9223372036854775807):
print("long")
else:
print("BigInteger") |
674 | 690_F1. Tree of Life (easy) | Heidi has finally found the mythical Tree of Life β a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies.
On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of n points (... | n = int(input())
a = [0]*(n+1)
for _ in range(n-1):
x, y = input().split(' ')
x, y = [int(x), int(y)]
a[x] += 1
a[y] += 1
too = 0
for x in a:
too += (x * (x-1))//2
print(too)
|
675 | 735_E. Ostap and Tree | Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no m... | def main():
n, k = map(int, input().split())
cnt = [[[0] * 21 for _ in (0, 1)] for _ in range(n + 1)]
edges, mod = [[] for _ in range(n + 1)], 1000000007
for _ in range(n - 1):
u, v = map(int, input().split())
edges[u].append(v)
edges[v].append(u)
def dfs(u, f):
cnt[... |
676 | 780_D. Innokenty and a Football League | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.
Each club's full name consist of two wo... | from collections import defaultdict
names = int(input())
inp = [input().split() for x in range(names)]
choice = []
res = defaultdict(lambda: [])
for x, word in enumerate(inp):
choice.append(False)
res[word[0][:3]].append(x)
while True:
changes = []
for key in res.keys():
if len(res[key]) > 1:
... |
677 | 804_A. Find Amir | A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j co... | n = int(input())
print(int((n + 1) / 2) - 1) |
678 | 948_B. Primal Sport | Alice and Bob begin their day with a quick game. They first choose a starting number X0 β₯ 3 and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and anno... | import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int... |
679 | 976_B. Lara Croft and the New Game | You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy.
Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D e... | import sys
n,m,k=map(int,input().split())
if(k<n):
print(k+1,1)
sys.exit()
k-=n
x=n-(k)//(m-1)
if(x%2==0):
y=k%(m-1)+2
else:
y=m-k%(m-1)
print(x,y)
|
680 | 1030_C. Vasya and Golden Ticket | Recently Vasya found a golden ticket β a sequence which consists of n digits a_1a_2... a_n. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket 350178 is lucky since it can be divided into three segments 350, 17 and 8: 3+5+0=1+7=8. No... | n = int(input())
s = input()
arr = list()
arr.append(int(s[0]))
summ = arr[0]
bigflg = False
for i in range(1,len(s)):
arr.append(int(s[i]))
summ+=arr[i]
for i in range(2,len(s)+1):
if summ % i == 0:
amount = summ / i
sm = 0
flg = True
for j in range(len(arr)):
sm... |
681 | 1053_A. Vasya and Triangle | Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 β€ x_1, x_2, x_3 β€ n, 0 β€ y_1, y_2, y_3 β€ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutio... | from math import gcd
def tfit(n, m, No, Mo):
if (n < m) != (No < Mo):
n, m = m, n
if n > No or m > Mo:
return -1, -1
return n, m
def sv():
N, M, K = map(int, input().split())
No = N
Mo = M
x = gcd(N, K)
N //= x
K //= x
x = gcd(M, K)
M //= x
K //= x
if K > 2:
print('NO')
return
elif K == 2:
Nres ... |
682 | 1096_C. Polygon for the Angle | You are given an angle ang.
The Jury asks You to find such regular n-gon (regular polygon with n vertices) that it has three vertices a, b and c (they can be non-consecutive) with \angle{abc} = ang or report that there is no such n-gon.
<image>
If there are several answers, print the minimal one. It is guarantied t... | import math
t=int(input())
for e in range(t):
n=int(input())
g=math.gcd(n,180)
p=n//g
q=180//g
if n==180 or n==0: print(-1)
else:
if p==q-1: print(2*q)
else: print(q)
|
683 | 1117_D. Magic Gems | Reziba has many magic gems. Each magic gem can be split into M normal gems. The amount of space each magic (and normal) gem takes is 1 unit. A normal gem cannot be split.
Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is N units. If a magic g... | import sys
MOD = 10**9+7
def mult(A,B):
n = len(A)
C = []
for x in range(n):
c = [0]*n
for z in range(n):
b = B[x][z]
a = A[z]
for y in range(n):
c[y] += a[y]*b
for y in range(n):
c[y]%=MOD
C.append(c)
retu... |
684 | 1143_F. U2 | Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one.
Vasya drew several distinct points with integer coordinates on a plane and then drew an... | import sys
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
N = int(input())
A = [None]*N
for i in range(N):
x, y = map(int, sys.stdin.readline().split())
A[i] = (x, y-x*x)
A.sort()
upper = []
for p in reversed(A):
while len(upper) >= 2 and cross(upper[-2], upper... |
685 | 1163_E. Magical Permutation | Kuro has just learned about permutations and he is really excited to create a new permutation type. He has chosen n distinct positive integers and put all of them in a set S. Now he defines a magical permutation to be:
* A permutation of integers from 0 to 2^x - 1, where x is a non-negative integer.
* The [bitwis... | def size(k):
return int(math.log2(k))
def v2(k):
if k%2==1:
return 0
else:
return 1+v2(k//2)
n=int(input())
s=list(map(int,input().split()))
import math
s.sort()
used=[]
use=0
found={0:1}
good=0
for guy in s:
big=size(guy)
if guy not in found:
used.append(guy)
use+=1
... |
686 | 1184_B1. The Doctor Meets Vader (Easy) | Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he und... | def bs(num):
low=0
high=b-1
while low<high:
mid=(low+high)//2
if bases[mid][0]<=num:low=mid+1
else:high=mid-1
if bases[low][0]<=num:return low
else:return low-1
n,b=map(int,input().split())
ar=list(map(int,input().split()))
bases=[];summ=0
for i in range(b):
bases.append(list(map... |
687 | 1202_A. You Are Given Two Binary Strings... | You are given two binary strings x and y, which are binary representations of some two integers (let's denote these integers as f(x) and f(y)). You can choose any integer k β₯ 0, calculate the expression s_k = f(x) + f(y) β
2^k and write the binary representation of s_k in reverse order (let's denote it as rev_k). For e... | for _ in range(int(input())):
x=input()[::-1]
y=input()[::-1]
posy=y.index('1')
posx=x.index('1',posy)
print(posx-posy)
|
688 | 1263_E. Editor | The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text.
Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters)... | '''input
11
(R)R(R)Ra)c
'''
# MODIFIED SEGMENT TREE (MIN = MINIMUM PREFIX SUM instead of MINIMUM ELEMENT IN PREFIX)
class SegmentTree:
def __init__(self, n, arr=[]):
self.n = n
self.tsum = [0] * (2 * n)
self.tmin = [0] * (2 * n)
self.tmax = [0] * (2 * n)
if arr:
... |
689 | 1285_A. Mezo Playing Zoma | Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands:
* 'L' (Left) sets the position x: =x - 1;
* 'R' (Right) sets the position x: =x + 1.
Unfortunately, Mezo's controller malfunctions sometimes. ... | def func(n):
x = input()
ans = 0
l_counter = x.count('L')
r_counter = x.count('R')
y = 0 - l_counter
z = 0 + r_counter
for i in range(y,z+1):
ans += 1
print(ans)
n = int(input())
func(n) |
690 | 1391_A. Suborrays | A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
For a positive integer n, we call a... | import sys
input = sys.stdin.readline
from collections import *
for _ in range(int(input())):
n = int(input())
print(*[i for i in range(1, n+1)]) |
691 | 1413_D. Shurikens | Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available... | import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from itertools import permutations,combinations
def data(): r... |
692 | 1455_D. Sequence and Swaps | You are given a sequence a consisting of n integers a_1, a_2, ..., a_n, and an integer x. Your task is to make the sequence a sorted (it is considered sorted if the condition a_1 β€ a_2 β€ a_3 β€ ... β€ a_n holds).
To make the sequence sorted, you may perform the following operation any number of times you want (possibly ... | import math
for _ in range(int(input())):
n,k=map(int,input().split())
a=list(map(int,input().split()))
ans=0
prob=0
rang=0
for i in range(1,n):
if a[i]<a[i-1]:
prob=1
rang=i
for i in range(rang):
if a[i]>k:
a[i],k=k,a[i]
ans+=1... |
693 | 1506_D. Epic Transformation | You are given an array a of length n consisting of integers. You can apply the following operation, consisting of several steps, on the array a zero or more times:
* you select two different numbers in the array a_i and a_j;
* you remove i-th and j-th elements from the array.
For example, if n=6 and a=[1, 6,... | import sys
input=sys.stdin.readline
t = int(input())
for i in range(t):
n=int(input())
a=[int(x) for x in input().split()]
a.sort()
temp=1
if n==1:
print(1)
continue
count=[]
for i in range(1,n):
if a[i]==a[i-1]:
temp+=1
if i==n-1:
... |
694 | 152_C. Pocket Book | One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.
As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 β€ i < j β€ n, ... | mod=10**9+7
n,m=map(int,input().split())
mat=[]
for _ in range(n):
s=input()
mat.append(s)
b=ord("A")
s=[False]*255
res=1
for j in range(m):
for i in range(b,b+26):
s[i]=False
for i in range(n):
s[ord(mat[i][j])]=True
r=0
for i in range(b,b+26):
if(s[i]):r+=1
res*=r
print(res%mod) |
695 | 180_B. Divisibility Rules | Vasya studies divisibility rules at school. Here are some of them:
* Divisibility by 2. A number is divisible by 2 if and only if its last digit is divisible by 2 or in other words, is even.
* Divisibility by 3. A number is divisible by 3 if and only if the sum of its digits is divisible by 3.
* Divisibility by ... | b, d = map(int, input().split())
for i in range(1, 10):
if (b**i) % d == 0:
print("2-type")
print(i)
exit()
if (b-1) % d == 0:
print("3-type")
exit()
if (b+1) % d == 0:
print("11-type")
exit()
for i in range(2, d+1):
if d % i == 0:
x = 1
while d % i == 0: ... |
696 | 203_C. Photographer | Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve.
The camera's memory is d megabytes. Valera's camera can take photos of high and l... | n, d = map(int, input().split())
d1, d2 = map(int, input().split())
arr = [0] * n
for i in range(n):
a, b = map(int, input().split())
arr[i] = [d1*a + d2*b, i+1]
arr.sort()
res, idx = 0, ''
for i in arr:
if d - i[0] < 0:
break
d -= i[0]
res += 1
idx += str(i[1]) + ' '
print(res)
print(id... |
697 | 277_A. Learning Languages | The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official language... | from sys import stdin,stdout
input = stdin.readline
def main():
n, m = map(int,input().split())
sets = list(range(n+1+m))
sizes = [1]*(n+1+m)
def get(a):
if sets[a] != a:
sets[a] = get(sets[a])
return sets[a]
def union(a, b):
a = get(a)
b = get(b)
... |
698 | 323_A. Black-and-White Cube | You are given a cube of size k Γ k Γ k, which consists of unit cubes. Two unit cubes are considered neighbouring, if they have common face.
Your task is to paint each of k3 unit cubes one of two colours (black or white), so that the following conditions must be satisfied:
* each white cube has exactly 2 neighbourin... | k=int(input())
if k%2==1:
print(-1)
else:
for i in range(k):
for j in range(k):
a=''
for l in range(k):
a+='bw'[(i//2+j+l//2)%2]
print(a)
if i<k-1:
print() |
699 | 347_D. Lucky Common Subsequence | In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substri... | def Solve(x,y,c):
if(c==len(virus)):
return 0
if(x==len(s1) or y==len(s2)):
return ""
if((x,y,c) in Mem):
return Mem[(x,y,c)]
ans=""
if(s1[x]==s2[y]):
q=0
if(s1[x]==virus[c]):
q=Solve(x+1,y+1,c+1)
if(q!=0):
q=s1[x]+q
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.