name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1261_E. Not Same
You are given an integer array a_1, a_2, ..., a_n, where a_i represents the number of blocks at the i-th position. It is guaranteed that 1 ≤ a_i ≤ n. In one operation you can choose a subset of indices of the given array and remove one block in each of these indices. You can't remove a block from a position without b...
```python n = int(input()) v, c = list([[0, 0]]), list() z = ['0' for i in range(n)] for i, x in enumerate(input().split()) : v.append([int(x), i]) v.sort(reverse=True) def S_N_U_F_F(z, v, c) : y, k, x, count = -1, 0, len(v)-1, len(v)-1 while v[0][0] != 0 : if k > 0 and k < len(v)-1 : z[v[y+k][1]] = '0...
1284_B. New Year and Ascent Sequence
A sequence a = [a_1, a_2, …, a_l] of length l has an ascent if there exists a pair of indices (i, j) such that 1 ≤ i < j ≤ l and a_i < a_j. For example, the sequence [0, 2, 0, 2, 0] has an ascent because of the pair (1, 4), but the sequence [4, 3, 3, 3, 1] doesn't have an ascent. Let's call a concatenation of sequence...
```python n=int(input()) l=[] ans=0 minn=[] maxx=[] c=0 for _ in range(n): ar=[int(x) for x in input().split()] ar=ar[1:] m=10**10 f=0 for i in ar: if i<=m: m=i else: f=1 break if f==1: continue else: minn.append(min(ar)) ...
1303_D. Fill The Bag
You have a bag of size n. Also you have m boxes. The size of i-th box is a_i, where each a_i is an integer non-negative power of two. You can divide boxes into two parts of equal size. Your goal is to fill the bag completely. For example, if n = 10 and a = [1, 1, 32] then you have to divide the box of size 32 into tw...
```python from math import log2 for i in range(int(input())): K,N=map(int,input().split()) L=list(map(int,input().split())) bit=[0]*61 Sum=0 for i in L: bit[int(log2(i))]+=1 Sum+=i if Sum<K: print("-1") continue i=0 res=0 while i<60: if (1<<i)&...
1327_E. Count The Blocks
You wrote down all integers from 0 to 10^n - 1, padding them with leading zeroes so their lengths are exactly n. For example, if n = 3 then you wrote out 000, 001, ..., 998, 999. A block in an integer x is a consecutive segment of equal digits that cannot be extended to the left or to the right. For example, in the i...
```python # | # _` | __ \ _` | __| _ \ __ \ _` | _` | # ( | | | ( | ( ( | | | ( | ( | # \__,_| _| _| \__,_| \___| \___/ _| _| \__,_| \__,_| import sys def read_line(): return sys.stdin.readline()[:-1] def read_int(): return...
1368_E. Ski Accidents
Arthur owns a ski resort on a mountain. There are n landing spots on the mountain numbered from 1 to n from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are no directed cycles formed by the tracks. There are at mos...
```python import sys # import math from collections import deque # import heapq # from math import inf # from math import gcd # print(help(deque)) # 26 pprint = lambda s: print(' '.join(map(str, s))) input = lambda: sys.stdin.readline().strip() ipnut = input for i in range(int(input())): n, m = map(int, input().s...
140_D. New Year Contest
As Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest. The New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are n problems for the contest. The penalty time fo...
```python from bisect import bisect_right n = int(input()) t = list(map(int, input().split())) t.sort() for i in range(1, n): t[i] += t[i - 1] i = bisect_right(t, 350) j = bisect_right(t, 710) print(j, sum(t[k] for k in range(i, j)) - 350 * (j - i)) ```
1454_D. Number into Sequence
You are given an integer n (n > 1). Your task is to find a sequence of integers a_1, a_2, …, a_k such that: * each a_i is strictly greater than 1; * a_1 ⋅ a_2 ⋅ … ⋅ a_k = n (i. e. the product of this sequence is n); * a_{i + 1} is divisible by a_i for each i from 1 to k-1; * k is the maximum possible (i. e...
```python import math tc = int(input()) for i in range(tc): integer = int(input()) k = integer kamus = dict() while k % 2 == 0: try: kamus[2] += 1 except: kamus[2] = 1 k /= 2 for i in range(3,int(math.sqrt(k))+1,2): while k % i == 0: ...
1478_B. Nezzar and Lucky Number
Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≤ i ≤ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a singl...
```python r=int(input()) res=[] for u in range(r): x,n = map(int,input().split(" ")) db= [int(x) for x in input().split()] for i in db: # operation if i%n==0: res.append("yes") else:# bech ne7ou n kol mara w njarbou k=0 ok=0 while((i-k*n)>=n):...
1505_E. Cakewalk
A mouse encountered a nice big cake and decided to take a walk across it, eating the berries on top of the cake on its way. The cake is rectangular, neatly divided into squares; some of the squares have a berry in them, and some don't. The mouse is in a bit of a hurry, though, so once she enters the cake from its nort...
```python h, w = map(int, input().split()) grid = [] for i in range(h): grid.append(input()) r,c = 0,0 ans = 0 for i in range(h+w-2): # print(r,c) if grid[r][c] == '*': ans += 1 if r==h-1: c += 1 continue if c == w-1: r+=1 continue right = (111111,111) ...
17_A. Noldbach problem
Nick is interested in prime numbers. Once he read about Goldbach problem. It states that every even integer greater than 2 can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it Noldbach problem. Since Nick is interested only in prime numbers, Nold...
```python y = [2] h = [] j = 0 for i in range(3,1000): z = 0 for x in range(2, int(i**0.5)+1): if i%x == 0: z+=1 if z == 0: y.append(i) for i in range(0,len(y)-1): x = y[i]+y[i+1] h.append(x) k = list(input().split()) a = int(k[0]) b = int(k[1]) for i in range(0,len(h))...
202_B. Brand New Easy Problem
A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's probl...
```python import itertools def count_inversions(enumerate_seq): tmp = list(enumerate_seq[:]) result = 0 for i in range(len(tmp)): for j in range(len(tmp) - 1): if tmp[j][0] > tmp[j + 1][0]: result += 1 tmp[j], tmp[j + 1] = tmp[j + 1], tmp[j] return r...
227_A. Where do I Turn?
Trouble came from the overseas lands: a three-headed dragon Gorynych arrived. The dragon settled at point C and began to terrorize the residents of the surrounding villages. A brave hero decided to put an end to the dragon. He moved from point A to fight with Gorynych. The hero rode from point A along a straight road ...
```python xa, ya = map(int,input().split()) xb, yb = map(int,input().split()) xc, yc = map(int,input().split()) dif = ((xb-xa)*(yc-yb)) - ((yb-ya)*(xc-xb)) if(dif == 0): print("TOWARDS") elif(dif > 0): print("LEFT") else: print("RIGHT") ```
250_D. Building Bridge
Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages. The river banks can be assumed to be vertical straight lines x = a and x = b (0 < a < b). The west village lies in a steppe at point O = (0...
```python import sys def pro(): return sys.stdin.readline().strip() def rop(): return map(int, pro().split()) def main(): s = list(rop()) a = list(rop()) q = list(rop()) o = list(rop()) p = -1 t = (1e100, -1, -1) for i in range(s[1]): while not((p == - 1 or s[2] * q[i] - s[3] * a[p] >= 0) and (p + 1...
299_B. Ksusha the Squirrel
Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that K...
```python n,k=map(int,input().split()) s=input() list=[] i=0 while(i<n): p=0 while(s[i]=='#'): p+=1 i+=1 list.append(p) i+=1 if(max(list)<k): print("YES") else: print("NO") ```
414_B. Mashmokh and ACM
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced prog...
```python import math def C(n,k): w=1 for i in range(n-k+1,n+1): w*=i for i in range (1,k+1): w//=i return w def multiples(limit): tmp = 1 m = limit for j in range(2, limit + 1): no_multiples = 0 while m % j == 0: no_multiples += 1 ...
463_A. Caisa and Sugar
Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town. Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But t...
```python # Author: SaykaT # Problem: 463A # Time Created: July 21(Tuesday) 2020 || 02:59:52 #>-------------------------<# # Helper Functions. -> Don't cluster your code. # IO Functions. -> Input output def io(): n, s = map(int, input().split()) sugar = [] for _ in range(n): x, y = map(int, input...
486_E. LIS of Sequence
The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson. Nam created a sequence a consisting of n (1 ≤ n ≤ 105) elements a1, a2, ..., an (1 ≤ ai ≤ 105). A subsequence ai1,...
```python # a simple parser for python. use get_number() and get_word() to read def main(): def parser(): while 1: data = list(input().split(' ')) for number in data: if len(number) > 0: yield(number) input_parser = parser() gets = lambda:...
50_D. Bombing
The commanding officers decided to drop a nuclear bomb on the enemy's forces. You are ordered to determine the power of the warhead that needs to be used. The enemy has N strategically important objects. Their positions are known due to the intelligence service. The aim of the strike is to deactivate at least K import...
```python import math n = int(input()) k, epsilon = list(map(int, input().split(" "))) x0, y0 = list(map(int, input().split(" "))) epsilon /= 1000.0 l = [] for i in range(n): l.append(list(map(int, input().split(" ")))) d = sorted([(p[0] - x0) ** 2 + (p[1] - y0) ** 2 for p in l]) rmin = 0 rmax = math.sqrt(...
55_A. Flea travel
A flea is sitting at one of the n hassocks, arranged in a circle, at the moment. After minute number k the flea jumps through k - 1 hassoсks (clockwise). For example, after the first minute the flea jumps to the neighboring hassock. You should answer: will the flea visit all the hassocks or not. We assume that flea has...
```python n = int(input()) visited = [False] * n k = 0 for i in range(n ** 2 + 1): k += i + 1 visited[k % n] = True for i in visited: if not i: print("NO") exit() print("YES") ```
585_D. Lizard Era: Beginning
In the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has n mandatory quests. To perform each of them, you need to take exactly two companions. The attitude of each of the companions to the hero is an integer. Initially, the attitude of each o...
```python import sys import itertools n = int(input()) data = [list(map(int, input().split())) for __ in range(n)] if n == 1: if data[0].count(0) < 2: print('Impossible') else: print(''.join([i for i, a in zip('LMW', data[0]) if a == 0][:2])) sys.exit() pre = n//2 dat1 = data[:pre] dat2 = dat...
629_C. Famil Door and Brackets
As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings! The sequence of round brackets is called valid if and only if: 1...
```python n, m = map(int, input().split()) s = input() mod = 10 ** 9 + 7 c, b, ans, d, k = 0, 0, 0, [[1]], n - m for i in s: c += (i == '(') * 2 - 1 b = min(c, b) for i in range(n - m): nd = d[-1][1:] + [0] * 2 for j in range(1, i + 2): nd[j] = (nd[j] + d[-1][j - 1]) % mod d.append(nd) for i...
653_D. Delivery Bears
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city. In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge ...
```python from collections import defaultdict, deque def bfs(graph, inicio, destino, parent): parent.clear() queue = deque() queue.append([inicio, float("Inf")]) parent[inicio] = -2 while (len(queue)): current, flow = queue.popleft() for i in graph[current]: if parent...
679_B. Bear and Tower of Cubes
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length. A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3....
```python def rec(m): if m <= 0: return m, 0 a = int((m + 1e-9) ** (1 / 3)) x, y = rec(m - a ** 3) q, w = rec(a ** 3 - (a - 1) ** 3 - 1) return max((x + 1, a ** 3 + y), (q + 1, (a - 1) ** 3 + w)) print(*rec(int(input()))) ```
701_C. They Are Everywhere
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is on...
```python n = int(input()) s = input() alles = {} l, r, c, ans, le = 0, 0, 0, float("+inf"), len(set(s)) for i in s: if i not in alles: alles[i] = 0 c += 1 alles[i] += 1 if c == le: while alles[s[l]] > 1: alles[s[l]] -= 1 l += 1 ans = min(ans, r-l+1)...
723_D. Lakes in Berland
The map of Berland is a rectangle of the size n × m, which consists of cells of size 1 × 1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that...
```python def find_neigh(t,x,y): return [(i,j) for (i,j) in [(x-1,y),(x+1,y),(x,y-1),(x,y+1),(x,y+1)] if t[i][j]=='.'] def lake(table): return [(i,j) for i in range(0,len(table)-1) for j in range(0, len(table[i])-1) if table[i][j] == '.'] stack=set() def the_lake(tabl...
745_C. Hongcow Builds A Nation
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries. The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world. There is at most one...
```python from collections import deque n,m,k = map(int,input().split()) line = input().split() gov = [] for i in range(k): gov.append(int(line[i])-1) graph = {} for i in range(m): u,v = map(int,input().split()) u -= 1 v -= 1 if u not in graph: graph[u] = set() if v not in graph: ...
768_E. Game of Stones
Sam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple: * The game starts with n piles of stones indexed from 1 to n. The i-th pile contains si stones. * The players make their moves alternatively. A move ...
```python memo = {} def get_reachable_states(k, max_allowed): states = [] for i in range(1, min(k,max_allowed) + 1): new_k = k - i states.append((new_k, i - 1)) return states def Grundy(k, max_allowed): if k == 0: return 0 if (k, max_allowed) in memo: return memo[...
792_D. Paths in a Complete Binary Tree
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n ...
```python from math import log n, q = [int(i) for i in input().split()] maxlvl = int(log(n + 1, 2)) + 1 steps = [2 ** i for i in range(maxlvl)] def calc_lvl(m): for lvl in range(1, maxlvl): if (m - steps[lvl-1]) % steps[lvl] == 0: return (lvl, ((m - steps[lvl-1]) % (2 * steps[lvl]) == 0)) #pri...
813_A. The Contest
Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place! This contest consists of n problems, and Pasha solves ith problem in ai time units (his solutions are always correct). At any moment of time he can be thinking about a so...
```python from sys import stdin import re def readInt(count=1): m = re.match('\s*' + ('([+-]?\d+)\s*' * count), stdin.readline()) if m is not None: ret = [] for i in range(1, m.lastindex + 1): ret.append(int(m.group(i))) return ret return None taskCount, = readInt() thi...
859_C. Pie Rules
You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be ...
```python import os import sys from io import BytesIO, IOBase def main(): import bisect import math # import itertools # import heapq # from queue import PriorityQueue, LifoQueue, SimpleQueue # import sys.stdout.flush() use for interactive problems alpha = 'abcdefghijklmnopqrstuvwxyz' ...
884_B. Japanese Crosswords Strike Back
A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect. For example: * If x = 6 and the crossw...
```python n, x = map(int, input().split()) print(['NO', 'YES'][sum(map(int, input().split())) + n - 1 == x]) ```
908_D. New Year and Arbitrary Arrangement
You are given three integers k, pa and pb. You will construct a sequence with the following algorithm: Initially, start with the empty sequence. Each second, you do the following. With probability pa / (pa + pb), add 'a' to the end of the sequence. Otherwise (with probability pb / (pa + pb)), add 'b' to the end of the...
```python k, pa, pb = map(int, input().split()) MOD = 10**9 + 7 INF = ((pa + pb) * pow(pb, MOD-2, MOD)) % MOD rAB = pow(pa+pb, MOD-2, MOD) rB = pow(pb, MOD-2, MOD) memo = {} def dfs(a, ab): if ab >= k: return ab if a + ab >= k: #return INF #return (pa + pb) / pb return ((a + M...
92_C. Newspaper Headline
A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new...
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') s = [ord(c) - 97 for c in input().rstrip()] t = [ord(c) - 97 for c in input().rstrip()] n, m = len(s), len(t) next_c = [[-1] * 26 for _ in range(n)] for _ in range(2): for i in range(...
958_B1. Maximum Control (easy)
The Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect s...
```python __author__ = 'Esfandiar' n = int(input()) g = [[] for i 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) print(sum([len(g[i])==1 for i in range(n)])) ```
983_C. Elevator
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator. Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you...
```python # python3 import sys from collections import namedtuple def readline(): return map(int, input().split()) def readlines(): for line in sys.stdin.readlines(): yield map(int, line.split()) class State(namedtuple('State', 'payload time floor')): def hook(self, pivot, a, b): lo, up = ...
p02566 AtCoder Library Practice Contest - Number of Substrings
You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input missi...
```python class StrAlg: @staticmethod def sa_naive(s): n = len(s) sa = list(range(n)) sa.sort(key=lambda x: s[x:]) return sa @staticmethod def sa_doubling(s): n = len(s) sa = list(range(n)) rnk = s tmp = [0] * n k = 1 whi...
p02697 AtCoder Beginner Contest 165 - Rotation Matching
You are going to hold a competition of one-to-one game called AtCoder Janken. (Janken is the Japanese name for Rock-paper-scissors.) N players will participate in this competition, and they are given distinct integers from 1 through N. The arena has M playing fields for two players. You need to assign each playing fiel...
```python n,m=map(int,input().split()) if n%2==1: for i in range(m): print(n-i-1,i+1) else: cnt=1 for i in range(m): if i%2==0: print(n//4-i//2,n//4-i//2+cnt) else: print(n//2+n//4-i//2,n//2+n//4-i//2+cnt) cnt+=1 ```
p02826 AtCoder Grand Contest 041 - Problem Scores
N problems have been chosen by the judges, now it's time to assign scores to them! Problem i must get an integer score A_i between 1 and N, inclusive. The problems have already been sorted by difficulty: A_1 \le A_2 \le \ldots \le A_N must hold. Different problems can have the same score, though. Being an ICPC fan, y...
```python N,M=map(int,input().split()) A = list(range(1,N//2+1))*2 if N&1:A+=[(N+1)//2] d=[1]+[0]*(N+N) for x in A: for i in range(N+1): d[i]%=M d[i+x]+=d[i] print(sum(d[:N])%M) ```
p02963 AtCoder Grand Contest 036 - Triangle
Given is an integer S. Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions: * 0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9 * The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2. We can prove that ther...
```python s = int(input()) x2 = 10**9 y1 = -(-s//x2) y2 = 1 x1 = x2*y1-s print(0,0,x1,x2,y1,y2) ```
p03098 AtCoder Grand Contest 031 - A Sequence of Permutations
For two permutations p and q of the integers from 1 through N, let f(p,q) be the permutation that satisfies the following: * The p_i-th element (1 \leq i \leq N) in f(p,q) is q_i. Here, p_i and q_i respectively denote the i-th element in p and q. You are given two permutations p and q of the integers from 1 through...
```python n,k = map(int,input().split()) p = list(map(int,input().split())) q = list(map(int,input().split())) def perprod(x,y): #xy nn = len(x) ret = [0 for i in range(nn)] for i in range(nn): ret[i] = x[y[i]-1] return ret def perinv(x): #inverse nn = len(x) ret = [0 for i in range...
p03244 AtCoder Beginner Contest 111 - /\/\/\/
A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied: * For each i = 1,2,..., n-2, a_i = a_{i+2}. * Exactly two different numbers appear in the sequence. You are given a sequence v_1,v_2,...,v_n whose length is even. We would like to make this sequence /\/\/\/ by replacing s...
```python n=int(input()) l=[int(i) for i in input().split()] o=[[0,i] for i in range(100001)] e=[[0,i] for i in range(100001)] for i in range(n//2): o[l[i*2]][0]+=1 e[l[i*2+1]][0]+=1 o.sort(reverse=True) e.sort(reverse=True) res=10000000000000000 for i in range(2): for j in range(2): if o[i][1]!=e[j][1]: ...
p03562 AtCoder Regular Contest 084 - XorShift
There are N non-negative integers written on a blackboard. The i-th integer is A_i. Takahashi can perform the following two kinds of operations any number of times in any order: * Select one integer written on the board (let this integer be X). Write 2X on the board, without erasing the selected integer. * Select two...
```python N, X = input().split() N = int(N); X = int(X, 2) p = int(input(), 2) for i in range(N-1): v = int(input(), 2) if p > v: p, v = v, p while 0 < p: q = (v ^ (p << (v.bit_length() - p.bit_length()))) if p < q: p, v = p, q else: p, v = q, p p ...
p03717 AtCoder Regular Contest 074 - RGB Sequence
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right. Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is: * There are exactly x_i different colors among squares l_i, ...
```python N,M=map(int,input().split()) q=[[] for i in range(N+1)] for i in range(M): l,r,x=map(int,input().split()) q[r].append((l,x)) mod=10**9+7 dp=[[0 for i in range(N+1)] for i in range(N+1)] i=N for j in range(N+1): for k in range(N+1): check=7 for l,x in q[i]: if i==l: ...
p04038 AtCoder Grand Contest 002 - Leftmost Ball
Snuke loves colorful balls. He has a total of N×K balls, K in each of his favorite N colors. The colors are numbered 1 through N. He will arrange all of the balls in a row from left to right, in arbitrary order. Then, for each of the N colors, he will paint the leftmost ball of that color into color 0, a color differe...
```python def pow_mod(MOD, a, n): ret = 1 while n != 0: if n % 2 == 1: ret = ret * a % MOD a = a * a % MOD n //= 2 return ret def fac(n): MOD = 1000000007 ret = 1 for i in range(1, n + 1): ret = ret * i % MOD return ret def fac_gen(first, last): MOD = 10...
p00119 Taro's Obsession
A serious incident happened at Taro's house, which loves steamed buns. One of the three steamed buns offered at the Buddhist altar in the Japanese-style room was gone. When Taro, who was aiming for a snack someday, started an investigation to find the criminal, it turned out that there were many people who entered the ...
```python # Aizu Problem 00119: Taro's Obsession # import sys, math, os # read input: PYDEV = os.environ.get('PYDEV') if PYDEV=="True": sys.stdin = open("sample-input.txt", "rt") class DirectedGraph(): def __init__(self): self.edges = {} def AddNode(self, node): if node not in self.edges:...
p00252 Railway Ticket
To get on the Shinkansen, you need two tickets, a "ticket" and a "limited express ticket". These are separate tickets because some of the routes may not use the Shinkansen, but for routes that use only the Shinkansen, one ticket can be used as both a ticket and a limited express ticket. It may also be issued. Automati...
```python b1,b2,b3=map(int,input().split()) if b1==1: if b2==1: print("Open") else: print("Close") elif b3==1: print("Open") else: print("Close") ```
p00437 Quality Checking
problem You are in charge of quality control at a machine manufacturing plant. This machine requires a power supply, a motor, and a cable as parts. The manufacturing plant has a power supply, b motors, and c cables, numbered from 1 to a, a + 1 to a + b, and a + b + 1 to a + b + c, respectively. attached. The trouble i...
```python for e in iter(input,'0 0 0'): d=[2]*-~sum(map(int,e.split())) f=[] for _ in[0]*int(input()): s,t,u,v=map(int,input().split()) if v:d[s]=d[t]=d[u]=1 else:f+=[(s,t,u)] for s,t,u in f: if d[t]*d[u]==1:d[s]=0 if d[u]*d[s]==1:d[t]=0 if d[s]*d[t]==1:d[u]=0 print(*d[1:],sep='\n') ```
p00629 Selecting Teams Advanced to Regional
In order to participate in the Asian Regional Qualifiers of the International Collegiate Programming Contest held every year in Japan, we must break through the strict domestic qualifiers. Even though it is a university competition, multiple teams from one school will participate. Therefore, the following selection ru...
```python while 1: n = int(input()) if n == 0: break data = [] for _ in range(n): i, u, a, p = map(int, input().split()) data.append([i, u, a, p]) data = sorted(data, key=lambda x: (-x[2], x[3], x[0])) union = [0] * 1001 cnt = 0 for d in data: i, u, a, ...
p00773 Tax Rate Changed
Tax Rate Changed VAT (value-added tax) is a tax imposed at a certain rate proportional to the sale price. Our store uses the following rules to calculate the after-tax prices. * When the VAT rate is x%, for an item with the before-tax price of p yen, its after-tax price of the item is p (100+x) / 100 yen, fractions ...
```python from math import floor while(True): x,y,s=map(int,input().split()) if (x,y,s)==(0,0,0): quit() ans=0 for i in range(1,s): j=s-floor(i*(100+x)/100) if j<1: continue j=floor((j+1)*(100/(100+x))) for k in [j-1,j]: if floor(i*(100+x)/...
p00904 Ginkgo Numbers
We will define Ginkgo numbers and multiplication on Ginkgo numbers. A Ginkgo number is a pair <m, n> where m and n are integers. For example, <1, 1>, <-2, 1> and <-3,-1> are Ginkgo numbers. The multiplication on Ginkgo numbers is defined by <m, n> * <x, y> = <mx − ny, my + nx>. For example, <1, 1> * <-2, 1> = <-3,-1>...
```python #!/usr/bin/env python # -*- coding: utf-8 -*- """ Problems 1325 Problem A: Ginkgo Numbers """ for _ in range(int(input())): m, n = map(int,input().split()) count = 0 for p in range(142): for q in range(142): if (p > 0 or q > 0) and ((m*q + n*p) % (p*p + q*q) == 0) and ((n*q - m...
p01037 A White Wall
Background The site of Mr. A's house, which lives in a certain city, is surrounded by white walls. Feeling unsatisfied with the wall, Mr. A decided to invite the children in the neighborhood to paint the wall freely. Ask the children to choose their favorite section of the wall and paint it. So how was the wall painte...
```python N, M = map(int, input().split()) L = [0]*(N*2) for i in range(M): a, l = map(int, input().split()) for ll in range(a, a+l): L[ll] = 1 for i in range(N, 2*N): L[i-N] = max(L[i-N], L[i]) #print(L) left = 0 i = 0 while L[i]==1: left += 1 i += 1 if i==N: print(N, 1) ...
p01171 Everlasting...?
Everlasting Sa-Ga, a new, hot and very popular role-playing game, is out on October 19, 2008. Fans have been looking forward to a new title of Everlasting Sa-Ga. Little Jimmy is in trouble. He is a seven-year-old boy, and he obtained the Everlasting Sa-Ga and is attempting to reach the end of the game before his frien...
```python import math def Soinsu(a, b) : global soin while True : if a % b == 0 : soin.append(b) if a/b == 1 : break else : Soinsu(a/b, b) break else : b += 1 if math.sqrt(a) < b : ...
p01636 Mysterious Operator
When Mr. Kay was browsing a certain SNS as usual, the problem that "there are people who can solve IQ150 or more" came to the timeline. Mr. Kay has an IQ of over 150, so he solved the problem in an instant without even looking at it. For him, he doesn't have to work on such a mystery. It is enough to leave it to the co...
```python a = input() ans = 0 for i in range(1, len(a)): df = a[:i] sm = a[i:] if sm[0] == "0":continue df = int(df) sm = int(sm) if (df + sm) % 2 == 0 and sm >= df and (sm - df) % 2 == 0: ans += 1 if int(a) % 2 == 0:ans += 1 print(ans) ```
p01923 JAG Practice Contest
JAG mock qualifying practice session The ACM-ICPC OB / OG Association (Japanese Alumni Group; JAG) has N questions in stock of questions to be asked in the mock contest, and each question is numbered with an integer from 1 to N. Difficulty evaluation and recommendation voting are conducted for each problem. Problem i ...
```python while True: N,M=map(int,input().split()) if N==0 and M==0: break l = [0]*M for i in range(N): d,v=map(int,input().split()) if l[d-1]<v: l[d-1]=v total = 0 for i in range(M): total += l[i] print(total) ```
p02061 Doubling
B: Twice as own problem You will be given Q queries. Since one positive integer N is given for each query, find the number of positive integers M that satisfy the following two conditions. * 2 Satisfy \ leq M \ leq N * Of the divisors of M, excluding M, the total product is more than twice that of M Input format ...
```python import bisect MAX_N=2*10**5 isdmore5=[1 for i in range(MAX_N+1)] isprime=[1 for i in range(MAX_N+1)] i=2 isprime[0]=0;isprime[1]=0 isdmore5[0]=0;isdmore5[1]=0 while(i*i<=MAX_N): if isprime[i]!=0: for j in range(2*i,MAX_N+1,i): isprime[j]=0 i+=1 prime=[] for i in range(MAX_N+1): ...
p02203 Auction
Auction square1001 You were watching a certain auction. An auction is a transaction in which when there are a large number of buyers and the number of items is limited, the one with the highest price is given the right to buy. (From the 7th edition of the Shinmei Kokugo Dictionary) The rules of the auction here are ...
```python n = int(input()) v = list(map(int,input().split())) cnt = 1 for i in range(n-1): if v[i+1]<=v[i]: cnt+=1 print(cnt) print(n) ```
p02357 Sliding Minimum Elements
For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $L$, find the minimum of each possible sub-arrays with size $L$ and print them from the beginning. For example, for an array $\\{1, 7, 7, 4, 8, 1, 6\\}$ and $L = 3$, the possible sub-arrays with size $L = 3$ includes $\\{1, 7, 7\\}$, $\\{7, 7, ...
```python from collections import deque if __name__ == "__main__": N, L = map(int, input().split()) a = list(map(lambda x: int(x), input().split())) que: deque = deque() ans = [] for i, elem in enumerate(a): while (que and elem <= que[-1][1]): que.pop() que.append((i, ...
1025_A. Doggo Recoloring
Panic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive. The committee rules strictly prohibit even the smallest diversity between dog...
```python from collections import Counter n = int(input()) print("Yes" if n == 1 or max(Counter(input()).values()) >= 2 else "No") ```
1068_C. Colored Rooks
Ivan is a novice painter. He has n dyes of different colors. He also knows exactly m pairs of colors which harmonize with each other. Ivan also enjoy playing chess. He has 5000 rooks. He wants to take k rooks, paint each of them in one of n colors and then place this k rooks on a chessboard of size 10^{9} × 10^{9}. L...
```python from sys import stdin, stdout int_in = lambda: int(stdin.readline()) arr_in = lambda: [int(x) for x in stdin.readline().split()] mat_in = lambda rows: [arr_in() for y in range(rows)] str_in = lambda: stdin.readline().strip() out = lambda o: stdout.write("{}\n".format(o)) arr_out = lambda o: out(" ".join(map(...
1090_A. Company Merging
A conglomerate consists of n companies. To make managing easier, their owners have decided to merge all companies into one. By law, it is only possible to merge two companies, so the owners plan to select two companies, merge them into one, and continue doing so until there is only one company left. But anti-monopoly ...
```python n=int(input());l,q,r=[0]*n,[0]*n,0 for i in range(n): a=list(map(int,input().split())) l[i]=a[0] a.remove(l[i]) q[i]=max(a) z=max(q) for i in range(len(q)):r+=(z-q[i])*l[i] print(r) ```
1139_B. Chocolates
You went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock. You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 ≤ x_i ≤ a_i), then for all 1 ≤ j < i at ...
```python n = int(input()) a = list(map(int,input().split())) max = a[len(a)-1] sum = max for i in range(len(a)-2,-1,-1): # print(max) if (max<=0): break if (a[i]>=max): # print(a[i]) max = max-1 sum += max else: # print(a[i]) max = a[i] sum += max...
1157_C1. Increasing Subsequence (easy version)
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2). You are given a sequence a consisting of n integers. All these integers are distinct, each value from 1 to n appears in the sequence exactly once. You are making a sequen...
```python n=int(input()) d=list(map(int,input().split())) p=[0,n-1] e=[0] c="" while p[0]<=p[1]: if d[p[0]]<d[p[1]]: if e[-1]<d[p[0]]: e.append(d[p[0]]) p[0]+=1 c+="L" elif e[-1]<d[p[1]]: e.append(d[p[1]]) p[1]-=1 c+="R" ...
1238_A. Prime Subtraction
You are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y? Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime...
```python #import math #def findPrimeFactor(difference): # if difference % 2 == 0: # print("YES") # else: # findOddPrimeFactor(int(difference)) num = int(input()) for i in range(num): x, y = input().split(" ") difference = int(x) - int(y) if difference != int(1) and difference > (0): print("YES") ...
1256_B. Minimize the Permutation
You are given a permutation of length n. Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (n=3 but there is 4 ...
```python def fn(n,a): v=[False]*n for i in range(1,n+1): c=a.index(i)-1 while(c>=0): if(a[c]>a[c+1] and v[c]==False): v[c]=True a[c],a[c+1]=a[c+1],a[c] c=c-1 return " ".join(str(x) for x in a) m=int(input()) for i in range(m): n=in...
127_B. Canvas Frames
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break th...
```python import sys import math n = int(sys.stdin.readline()) an = [int(x) for x in (sys.stdin.readline()).split()] k = [0] * 101 for i in an: k[i] += 1 res = 0 for i in k: res += int(i / 2) print(int(res / 2)) ```
12_A. Super Agent
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage...
```python mat=[] for i in range(3): a = input() mat.append(list(a)) p=0 if mat[0][0]==mat[2][2] and mat[0][1]==mat[2][1] and mat[0][2]==mat[2][0] and mat[1][2]==mat[1][0]: print("YES") else: print("NO") ```
1323_C. Unusual Competitions
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. The teacher gave Dmitry's class a very strange task — she asked every student...
```python n=int(input()) s=input().strip() c=0 v=0 o=0 cl=0 for j in range(n): if s[j]=='(': o=o+1 if cl>0: v=v+1 else: cl=cl+1 if o==0: v=v+1 if o>0: cl=cl-1 o=o-1 if cl>0: v=v+1 if o==cl: ...
1342_B. Binary Period
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property. Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=...
```python import sys t=int(sys.stdin.readline()) for _ in range(t): a=input() a=a[::] a=list(map(int, a)) i=0 if a.count(0)==0 or a.count(1)==0: for j in range(len(a)): print(a[j], end='') print() else: while True: if i==len(a)-1: ...
1364_B. Most socially-distanced subsequence
Given a permutation p of length n, find its subsequence s_1, s_2, …, s_k of length at least 2 such that: * |s_1-s_2|+|s_2-s_3|+…+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2. * Among all such subsequences, choose the one whose length, k, is as small as possible. If mul...
```python import math,sys,bisect from collections import defaultdict,Counter,deque from itertools import groupby,accumulate #sys.setrecursionlimit(1000000) input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ ilele = lambda: map(int,input().split()) alele = lambda: list(map(int, input().split())) #def l...
1384_C. String Transformation 1
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two...
```python from sys import maxsize def compare(a, b): for i in range(len(a)): if a[i] != b[i]: return False return True for _ in range(int(input())): n = int(input()) a = list(input()) b = list(input()) cnt = 0 for i in range(20): c = chr(97 + i) mn = maxsize f = False for j in range(n): if a[...
1405_E. Fixed Point Removal
Let a_1, …, a_n be an array of n positive integers. In one operation, you can choose an index i such that a_i = i, and remove a_i from the array (after the removal, the remaining parts are concatenated). The weight of a is defined as the maximum number of elements you can remove. You must answer q independent queries...
```python class Fenwick: def __init__(self, size): self.size = size self.tree = [0] * (size + 1) def add(self, idx, val): idx = int(idx) while idx <= self.size: self.tree[idx] += val idx += idx & (-idx) def sum(self, idx): ret = 0 idx...
1427_A. Avoiding Zero
You are given an array of n integers a_1,a_2,...,a_n. You have to create an array of n integers b_1,b_2,...,b_n such that: * The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_...
```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)...
1450_A. Avoid Trygub
A string b is a subsequence of a string a if b can be obtained from a by deletion of several (possibly, zero or all) characters. For example, "xy" is a subsequence of "xzyw" and "xy", but not "yx". You are given a string a. Your task is to reorder the characters of a so that "trygub" is not a subsequence of the result...
```python t = int(input()) for i in range(t): n = int(input()) a = input() check = [] trygub = "trygub" k = 0 for j in range(len(trygub)): for m in range(k,len(a)): if(trygub[j] == a[m]): check.append(a[m]) k = m+1 break ...
1473_F. Strange Set
Note that the memory limit is unusual. You are given an integer n and two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Let's call a set of integers S such that S ⊆ \{1, 2, 3, ..., n\} strange, if, for every element i of S, the following condition is met: for every j ∈ [1, i - 1], if a_j divides a_i, then j is...
```python # Author: yumtam # Created at: 2021-03-02 20:19 def main(): n = int(input()) A = [int(t) for t in input().split()] cost = [int(t) for t in input().split()] g = Flow(n+2) s, t = n, n+1 last = [-1] * 101 for i, x in enumerate(A): for d in range(1, 101): if ...
149_A. Business trip
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water...
```python #149A k=int(input()) a=list(map(int,input().split())) a.sort(reverse=True) k1,count=0,0 for i in range(len(a)): if k<=k1: break else: k1+=a[i] count+=1 if k<=k1 : print(count) else: print(-1) ```
1523_A. Game of Life
<image> William really likes the cellular automaton called "Game of Life" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing n cells, with each cell either being alive or dead. Evolution of the array in William's cellular automaton occurs ite...
```python import os import sys from io import BytesIO, IOBase ONLINE_JUDGE = 1 # <============= code from here =============> def main(): for _ in range(int(input())): n, m = map(int, input().split()) a = list(map(int, input())) a_ = a[:] for _ in range(min(n, m)): if...
177_B2. 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. ...
```python n = int(input()) i, s = 2, n m = int(n ** 0.5) + 1 while n > 1 and i < m: if n % i: i += 1 else: n //= i s += n print(s + (n > 1)) ```
198_A. About Bacteria
Qwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high. At the beginning of the first experiment there is a single bacterium in the test tub...
```python k, b, n, t = list(map(int, input().split())) p = 1 while p <= t: p = k * p + b n -= 1 print(max(0, n+1)) ```
221_B. Little Elephant and Numbers
The Little Elephant loves numbers. He has a positive integer x. The Little Elephant wants to find the number of positive integers d, such that d is the divisor of x, and x and d have at least one common (the same) digit in their decimal representations. Help the Little Elephant to find the described number. Input ...
```python from math import sqrt def check(n, d): n = str(n) d = str(d) for c in d: if c in n: return True return False def get_divisors(n): m = int(sqrt(n)) + 1 divisors = set() for d in range(1, m): if n % d == 0: divisors.add(d) divis...
245_C. Game with Coins
Two pirates Polycarpus and Vasily play a very interesting game. They have n chests with coins, the chests are numbered with integers from 1 to n. Chest number i has ai coins. Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer x (2·x + 1 ≤ n) and...
```python n, s = int(input()), 0 a = [0] + list(map(int, input().split())) if n % 2 == 0 or n == 1: print(-1) else: for i in range(n, 1, -2): mx = max(a[i], a[i - 1]) s += mx a[i // 2] = max(0, a[i // 2] - mx) print(s + a[1]) ```
270_A. Fancy Fence
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot. He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a. Will the robot be able to build the fence Emuskald...
```python def solve(angle): if 360%(180-angle)!=0: return "NO" else: return "YES" cases=int(input()) results=list() for i in range(cases): results.append(int(input())) for res in results: print(solve(res)) ```
317_A. Perfect Pair
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not. Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the number...
```python import bisect from itertools import accumulate, count import os import sys import math from decimal import * from io import BytesIO, IOBase from sys import maxsize BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer =...
341_A. Tourist Problem
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents t...
```python def gcd(m, n): return m if n == 0 else gcd(n, m%n) n = int(input()) a = sorted(map(int, input().split())) cur = sum(a) ans = cur pre = 0 for i in range(n): cur += (i+i-n) * (a[i]-pre) ans += cur pre = a[i] g = gcd(ans, n) print(ans//g, n//g) ```
388_B. Fox and Minimal path
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2." Same with some writers, she wants to make an example with some certain output...
```python n, m, cnt = int(input()), 148, 0 ans = [['N'] * m for i in range(m)] def edge(i, j): ans[i][j] = ans[j][i] = 'Y' def node(*adj): global cnt i = cnt cnt += 1 for j in adj: edge(i, j) return i start, end, choice = node(), node(), node() if n&1: edge(choice, end) for i in r...
436_A. Feed with Candy
The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem. <image> One day, Om Nom visited his friend Evan. Evan has n candies of two types (fruit drops and caramel drops), the i-th candy hangs at the height of hi centimeters a...
```python import queue n,maxh=[int(x) for x in input().split()] car=[] fru=[] hcar=queue.PriorityQueue(2000) hfru=queue.PriorityQueue(2000) for i in range(n): a,b,c=[int(x) for x in input().split()] if a==0: car.append((b,c)) else: fru.append((b,c)) pcar=0 mcar=len(car) pfru=0 mfru=len(fru) car.sort() fru.sort()...
459_B. Pashmak and Flowers
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i...
```python n = int(input()) a = list(map(int,input().split())) a.sort() i = 0 ln = nn = 1 j = n-1 while (a[i]==a[i+1] and i<n-1 and a[0]!=a[-1]): i+=1 nn+=1 while(a[j]==a[j-1] and j>0 and a[0]!=a[-1]): j-=1 ln+=1 dis = a[-1]-a[0] if a[0]!=a[-1]: k = ln*nn else: k = n*(n-1)//2 print(dis, end = " ") print(...
480_A. Exams
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order. According to the schedule, a stud...
```python # your code goes n=int(input()) l=[] for i in range(n): k=tuple(map(int,input().split())) l.append(k) d=sorted(l) a=-2 for i in range(n): if a<=d[i][1]: a=d[i][1] else: a=d[i][0] print(a) ```
505_A. Mr. Kitayuta's Gift
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into s to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" a...
```python # 505A __author__ = 'artyom' # SOLUTION def main(): s = list(read(0)) n = len(s) m = n // 2 for i in range(n + 1): p = s[:i] + [s[n - i - (i <= m)]] + s[i:n] if p == p[::-1]: return p return 'NA' # HELPERS def read(mode=2): # 0: String # 1: List of strings # 2: List of int...
554_B. Ohana Cleans Up
Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it ...
```python from collections import Counter n = int(input()) print(max(Counter([input() for _ in range(n)]).values())) ```
580_A. Kefa and First Steps
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
```python n,a=int(input()),list(map(int,input().split())) mx=1 c=1 for i in range(n-1): if(a[i+1]>=a[i]): c+=1 if(c>mx): mx=c else: c=1 print(mx) ```
624_C. Graph and String
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to...
```python n, m = map(int, input().split()) s = [[0] * n for i in range(n)] for i in range(m): a, b = map(int, input().split()) s[a - 1][b - 1] = 1 s[b - 1][a - 1] = 1 for i in range(n): s[i][i] = 1 answer = [0] * n for i in range(n): flag = True for j in range(n): if s[i][j] == 0: ...
698_A. Vacations
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and...
```python day = int(input()) situations = input().split(" ") dp = [[float('inf') for _ in range(3)] for _ in range(day+1)] # Base Case: for j in range(3): dp[0][j] = 0 # Inductive Step: for i in range(1, day+1): # 0: rest dp[i][0] = 1 + min(dp[i-1][0], dp[i-1][1], dp[i-1][2]) # 1: gym dp[i][1] = ...
719_A. Vitya in the Countryside
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down. Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units...
```python n = int(input()) list1=input().split() list1 = list(map(int, list1)) if list1[n-1] == 0: print("UP") elif list1[n-1] == 15: print("DOWN") elif list1[n-1] - list1[n-2] == 1: print("UP") elif list1[n-1] - list1[n-2] == -1: print("DOWN") else: print("-1") ```
763_C. Timofey and remoduling
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere. One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. ...
```python def solve(n, m, a): if n == 0: return 0, 1 if n == 1: return a[0], 1 d = (a[1]-a[0]) % m if d < 0: d += m st = set(a) cnt = 0 for v in a: cnt += ((v + d) % m) in st cnt = n-cnt d = (d * pow(cnt, m-2, m)) % m now = a[0] while (now + m - d) % m...
808_D. Array Division
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element be...
```python import sys import bisect from bisect import bisect_left as lb input_=lambda: sys.stdin.readline().strip("\r\n") from math import log from math import gcd from math import atan2,acos from random import randint sa=lambda :input_() sb=lambda:int(input_()) sc=lambda:input_().split() sd=lambda:list(map(int,input_(...
878_A. Short Program
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an...
```python n = int(input()) zero = 0 ones = 1023 for _ in range(n): op, num = input().split() num = int(num) if op == '&': zero &= num ones &= num elif op == '|': zero |= num ones |= num else: zero ^= num ones ^= num and_bits = 0 or_bits =...
901_C. Bipartite Segments
You are given an undirected graph with n vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to n. You have to answer q queries. Each query is described by a segment of vertices [l; r...
```python def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0...
952_B. A Map of the Cat
If you have ever interacted with a cat, you have probably noticed that they are quite particular about how to pet them. Here is an approximate map of a normal cat. <image> However, some cats won't tolerate this nonsense from the humans. Here is a map of a grumpy cat. <image> You have met a cat. Can you figure out w...
```python #copy marsi bal ! print('grumpy' if input('9\n')[-2:] in ['s?', 'le', 'se', 'ay', 'en'] else 'normal') ```
999_E. Reachability from the Capital
There are n cities and m roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way. What is the minimum number of new roads that need to be built to make all the cities reachable from the capital? New roads will also be one-way. Input The first line of input consists of three integers ...
```python def main(): import sys sys.setrecursionlimit(10**5) from collections import deque n, m, s = map(int, input().split()) s -= 1 graph = [[] for _ in range(n)] for _ in range(m): u, v = map(int, input().split()) graph[u-1].append(v-1) seen = [False]*n li = dequ...
p02536 ACL Beginner Contest - Connect Cities
There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M. Road i connects City A_i and City B_i. Snuke can perform the following operation zero or more times: * Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities. After he...
```python from collections import deque N, M = map(int, input().split()) AB = [[] for _ in range(N)] for _ in range(M): a,b = map(lambda x: int(x)-1, input().split()) AB[a].append(b) AB[b].append(a) visited = [0] * N ans = [] for i in range(N): if visited[i]: continue group = [i] d =...