name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p03953 AtCoder Grand Contest 006 - Rabbit Exercise
There are N rabbits on a number line. The rabbits are conveniently numbered 1 through N. The coordinate of the initial position of rabbit i is x_i. The rabbits will now take exercise on the number line, by performing sets described below. A set consists of M jumps. The j-th jump of a set is performed by rabbit a_j (2≤...
```python n = int(input()) x = list(map(int,input().split())) m,k = map(int,input().split()) a = list(map(int,input().split())) b = [] x2 = [] c = [] for i in range(1,n): b.append(i-1) x2.append(x[i]-x[i-1]) for i in range(m): to = a[i]-1 b[to],b[to-1] = b[to-1],b[to] c = [-1] * (n-1) for i in range(n-1): c[b...
p00043 Puzzle
There is a puzzle to complete by combining 14 numbers from 1 to 9. Complete by adding another number to the given 13 numbers. The conditions for completing the puzzle are * You must have one combination of the same numbers. * The remaining 12 numbers are 4 combinations of 3 numbers. The combination of three numbers i...
```python import sys def f(c): if sum(c)in c:return 1 if 5 in c:return 0 if 4 in c: k=c.index(4);c[k]-=3 if f(c):return 1 c[k]+=3 if 3 in c: k=c.index(3);c[k]-=3 if f(c):return 1 c[k]+=3 for i in range(7): if c[i]and c[i+1]and c[i+2]: c[i]-=1;c[i+1]-=1;c[i+2]-=1 if f(c):return 1 c[i]+=1;c[i+...
p00175 Quaternary Notation
Decimal numbers are a common notation system currently in use and use ten symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 to represent all numbers. Binary numbers are a popular notation in the computer world and use two symbols, 0 and 1, to represent all numbers. Only the four numbers 0, 1, 2, and 3 are used in quaternary n...
```python while True: v = int(input()) if v == -1: break if v < 4: print(v) else: b = str(bin(v))[2:] bb = [b[i:i+2] for i in range(len(b)-2, -1, -2)] if len(b) % 2 != 0: bb.append(b[0]) ans = [] for t in bb: tmp = 0 ...
p00331 Sunrise and Sunset
The appearance of the sun is called "sunrise" and the hiding is called "sunset". What is the exact time when the sun is on the horizon? As shown in the figure below, we will represent the sun as a circle and the horizon as a straight line. At this time, the time of "sunrise" and "sunset" of the sun is the moment when ...
```python h,r=map(int,input().split()) if h>=0: print(1) elif h+r==0: print(0) else: print(-1) ```
p00688 Factorization of Quadratic Formula
As the first step in algebra, students learn quadratic formulas and their factorization. Often, the factorization is a severe burden for them. A large number of students cannot master the factorization; such students cannot be aware of the elegance of advanced algebra. It might be the case that the factorization increa...
```python import fractions while True: a, b, c = map(int, input().split()) if not a: break d = (b ** 2 - 4 * a * c) ** 0.5 if isinstance(d, complex) or d - int(d) > 1e-6: print('Impossible') continue num1, num2 = -b + int(d), -b - int(d) den = 2 * a cmn1, cmn2 = frac...
p00830 Pathological Paths
Professor Pathfinder is a distinguished authority on the structure of hyperlinks in the World Wide Web. For establishing his hypotheses, he has been developing software agents, which automatically traverse hyperlinks and analyze the structure of the Web. Today, he has gotten an intriguing idea to improve his software a...
```python # from urllib.parse import urljoin def testcase_ends(): n, m = map(int, input().split()) if (n, m) == (0, 0): return 1 htmls = set(input() for i in range(n)) files = set('/') for html in htmls: sp = html.split('/') for i in range(2, len(sp)): files.add...
p01094 Look for the Winner!
Look for the Winner! The citizens of TKB City are famous for their deep love in elections and vote counting. Today they hold an election for the next chairperson of the electoral commission. Now the voting has just been closed and the counting is going to start. The TKB citizens have strong desire to know the winner a...
```python from collections import Counter while True: n = int(input()) if n == 0: quit() elif n == 1: print(input(), 1) else: c = list(input().split()) h = [0 for i in range(26)] flag = 0 for i in range(n): h[ord(c[i])-65] += 1 if ...
p01364 Two-Wheel Buggy
International Car Production Company (ICPC), one of the largest automobile manufacturers in the world, is now developing a new vehicle called "Two-Wheel Buggy". As its name suggests, the vehicle has only two wheels. Quite simply, "Two-Wheel Buggy" is made up of two wheels (the left wheel and the right wheel) and a axle...
```python from math import pi, cos, sin def solve(): def rotate(x, y, theta): cv = cos(theta); sv = sin(theta) return x*cv - y*sv, x*sv + y*cv N, D = map(int, input().split()) if N == D == 0: return False x0 = -D; x1 = D y0 = y1 = 0 for i in range(N): dl, dr, t = ...
p01546 Sports Days 2
The University of Aizu Elementary School (Aizu University and Small) is famous as one of Japan's leading competition programmer training schools. Of course, it is essential to practice the algorithm even when attending an athletic meet. Of course you, the director of the competitive programming department, want to win ...
```python from heapq import heappush, heappop, heapify import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, M, K = map(int, readline().split()) INF = 10**18 E = [[-INF]*N for i in range(N)] for i in range(M): a, b, c = map(int, readline().split()) E[a][b] = m...
p01702 Unknown Switches
Problem Statement In the headquarter building of ICPC (International Company of Plugs & Connectors), there are $M$ light bulbs and they are controlled by $N$ switches. Each light bulb can be turned on or off by exactly one switch. Each switch may control multiple light bulbs. When you operate a switch, all the light b...
```python while 1: n,m,q=map(int,input().split()) if (n|m|q)==0: break p=[] res=[{_ for _ in range(n)} for _ in range(m)] for i in range(q): s,b=[[int(c) for c in s] for s in input().split()] if i>0: for j in range(n): s[j]^=p[j] zero={i for i in range(n) if s[i]==0} one={i fo...
p01846 jfen
jfen There is a one-person game to play on the H × W board. This game is a game to move 0 or 1 balls in each cell. You were playing this game and found it difficult to move the ball accurately from cell to cell because the ball is so round. So you decided to make a robot that would move the ball as instructed. Here, t...
```python while True: s = input() if s == "#":break s = s.split("/") area = [0] * len(s) for i in range(len(s)): t = [] while True: if s[i][0] == "b": t.append(1) s[i] = s[i][1:] else: if "b" in s[i]: ...
p01982 Generalized Leap Years
Generalized leap year Normally, whether or not the year x is a leap year is defined as follows. 1. If x is a multiple of 400, it is a leap year. 2. Otherwise, if x is a multiple of 100, it is not a leap year. 3. Otherwise, if x is a multiple of 4, it is a leap year. 4. If not, it is not a leap year. This can be ge...
```python def solve(n ,l, r, A): res = 0 for x in range(l, r+1): for i in range(n): if (not x%A[i]) : res += 0 if (i&1) else 1 break else: res += 0 if (n&1) else 1 return res def main(): ans = [] while True: n, l, r =...
p02128 Light
Problem There are $ N $ streetlights on a two-dimensional square of $ W \ times H $. Gaccho wants to start with $ (1,1) $ and go to $ (W, H) $. Gaccho is afraid of dark places, so he only wants to walk in the squares that are brightened by the streetlights. Initially, all streetlights only brighten the squares with th...
```python import heapq class point: def __init__(self, total, use, place): self.total = total self.use = use self.place = place def __lt__(self, other): return self.total < other.total or (self.total == other.total and self.use > self.use) w, h, n = map(int, input().split()) i...
p02269 Dictionary
Your task is to write a program of a simple dictionary which implements the following instructions: * insert str: insert a string str in to the dictionary * find str: if the distionary contains str, then print 'yes', otherwise print 'no' Notes Template in C Constraints * A string consists of 'A', 'C', 'G', or 'T' ...
```python n = int(input()) dic = {} for i in range(n): a = input() if a[0] == "i": dic[a[7:]] = 0 else: if a[5:] in dic: print("yes") else: print("no") ```
p02416 Sum of Numbers
Write a program which reads an integer and prints sum of its digits. Input The input consists of multiple datasets. For each dataset, an integer x is given in a line. The number of digits in x does not exceed 1000. The input ends with a line including single zero. Your program should not process for this terminal ...
```python while True: n = input() if n == "0": break n = map(int, n) print(sum(n)) ```
1013_A. Piles With Stones
There is a beautiful garden of stones in Innopolis. Its most beautiful place is the n piles with stones numbered from 1 to n. EJOI participants have visited this place twice. When they first visited it, the number of stones in piles was x_1, x_2, …, x_n, correspondingly. One of the participants wrote down this sequ...
```python n=int(input()) p=input().split(' ') c=input().split(' ') t=z=0 for k in range(n): t+=int(p[k]) z+=int(c[k]) if (t<z): print('No') else: print('Yes') ```
1060_C. Maximum Subrectangle
You are given two arrays a and b of positive integers, with length n and m respectively. Let c be an n × m matrix, where c_{i,j} = a_i ⋅ b_j. You need to find a subrectangle of the matrix c such that the sum of its elements is at most x, and its area (the total number of elements) is the largest possible. Formally...
```python n,m=[int(x) for x in input().split()] a=[int(x) for x in input().split()] b=[int(x) for x in input().split()] x=int(input()) csa=[0]*(n+1) csb=[0]*(m+1) ans=0 for i in range(1,n+1): csa[i]=(csa[i-1]+a[i-1]) for i in range(1,m+1): csb[i]=(csb[i-1]+b[i-1]) misubsa=[0]*(n+1) misubsb=[0]*(m+1) for i in ra...
1082_A. Vasya and Book
Vasya is reading a e-book. The file of the book consists of n pages, numbered from 1 to n. The screen is currently displaying the contents of page x, and Vasya wants to read the page y. There are two buttons on the book which allow Vasya to scroll d pages forwards or backwards (but he cannot scroll outside the book). F...
```python T = int(input()) from math import ceil for i in range(T): n,in_,fin_,d = map(int,input().split()) r1 = in_%d r2 = fin_%d r = n%d z = float("inf") a1,a2,a3 = float("inf"),float("inf"),float("inf") if r1 == r2: a1 = abs(fin_-in_)//d if r2 == r: a2 = ceil((n-in_)/d)+abs((fin_-n)//d) if r2 == 1: ...
1101_C. Division and Union
There are n segments [l_i, r_i] for 1 ≤ i ≤ n. You should divide all segments into two non-empty groups in such way that there is no pair of segments from different groups which have at least one common point, or say that it's impossible to do it. Each segment should belong to exactly one group. To optimize testing pr...
```python for _ in range(int(input())): n=int(input()) a=sorted(list(map(int,input().split()))+[i] for i in range(n)) ans=[0]*n group=1 maxx=a[0][1] for l,r,i in a: if group==1 and maxx<l: group=2 if r>maxx: maxx=r ans[i]=group if group==2: ...
112_A. Petya and Strings
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
```python a=input();b=input() A=a.lower();B=b.lower() if A==B: print(0) elif A>B: print(1) elif A<B: print(-1) ```
114_B. PFAST Inc.
When little Petya grew up and entered the university, he started to take part in АСМ contests. Later he realized that he doesn't like how the АСМ contests are organised: the team could only have three members (and he couldn't take all his friends to the competitions and distribute the tasks between the team members eff...
```python '''input 7 12 Pasha Lesha Vanya Taras Nikita Sergey Andrey Pasha Taras Pasha Nikita Pasha Andrey Pasha Sergey Lesha Taras Lesha Nikita Lesha Andrey Lesha Sergey Vanya Taras Vanya Nikita Vanya Andrey Vanya Sergey ''' from sys import stdin, stdout from collections import deque import sys from copy import deepco...
1189_E. Count Pairs
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k. Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p. Input The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime. The se...
```python from collections import Counter n, p, k = map(int, input().split()) arr = [ (x ** 4 - k * x) % p for x in list(map(int, input().split())) ] print( sum([ (x * (x - 1)) // 2 for x in Counter(arr).values() ]) ) ```
126_B. Password
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them. A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the t...
```python from fractions import Fraction import bisect import os from collections import Counter import bisect from collections import defaultdict import math import random import heapq as hq from math import sqrt import sys from functools import reduce, cmp_to_key from collections import deque import threading from it...
1292_A. NEKO's Maze Game
[3R2 as DJ Mashiro - Happiness Breeze](https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak) [Ice - DJ Mashiro is dead or alive](https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive) NEKO#ΦωΦ has just got a new maze game on her PC! The game's main puzzle is a maze, in the forms of a 2 × n rectangle grid. NEKO...
```python import sys input = sys.stdin.readline hell=1000000007 def meowmeow321(): n,q=map(int,input().split()) cnt=0 mark1 = [0]*(n+5) mark2 = [0]*(n+5) for i in range(q): r,c = map(int,input().split()) if r==1: if mark1[c]: cnt-=mark2[c] ...
1312_B. Bogosort
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, ...
```python N=int(input()) for i in range(N): b=int(input()) a=list(map(int, input().split()[:b])) print(*sorted(a)[::-1]) ```
1355_A. Sequence with Digits
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
```python ans = [] for h in range(int(input())): a, k = map(int, input().strip().split()) temp = a a = str(a) for i in range(k-1): maxi = int(max(a)); mini = int(min(a)) a = str(temp + maxi*mini) if '0' in a: break temp = int(a) ans.append(a) print('...
1374_F. Cyclic Shifts Sorting
You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no m...
```python def swap(i): tmp = a[i+2] a[i+2] = a[i+1] a[i+1] = a[i] a[i] = tmp ans.append(i+1) #print (*a) tt = int(input()) for loop in range(tt): n = int(input()) a = list(map(int,input().split())) sa = 0.0001 lis = [sa] * 501 b1 = [] b2 = [] f2 ...
1398_C. Good Subarrays
You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1...
```python from collections import defaultdict as dd # d=dd(lambda:0) from sys import stdin stdin.readline def mp(): return list(map(int, stdin.readline().strip().split())) def it():return int(stdin.readline().strip()) for _ in range(it()): n=it() l=input() v=[] for i in l: v.append(int(i)) # for i in range(n):...
1421_D. Hexagons
Lindsey Buckingham told Stevie Nicks ["Go your own way"](https://www.youtube.com/watch?v=6ul-cZyuYq4). Nicks is now sad and wants to go away as quickly as possible, but she lives in a 2D hexagonal world. Consider a hexagonal tiling of the plane as on the picture below. <image> Nicks wishes to go from the cell marked...
```python import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) #import sys #input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'....
143_C. 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...
```python from math import sqrt p, n = [], int(input()) def f(x, y): return (x + 2) * (y + 2) + (2 * (x + y + 2) * n) // (x * y) for x in range(2, int(sqrt(n)) + 1): if n % x == 0: p.append(x) p += [n // x for x in reversed(p)] p.append(n) u = v = f(1, 1) for m in p: for x in range(1, int(sqrt(m)) + 1)...
1491_B. Minimal Cost
There is a graph of n rows and 10^6 + 2 columns, where rows are numbered from 1 to n and columns from 0 to 10^6 + 1: <image> Let's denote the node in the row i and column j by (i, j). Initially for each i the i-th row has exactly one obstacle — at node (i, a_i). You want to move some obstacles so that you can reach ...
```python t=int(input()) while t: n,v,h=map(int,input().split()) a=list(map(int,input().split())) diff=0 for i in range(1,n): diff=max(abs(a[i]-a[i-1]),diff) if diff>=2: print(0) elif diff==1: print(min(v,h)) elif diff==0: print(min(h+h,v+h)) t=t-1 ```
1513_E. Cost Equilibrium
An array is called beautiful if all the elements in the array are equal. You can transform an array using the following steps any number of times: 1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index. 2. Decrease the i-th element by x, an...
```python n=int(input());a=*map(int,input().split()),;s=sum(a) if s%n:print(0);exit(0) M=10**9+7;s//=n;f=[1]*(n+1);b=[0]*3;d=dict() for i in range(2,n+1):f[i]=f[i-1]*i%M for x in a: b[(x>s)-(x<s)]+=1 try:d[x]+=1 except:d[x]=1 k=1 for x in d.values():k*=f[x] k=f[n]*pow(k,M-2,M) print([k%M,f[b[1]]*f[b[-1]]*2*pow(f[n-b...
168_C. Wizards and Trolleybuses
In some country live wizards. They love to ride trolleybuses. A city in this country has a trolleybus depot with n trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of d meters from the depot. We know for the i-th trolleybus that it lea...
```python # written with help of passed solutions from math import sqrt n, a, d = map(int, input().split()) a = float(a) ans = [0] * n tm = 0 for i in range(n): t, v = map(int, input().split()) acc_t = v / a add_t = 0 if acc_t ** 2 * a > 2 * d: add_t = sqrt(2 * d / a) else: add_t ...
189_A. Cut Ribbon
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions: * After the cutting each ribbon piece should have length a, b or c. * After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces ...
```python from math import *; lineup=[int(x) for x in input().split()] a,b,c=sorted(lineup[1:4]) n=lineup[0] value=0 if a==1: print(n) exit() for i in range(0,n+1,a): for j in range(0,n+1,b): z=(n-i-j)/c if ceil(z)==floor(z) and int(z)>=0: x=i//a y=j//b z=int(z) value=max(value,x+y+z) print(int(value...
236_A. Boy or Girl
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
```python for _ in range(1): x=set(list(input())) if len(x)%2==0: print('CHAT WITH HER!') else: print("IGNORE HIM!") ```
260_D. Black and White Tree
The board has got a painted tree graph, consisting of n nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles. Each node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each edge...
```python n = int(input()) white, black = [], [] for i in range(n): color, weightSum = map(int, input().split()) if color == 0: white.append([weightSum, i+1]) else : black.append([weightSum, i+1]) #white.sort() #black.sort() wc,bc, wl, bl, edges = 0 , 0, len(white), len(black), [] while...
332_B. Maximum Absurdity
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed. This time mr. Boosch plans to sign 2k l...
```python def main(): wynik = 0 para = (0,0) n,k = input().split() n,k = int(n), int(k) odl = [] tab = list(map(int, input().split())) pocz = tab[0] odl = [pocz] for i in range(1,n): if i < k : odl.append(odl[i-1]+tab[i]) else: odl.append(odl[...
355_B. Vasya and Public Transport
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m. Public transport is not free. There are 4 types of tickets: 1. A ticket for one r...
```python c1,c2,c3 ,c4 = map(int,input().split()) n , m = map(int, input().split()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] ans1 = 0 ans2 = 0 for i in a: ans1 += min(c1 * i,c2) ans1 = min(ans1, c3) for i in b: ans2 += min(c1 * i,c2) ans2 = min(ans2, c3) ans = min(ans1 + ans2,...
379_C. New Year Ratings Change
One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors. There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai ratin...
```python n = int(input()) x = list(map(int, input().split())) ans = x.copy() b = sorted(x.copy()) k = b[0] + 1 d = {b[0]: [1, b[0]]} for i in range(1, n): if b[i - 1] == b[i]: d[b[i]].append(k) k += 1 else: if b[i] < k: d[b[i]] = [1, k] else: d[b[i]] = [1...
39_J. Spelling Check
Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he d...
```python s,t=input(),input() n=idx=len(t) for i in range(n): if s[i]!=t[i]: idx=i break for i in range(idx+1,n+1): if s[i]!=t[i-1]: print(0) import sys sys.exit() i=idx while i>0 and s[i-1]==s[idx]: i-=1 print(idx-i+1) print(' '.join(map(str,range(i+1,idx+2)))) ```
426_A. Sereja and Mugs
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and n water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume that...
```python n, s = map(int, input().split()) arr = list(map(int, input().split())) print("NO" if sum(arr) - max(arr) > s else "YES") ```
495_A. Digital Counter
Malek lives in an apartment block with 100 floors numbered from 0 to 99. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with 7 light sticks by turning them on or off. The picture below shows how the elevator shows each ...
```python from sys import stdin def nb_good_numbers(n): by_digit = { "0": 2, "1": 7, "2": 2, "3": 3, "4": 3, "5": 4, "6": 2, "7": 5, "8": 1, "9": 2, } result = 1 for digit in n: result *= by_digit[digit] return...
519_D. A and B and Interesting Substrings
A and B are preparing themselves for programming contests. After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes. A likes lowercase letters of the Latin alphabet. He has assigned to each letter a ...
```python xx = [int(i) for i in input().split()] s = input() x = [{} for _ in range(0,26)] ss = 0 ans = 0 for i in s: ans += x[ord(i)-97].get(ss,0) ss += xx[ord(i)-97] x[ord(i)-97][ss] = x[ord(i)-97].get(ss,0)+1 print(ans) ```
545_E. Paths and Trees
Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows. Let's assume that we are given a c...
```python import heapq n, m = map(int, input().split()) g = [[] for _ in range(n + 1)] for i in range(1, m + 1): u, v, w = map(int, input().split()) g[u].append((i, v, w)) g[v].append((i, u, w)) src = int(input()) pq = [(0, 0, src, -1)] mk = [0] * (n + 1) t = [] s = 0 while pq: d, w, u, e = heapq.heap...
572_B. Order Book
In this task you need to process a set of stock exchange orders and use them to create order book. An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell...
```python n,s = [int(x) for x in input().split()] buy_dict = {} sell_dict = {} for i in range(n): chtype,pi,di = input().split() pi = int(pi) di = int(di) if chtype=='B': buy_dict[pi] = buy_dict.get(pi,0)+di else: sell_dict[pi] = sell_dict.get(pi,0)+di buy_list = sorted(buy_dict.items(),reverse=True)[:s] sell_...
615_C. Running Track
A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art. First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the tra...
```python def find_max_substr(t, s): l, r = 0, len(t) while l != r: m = (l + r) // 2 if t[:m + 1] in s: l = m + 1 else: r = m l1 = l rs = s[::-1] l, r = 0, len(t) while l != r: m = (l + r) // 2 if t[:m + 1] in rs: l = m ...
634_E. Preorder Test
For his computer science class, Jacob builds a model tree with sticks and balls containing n nodes in the shape of a tree. Jacob has spent ai minutes building the i-th ball in the tree. Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to ...
```python import sys input = sys.stdin.readline n, k = map(int, input().split()) a = [int(i) for i in input().split()] g = [[] for _ in range(n)] for i in range(n - 1): u, v = map(int, input().split()) g[u-1].append(v-1) g[v-1].append(u-1) stack = [0] done = [False] * n par = [0] * n order = [] while len(stack) > 0...
688_A. Opponents
Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya...
```python import math from typing import Iterable, List def solve(arr:Iterable[str], n: int) -> int: curr = 0 res = 0 for v in arr: if v == '1'*n: curr = 0 else : curr += 1 res = max(res , curr) return res def main(): n,d = map(int, input().split(' ')) arr = [] ...
755_B. PolandBall and Game
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses. You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, i...
```python import sys input = sys.stdin.readline n, m = input().split() n = int(n) m = int(m) polW = [] eneW = [] turnsP = 0 turnsE = 0 same = 0 for i in range(n): polW.append(input()) turnsP+=1 for i in range(m): word = input() if word in polW: turnsP-=1 same+=1 else: ...
776_C. Molly's Chemicals
Molly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The i-th of them has affection value ai. Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affectio...
```python from sys import stdin n,k = [int(x) for x in stdin.readline().split()] arr = [int(x) for x in stdin.readline().split()] sums = [0] for x in arr: sums.append(sums[-1]+x) powers = [1] base = 1 if k != 1 and k != -1: while abs(base) <= 10**14: base *= k powers.append(base) if k == -1: powers.ap...
821_A. Okabe and Future Gadget Laboratory
Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an n by n square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. In o...
```python def good(lab): for i, line in enumerate(lab): for j, item in enumerate(line): if item == 1: continue flag = False for k, x in enumerate(line): if j==k: continue col = [l[j] for l in lab] ...
847_A. Union of Doubly Linked Lists
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each eleme...
```python if __name__=='__main__': n=int(input()) dl=[[0,0]] end=0 for i in range(n): dl.append(list(map(int,input().split()))) for i in range(1,n+1): if not dl[i][0]: dl[end][1]=i dl[i][0]=end j=i while(dl[j][1]): #print(dl[j]) #j+=1 j=dl[j][1] end=j for node in dl[1:]: print(*no...
868_C. Qualification Rounds
Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset. k experienced teams are participating in the contest. Some of these teams already know some of the problems...
```python from itertools import accumulate, permutations, combinations from sys import stdout R = lambda: map(int, input().split()) n, k = R() s = set(tuple(R()) for x in range(n)) res = False for l in range(1, len(s) + 1): for x in combinations(s, l): res = res or all(2 * sum(t) <= l for t in zip(*x)) pri...
915_C. Permute Digits
You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0. It is allowed to leave a as it is. Input The first line contains integer a (1 ≤ a ≤ 1018). The second line contains i...
```python import copy Num1, Num2 = sorted(list(input())), list(input()) Num1.reverse() Temp1, Temp2, i, j, Result= copy.copy(Num1), copy.copy(Num2), 0, 0, [] if len(Temp1) < len(Temp2): print(''.join(Temp1)) exit() while True: if i + 1 > len(Temp1): Temp1.append(Result[len(Result) - 1]) Te...
938_D. Buy a Ticket
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from c...
```python from __future__ import division, print_function import os import sys import io class FastI(): """ FastIO for PyPy3 by Pajenegod """ stream = io.BytesIO() newlines = 0 def read1(self): b, ptr = os.read(0, (1 << 13) + os.fstat(0).st_size), self.stream.tell() self.stream.seek(...
990_G. GCD Counting
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i. Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). For ...
```python import os import sys from io import BytesIO, IOBase from collections import defaultdict, deque, Counter, OrderedDict import threading def main(): ans = 1 flag = True primes = [] for i in range(2, 500): v = 1 for p in primes: if i % p == 0: v = 0 if v: pr...
p02615 AtCoder Beginner Contest 173 - Chat in a Circle
Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i. The N players will arrive at the place one by one in some order. To ma...
```python n,*a=map(int,open(0).read().split()) a.sort() a=a[::-1] ans=0 for i in range(1,n): ans+=a[i//2] print(ans) ```
p02746 Panasonic Programming Contest 2020 - Fractal Shortest Path
For a non-negative integer K, we define a fractal of level K as follows: * A fractal of level 0 is a grid with just one white square. * When K > 0, a fractal of level K is a 3^K \times 3^K grid. If we divide this grid into nine 3^{K-1} \times 3^{K-1} subgrids: * The central subgrid consists of only black squares. * Ea...
```python q=abs;s=lambda t,i:0--t//3**i;m=lambda a,b,c,d:max([i for i in range(30)if s(a,i)==s(c,i)and s(a,i)%3==2and 1<q(s(b,i)-s(d,i))]+[-1])+1 for _ in[0]*int(input()): a,b,c,d=map(int,input().split());h=m(a,b,c,d);w=m(b,a,d,c) if h==w==0:print(q(b-d)+q(a-c));continue if h<w:h,a,b,c,d=w,b,a,d,c i=3**h//3;x=2...
p02881 AtCoder Beginner Contest 144 - Walk on Multiplication Table
Takahashi is standing on a multiplication table with infinitely many rows and columns. The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1). In one move, he can move from (i,j) to either (i+1,j) or (i,j+1). Given an integer N, find the minimum number of moves needed to reach a ...
```python N = int(input()) n = 1 last = 0 while n**2 <= N: if N%n == 0 : last = n n += 1 print(last + N//last - 2) ```
p03016 AtCoder Beginner Contest 129 - Takahashi's Basics in Education and Learning
There is an arithmetic progression with L terms: s_0, s_1, s_2, ... , s_{L-1}. The initial term is A, and the common difference is B. That is, s_i = A + B \times i holds. Consider the integer obtained by concatenating the terms written in base ten without leading zeros. For example, the sequence 3, 7, 11, 15, 19 woul...
```python import math import sys sys.setrecursionlimit(10000) def nasu(A, B, L, D, M): if L == 1: return A ans = nasuA(A, L, D, M) ans = (ans + nasuB(1, L - 1, D, M) * B * D) % M return ans % M def nasuB(B, L, D, M): if L == 1: return B ans = powB(1, L, D, M) % M return ans % M def powB(B, L, D...
p03156 AISing Programming Contest 2019 - Contests
You have written N problems to hold programming contests. The i-th problem will have a score of P_i points if used in a contest. With these problems, you would like to hold as many contests as possible under the following condition: * A contest has three problems. The first problem has a score not greater than A poin...
```python n=int(input()) a,b=map(int, input().split()) *p,=map(int, input().split()) mn,md,mx=0,0,0 for pi in p: if pi<=a: mn+=1 elif pi<=b: md+=1 else: mx+=1 print(min(mn,md,mx)) ```
p03299 AtCoder Grand Contest 026 - Histogram Coloring
Let us consider a grid of squares with 10^9 rows and N columns. Let (i, j) be the square at the i-th column (1 \leq i \leq N) from the left and j-th row (1 \leq j \leq 10^9) from the bottom. Snuke has cut out some part of the grid so that, for each i = 1, 2, ..., N, the bottom-most h_i squares are remaining in the i-t...
```python from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil,...
p03457 AtCoder Beginner Contest 086 - Traveling
AtCoDeer the deer is going on a trip in a two-dimensional plane. In his plan, he will depart from point (0, 0) at time 0, then for each i between 1 and N (inclusive), he will visit point (x_i,y_i) at time t_i. If AtCoDeer is at point (x, y) at time t, he can be at one of the following points at time t+1: (x+1,y), (x-1...
```python N = int(input()) T,X,Y =0,0,0 count = 0 for i in range(N): t,x,y = map(int,input().split()) if abs(t-T) >= abs((x+y)-(X+Y)) and t%2==(x+y)%2: count+=1 T,X,Y=t,x,y print('Yes' if count==N else 'No' ) ```
p03618 AtCoder Grand Contest 019 - Reverse and Compare
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters. You can choose any two indices i and j such that 1 \leq i \leq j \leq n and reverse substring A_i A_{i+1} ... A_j. You can perform this operation at most once. How many different strings can you obtain? Constraints * 1 \leq |A| \leq 200...
```python A=input() N=len(A) from collections import defaultdict cnt=defaultdict(int) ans=1+N*(N-1)//2 for a in A: ans-=cnt[a] cnt[a]+=1 print(ans) ```
p03776 AtCoder Beginner Contest 057 - Maximum Average Sets
You are given N items. The value of the i-th item (1 \leq i \leq N) is v_i. Your have to select at least A and at most B of these items. Under this condition, find the maximum possible arithmetic mean of the values of selected items. Additionally, find the number of ways to select items so that the mean of the values o...
```python import math def com(n, r): return math.factorial(n) // (math.factorial(n - r) * math.factorial(r)) n,a,b = map(int, input().split()) vl = list(map(int, input().split())) vl.sort(reverse=True) if vl[0] == vl[a-1]: v = vl[0] print(v) v_cnt = vl.count(v) max_r = min(v_cnt,b) ans = 0 ...
p03945 AtCoder Beginner Contest 047 - 1D Reversi
Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones b...
```python s=input() a=s[0] c=0 for i in range(1,len(s)): if s[i]!=a: c+=1 a=s[i] print(c) ```
p00037 Path on a Grid
Seen from above, there is a grid-like square shaped like Figure 1. The presence or absence of "walls" on each side of this grid is represented by a sequence of 0s and 1s. Create a program that stands at point A, puts your right hand on the wall, keeps walking in the direction of the arrow, and outputs the route to retu...
```python import sys loc = [3, 1] def print_dir(h): if h == 0: print('R', end='') elif h == 1: print('D', end='') elif h == 2: print('L', end='') elif h == 3: print('U', end='') dir = [[1, 0], [0, 1], [-1, 0], [0, -1]] hand = 3 board = [[0 for _ in range(11)] for _ in...
p00169 Blackjack
Blackjack is a type of card game played in casinos, where the game is played using cards with numbers from 1 to 13. The score of each card is decided as follows. * 1 is 1 point or 11 points * From 2 to 9, the score is as written. * 10 points from 10 to 13 There are several participants in this game, including paren...
```python while True: inp = input() if inp == '0': break inp = inp.replace('11', '10') inp = inp.replace('12', '10') inp = inp.replace('13', '10') cards = tuple(map(int, inp.split())) ans = sum(cards) for i in range(cards.count(1)): if sum(cards) + 10 * (i+1) > 21: ...
p00325 Halting Problem
Have you ever had an infinite loop when you ran a hard-working program? It would be convenient to be able to determine in advance whether a program will stop executing without having to execute it. Unfortunately, it is not possible to make such a decision for any program in the programming language you normally use. H...
```python def solve(): from sys import stdin f_i = stdin N = int(f_i.readline()) from string import ascii_lowercase next_line = {} S = {} # statements V = {} # values line = 0 for i in range(N): stmt = f_i.readline().split() next_line[line] = stmt[0] ...
p00497 Nails
JOI is playing with a nail in the board. As shown in the figure below, JOI stabbed nails in the shape of an equilateral triangle with N sides. A nails are lined up in the ath line (1 ≤ a ≤ N) from the top. The bth nail (1 ≤ b ≤ a) from the left is represented by (a, b). <image> Figure 1: Arrangement of nails (when N =...
```python n,m = map(int,input().split()) t = [[0]*(n+2) for i in range(n+2)] for i in range(m): a,b,x = map(int,input().split()) a -= 1 b -= 1 t[a][b] += 1 t[a][b+1] -= 1 t[a+x+1][b] -= 1 t[a+x+1][b+x+2] += 1 t[a+x+2][b+1] += 1 t[a+x+2][b+x+2] -= 1 for i in range(n+2): for ...
p00682 Area of Polygons
Polygons are the most fundamental objects in geometric processing. Complex figures are often represented and handled as polygons with many short sides. If you are interested in the processing of geometric data, you'd better try some programming exercises about basic operations on polygons. Your job in this problem is ...
```python idx = 1 while True: n = int(input()) if n==0: break x = [] y = [] for _ in range(n): a,b = map(int,input().split()) x.append(a) y.append(b) x.append(x[0]) y.append(y[0]) s = 0.0 for i in range(n): s += x[i]*y[i+1] - x[i+1]*y[i] print(idx...
p01088 500-yen Saving
500-yen Saving "500-yen Saving" is one of Japanese famous methods to save money. The method is quite simple; whenever you receive a 500-yen coin in your change of shopping, put the coin to your 500-yen saving box. Typically, you will find more than one million yen in your saving box in ten years. Some Japanese people...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+9 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01224 Perfect Number
Let S be the sum of divisors of an integer N excluding the number itself. When N = S, N is called a perfect number, when N> S, N is called a defendant number, and when N <S, N is called an abundant number. Create a program that determines whether a given integer is a perfect number, a missing number, or an abundant num...
```python def f(p): ans=1 if p<=5: return 0 for n in range(2,int(p**0.5)+1): if p%n==0: if n!=p//n:ans+=n+p//n else:ans+=n return ans while 1: n=int(input()) if n==0:break m=f(n) if n==m:print('perfect number') else: print('deficient number' if n>m el...
p01358 Usaneko Matrix
Rabbits and cats are competing. The rules are as follows. First, each of the two animals wrote n2 integers on a piece of paper in a square with n rows and n columns, and drew one card at a time. Shuffle two cards and draw them one by one alternately. Each time a card is drawn, the two will mark it if the same number a...
```python # coding: utf-8 n,u,v,m=map(int,input().split()) usa=[list(map(int,input().split())) for i in range(n)] neko=[list(map(int,input().split())) for i in range(n)] usadic={} nekodic={} usatable=[0 for i in range(2*n+2)] nekotable=[0 for i in range(2*n+2)] for i in range(n): for j in range(n): usadic[u...
p01540 Treasure Hunt
Taro came to a square to look for treasure. There are many treasures buried in this square, but Taro has the latest machines, so he knows everything about where the treasures are buried. Since the square is very wide Taro decided to look for the treasure to decide the area, but the treasure is what treasure does not kn...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01696 Broken Cipher Generator
Broken crypto generator JAG (Japanese Alumni Group) is a mysterious organization composed of many programmers, and in order to enter the building where the headquarters of this organization is located, it is necessary to solve the ciphertext generated by a certain machine every time. This ciphertext consists of the sy...
```python def pm_to_chr(s): s=s.group() if s[-1]=='?': return 'A' ans=chr((((ord(s[-1])+s.count('+')-s.count('-'))-ord('A'))%26)+ord('A')) return ans def reverse(s): s=s.group() s=s[1:-1] ans=''.join(reversed(s)) return ans import re s=input() while s!='.': s=re.sub("[\+\-...
p01840 Delivery to a Luxurious House
B-Mansion and courier Problem Statement Taro lives alone in a mansion. Taro, who loves studying, intends to study in his study in the house today. Taro can't concentrate outside the study, so he always studies in the study. However, on this day, $ N $ of courier service to Taro arrived. $ i $ ($ 1 \ leq i \ leq N $)...
```python l_raw = input().split() l = [int(n) for n in l_raw] a_raw = input().split() a_ = [int(n) for n in a_raw] study = 0 state = 0 now=0 for a in a_: if state==0: if l[1]<a-now: study+=a-now-l[1] now=a state=1 elif state==1: if 2*l[1]<a-now: study+=a...
p01976 Anagram
problem Given a sequence $ a_i $ of length $ N $. Output all integers $ K (1 \ le K \ le N) $ that satisfy the following conditions. Condition: Well sorted $ a_1, \ cdots, a_K $ matches $ a_ {N-K + 1}, \ cdots, a_N $. Example Input 8 5 2 4 9 4 9 2 5 Output 1 2 4 6 7 8
```python from collections import Counter n = int(input()) a = input().split() # a = list(map(int, input().split())) ans = '' # t1, t2 = [], [] t1, t2 = Counter(), Counter() for i in range(n): t1.update(a[i]) t2.update(a[n-1-i]) t3 = t1 & t2 t1 -= t3 t2 -= t3 if t1 == t2: ans += str(i+1...
p02262 Shell Sort
Shell Sort Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$. 1 insertionSort(A, n, g) 2 for i = g to n-1 3 v = A[i] 4 j = i - g 5 while j >= 0 && A[j] > v 6 A[j+g] = A[j] 7 j = j - g 8 cnt++ 9 A[j+g...
```python def insertionSort(a, n, g): global cnt for i in range(g, n): v = a[i] j = i - g while j >= 0 and a[j] > v: a[j+g] = a[j] j = j - g cnt = cnt + 1 a[j+g] = v def shellSort(a, n): global cnt global G global m cnt = 0 ...
p02410 Matrix Vector Multiplication
Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$. A column vector with m elements is represented by the following equation. \\[ b = \left( \begin{array}{c} b_1 \\\ b_2 \\\ : \\\ b_m \\\ \end{array} \right) \\] A $n \times m$ matrix with $m$ column ve...
```python n, m = list(map(int, input().split())) matrix_a = [list(map(int, input().split())) for i in range(n)] matrix_b = [int(input()) for i in range(m)] for i in range(n): print(sum([x*y for (x,y) in zip(matrix_b,matrix_a[i])])) ```
1032_D. Barcelonian Distance
In this problem we consider a very simplified model of Barcelona city. Barcelona can be represented as a plane with streets of kind x = c and y = c for every integer c (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal...
```python import math a,b,c=map(int,input().split()) x1,y1,x2,y2=map(int,input().split()) s=abs(x1-x2)+abs(y1-y2) if a!=0: xk1=-1*(b*y1+c)/a xk2=-1*(b*y2+c)/a else: xk1=10**18 xk2=10**18 if b!=0: yk1=-1*(a*x1+c)/b yk2=-1*(a*x2+c)/b else: yk1=10**18 yk2=10**18 lx1=abs(y1-yk1) lx2=abs(y2-y...
1055_B. Alice and Hairdresser
Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic... To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most l centimeters after haircut, where l is her favorite number. Suppose, that the Alice's he...
```python n, m, l = map(int, input().split()) a = list(map(int, input().split())) nexxt = {} prevv = {} nexxt[-1] = n prevv[n] = -1 summ = 0 p = -1 l += 1 for k in range(n): if a[k] < l: p1 = p p = k nexxt[k] = n prevv[k] = p1 nexxt[p1] = k if k - prevv[k] > 1: ...
1077_C. Good Array
Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array a=[1, 3, 3, 7] is good because there is the element a_4=7 which equals to the sum 1 + 3 + 3. You are given an array a consisting of n integers. Your task is to print all indices j of this a...
```python n=int(input()) a=list(map(int,input().split())) s=sum(a) d=dict() for i in range(n): if a[i] in d: d[a[i]].append(i+1) else: d[a[i]]=[i+1] ans=[] for k in d.keys(): if (s-k)%2>0: continue m=(s-k)//2 #print(m) if m in d and (m!=k or len(d[k])>1): ans+=d[k...
1098_B. Nice table
You are given an n × m table, consisting of characters «A», «G», «C», «T». Let's call a table nice, if every 2 × 2 square contains all four distinct characters. Your task is to find a nice table (also consisting of «A», «G», «C», «T»), that differs from the given table in the minimum number of characters. Input First...
```python from itertools import permutations from sys import stdin, stdout ly, lx = map(int, input().split()) grid = [[c for c in inp] for inp in stdin.read().splitlines()] first = set() bl = [] bpattern = [] bcost = 1e6 flip_row = False for l in permutations('AGCT'): if bcost == 0: break if ''.join(l...
1119_C. Ramesses and Corner Inversion
Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task. You are given two matrices A and B of size n × m, each of which consists of 0 and 1 only. You can apply the following operation to the matrix A arbitrary number of times: take any subma...
```python def solve(): n, m = [int(x) for x in input().split(' ')] A = [[int(x) for x in input().split(' ')] for row in range(n)] B = [[int(x) for x in input().split(' ')] for row in range(n)] def row_par(M, k): return sum(M[k]) % 2 def col_par(M, k): return sum([r[k] for r in M]) ...
1185_C2. Exam in BerSU (hard version)
The only difference between easy and hard versions is constraints. If you write a solution in Python, then prefer to send it in PyPy to speed up execution time. A session has begun at Beland State University. Many students are taking exams. Polygraph Poligrafovich is going to examine a group of n students. Students ...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools # import time,random,resource # sys.setrecursionlimit(10**6) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 mod2 = 998244353 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)...
1204_A. BowWow and the Timetable
In the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k ≥ 0. Team BowWow has arrived at the station at the time s and it is trying to co...
```python n=int(input(),2) temp=0 l=[] while(4**temp<n): l.append(4**temp) temp+=1 print(len(l)) ```
1246_B. Power Products
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100). The second line contains n integers a_1, …, a_n (1 ≤ a_...
```python n,k=map(int,input().split()) A=list(map(int,input().split())) import math from collections import Counter C=Counter() for x in A: L=int(math.sqrt(x)) FACT=dict() for i in range(2,L+2): while x%i==0: FACT[i]=FACT.get(i,0)+1 x=x//i if x!=1: FAC...
1287_B. Hyperset
Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every...
```python import sys input = sys.stdin.readline n, k = map(int, input().split()) S = [input().strip() for i in range(n)] SET = set(S) p=0 for i in range(n - 1): for j in range(i + 1, n): c = [] for l in range(k): if S[i][l] == S[j][l]: c += S[i][l] else: ...
1307_B. Cow and Friend
Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from (0,0) to (x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance betw...
```python for _ in range(int(input())): n, x = map(int, input().split()) a = list(map(int, input().split())) ans = 10**18 for i in range(n): cnt = x // a[i] if x % a[i]: cnt += 1 if cnt else 2 ans = min(ans, cnt) print(ans) ```
1330_B. Dreamoon Likes Permutations
The sequence of m integers is called the permutation if it contains all integers from 1 to m exactly once. The number m is called the length of the permutation. Dreamoon has two permutations p_1 and p_2 of non-zero lengths l_1 and l_2. Now Dreamoon concatenates these two permutations into another sequence a of length...
```python import sys input = sys.stdin.readline Q = int(input()) Query = [] for _ in range(Q): N = int(input()) A = list(map(int, input().split())) Query.append((N, A)) for N, A in Query: leftOK = [True]*(N+1) already = set() MAX = 0 for i, a in enumerate(A): if a in already: ...
1350_B. Orac and Models
There are n models in the shop numbered from 1 to n, with sizes s_1, s_2, …, s_n. Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes). Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices i_j and i_{j+1} ...
```python import sys import math t=int(sys.stdin.readline()) for _ in range(t): n=int(sys.stdin.readline()) arr=list(map(int,sys.stdin.readline().split())) dp=[1 for x in range(n+1)] for i in range(n-1,0,-1): j=i*2 cnt=2 cur=1 while j<=n: y=dp[j] ...
1370_E. Binary Subsequence Rotation
Naman has two binary strings s and t of length n (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert s into t using the following operation as few times as possible. In one operation, he can choose any subsequence of s and rotate it clockwise once. For example, if s = ...
```python # -*- coding: utf-8 -*- """ @author: Saurav Sihag """ rr = lambda: input().strip() # rri = lambda: int(rr()) rri = lambda: int(stdin.readline()) rrm = lambda: [int(x) for x in rr().split()] # stdout.write(str()+'\n') from sys import stdin, stdout def sol(): n=rri() s=rr() t=rr() cnt=0 m...
1393_A. Rainbow Dash, Fluttershy and Chess Coloring
One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with si...
```python for i in range(int(input())): n = int(input()) res = int(n/2)+1 print(res) ```
145_B. Lucky Number 2
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meet...
```python a1,a2,a3,a4=map(int,input().split()) L=[] def Solve(a1,a2,a3,a4): if(a3-a4<-1 or a3-a4>1 or a1<a3 or a1<a4 or a2<a3 or a2<a4): return -1 elif(a3-a4==0): Ans="47"*a3 Ans+="4" if(a1-a3==0 and a2-a4==0): return -1 elif(a1-a3==0): return "7...
1485_D. Multiples and Power Differences
You are given a matrix a consisting of positive integers. It has n rows and m columns. Construct a matrix b consisting of positive integers. It should have the same size as a, and the following conditions should be met: * 1 ≤ b_{i,j} ≤ 10^6; * b_{i,j} is a multiple of a_{i,j}; * the absolute value of the dif...
```python n, m = list(map(int, input().split())) matrix = [] for i in range(n): row = list(map(int, input().split())) matrix.append(row) #print(matrix) res = [ [ 0 for i in range(m) ] for j in range(n) ] for i in range(n): for j in range(m): if (i + j) % 2: res[i][j] = 720720 + matr...
150_B. Quantity of Strings
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to ...
```python n,m,k = map(int,input().split()) mod = 10**9 + 7 if k == 1 or k>n: print(pow(m,n,mod)) elif k == n: print(pow(m,(n+1)//2,mod)) elif k%2== 0: print(m%mod) else: print(pow(m,2,mod)) ```
182_E. Wooden Fence
Vasya has recently bought some land and decided to surround it with a wooden fence. He went to a company called "Wooden board" that produces wooden boards for fences. Vasya read in the catalog of products that the company has at its disposal n different types of wood. The company uses the i-th type of wood to produce ...
```python from sys import stdin, stdout MOD = 10 ** 9 + 7 sze = 101 n, l = map(int, stdin.readline().split()) dp = [[[0, 0] for j in range(l + sze + 1)] for i in range(n)] bars = [] challengers = [[] for i in range(sze)] for i in range(n): a, b = map(int, stdin.readline().split()) bars.append((a, b)) ...
230_A. Dragons
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'...
```python n,m=map(int, input().split()) r=3 ar=[] for i in range (m): q=list(map(int, input().split())) ar.append (q) ar.sort() for i in range (m): if n>ar[i][0]: n+=ar[i][1] else: r=5 print ('NO') break if r!=5: print ('YES') ```
279_E. Beautiful Decomposition
Valera considers a number beautiful, if it equals 2k or -2k for some integer k (k ≥ 0). Recently, the math teacher asked Valera to represent number n as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible. Help Valera and find, how many nu...
```python t = input() j = t[0] d, s = 0, int(j) for i in t[1: ]: if j != i: if d == 1: d, s = 0, s + 1 else: d = 1 j = i else: d = 1 print(s + (d and j == '1')) ```