Unnamed: 0
int64
0
999
name
stringlengths
9
60
description
stringlengths
168
5.26k
solution
stringlengths
38
20.8k
800
1051_E. Vasya and Big Integers
Vasya owns three big integers — a, l, r. Let's define a partition of x such a sequence of strings s_1, s_2, ..., s_k that s_1 + s_2 + ... + s_k = x, where + is a concatanation of strings. s_i is the i-th element of the partition. For example, number 12345 has the following partitions: ["1", "2", "3", "4", "5"], ["123",...
def kmp(pat,text,t): s=pat+"?"+text; #z[i] es el tamaño del prefijo mas largo de, formado por una subcadena s[i:...] z=[0 for i in range(len(s))] L=0;R=0;n=len(s); for i in range(1,len(s)): if i>R: L=R=i while R<n and s[R-L]==s[R]: R+=1 z[i...
801
1095_F. Make It Connected
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph. You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are...
n, m = map(int, input().split()) a = list(map(int, input().split())) e = [] for _ in range(m) : u, v, w = map(int, input().split()) e.append((u-1, v-1, w)) a = sorted(zip(a, range(n)), key = lambda x : x[0]) for i in range(1, n) : e.append((a[0][1], a[i][1], a[0][0] + a[i][0])) fa = list(range(n)) rk = [...
802
1117_A. Best Subsegment
You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 ≤ l ≤ r ≤ n) with maximum arithmetic mean (1)/(r - l + 1)∑_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding). If there are many such subsegments find the longest one. Input The first line contains single integer...
n=int(input()) s=[int(x) for x in input().split()] el=max(s) pos1=-1 pos2=-1 c=0 ans=0 for i in range(0,len(s)): if(s[i]==el): c=c+1 else: ans=max(ans,c) c=0 ans=max(ans,c) print(ans)
803
1143_C. Queen
You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the ...
""" https://codeforces.com/problemset/problem/1143/C """ n = int(input()) respect = [0 for _ in range(n)] child_respect = [0 for _ in range(n)] root = -1 for i in range(n): p, c = map(int,input().split()) if p == -1: root = i continue respect[i] = c if p != -1 and not c: child_respec...
804
1163_C1. Power Transmission (Easy Edition)
This problem is same as the next one, but has smaller constraints. It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system cons...
import sys import collections import math import heapq from operator import itemgetter def getint(): return int(input()) def getints(): return [int(x) for x in input().split(' ')] n = getint() points = [tuple(getints()) for _ in range(n)] result = 0 slopes = collections.defaultdict(set) for i in range(n - 1...
805
1184_A1. Heidi Learns Hashing (Easy)
Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor. Heidi figured out that Madame Kovarian uses a...
from math import sqrt def get_int(): from sys import stdin return int(stdin.readline().replace('\n', '')) def is_even(n): return n%2 == 0 def heidi_hash(r): k = r-1 rt = int(sqrt(k)) for x in range(1, rt+2): if k % x == 0: temp = k/x -x -1 if temp > 0 and is_e...
806
1201_D. Treasure Hunting
You are on the island which can be represented as a n × m table. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are k treasures on the island, the i-th of them is located at the position (r_i, c_i). Initially you stand at the lower left corner of the island, at the position (1, 1). I...
from sys import stdin from bisect import bisect_left input=stdin.readline n,m,k,q=map(int,input().split(' ')) x=sorted(list(map(int,input().split(' ')))for i in range(k)) y=sorted(list(map(int,input().split(' ')))) def rr(c0,c1,c2): return abs(c2-c0)+abs(c1-c2) def tm(c0,c1): t=bisect_left(y,c0) tt=[] ...
807
1219_C. Periodic integer number
Alice became interested in periods of integer numbers. We say positive X integer number is periodic with length L if there exists positive integer number P with L digits such that X can be written as PPPP…P. For example: X = 123123123 is periodic number with length L = 3 and L = 9 X = 42424242 is periodic number with...
import math as m def main(): n = int(input()) s = input() l = len(s) p = int(m.ceil(l/n)) if l%n!=0 : t = '1' for i in range(1,n): t+='0' for i in range(0,p): print(t ,end = '') else : z = s[0:n] t='' for i in range(0,p): t+=z if t > s: print(t) return z = str(int(s[0:n])+1) if ...
808
1243_C. Tile Painting
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate. The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles wit...
def prime_factor(n): ass = [] for i in range(2,int(n**0.5)+1): while n % i==0: ass.append(i) n = n//i if n != 1: ass.append(n) return ass n = int(input()) p = list(set(prime_factor(n))) if len(p) == 1: print(p[0]) else: print(1)
809
1328_A. Divisibility Problem
You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test c...
t=int(input()) for i in range(0,t): a,b=input().split() a=int(a) b=int(b) print((b-a%b)%b)
810
1348_A. Phoenix and Balance
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even. He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh...
t=eval(input()) for j in range(t): n=eval(input()) if n==2 : print(2) else: sum=2 for i in range(1,n//2): sum=sum+2**(i+1) print(sum)
811
1413_A. Finding Sasuke
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is e...
T = int(input()) a = [] b=[] i = 0 j = 0 n = 0 for i in range(T): n = int(input()) a = list(map(int, input().split())) b.append([]) for j in range(int(n/2)): if (a[j*2] > a[j*2 + 1]): b[i].append(a[j*2 + 1]) b[i].append(-a[j*2]) elif(a[j*2 + 1] >= a[j*2]): ...
812
1455_A. Strange Functions
Let's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111. Let's define another function g(x) = (x)/(f(f(x))) (x is a positive integer as well...
from sys import stdout,stdin,maxsize from collections import defaultdict,deque import math t=int(stdin.readline()) for _ in range(t): #n=int(stdin.readline()) #d=map(int,stdin.readline().split()) #l=list(map(int,stdin.readline().split())) s=input() print(len(s)) ...
813
1479_B2. Painting the Array II
The only difference between the two versions is that this version asks the minimal possible answer. Homer likes arrays a lot. Today he is painting an array a_1, a_2, ..., a_n with two kinds of colors, white and black. A painting assignment for a_1, a_2, ..., a_n is described by an array b_1, b_2, ..., b_n that b_i ind...
import sys input = lambda: sys.stdin.readline().rstrip() N = int(input()) A = [int(a) for a in input().split()] S = set() ans = 0 la = -1 for a in A: if a == la: continue elif a in S: S = {a, la} else: S.add(a) la = a ans += 1 print(ans)
814
1529_B. Sifid and Strange Subsequences
A sequence (b_1, b_2, …, b_k) is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair (i, j) with 1 ≤ i<j ≤ k, we have |a_i-a_j|≥ MAX, where MAX is the largest element of the sequenc...
""" Author : Ashish Sasmal Python3 / PyPy3 """ from sys import stdin as sin def aint():return int(input()) def amap():return map(int,sin.readline().split()) def alist():return list(map(int,sin.readline().split())) def astr():return input() for _ in range(aint()): n = aint() l = alist() l.sort() ...
815
160_B. Unlucky Ticket
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches th...
number_of_testcases = 1 #int(input()) for _ in range(number_of_testcases): number_of_digits = int(input()) ticket_number = input() ticket_number = list(ticket_number) first_half = ticket_number[:number_of_digits] second_half = ticket_number[number_of_digits:] #print(first_half) first_half....
816
227_D. Naughty Stone Piles
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you. During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of...
n = int(input()) stones = list(map(lambda t : int(t), input().split())) q = int(input()) queries = list(map(lambda t : int(t), input().split())) stones.sort() added_stones = [] added_stones.append(stones[0]) for i in range(1, n, 1): added_stones.append(stones[i] + added_stones[i - 1]) computed_queries = {} for ...
817
251_B. Playing with Permutations
Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n. A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n), all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha...
n,k=map(int,input().strip().split()) a=list(map(int,input().strip().split())) b=list(map(int,input().strip().split())) ups = [[i+1 for i in range(n)]] downs = [[i+1 for i in range(n)]] def apply(arr): out = [0]*n for i in range(n): out[i] = arr[a[i]-1] return out def unapply(arr): out = [0]*n ...
818
276_C. Little Girl and Maximum Sum
The little girl loves the problems on array queries very much. One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). You need to f...
n,m = map(int,input().split()) a = list(map(int,input().split())) l = [0]*(n+2) for i in range(m): x,y=map(int,input().split()) l[x] += 1 l[y+1] -= 1 for i in range(2, n+2): l[i] += l[i-1] l.sort(reverse=True) a.sort(reverse=True) # print(l, a) ans=0 for i in range(n): ans += l[i]*a[i] print(ans)
819
322_C. Ciel and Robot
Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all: * 'U': go up, (x, y) → (x, y+1); * 'D': go down, (x, y) → (x, y-1); * 'L': go left...
target = tuple(map(int, input().split())) s = input() #print(target) #print(s) ok = False pos = (0, 0) for c in s: if c == 'L': pos = (pos[0]-1, pos[1]) if c == 'R': pos = (pos[0]+1, pos[1]) if c == 'U': pos = (pos[0], pos[1]+1) if c == 'D': pos = (pos[0], pos[1]-1) if pos == target: ok = True if...
820
347_A. Difference Row
You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers. More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The ...
# t=int(input()) # import math # for _ in range(t): # n,k=list(map(int,input().split())) # s=input() # a=[] # summer=0 # for i in range(len(s)): # if(s[i]=='1'): # a.append(i) # i=0 # while(i<len(a)-1): # dist=a[i+1]-k-1-(a[i]+k+1)+1 # # print(a,dist) # ...
821
370_B. Berland Bingo
Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains mi numbers. During the game the host takes num...
n = int(input()) cards = [None] + [[] for i in range(n)] for i in range(1, n+1): cards[i] = list(map(int, input().split()))[1:] ans = [None] + [True for i in range(n)] #print(cards, ans) for i in range(1, n + 1): for j in range( 1, n + 1): if i == j : continue; if set(cards[i]) & se...
822
441_C. Valera and Tubes
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y). Valera wants to place...
import sys import math as mt #input=sys.stdin.buffer.readline #import bisect mod=1000000007 #t=int(input()) #tot=0 t=1 for __ in range(t): #n=int(input()) n,m,k=map(int,input().split()) x,y=1,0 d=0 r=1 ch=1 cnt1=1 for i in range(k-1): print(2,end=" ") for j in range(...
823
463_D. Gargari and Permutations
Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can...
n, k = map(int, input().split()) ra = [[0] * k for _ in range(n)] for p in range(k): for i, v in enumerate(map(int, input().split())): v -= 1 ra[v][p] = i g = [[] for _ in range(n)] for u in range(n): for v in range(n): if all(x < y for x, y in zip(ra[u], ra[v])): g[u].append...
824
487_C. Prefix Product Sequence
Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence <image>. Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1]. Input The only input line contains an integer n (1 ≤ n ≤ 105). Output In the first output line, print ...
n = int(input()) if n == 1: print('YES\n1') exit(0) if n == 4: print('YES\n1 3 2 4') exit(0) for p in range(2, int(n ** 0.5) + 1): if n % p == 0: print('NO') exit(0) print('YES') print(1) for j in range(2, n): print(j * pow(j - 1, n - 2, n) % n) print(n)
825
510_B. Fox And Two Dots
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this: <image> Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors. The key of this game is to find a cycle that contain d...
''' Zijian He 1429876 ''' # Import from sys import setrecursionlimit setrecursionlimit(10**6) # Function from class class Graph: def __init__ (self): self._alist = {} def add_vertex (self, vertex): if vertex not in self._alist: self._alist[vertex] = set() def add_edge (self, ...
826
535_C. Tavas and Karafs
Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. <image> Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is ...
a,b,n=map(int,input().split()) for _ in range(n): l,t,m=map(int,input().split()) lo=l hi=100000000 while lo<hi: mid=(lo+hi)//2 count=(mid-l)+1 first=a+(l-1)*b last=a+(mid-1)*b if last<=t and (count*(first+last))//2<=m*t: lo=mid+1 else: ...
827
586_A. Alena's Schedule
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying. One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes). The University works in such a way that every day it...
n = int(input()) a = list(map(int, input().split())) + [0] home = True ans = 0 for i in range(n): if a[i]: ans += 1 home = False elif not a[i + 1] and not home: home = True elif not home: ans += 1 print(ans)
828
608_B. Hamming Distance Sum
Genos needs your help. He was asked to solve the following programming problem by Saitama: The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as <image>, where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming ...
from sys import stdin input=stdin.readline ''' if i+k ''' def getcnt(a): cnt=[[0,0] for i in range(len(a)+1)] for i in range(len(a)): # if i==0: # cnt[i][a[i]]+=1 # else: cnt[i+1][0]=cnt[i][0] cnt[i+1][1]=cnt[i][1] cnt[i+1][a[i]]+=1 return cnt def f(a,b):...
829
62_A. A Student's Dream
Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them. A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable profess...
g_l,g_r=input().split() b_l,b_r=input().split() g_l=int(g_l) g_r=int(g_r) b_l=int(b_l) b_r=int(b_r) flag=0 if g_l==b_r: flag=1 elif g_l>b_r and g_l-1==b_r: flag=1 elif b_r>g_l and 2*g_l+2>=b_r: flag=1 if flag==0: if g_r == b_l: flag = 1 elif g_r > b_l and g_r - 1 == b_l: flag = 1 ...
830
724_A. Checking the Calendar
You are given names of two days of the week. Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong t...
a = str(input()) b = str(input()) k = {'monday':1,'tuesday':2,'wednesday':3,'thursday':4,'friday':5,'saturday':6,'sunday':7} a=k[a]-1 b=k[b]-1 res = False res = res or ((a+2)%7+1)%7==b res = res or ((a+1)%7+1)%7==b res = res or ((a+6)%7+1)%7==b if res: print("YES") else: print("NO")
831
746_A. Compote
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, ...
l = int(input()) a = int(input()) p = int(input()) ll = l aa = a // 2 pp = p // 4 print(min(ll,aa,pp) * 1 + min(ll,aa,pp) * 2 + min(ll,aa,pp) * 4)
832
769_A. Year of University Entrance
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups f...
n = int(input()) a = list(map(int, input().split())) a.sort() if n % 2: print(a[n//2])
833
793_A. Oleg and shares
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg...
n,k=map(int,input().split()) l=list(map(int,input().split())) K=min(l) for i in range(n): if (l[i]-K)%k!=0: print(-1) exit() Sum=sum(l) K=K*n Sum=Sum-K print(Sum//k)
834
813_D. Two Melodies
Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time! Alice has a sheet with n notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal. ...
import sys n = int(input()) + 1 a = [0] + list(map(int, input().split())) mod7 = [x % 7 for x in a] dp = [[0]*n for _ in range(n)] maxnum = [0]*(10**5+10) ans = 0 for i in range(n): maxmod = [0]*7 for j in range(n): maxnum[a[j]] = 0 for j in range(i): maxnum[a[j]] = max(maxnum[a[j]], dp...
835
908_G. New Year and Original Order
Let S(n) denote the number that represents the digits of n in sorted order. For example, S(1) = 1, S(5) = 5, S(50394) = 3459, S(353535) = 333555. Given a number X, compute <image> modulo 109 + 7. Input The first line of input will contain the integer X (1 ≤ X ≤ 10700). Output Print a single integer, the answer to ...
# Problem G num = input() num_list = [] for i in range(len(num)): num_list.append(int(num[i])) myMod = (10 ** 9) + 7 length = len(num_list) f = [0] * (length + 1) t = [1] * (length + 1) for i in range(length): f[i+1] = (f[i] * 10 + 1) % myMod t[i+1] = (t[i] * 10) % myMod ans = 0 for i in range(1, 10): dp...
836
930_A. Peculiar apple-tree
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch...
from collections import defaultdict,Counter,deque as dq from sys import stdin input=stdin.readline n=int(input()) g=defaultdict(list) w=list(map(int,input().strip().split())) for i in range(len(w)): g[w[i]-1].append(i+1) g[i+1].append(w[i]-1) # print(g) q=dq([0]) d=[-1]*(n) d[0]=1 cnt=defaultdict(int) cnt[1]+=1 wh...
837
984_A. Game
Two players play a game. Initially there are n integers a_1, a_2, …, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate t...
x = int(input()) l = [int(n) for n in input().split()] l.sort() i = 0 while len(l) > 1: if i % 2 == 0: l = l[0:len(l) - 1] else: l = l[1:len(l)] i = i + 1 print(l[0])
838
1045_B. Space Isaac
Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is \{0,1,…,M-1\}, for some positive integer M. Ajs draws a number from the first bag and a num...
import sys input = sys.stdin.readline def main(): n, m = map(int, input().split()) a = list(map(int, input().split())) + [0]*500000 ans_S = 0 a[n] = a[0] + m s = [0]*600600 for i in range(n): s[i] = a[i + 1] - a[i] s[n] = -1 for i in range(n): s[2*n - i] = s[i] for i...
839
1068_B. LCM
Ivan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes ([a, b])/(a) on blackboard. Here [a, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the boa...
b=int(input()) out=[1] n=b i=0 while n%2==0: i=i+1 out.append(2**i) n=int(n/2) out1=[] for i in range (1,int(n**0.5)+1,2): if n%i==0: out1.append(i) out1.append(int(n/i)) out2=set() for i in out: for j in out1: out2.add(i*j) #print (out2) print (len(out2))
840
1139_A. Even Substrings
You are given a string s=s_1s_2... s_n of length n, which only contains digits 1, 2, ..., 9. A substring s[l ... r] of s is a string s_l s_{l + 1} s_{l + 2} … s_r. A substring s[l ... r] of s is called even if the number represented by it is even. Find the number of even substrings of s. Note, that even if some subs...
n = int(input()) s = input() k = 0 for i in range(1, n + 1): d = int(s[i - 1]) if d % 2 == 0: k += i print(k)
841
1157_B. Long Number
You are given a long decimal number a consisting of n digits from 1 to 9. You also have a function f that maps every digit from 1 to 9 to some (possibly the same) digit from 1 to 9. You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in a, and replace each digi...
n = int(input()) a = list(input()) a = [int(x) for x in a] d = {} replacements = list(map(int, input().split())) for i in range(9): d[i+1] = replacements[i] b = [d[x] for x in a] ans = "" flag = False i = 0 j = 0 k = 0 for i in range(len(a)): if(a[i] >= b[i]): ans += str(a[i]) else: flag = True break if(flag):...
842
1197_E. Culture Code
There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has n different matryoshkas. Any matryoshka is a figure of volume out_i with an empty space inside of volume in_i (of course, out_i > in_i). You don't have much free spac...
from sys import stdin, stdout mod = 10**9+7 n = int(input()) dolls = [] for i in range(n): o, i = map(int, stdin.readline().split()) dolls.append((o, i)) dolls.sort() dolls = [(i, o) for (o, i) in dolls] #print(dolls) def bin_search(i): lo = -1 hi = n-1 while lo+1 < hi: mid = (lo+hi-1)/...
843
127_A. Wasted Time
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers. Mr. Scrooge's signature can be represented as a polyline ...
n,k = list(map(int,input().split())) ans = 0 for i in range(n): if i==0: x,y= list(map(int,input().split())) else: X,Y = list(map(int,input().split())) d = ((X-x)**2+(Y-y)**2)**(1/2) x,y=X,Y ans += d ans=((ans*k)/50) print('%.9f'%ans)
844
1323_B. Count Subrectangles
You are given an array a of length n and array b of length m both consisting of only integers 0 and 1. Consider a matrix c of size n × m formed by following rule: c_{i, j} = a_i ⋅ b_j (i.e. a_i multiplied by b_j). It's easy to see that c consists of only zeroes and ones too. How many subrectangles of size (area) k con...
n, m, k = map(int, input().split()) def intervals(arr): res = [] curr = 0 for e in arr: if e == 1: ...
845
1342_A. Road To Zero
You are given two integers x and y. You can perform two types of operations: 1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation: * x = 0, y = 6; * x = 0, y = 8; * x = -1, y = 7; * x = 1, y = ...
def to_list(s): return list(map(lambda x: int(x), s.split(' '))) def solve(x,y,a,b): cost = 0 if b <= 2*a: min_val = min(x,y) cost += b*min_val x -= min_val y -= min_val max_val = max(x,y) cost += max_val*a else: cost = (x+y)*a print(cost) ...
846
1384_B2. Koa and the Beach (Hard Version)
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved. Koa the Koala is at the beach! The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the sho...
import sys import os,io input = sys.stdin.readline # input_all = sys.stdin.read # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # input_all = io.BytesIO(os.read(0,os.fstat(0).st_size)).read def read_int(): return map(int, input().split()) def read_list(): return list(map(int, input().split())) def print...
847
1405_D. Tree Tag
Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first mov...
for t in range(int(input())): n, a, b, da, db = map(int, input().split()) graph = [set() for i in range(n + 1)] for i in range(n - 1): u, v = map(int, input().split()) graph[u].add(v) graph[v].add(u) visited = {1} last_visits = set() visit_now = {1} while len(visited) < n: while visit_now: i = visit...
848
1426_F. Number of Subsequences
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?". Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and...
n=int(input()) s=input() a=[[0,0,0] for i in range(4)] k=s.count('?') b=[1] for i in range(k): b.append(b[i]*3%1000000007) for i in range(n): if s[i]=='a': a[0][0]+=1 elif s[i]=='b': a[0][1]+=a[0][0] a[1][1]+=a[1][0] elif s[i]=='c': a[0][2]+=a[0][1] a[1][2]+=a[1][...
849
1473_E. Minimum Path
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_...
import io import os # import __pypy__ def dijkstra(*args): # return dijkstraHeap(*args) # 2979 ms return dijkstraHeapComparatorWrong(*args) # 2823 ms # return dijkstraHeapComparator(*args) # 2370 ms # return dijkstraSegTree(*args) # 2417 ms with inf=float('inf), 2995 ms with inf=-1 # return d...
850
1550_E. Stringforces
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark. You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized. Let f_i be the maximum length substring of str...
import sys input = sys.stdin.readline n, k = map(int, input().split()) s = input()[:-1] left, right = 0, n while left < right: mid = right - (right - left) // 2 A = [[0] * (n + 2) for _ in range(k)] for c in range(k): A[c][n] = A[c][n + 1] = n + 1 L = 0 for i in range(n - 1, -1, -1...
851
177_B1. Rectangular Game
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. ...
n=int(input()) r=n+1 i=2 s=n**0.5 while i<=s: if n%i==0: r+=n//i n//=i s=n**0.5 i=1 i+=1 print(r)
852
221_A. Little Elephant and Function
The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: ...
n=int(input()) l=list(range(1,n+1)) l=sorted(l) l.insert(0,l[-1]) l.pop() print(*l)
853
245_B. Internet Address
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>] where: * <protocol> can equal either "http" (without the quotes) or "ftp" (without the q...
s = input() if s[:3] == "ftp": pre = "ftp://" s = s[3:] elif s[:4] == "http": pre = "http://" s = s[4:] index = s[1:].index("ru")+1 if index == len(s)-2: s = pre+s[:index]+"."+s[index:] else: s = pre+s[:index]+"."+s[index:index+2]+"/"+s[index+2:] print(s)
854
26_E. Multithreading
You are given the following concurrent program. There are N processes and the i-th process has the following pseudocode: repeat ni times yi := y y := yi + 1 end repeat Here y is a shared variable. Everything else is local for the process. All actions on a given row are a...
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, w = map(int, input().split()) a = [0] + list(map(int, input().split())) total = sum(a) def ng(): print('No') exit() def ok(a): print('Yes') print(*a) exit() if w < 1 or t...
855
340_E. Iahub and Permutations
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the resea...
#lahub and Permutations import sys readline = sys.stdin.buffer.readline def even(n): return 1 if n%2==0 else 0 mod = 10**9+7 def pow(n,p,mod=mod): #繰り返し二乗法(nのp乗) res = 1 while p > 0: if p % 2 == 0: n = n ** 2 % mod p //= 2 else: res = res * n % mod ...
856
388_A. Fox and Box Accumulation
Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most xi boxes on its top (we'll call xi the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For exampl...
I=lambda:list(map(int,input().split())) n,=I() l=I() l.sort() ans=0 i=0 k=1 while i<n: if l[i]<i//k: k+=1 i+=1 print(k)
857
408_D. Long Path
One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one. The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (...
n = int(input()) a = list(map(int,input().split())) values = [0 for k in range(n)] for k in range(n) : back = a[k] if a[k] == k+1 : values[k] = 2 else : values[k] += 2 for t in range(a[k]-1,k) : values [k] += values[t] values[k] %= int(1e9 +7) print(in...
858
459_A. Pashmak and Garden
Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al...
#!/usr/bin/env python3 import atexit import io import sys import bisect _I_B = sys.stdin.read().splitlines() input = iter(_I_B).__next__ _O_B = io.StringIO() sys.stdout = _O_B @atexit.register def write(): sys.__stdout__.write(_O_B.getvalue()) def main(): x1,y1,x2,y2=map(int,input().split()) if x1==x2: ...
859
554_A. Kyoya and Photobooks
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho...
s = input() l = list(s) a = 'abcdefghijklmnopqrstuvwxyz' for i in range(len(s)+1): for j in a: l.insert(i, j) print(len(l)-2*len(s))
860
624_B. Making a String
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied: * the i-th letter occurs in the string no more than ai times; * the number of occurrences of each letter in the string must be distinct for all the lette...
n = int(input()) m = list(map(int, input().split())) m.sort(reverse = True) ans = m[0] last = m[0] for i in range(1, len(m)): last = max(min(last - 1, m[i]), 0) ans += last print(ans)
861
672_D. Robin Hood
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor. There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to t...
import sys sys.stderr = sys.stdout def hood(n, k, C): C.sort() m, r = divmod(sum(C), n) m1 = (m + 1) if r else m c_lo = C[0] k_lo = k for i, c in enumerate(C): if c_lo == m: break c_m = min(c, m) dc = c_m - c_lo dk = i * dc if k_lo >= dk: ...
862
832_D. Misha, Grisha and Underground
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other. The boys decided to have fun and came up with a plan. Namely, in some day in the morning M...
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.writable = "x" in file.mode or "r" ...
863
853_B. Jury Meeting
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process. There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for...
from bisect import * from sys import * n,m,k=[int(i) for i in input().split()] pln=[] if m==0: print(-1) exit(0) for i in range(m): pln.append([int(i) for i in input().split()]) pln.sort() grp=[[pln[0]]];gt=0; for i in range(1,m): if pln[i][0]!=pln[i-1][0]: gt=gt+1 grp.append([]) gr...
864
877_F. Ann and Books
In Ann's favorite book shop are as many as n books on math and economics. Books are numbered from 1 to n. Each of them contains non-negative number of problems. Today there is a sale: any subsegment of a segment from l to r can be bought at a fixed price. Ann decided that she wants to buy such non-empty subsegment t...
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file....
865
901_B. GCD of Polynomials
Suppose you have two polynomials <image> and <image>. Then polynomial <image> can be uniquely represented in the following way: <image> This can be done using [long division](https://en.wikipedia.org/wiki/Polynomial_long_division). Here, <image> denotes the degree of polynomial P(x). <image> is called the remainder o...
""" NTC here """ import sys inp= sys.stdin.readline input = lambda : inp().strip() flush= sys.stdout.flush # import threading # sys.setrecursionlimit(10**6) # threading.stack_size(2**25) def iin(): return int(input()) def lin(): return list(map(int, input().split())) # range = xrange # input = raw_input def main():...
866
952_A. Quirky Quantifiers
Input The input contains a single integer a (10 ≤ a ≤ 999). Output Output 0 or 1. Examples Input 13 Output 1 Input 927 Output 1 Input 48 Output 0
b=int(input()) if b%2==0: print(0) else: print(1)
867
979_C. Kuro and Walking Route
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choos...
def calculate_max_paths(edges, node, dest, par, cnt): ans = 1 for child in edges.get(node, []): if child != par: ans += calculate_max_paths(edges, child, dest, node, cnt) if dest == node: cnt[0] = ans return ans def main(): from collections import defaultdict ...
868
1004_D. Sonya and Matrix
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit. Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers ...
def get(n,m,a,b,t): freq=[0]*(t+1) for i in range(n): for j in range(m): val=abs(i-a)+abs(j-b) freq[val]+=1 return freq t=int(input()) a=list(map(int,input().split())) mx=max(a) f=[0]*(t+1) for i in a: f[i]+=1 b=1 for i in range(1,mx+1): if f[i]!=4*i: b=i ...
869
1028_D. Order book
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price. At every moment of time, every SELL offer has higher price than every BUY offer. In th...
from sys import stdin import heapq MOD = pow(10, 9) + 7 n=int(stdin.readline()) a=[] for i in range(n): x=stdin.readline().split() if x[0]=='ADD': a.append((0,int(x[1]))) else: a.append((1,int(x[1]))) next_accept=[-1]*n accept = -1 for i in range(n-1, -1, -1): if a[i][0]== 1: acc...
870
1092_D2. Great Vova Wall (Version 2)
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches. The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th par...
n=int(input()) a=list(map(int,input().split())) down=[] good=True for guy in a: if len(down)==0: down.append(guy) elif down[-1]>guy: down.append(guy) elif down[-1]==guy: down.pop() else: good=False break if not good: print("NO") elif len(down)>1: print("NO...
871
1111_C. Creative Snap
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base. Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the...
def solve (l,r,y) : if (len(y) == 0) : return a if (l == r) : return b*len(y) c = [] d = [] m = (l+r)//2 for i in y : if i <= m : c += [i] else : d += [i] return min(b*(r-l+1)*len(y) , solve(l,m,c) + solve(m+1,r,d)) n,k,a,b = list(...
872
1141_A. Game 23
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves. Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so. It is easy to prove that any way to trans...
def fun(a,b): if a % b != 0: return -1 temp = 0 m = a/b while m % 2 == 0: m = m / 2 temp += 1 while m % 3 == 0: m = m/3 temp += 1 if m == 1: return temp else : return -1 a,b = map(int,input().split()) print(fun(b,a))
873
1260_A. Heating
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house. Your house has n rooms. In the i-th room you can install at most c_i heating radiators. Each radiator can have several sections, but ...
n=int(input()) for i in range(n): x = list(map(int, input().split(" "))) print(((x[1]%x[0])*((x[1]//x[0]+1)**2))+(((x[1]//x[0])**2)*(x[0]-(x[1]%x[0]))))
874
1282_B1. K for the Price of One (Easy Version)
This is the easy version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: k=2. Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in store...
""" Author : thekushalghosh Team : CodeDiggers """ import sys,math input = sys.stdin.readline ############ ---- USER DEFINED INPUT FUNCTIONS ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(s[:len(s) - 1]) def ...
875
1326_B. Maximums
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0. For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}. Then, she calculated an array, b_1, b_2, …, b_n: ...
input() b = list(map(int,input().split())) a = list() sumnum = 0 negnum = 0 for i in range(len(b)): sumnum += b[i] a.append(sumnum+abs(negnum)) if b[i]<0: negnum += b[i] print(*a)
876
1408_G. Clusterization Counting
There are n computers in the company network. They are numbered from 1 to n. For each pair of two computers 1 ≤ i < j ≤ n you know the value a_{i,j}: the difficulty of sending data between computers i and j. All values a_{i,j} for i<j are different. You want to separate all computers into k sets A_1, A_2, …, A_k, suc...
# import itertools as it # import functools as ft import math teststring = """4 0 3 4 6 3 0 2 1 4 2 0 5 6 1 5 0 """ online = __file__ != "/home/jhli/py/Grakn/Problem_G2.py" true, false = True, False if True: def spitout(): for c in teststring.splitlines(): yield c _ito = spitout() ...
877
142_A. Help Farmer
Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simple...
import math n = int(input()) mx = 0 mn = 4 * 10**18 for A in range(1, n+1): if A * A * A > n: break if n % A: continue nn = n // A for B in range(1, nn+1): if B * B > nn: break if nn % B: continue C = nn // B mn = min(mn, (A + 1) * (B + 2) * (C + 2) - n) mx = max(mx, (A + 1) * (B + 2) * (C +...
878
1452_E. Two Editorials
Berland regional ICPC contest has just ended. There were m participants numbered from 1 to m, who competed on a problemset of n problems numbered from 1 to n. Now the editorial is about to take place. There are two problem authors, each of them is going to tell the tutorial to exactly k consecutive tasks of the proble...
# Enter your code here. Read input from STDIN. Print output to STDOUT# =============================================================================================== # importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import Byt...
879
158_B. Taxi
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
n=int(input()) a=list(map(int,input().split())) s=[0]*5 sum=0 for i in a: s[i]+=1 sum+=s[4]+s[3] if s[3]<s[1]: s[1]-=s[3] s[3]=0 else : s[3]=0 s[1]=0 sum+=s[2]//2 s[2]%=2 sum+=s[1]//4 s[1]%=4 end=s[2]*2+s[1] if end>4:sum+=2 elif end>0: sum+=1 print(int(sum))
880
224_D. Two Strings
A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≤ k1 < k2 < ... < k|x| ≤ |s|). You've got two strings — s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at...
import bisect import string s = input() t = input() max_match = [0 for i in range(len(s))] min_match = [0 for i in range(len(s))] char_idx = [0 for i in range(30)] char_occur = [ [] for i in range(30) ] for (i, ch) in enumerate(t): idx = ord(ch) - ord('a') char_occur[idx].append(i) for ch in string.ascii_lo...
881
249_B. Sweets for Everyone!
For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her paren...
def check(n, casas): #print('n:',n) global T,N,street current = n time = T need = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == ...
882
296_E. Greg and Friends
One day Greg and his friends were walking in the forest. Overall there were n people walking, including Greg. Soon he found himself in front of a river. The guys immediately decided to get across the river. Luckily, there was a boat by the river bank, just where the guys were standing. We know that the boat can hold pe...
from collections import deque n, k = [int(i) for i in input().split()] a = [int(i) for i in input().split()] c50 = sum([1 for i in a if i == 50]) c100 = sum([1 for i in a if i == 100]) c = [[0] * 51 for i in range(51)] c[0][0] = 1 c[1][0] = 1 c[1][1] = 1 for x in range(2, 51): for y in range(x + 1): c[x][y...
883
31_C. Schedule
At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, becaus...
from operator import add import sys from array import array # noqa: F401 from typing import TypeVar, Generic, Callable, List T = TypeVar('T') class SegmentTree(Generic[T]): __slots__ = ["size", "tree", "identity", "op", "update_op"] def __init__(self, size: int, identity: T, op: Callable[[T, T], T], ...
884
344_C. Rational Resistance
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value. However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will co...
import sys import string import math import heapq from collections import defaultdict from collections import deque from collections import Counter from functools import lru_cache from fractions import Fraction def mi(s): return map(int, s.strip().split()) def lmi(s): return list(mi(s)) def tmi(s): retur...
885
390_A. Inna and Alarm Clock
Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 × 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square. The morning has ...
n = int(input()) x_set = set() y_set = set() for i in range(n): x,y = map(int, input().split()) x_set.add(x) y_set.add(y) print(min(len(x_set), len(y_set)))
886
411_C. Kicker
Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the ...
x = [tuple(int(i) for i in input().split()) for j in range(4)] if x[0][0] + x[1][1] > x[0][1] + x[1][0]: t1atk = x[1][1] t1def = x[0][0] else: t1atk = x[0][1] t1def = x[1][0] def f(): if t1atk > t2def and t1def > t2atk: return 0 elif t1atk < t2def and t1def < t2atk: return 2 ...
887
439_B. Devu, the Dumb Guy
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously. Let us say that his initial per chapter learning power of a subject is x hours. In other words he can...
n, x = map(int, input().split()) m = list(map(int, input().split())) m.sort() ans = 0 for i in range(n): ans += m[i] * x if x > 1: x -= 1 print(ans)
888
460_D. Little Victor and Set
Little Victor adores the sets theory. Let us remind you that a set is a group of numbers where all numbers are pairwise distinct. Today Victor wants to find a set of integers S that has the following properties: * for all x <image> the following inequality holds l ≤ x ≤ r; * 1 ≤ |S| ≤ k; * lets denote the i-th...
import random l, r, k = map(int, input().split(' ')) if k == 1: print(l) print(1) print(l) quit() if k == 2: if r == l+1: a = l b = l^r if a <= b: print(a) print(1) print(l) quit() else: print(b) ...
889
508_C. Anya and Ghosts
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one can...
import sys ghosts, duration, candles = input().split() arrival = input().split() burn = [] for j in range(len(arrival)): time = int(arrival[len(arrival) - 1 - j]) candle = int(candles) if len(burn) != 0: for k in range(len(burn)): if burn[k] <= time: candle -= 1 for ...
890
557_D. Vitaly and Cycle
After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not ne...
def connected_components(n, graph): components, visited = [], [False] * n def dfs(start): component, stack = [], [start] while stack: start = stack[-1] if visited[start]: stack.pop() continue else: visited[sta...
891
583_B. Robot's Task
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at ...
n = int(input()) a = [int(x) for x in input().split()] hacked = 0 pos = 0 changes = 0 right = True while hacked < n: if right: r = range(pos, n) else: r = range(pos, -1, -1) for i in r: if a[i] <= hacked: a[i] = n + 1 hacked += 1 pos = i if ...
892
605_B. Lazy Student
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following defin...
n, m = (int(x) for x in input().split()) edges = [] for i in range(m): w, in_tree = input().split() edges.append([int(w), i, int(in_tree)]) sorted_edges = sorted(edges, key = lambda e: (e[0], -e[2])) print def free_edge(): for y in range(3, n+1): for x in range(2, y): yield [x, y] f = fr...
893
627_C. Package Delivery
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d. Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes ...
destination, max_gas_tank_volume, gas_prices_number = map(int, input().split()) start_point = 0 gas_prices = {start_point:0} for i in range(gas_prices_number): coordinate, price = map(int, input().split()) gas_prices[coordinate] = price points = sorted(gas_prices.keys(), reverse = True) current_point = start_po...
894
651_C. Watchmen
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi). They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan consider...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def inc_val_of_dict(dictionary, key): if key not in dictionary: dictionary[key] = 0 dictionary[key] += 1 def main(): n = int(input()) p_ctr = dict() x_ctr = dict() y_ctr = dict() for _ in range(n): x, y = map(int, input().spl...
895
677_A. Vanya and Fence
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
lin1 = input().split() h = input().split() for i in range(len(h)): h[i] = int(h[i]) n_friends = int(lin1[0]) h_fence = int(lin1[1]) total = 0 for i in h: if i > h_fence: total += 2 else: total += 1 print(total)
896
6_A. Triangle
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allo...
# https://codeforces.com/problemset/problem/6/A import sys #-----------------------------------------------------------------------------# # # comment before submission # sys.stdin = open('inputs.txt', 'r') # sys.stdout = open('output.txt', 'w') #------------------------------------------------------------------------...
897
721_C. Journey
Recently Irina arrived to one of the most famous cities of Berland — the Berlatov city. There are n showplaces in the city, numbered from 1 to n, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there are no cyclic routes between showplaces. Initially Irina...
n, m, T = map(int, input().split()) graph_a = [[] for _ in range(n+1)] graph_b = [[] for _ in range(n+1)] double_graph_a = [[0 for _ in range(n+1)] for _ in range(n+1)] double_graph_b = [[0 for _ in range(n+1)] for _ in range(n+1)] for i in range(m): u, v, t = map(int, input().split()) graph_a[v].append(u) ...
898
743_A. Vladik and flights
Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad. Vladik knows n airports. All the airports are located on a straight line. Each airport has uni...
n, a, b = list(map(int, input().split())) line = [] aa = input() for i in range(n): line += [int(aa[i])] print(0 + (line[a-1] != line[b-1]))
899
766_C. Mahmoud and a Message
Mahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alpha...
N, s, l = int(input()), [ord(x) - ord('a') for x in input()], [int(x) for x in input().split()] arr = [[1, l[s[0]]]] total = 1 ma = 1 t = 1 mi = 1 for c in s[1:]: tmp = 0 for i in range(len(arr)): arr[i][1] = min(arr[i][1],l[c]) if i + 1 >= arr[i][1]: arr = arr[:i] if(t > i): t = 0 mi += 1 break ...