Unnamed: 0
int64
0
999
name
stringlengths
9
60
description
stringlengths
168
5.26k
solution
stringlengths
38
20.8k
500
1349_A. Orac and LCM
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow: * \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x. * lcm(s) is the minimum positive integer x, that divisible on all integ...
from collections import Counter from math import floor, sqrt try: long except NameError: long = int def fac(n): step = lambda x: 1 + (x<<2) - ((x>>1)<<1) maxq = long(floor(sqrt(n))) d = 1 q = 2 if n % 2 == 0 else 3 while q <= maxq and n % q != 0: q = step(d) d += 1 ...
501
1391_D. 505
A binary matrix is called good if every even length square sub-matrix has an odd number of ones. Given a binary matrix a consisting of n rows and m columns, determine the minimum number of cells you need to change to make it good, or report that there is no way to make it good at all. All the terms above have their...
def f( l, a): i, count = 0,0 for x in l: count += x not in a[i] #print( x, a[i], count ) i = (i+1) %2 return count def g( l, mx ): return min( [ f(l,mx[i]) for i in range(len(mx)) ] ) def two(): l = [ x[0]+x[1] for x in zip(input(),input())] mx = ( [['...
502
1416_A. 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...
t = int(input()) ns = [] for i in range(t): n = int(input()) arr = list(map(int, input().split())) nums = set(arr) dct1 = {} dct2 = {num: 0 for num in nums} for idx, el in enumerate(arr): if el in dct1: dct2[el] = max(dct2[el], idx - dct1[el]) else: d...
503
1480_A. Yet Another String Game
Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string s = s_1 s_2 ... s_n of length n consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move. In a move, a player must choose an index i (1 ≤ i ≤ n) ...
T = int(input()) for t in range (T): s = input() res = "" for i in range (len(s)): if (i%2 == 0): if (s[i] == 'a'): res += "b" else: res += "a" else: if (s[i] == 'z'): res += "y" else: ...
504
1506_G. Maximize the Remaining String
You are given a string s, consisting of lowercase Latin letters. While there is at least one character in the string s that is repeated at least twice, you perform the following operation: * you choose the index i (1 ≤ i ≤ |s|) such that the character at position i occurs at least two times in the string s, and del...
for _ in range(int(input())): s = input(); stack = []; seen = set(); last_occurrence = {c: i for i, c in enumerate(s)} for i, c in enumerate(s): if c not in seen: while stack and c > stack[-1] and i < last_occurrence[stack[-1]]: seen.discard(stack.pop(...
505
161_C. Abracadabra
Polycarpus analyzes a string called abracadabra. This string is constructed using the following algorithm: * On the first step the string consists of a single character "a". * On the k-th step Polycarpus concatenates two copies of the string obtained on the (k - 1)-th step, while inserting the k-th character of ...
def solve(x,l1,r1,l2,r2): if x==0:return 1 if l1>x: l1-=x+1 r1-=x+1 if l2>x: l2-=x+1 r2-=x+1 ans=max(0,min(r1,r2)-max(l1,l2)+1) if l1<=x and x<=r1 and l2<=x and x<=r2: if l1==0 or r1==x*2: ans=max(ans,max(x-l2,r2-x)) elif l2==0 or r2==x*2: ans=max(ans,max(x-l1,r1-x)) else: if l1<=x-1 and r2>...
506
180_E. Cubes
Let's imagine that you're playing the following simple computer game. The screen displays n lined-up cubes. Each cube is painted one of m colors. You are allowed to delete not more than k cubes (that do not necessarily go one after another). After that, the remaining cubes join together (so that the gaps are closed) an...
# ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- impor...
507
204_A. Little Elephant and Interval
The Little Elephant very much loves sums on intervals. This time he has a pair of integers l and r (l ≤ r). The Little Elephant has to find the number of such integers x (l ≤ x ≤ r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be inclu...
def F (x) : if (x < 10) : return x rv = 9 tmp = x len = 0 while (tmp > 0) : len += 1 tmp = tmp // 10 d = int (x // pow(10, len-1)) tmp = 1 for i in range(len - 2) : rv += 9 * tmp tmp *= 10 for i in range (1, 10) : if (i < d) : ...
508
228_E. The Road to Berland is Paved With Good Intentions
Berland has n cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not. The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads...
s=list(map(int,input().split())) n=s[0] m=s[1] roads=[] for i in range(0,n+1): roads.append([]) for i in range(0,m): s=list(map(int,input().split())) roads[s[0]].append([s[1],s[2]]) roads[s[1]].append([s[0],s[2]]) col=[-1]*(n+1) ##def dfs(v,c): ## success=True ## col[v]=c ## for e in roads[...
509
252_C. Points on Line
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d. Note that the order of the points inside the group of three chosen point...
n,d=map(int,input().split()) nums=list(map(int,input().split())) count=0 j=0 for i in range(n): while j<n and nums[j]-nums[i]<=d: j+=1 temp_length=(j-i-1) count+=int((temp_length*(temp_length-1))/2) print(count)
510
2_A. Winner
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla...
n = int(input()) d = {} l = [] for _ in range(n): name, score = input().split() score = int(score) l.append((name,score)) d[name] = d.get(name, 0) + score m = max([x for x in d.values()]) ties = [x for x,y in d.items() if y == m] # print(ties) if len(ties) == 1: print(ties[0]) exit() el...
511
325_A. Square and Rectangles
You are given n rectangles. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle). Your task is to determine if the rectan...
xmin, ymin, xmax, ymax, a = 31400, 31400, 0, 0, 0 for i in range(int(input())): x1, y1, x2, y2 = map(int, input().split()) xmin = min(xmin, x1) ymin = min(ymin, y1) xmax = max(xmax, x2) ymax = max(ymax, y2) a += (x2 - x1) * (y2 - y1) print('YES' if xmax - xmin == ymax - ymin and a == (xmax - xmi...
512
371_C. Hamburgers
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (...
st = input() B = st.count('B') S = st.count('S') C = st.count('C') b,s,c=map(int,input().split()) bp, sp, cp = map(int,input().split()) r=int(input()) lm=0; rm=int(1e15)+1 while rm-lm>1: m=(rm+lm)//2 # print(m) bb=max(m*B-b,0) ss=max(m*S-s,0) cc=max(m*C-c, 0) #print(bp*bb+ss*sp+cc*cp) if bp*b...
513
488_D. Strip
Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right. Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: * Each piece should contain at least l numbers. * The difference between the maximal and the minimal number on the piece...
def split(a,n,s,l): pieces = [] i = 1 tmpmin = a[0] tmpmax = a[0] tmppc = [a[0]] while i<n: if abs(a[i]-tmpmin)<=s and abs(a[i]-tmpmax)<=s: tmppc.append(a[i]) if a[i]<tmpmin: tmpmin=a[i] elif a[i]>tmpmax: tmpmax = a[i] else: piece...
514
512_C. Fox And Dinner
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old. They will have dinner around some round tables. You want to distribute foxes such that: 1. Each fox is sitting at some table. 2. Each table has at least 3 foxes sitting around it. 3...
from collections import deque class Dinic(): def __init__(self, listEdge, s, t): self.s = s self.t = t self.graph = {} self.maxCap = 1000000 # dict các node lân cận # e[0]: from, e[1]: to, e[2]: dung luong for e in listEdge: ...
515
560_E. Gerald and Giant Chess
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of gia...
#!/usr/bin/env python # 560E_chess.py - Codeforces.com 560E Chess program # # Copyright (C) 2015 Sergey """ Input The first line of the input contains three integers: h,w,n the sides of the board and the number of black cells Next n lines contain the description of black cells. The ith of these lines contains number...
516
587_A. 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...
N = int(1e6+100) n = int(input()) arr = list(map(int, input().split())) cnt = [0] * N for i in arr: cnt[i] += 1 res, s = 0, 0 for i in range(N): s += cnt[i] res += s % 2 s //= 2 print(res)
517
609_C. Load Balancing
In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server. In order to balance the load for each server, you want to reassign some tasks to make the difference betw...
input() servers = [int(x) for x in input().split(" ", )] servers.sort() avg = int(sum(servers) / len(servers)) extra = sum(servers) % len(servers) count = 0 for i in range(len(servers)): count += abs(avg + (i >= (len(servers) - extra)) - servers[i]) / 2 print(int(count))
518
656_F. Ace It!
Input The only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid"). Output Output a single integer. Examples Input A221033 Output 21 Input A223635 Output 22 Input A232726 Outpu...
s = input() ans = 1 for i in s[1:]: x = int(i) if x == 0: x = 9 ans += x print(ans)
519
680_A. Bear and Five Cards
A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer. Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards. He is allowed to at most once discard two or three cards wi...
l=list(map(int,input().split())) ma=0 for i in l : k=0 for j in l : if i==j : k=k+1 if k>2 : break if k>1 : if ma<k*i : ma=k*i print(sum(l)-ma)
520
83_D. Numbers
One quite ordinary day Valera went to school (there's nowhere else he should go on a week day). In a maths lesson his favorite teacher Ms. Evans told students about divisors. Despite the fact that Valera loved math, he didn't find this particular topic interesting. Even more, it seemed so boring that he fell asleep in ...
def pr(x): d = 2 while d * d <= x: if x % d == 0: return 0 d += 1 return 1 def cnt(n, k): if not pr(k) or n < k: return 0 n1 = n // k return n1 - sum(cnt(n1, i) for i in range(2, min(k, n1 + 1))) a, b, k = map(int, input().split()) ans = cnt(b, k) - cnt(a - 1, k...
521
909_E. Coprocessor
You are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depen...
n, m = [int(x) for x in input().split()] tps = {i:int(t) for i, t in enumerate(input().split())} deps = {i:0 for i in range(n)} parents = {i:[] for i in range(n)} leafs = {i for i in range(n)} for i in range(m): x, y = [int(x) for x in input().split()] deps[x] += 1 parents[y].append(x) if x in leafs: ...
522
931_B. World Cup
The last stage of Football World Cup is played using the play-off system. There are n teams left in this stage, they are enumerated from 1 to n. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the four...
n,a,b=map(int,input().split()) a,b,r=a-1,b-1,0 while a!=b: a//=2 b//=2 r+=1 print(r if 2**r<n else 'Final!')
523
985_B. Switches and Lamps
You are given n switches and m lamps. The i-th switch turns on some subset of the lamps. This information is given as the matrix a consisting of n rows and m columns where ai, j = 1 if the i-th switch turns on the j-th lamp and ai, j = 0 if the i-th switch is not connected to the j-th lamp. Initially all m lamps are t...
def main(): n,m=map(int,input().split()) counts=[0]*m a=[None]*n for i in range(n): line=input() a[i]=line for j in range(m): counts[j]+=1 if line[j]=='1' else 0 if 1 not in counts: print('YES') return checks=[] for i in range(m): if counts[i]==1: checks.append(i) leng=len(checks) for i in r...
524
1012_A. Photo of The Sky
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes. Strictly speaking, it makes a photo of all points with coordinates (x, y), such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2, where (x_1, y_1) and (x...
n=int(input())-1 s=sorted(map(int,input().split())) sp=(s[n]-s[0])*(s[2*n+1]-s[n+1]) for i in range(n+1): sp=min(sp,(s[n+i]-s[i])*(s[2*n+1]-s[0])) print(sp)
525
1037_A. Packets
You have n coins, each of the same value of 1. Distribute them into packets such that any amount x (1 ≤ x ≤ n) can be formed using some (possibly one or all) number of these packets. Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single x, howeve...
import math n, = map(int, input().split()) print(math.floor(math.log2(n)) + 1)
526
1081_C. Colorful Bricks
On his free time, Chouti likes doing some housework. He has got one new task, paint some bricks in the yard. There are n bricks lined in a row on the ground. Chouti has got m paint buckets of different colors at hand, so he painted each brick in one of those m colors. Having finished painting all bricks, Chouti was s...
from math import factorial [n, m, k] = [int(i) for i in input().split()] mod = 998244353 l = m*((m-1)**k) L = factorial(n-1)//factorial(n-1-k)//factorial(k) print((l*L)%mod)
527
1129_A1. Toy Train (Simplified)
This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled. Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at...
n, m = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(m)] s = [[] for _ in range(n)] for q in a: s[q[0]-1].append(q[1]-1) d = [] for q in range(len(s)): if len(s[q]) == 0: d.append(0) else: p = min(s[q], key=lambda x: (x-q) % n) d.append((len(s[q])-1)*n...
528
1149_A. Prefix Sum Primes
We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it — either 1 or 2. However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in a...
n = int(input()) a = list(map(int, input().split())) aset = set(a) if len(aset) == 1: print(' '.join(map(str, a))) else: count = [-1, -1] for elem in a: count[elem - 1] += 1 print(2, 1, end = ' ') for i in range(count[1]): print(2, end = ' ') for i in range(count[0]): pri...
529
1291_A. Even But Not Even
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clar...
for _ in range(int(input())): n=int(input()) s=input() if len(s)==1: print(-1) else: #ans=s[0] ans='' f=0 for i in range(0,n): if int(s[i])%2==1 and f<2: ans+=s[i] f+=1 #break if f<2: ...
530
1311_B. WeirdSort
You are given an array a of length n. You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions. Your task is to determine if it is poss...
t=int(input()) for _ in range(t): n,m=map(int,input().split()) a=list(map(int,input().split())) b=[(a[i],i) for i in range(n)] b=sorted(b) p=list(map(int,input().split())) adj=[[] for i in range(n)] for i in range(m): p[i]=p[i]-1 for i in p: adj[i].append(i+1) adj...
531
1333_F. Kate and imperfection
Kate has a set S of n integers \{1, ..., n\} . She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b. Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection am...
from collections import * from math import * N = int(5e5+5) p = [0 for i in range(N)] for i in range(2,N): if(p[i] == 0): for j in range(i*i,N,i): if(p[j] == 0): p[j] = i n = int(input()) a = [1 for i in range(n+1)] primes = [] ct = 0 for i in range(1,n+1): if p[i] == 0: ct += 1 primes.append(i) g = 2 dig ...
532
1374_A. Required Remainder
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha...
t=int(input()) for i in range(t): x, y, n=map(int,input().split()) print(n-(n-y)%x)
533
1397_B. Power Sequence
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i. Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to: * Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change...
import math, sys from collections import defaultdict, Counter, deque INF = float('inf') MOD = 10 ** 9 + 7 def gcd(a, b): while b: a, b = b, a%b return a def isPrime(n): if (n <= 1): return False i = 2 while i ** 2 <= n: if n % i == 0: return False i += 1 return True def primeFactors(n): facto...
534
1420_C2. Pokémon Army (hard version)
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved. Pikachu is a cute and friendly pokémon living in the wild pikachu herd. But it has become known recently that infamous team R...
input=__import__('sys').stdin.readline def check(*inds): global localmax, localmin, maxs, mins for ind in inds: if not ok(ind):continue if localmax[ind]==0 and s[ind-1]<s[ind]>s[ind+1]:localmax[ind]=1;maxs+=s[ind] if localmin[ind]==0 and s[ind-1]>s[ind]<s[ind+1]:localmin[ind]=1;mins+=s[ind] def upd0(*inds): gl...
535
1490_C. Sum of Cubes
You are given a positive integer x. Check whether the number x is representable as the sum of the cubes of two positive integers. Formally, you need to check if there are two integers a and b (1 ≤ a, b) such that a^3+b^3=x. For example, if x = 35, then the numbers a=2 and b=3 are suitable (2^3+3^3=8+27=35). If x=4, t...
t = int(input()) f = [] for _ in range(t): n = int(input()) cubes = {} for i in range(1,int(n**(1./3.))+8): cubes[i**3] = 1 for i in range(1,len(cubes)): a = i**3 b = n - a g = cubes.get(b) if (g == None): ans = "No" else: ans ...
536
209_A. Multicolored Marbles
Polycarpus plays with red and blue marbles. He put n marbles from the left to the right in a row. As it turned out, the marbles form a zebroid. A non-empty sequence of red and blue marbles is a zebroid, if the colors of the marbles in this sequence alternate. For example, sequences (red; blue; red) and (blue) are zebr...
n=int(input()) mod=10**9+7 if n>=2: dp=[0 for i in range(n)] dp[0],dp[1]=1,2 ans=3 for i in range(2,n): dp[i]=(dp[i-1]+dp[i-2])%mod ans=(ans+dp[i])%mod print(ans) else: print(1)
537
25_C. Roads in Berland
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance betw...
n = int(input()) mat = [] for _ in range(n): mat.append(list(map(int, input().split()))) q = int(input()) ans= [] for _ in range(q): x, y, w = map(int, input().split()) x-=1 y-=1 mat[x][y] = mat[y][x] = min(mat[x][y], w) sum1 = 0 for i in range(n): for j in range(n): a = ...
538
354_A. Vasya and Robot
Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He us...
import sys n,L,r,QL,QR=map(int,sys.stdin.readline().split()) W=list(map(int,sys.stdin.readline().split())) minn=10**10 SumsL=[0]*n SumsR=[0]*n s=0 for i in range(n): s+=W[i] SumsL[i]=s for i in range(n-1): ans=L*SumsL[i]+r*(s-SumsL[i]) if(n-(i+1)>i+1): ans+=(abs(n-(i+1)-(i+1))-1)*QR ...
539
378_B. Semifinals
Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the peopl...
n = int(input()) sem1 = [] sem2 = [] l = [0,0] for cont in range(0,n): l = list(map(int, input().split())) sem1.append(l[0]) sem2.append(l[1]) kmax = int(n/2) max1 = 0 max2 = 0 for cont in range(0,n): if sem1[max1] < sem2[max2]: max1 += 1 else: max2 += 1 ris1 = ['1']*(max([max1,km...
540
39_D. Cubical Planet
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment ...
#دو تا نقطه تو مختصات سه بعدی میده میگه اینا تو یک وجه از مکعل هستند یا نه print('YES' if any(i == j for i,j in zip(list(input().split()) ,list(input().split()))) else 'NO')
541
449_C. Jzzhu and Apples
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater...
apples=int(input()) if apples<=3: print(0) else: halfpr=int(apples/2) def primes(n): isPrime = [True for i in range(n + 1)] isPrime[0] = isPrime[1] = False idx = 2 while idx * idx <= n: if isPrime[idx]: for i in range(idx * 2, ...
542
493_E. Vasya and Polynomial
Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that h...
t,a,b=map(int,input().split()) if t==2 and a==3 and b>10000: res=0 elif a==t: res=('inf' if a==1 else 2) if a==b else 0 else: res=0 if (a-b)%(t-a) else (1 if t != b else 0) print(res)
543
544_D. Destroying Roads
In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any ...
from itertools import combinations_with_replacement from collections import deque #sys.stdin = open("input_py.txt","r") n, m = map(int, input().split()) G = [ [] for i in range(n)] for i in range(m): x, y = map(int, input().split()) x-=1; y-=1 G[x].append(y) G[y].append(x) def BFS(s): dist = [-...
544
571_A. Lengthening Sticks
You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the l...
def f(a, b, c, l): k = min(l, a - b - c) return 0 if a < b + c else (k + 1) * (k + 2) // 2 solve = lambda i: f(a + i, b, c, l - i) + f(b + i, c, a, l - i) + f(c + i, a, b, l - i) a, b, c, l = map(int, input().split()) ans = (l + 1) * (l + 2) * (l + 3) // 6 - sum(solve(i) for i in range(l + 1)) print(ans)
545
592_D. Super M
Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go ...
from collections import deque from sys import stdin from sys import exit #parsea una línea def parser(): return map(int, stdin.readline().split()) #Método usado para obtener los vértices por los que debe pasar Super M def DFS_Discriminiting(): visited=[False for x in range(n)] visited[numbers_of_attacked_...
546
614_B. Gena's Code
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not en...
import sys def esdist(s): n=len(s) if (s[0] != '1'): return True for i in range(1,n): if (s[i]!='0'): return True return False l=0 for line in sys.stdin: if l==0: n = int(line) else: nums = line.split() l+=1 res = "1" ceros = 0 for i in range(n): s = nums[i] if (not esdist(s)): ceros += len(s)-1 else: ...
547
662_B. Graph Coloring
You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edge...
from collections import deque n, m = map(int, input().split()) adj = [[] for i in range(n)] for i in range(m): u, v, c = input().split() u, v = int(u)-1, int(v)-1 adj[u].append((v, c)) adj[v].append((u, c)) visited = S = T = None def bfs(i, k): q = deque([(i, 0)]) while q: u, p = q...
548
709_D. Recover the String
For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matc...
a00, a01, a10, a11 = map(int, input().split()) numZeros = 0 numOnes = 0 ans = True for n0 in range(1, 2*a00 + 1): if n0 * (n0 - 1) == 2 * a00: numZeros = n0 break elif n0 * (n0 - 1) > 2 * a00: ans = False break; for n1 in range(1, 2*a11 + 1): if n1 * (n1 - 1) == 2 * a11: ...
549
774_J. Stepan's Series
Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum num...
def process(S, k): n = len(S) if k > n: return 'NO' current = 0 for i in range(n): if S[i]=='N': current+=1 if current > k: return 'NO' else: current = 0 start_work = True for i in range(k): if S[i]=='Y': ...
550
79_C. Beaver
After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel fee...
s, n = input(), int(input()) t = [input() for i in range(n)] def f(i): global t for j in range(n): if i < j: if len(t[j]) < len(t[i]) and t[j] in t[i]: return False elif j < i and t[j] in t[i]: return False return True t = [t[i] for i in range(n) if f(i)] n = len(s) r = [0] * n...
551
846_A. Curriculum Vitae
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job. During all his career Hideo has produced n games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero)...
def main(): n = int(input()) games = list(map(int, input().split(' '))) result = max([games[:i].count(0) + games[i:].count(1) for i in range(n+1)]) print(result) if __name__ == "__main__": main()
552
867_C. Ordering Pizza
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai ...
def cns(ts,s): if ts/s==int(ts/s): return ts else: return (int(ts/s)+1)*s n,spp=[int(i) for i in input().split()] tsr=0 da=[[] for i in range(100005)] db=[[] for i in range(100005)] sl=[] for i in range(n): sl.append([int(j) for j in input().split()]) tsr+=sl[i][0] if sl[i][1]>sl[i][...
553
914_E. Palindromes in a Tree
You are given a tree (a connected acyclic undirected graph) of n vertices. Vertices are numbered from 1 to n and each vertex is assigned a character from a to t. A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome. For each vertex, output the number of pa...
import sys, os def centroid_decomp(coupl): n = len(coupl) bfs = [n - 1] for node in bfs: bfs += coupl[node] for nei in coupl[node]: coupl[nei].remove(node) size = [0] * n for node in reversed(bfs): size[node] = 1 + sum(size[child] for child in coupl[nod...
554
962_E. Byteland, Berland and Disputed Cities
The cities of Byteland and Berland are located on the axis Ox. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line Ox there are three types of cities: * the cities of Byteland, * the cities of Berland, * disputed cities. Recent...
def solve(length, cities): result = 0 lastP = None lastB = None lastR = None maxB = 0 maxR = 0 for idx, city in enumerate(cities): i, code = city if(code == 'B'): if(lastB != None): result += abs(i - lastB) maxB = max(maxB, abs(i - lastB)) lastB = i if(code == 'R'):...
555
990_A. Commentary Boxes
Berland Football Cup starts really soon! Commentators from all over the world come to the event. Organizers have already built n commentary boxes. m regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be...
n, m, a, b = list(map(int, input().split())) k = n%m print(min(k*b, (m - k)*a))
556
1066_A. Vova and Train
Vova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute — at the point 2 and so on). There are lanterns on the...
if __name__ == '__main__': t = input() t = int(t) while t: e, v, l, r = input().split() e = int(e) v = int(v) l = int(l) r = int(r) res = e//v if l % v != 0: st = l//v + 1 else: st = l//v en = r//v print...
557
1107_F. Vasya and Endless Credits
Vasya wants to buy himself a nice new car. Unfortunately, he lacks some money. Currently he has exactly 0 burles. However, the local bank has n credit offers. Each offer can be described with three numbers a_i, b_i and k_i. Offers are numbered from 1 to n. If Vasya takes the i-th offer, then the bank gives him a_i bur...
n = int(input()) a = [tuple(map(int, input().split())) for i in range(n)] a = [(y, x, k) for x, y, k in a] a.sort(reverse=True) dp = [[-1] * (n + 1) for i in range(n)] def f(i, j): if i < 0 or j < -1: return 0 if dp[i][j] == -1: y, x, k = a[i] dp[i][j] = f(i - 1, j) + max(0, x - k * y) ...
558
1137_A. Skyscrapers
Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by n streets along the Eastern direction and m streets across the Southern direction. Naturally, this city has nm intersections. At any intersection of i-th Eastern street and j-th Southern street there is a monument...
import sys input=sys.stdin.buffer.readline from bisect import bisect_left n,m=map(int,input().split()) arr=[] for i in range(n): arr.append(list(map(int,input().split()))) arr_maxi=[[0 for i in range(m)] for j in range(n)] arr_mini=[[0 for i in range(m)] for j in range(n)] for i in range(n): s=sorted(set(arr[i]...
559
1155_C. Alarm Clocks Everywhere
Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the i-th of them will start during the x_i-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes x_1, x_2, ..., x_n, so he will be awak...
def gcd(a,b): if b==0: return a else: return gcd(b,a%b) n, m = map(int, input().split(' ')) x = list(map(int, input().split(' '))) p = list(map(int, input().split(' '))) dx = [x[i+1]-x[i] for i in range(n-1)] d = dx[0] for i in dx: d = gcd(i, d) for i in range(m): if d % p[i] == 0: ...
560
1177_B. Digits Sequence (Hard Edition)
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the k-th digit of this sequence. Input The first and only lin...
#import sys #digit = int(sys.argv[1]) digit = int(input()) if int(digit) <= 9: print(digit) exit() start_range = 1 end_range = 9 power = 1 digit_count = 2 while not (start_range <= digit and digit <= end_range): start_range = end_range + 1 end_range = 9 * 10**power * digit_count + start_range - 1 ...
561
1236_C. Labs
In order to do some research, n^2 labs are built on different heights of a mountain. Let's enumerate them with integers from 1 to n^2, such that the lab with the number 1 is at the lowest place, the lab with the number 2 is at the second-lowest place, …, the lab with the number n^2 is at the highest place. To transpor...
n = int(input()) a = [[] for i in range(n)] j = 0 k = 1 cnt = 0 for i in range(n): for j in range(n): cnt += 1 if (i % 2 == 0): a[j].append(cnt) else: a[-j-1].append(cnt) for i in range(n): print(*a[i])
562
1254_B1. Send Boxes to Alice (Easy Version)
This is the easier version of the problem. In this version, 1 ≤ n ≤ 10^5 and 0 ≤ a_i ≤ 1. You can hack this problem only if you solve and lock both problems. Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes o...
from sys import stdin,stdout from math import gcd,sqrt,factorial,pi,inf from collections import deque,defaultdict from bisect import bisect,bisect_left from time import time from itertools import permutations as per from heapq import heapify,heappush,heappop,heappushpop input=stdin.readline R=lambda:map(int,input().spl...
563
1278_A. Shuffle Hashing
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems. Polycarp decided to store the hash of the password, generated by the following algorithm: 1. take the password p, consisting of lowercase Latin letters, and shuffle the l...
t = int(input()) for _ in range(t): s = input() t = input() ok = False s = ''.join(sorted(s)) for i in range(len(t) - len(s) + 1): temp = ''.join(sorted(t[i:i+len(s)])) if temp == s: ok = True break if ok: print("YES") else: print("NO")
564
1321_B. Journey Planning
Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to som...
from sys import stdin, gettrace if not gettrace(): def input(): return next(stdin)[:-1] def main(): n = int(input()) bb = [int(a) for a in input().split()] seq = {} for i, b in enumerate(bb): if b - i in seq: seq[b-i] += b else: seq[b-i] = b pri...
565
1362_A. Johnny and Ancient Computer
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m...
# from debug import debug import math t = int(input()) for ii in range(t): a, b = map(int, input().split()) if a == b: print(0) else: b, a = min(a,b), max(a,b) if a%b: print(-1) else: aa = int(math.log2(a//b)) if pow(2, aa) == a//b: c = 0 c += aa//3 aa = aa%3 c += aa//2 aa = aa...
566
1382_C1. Prefix Flip (Easy Version)
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ...
from collections import defaultdict as dd import sys input=sys.stdin.readline t=int(input()) while t: n=int(input()) #d=dd(int) #n,m=map(int,input().split()) #l=list(map(int,input().split())) a=list(map(int,input().strip())) b=list(map(int,input().strip())) j=n-1 ans=[] while j>=0: ...
567
1471_A. Strange Partition
You are given an array a of length n, and an integer x. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was [3, 6, 9], in a single operation one can replace the last two elements by their ...
from math import ceil t = int(input()) for _ in range(t): n,x = map(int,input().split()) a = list(map(int,input().split())) mx = 0 mn = 0 for y in a: mx += ceil(y/x) mn += y mn = ceil(mn/x) print(mn,mx)
568
1547_E. Air Conditioners
On a strip of land of length n there are k air conditioners: the i-th air conditioner is placed in cell a_i (1 ≤ a_i ≤ n). Two or more air conditioners cannot be placed in the same cell (i.e. all a_i are distinct). Each air conditioner is characterized by one parameter: temperature. The i-th air conditioner is set to ...
def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().split()) def msi(): return map(str,input().split()) def li(): return list(mi()) t=ii() for _ in range(t): s=si() n,k=mi() a=li() temp=li() ac=[] for i in range(k): ac.append([a[i],temp[i]]) ...
569
195_C. Try and Catch
Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that. The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks: 1. The try op...
import sys import math MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans)...
570
219_C. Color Stripe
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells. Input The first input line contains two integ...
n,k=map(int,input().split()) s=input() if(k==2): #A sol1=[s[i] for i in range(n)] ans1=0 for i in range(n): if(i%2==0 and sol1[i]=="B"): ans1+=1 sol1[i]="A" elif(i%2!=0 and sol1[i]=="A"): ans1+=1 sol1[i]="B" #B sol2=[s[i] f...
571
268_C. Beautiful Sets of Points
Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions: 1. The coordinates of each point in the set are integers. 2. For any two points from the set, the distance between them is a non-integer. Consider all poi...
if __name__ == '__main__': nums = input().split() n = int(nums[0]) m = int(nums[1]) k = min(m, n) + 1 print(k) for i in range(k): print(str(i) + " " + str(k-1-i))
572
385_C. Bear and Prime Numbers
Recently, the bear started studying data structures and faced the following problem. You are given a sequence of integers x1, x2, ..., xn of length n and m queries, each of them is characterized by two integers li, ri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answe...
import math, sys input = sys.stdin.buffer.readline def ints(): return map(int, input().split()) n = int(input()) x = list(ints()) MAX = max(x) + 1 freq = [0] * MAX for i in x: freq[i] += 1 sieve = [False] * MAX f = [0] * MAX for i in range(2, MAX): if sieve[i]: continue for j in range(i, MAX...
573
406_B. Toy Sum
Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris. There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them bac...
import sys INF = 10**20 MOD = 10**9 + 7 I = lambda:list(map(int,input().split())) from math import gcd from math import ceil from collections import defaultdict as dd, Counter from bisect import bisect_left as bl, bisect_right as br """ Facts and Data representation Constructive? Top bottom up down """ n, = I() a = I...
574
433_C. Ryouko's Memory Note
Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also bo...
def median(a): if len(a) == 0: return 0 if len(a) % 2 == 1: return a[len(a) // 2] else: return (a[len(a) // 2] + a[(len(a) // 2) - 1]) // 2 def profit(a, old_val): a.sort() med = median(a) sum_old = 0 sum_new = 0 for i in a: sum_old += abs(i - old_val) ...
575
478_C. Table Decorations
You have r red, g green and b blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number t of tables can be decorated if we know number of balloons of each color? Your task is to write a program tha...
a = sorted(list(map(int, input().split()))) a[2] = min(a[2], 2 * (a[0] + a[1])) print(sum(a) // 3)
576
500_E. New Year Domino
Celebrating the new year, many people post videos of falling dominoes; Here's a list of them: https://www.youtube.com/results?search_query=New+Years+Dominos User ainta, who lives in a 2D world, is going to post a video as well. There are n dominoes on a 2D Cartesian plane. i-th domino (1 ≤ i ≤ n) can be represented a...
''' from bisect import bisect,bisect_left from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import *''' #------------------------------------------------------------------------ import os ...
577
526_C. Om Nom and Candies
A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place? <image> One day, when he came to his friend Evan, Om Nom didn't find him at h...
C, Hr, Hb, Wr, Wb = map(int, input().split()) ans = 0 for i in range(10 ** 5): if Wr * i <= C: ans = max(ans, Hr * i + (C - Wr * i) // Wb * Hb) for i in range(10 ** 5): if Wb * i <= C: ans = max(ans, Hb * i + (C - Wb * i) // Wr * Hr) print(ans)
578
551_D. GukiZ and Binary Operations
We all know that GukiZ often plays with arrays. Now he is thinking about this problem: how many arrays a, of length n, with non-negative elements strictly less then 2l meet the following condition: <image>? Here operation <image> means bitwise AND (in Pascal it is equivalent to and, in C/C++/Java/Python it is equival...
# -*- coding: utf-8 -*- from collections import deque def calc(n, m): if n == 1: return [[1, 0], [0, 1]] a = calc(n // 2, m) if n % 2 == 0: res00 = (a[0][0] * a[0][0]) % m res00 = (res00 + a[0][0] * a[1][0]) % m res00 = (res00 + a[0][1] * a[0][0]) % m res01 = (a[0][0...
579
5_C. Longest Regular Bracket Sequence
This is yet another problem dealing with regular bracket sequences. We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not....
string = input() n = len(string) stack = [] mapping = [0]*n # First we create an array where the array called mapping where the index of array # gives the index of start of opening bracket in string and the value at that index # gives the index of closing bracket for corresponding opening bracket. for idx, char in ...
580
622_A. Infinite Sequence
Consider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not d...
n = int(input()) from math import sqrt # Find max m such that m(m+1)/2 <= n m = int((-1 + sqrt(1 + 8*n))/2) # l is the previous range l = m * (m + 1) // 2 print(m if n == l else n - l)
581
670_D1. Magic Powder - 1
This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only. Waking up in the ...
n, k = input().split(" ") n, k = [int(n), int(k)] list1 = list(map(int, input().split(" "))) list2 = list(map(int, input().split(" "))) low = 0 high = 2*(10**9) while low < high: if high - low % 2 != 0: mid = low + (high - low) // 2 + 1 else: mid = low + (high - low)//2 d = k list6 = []...
582
737_C. Subordinates
There are n workers in a company, each of them has a unique id from 1 to n. Exaclty one of them is a chief, his id is s. Each worker except the chief has exactly one immediate superior. There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate ...
f = lambda: map(int, input().split()) n, s = f() c = [0] * n t = list(f()) for i in t: c[i] += 1 k = t[s - 1] c[k] -= 1 d = c[0] c += [d] d += k > 0 i, j = 1, n while i < j: if c[i]: i += 1 elif c[j]: c[j] -= 1 i += 1 d += j < n else: j -= 1 print(d)
583
761_B. Dasha and friends
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation: The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you...
n,l = map(int,input().split()) kefa = list(map(int,input().split())) sasha = list(map(int,input().split())) diff1 = [kefa[i+1] - kefa[i] if i != n - 1 else l - kefa[-1] + kefa[0] for i in range(n) ] diff2 = [sasha[i+1] - sasha[i] if i != n - 1 else l - sasha[-1] + sasha[0] for i in range(n) ] def rotation(pos)...
584
784_D. Touchy-Feely Palindromes
Input The only line of the input contains a string of digits. The length of the string is between 1 and 10, inclusive. Output Output "Yes" or "No". Examples Input 373 Output Yes Input 121 Output No Input 436 Output Yes
# ⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚ # 1234567890 R = [ ("1", "' "), ("2", ": "), ("3", "''"), ("4", "':"), ("5", "'."), ("6", ":'"), ("7", "::"), ("8", ":."), ("9", ".'"), ("0", ".:"), ] s = input() for a,b in R: s = s.replace(a,b) print("Yes" if s==s[::-1] else "No")
585
805_C. 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...
print(max((int(input()) + 1) // 2 - 1, 0))
586
830_C. Bamboo Partition
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high. Vladimir has just planted n bamboos in a row, each of...
import itertools unfold = itertools.chain.from_iterable def jumps(a): d = speedup while d < a - 1: c = (a + d - 1) // d d = (a + c - 2) // (c - 1) yield d def calc(d): return sum(d - 1 - (i - 1) % d for i in a) def ans(): for d, pd in zip(D, D[1:]): d -= 1 cd...
587
89_E. Fire and Ice
The Fire Lord attacked the Frost Kingdom. He has already got to the Ice Fortress, where the Snow Queen dwells. He arranged his army on a segment n in length not far from the city walls. And only the frost magician Solomon can save the Frost Kingdom. <image> The n-long segment is located at a distance equal exactly to...
n = int(input()) a = [0] * 1010 b = [0] * 2010 S = 1000000007 W=0 b = list(map(int,input().strip().split()))[:n] for i in range(0,n): a.insert(i,b[i]) while(not a[n-1]): n-=1 for w in range(0,n+1): for i in range(0,n): b[i]=a[i] for i in range(w,n): if(b[i]): b[i]-=1 w0=0...
588
977_D. Divide by three, multiply by two
Polycarp likes to play with numbers. He takes some integer number x, writes it down on the board, and then performs with it n - 1 operations of the two kinds: * divide the number x by 3 (x must be divisible by 3); * multiply the number x by 2. After each operation, Polycarp writes down the result on the boar...
n = int(input()) li = list(map(int, input().split())) g = {} def dfs(e, v, order): if e not in v: v[e] = 1 if e % 3 == 0: if (e // 3) in g: order.append(e // 3) dfs(e // 3, v, order) if e * 2 in g: order.append(e * 2) dfs(...
589
997_B. Roman Digits
Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers 1, 5, 10 and 50 respectively. The use of other roman digits is not allowed. Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as...
def solve(n): s = set() for i in range(0, n + 1): for v in range(0, n - i + 1): for x in range(0, n - i - v + 1): l = n - i - v - x s.add(i + v * 5 + x * 10 + l * 50) return len(s) n = int(input()) if n < 11: print(solve(n)) else: print(49 * n - ...
590
1056_D. Decorate Apple Tree
There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from 1 to n, the junction 1 is called the root. A subtree of a junction v is a set of junc...
n=int(input()) p=[0,0]+list(map(int,input().split()))#tomamos la entrada d=[0]*(n+1)#aki vamos a contar la cantidad d colores q necesita cada union for i in range(n,1,-1):#empezamos x las hojas hasta llegar a la raiz if d[i]==0:#si no estas visitado eres una hoja => solo necesitas un color d[i]=1 d[p[i]...
591
111_D. Petya and Coloring
Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size n × m (n rows, m columns) in k colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number...
n, m, k = [int(x) for x in input().split()] mod = int(10**9 + 7) if m == 1: print(pow(k, n, mod)) exit() ans = 0 fac = [1] ifac = [1] tav = [0] for i in range(1, max(k + 1, n + 1)): fac.append((fac[i - 1] * i) % mod) for i in range(1, min(k + 1, n + 1)): ifac.append((ifac[i - 1] * pow(i, mod - 2, mod...
592
1147_A. Hide and Seek
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent. Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers x_1, x_2, …, x_k in order....
from collections import Counter nums, num_questions = map(int, input().split()) questions = list(map(int, input().split())) exist = set() things = dict(Counter(questions)) nums = nums * 3 - 2 - len(things) for i in questions: if i not in exist: exist.add(i) if things.get(i - 1): nums -= ...
593
1168_B. Good Triple
Toad Rash has a binary string s. A binary string consists only of zeros and ones. Let n be the length of s. Rash needs to find the number of such pairs of integers l, r that 1 ≤ l ≤ r ≤ n and there is at least one pair of integers x, k such that 1 ≤ x, k ≤ n, l ≤ x < x + 2k ≤ r, and s_x = s_{x+k} = s_{x+2k}. Find th...
def func(st,en): for i in range(st,en+1): for j in range(i+1,en+1 ): if (j-i+1)%2==1: if s[(i+j)//2]==s[i]==s[j]: return False #print(st, en) return True s=input().strip() c=0 n=len(s) for i in range(2,9): for j in range(len(s)): if i+...
594
1186_E. Vus the Cossack and a Field
Vus the Cossack has a field with dimensions n × m, which consists of "0" and "1". He is building an infinite field from this field. He is doing this in this way: 1. He takes the current field and finds a new inverted field. In other words, the new field will contain "1" only there, where "0" was in the current field...
from sys import stdin,stdout n,m,q = map(int, stdin.readline().split()) mat = [[0]*m for i in range(n)] for i in range(n): row = stdin.readline().strip() for j,c in enumerate(row): mat[i][j] = 1 if c == '1' else -1 #print(mat) def get(a,b): if a < 0 or b < 0: return 0 x = a^b ans...
595
1223_A. CME
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero. For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not. Now, you ha...
# import numpy as np import array def solution(): req = int(input()) for i in range(req): count = int(input()) result = 0 if count==2: print(2) continue while count % 2 != 0 : result+=1 count+=1 print(result) def coun...
596
1248_D2. The World Is Just a Programming Task (Hard Version)
This is a harder version of the problem. In this version, n ≤ 300 000. Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya beli...
n = int(input()) s = input() r = 0 l = n-1 root = [] buf = [] to_the_right = True for count in range(n): if to_the_right: i = r r += 1 else: i = l l -= 1 b = s[i] if b == '(': if len(buf) == 0 or buf[-1][0] != -1: buf.append([-1,-1,[]]) buf...
597
1267_B. Balls of Buma
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls). When the ball is inserted the following happens repeatedly: if so...
# -*- coding: utf-8 -*- """ Created on Sat Jul 18 16:25:32 2020 @author: MridulSachdeva """ s = input() n = len(s) condensed = [] temp = s[0] count = 1 for i in range(1, n): if s[i] == temp: count += 1 else: condensed.append((temp, count)) temp = s[i] count = 1 condensed.ap...
598
1461_F. Mathematical Expression
Barbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw n numbers a_1, a_2, …, a_n without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the numbers ...
import sys input = sys.stdin.readline n = int(input()) a = list(map(int,input().split())) ops = input().strip() if len(ops) == 1: print(ops.join(map(str, a))) elif '+' in ops and '*' in ops: seqs = [[a[0]]] output = [] # split into seqs of all 0's or non 0's # every seq in seqs is a list of all ...
599
1487_A. Arena
n heroes fight against each other in the Arena. Initially, the i-th hero has level a_i. Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute). When two heroes of equal levels fight,...
tests = int(input()) for t in range(tests): n = int(input()) heroes = list(map(int, input().split(' '))) m = min(heroes) print(sum([1 for x in heroes if x > m]))