name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p00232 Life Game
Taro went to a toy store to buy a game of life made by Aizu Hobby. Life games are played using a board with squares and roulette. As shown in the figure, the board has one start point and one goal point, which are connected by a single grid. First, the pieces are placed in the square at the starting point, and the piec...
```python from heapq import heappush, heappop def main(): while True: x, y, z = map(int, input().split()) if x == 0:break vlst = list(map(int, input().split())) events = {} for _ in range(z): n, e, a = map(int, input().split()) events[n] = (e, a) que = [] heappush(que, (...
p00610 Cleaning Robot 2
Dr. Asimov, a robotics researcher, released cleaning robots he developed (see Problem B). His robots soon became very popular and he got much income. Now he is pretty rich. Wonderful. First, he renovated his house. Once his house had 9 rooms that were arranged in a square, but now his house has N × N rooms arranged in...
```python # AOJ 1024 Cleaning Robot 2.0 # Python3 2018.7.5 bal4u mv = ((-1,0), (0,1), (1,0), (0,-1)) d2c = {0:'.', 1:'E'} while True: n, k = map(int, input().split()) if n == 0: break k, n1 = k-1, n-1 if (n & 1) or k >= (1<<(n>>1)): print("No\n") continue arr = [[-1 for c in range(n)] for r in range(n)] for...
p00748 Pollock's conjecture
The nth triangular number is defined as the sum of the first n positive integers. The nth tetrahedral number is defined as the sum of the first n triangular numbers. It is easy to show that the nth tetrahedral number is equal to n(n+1)(n+2) ⁄ 6. For example, the 5th tetrahedral number is 1+(1+2)+(1+2+3)+(1+2+3+4)+(1+2+...
```python def main(): INIT = 100 query = [] ans = [] while True: q = int(input()) if q == 0: break query.append(q) MAX = max(query) table = [INIT] * (MAX + 1) table[0] = 0 all_item = [i * (i + 1) * (i + 2) // 6 for i in range(1, 181)] odd_item = [i for i in all_item if i % 2] ...
p01017 Yu-kun Likes Rectangles
Background The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves rectangles as much as programming. Yu-kun decided to write a program to calculate the maximum score that can be obtained, thinking of a new play to ge...
```python H, W = map(int, input().split()) a_mp = [list(map(int, input().split())) for _ in range(H)] b_mp = [list(map(int, input().split())) for _ in range(H)] h, w = map(int, input().split()) c_mp = [list(map(int, input().split())) for _ in range(h)] INF = 10 ** 20 def check(x, y): ret = 0 for dy in range(h): ...
p01289 Strange Couple
Alice and Bob are going to drive from their home to a theater for a date. They are very challenging - they have no maps with them even though they don’t know the route at all (since they have just moved to their new home). Yes, they will be going just by their feeling. The town they drive can be considered as an undir...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools import time,random sys.setrecursionlimit(10**7) 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)] def LI(): ...
p01770 Arojam's Mask
Problem statement You are a hero. The world in which the hero is traveling consists of N cities and M roads connecting different cities. Road i connects town a_i and town b_i and can move in both directions. The purpose of the brave is to start from town S and move to town T. S and T are different cities. The hero ca...
```python from collections import deque n, m, e, s, t, r = map(int, input().split()) edges = [[] for _ in range(n * 2 ** e)] for _ in range(m): a, b = map(int, input().split()) for i in range(2 ** e): edges[a + n * i].append(b + n * i) edges[b + n * i].append(a + n * i) start = s slide = {} for i in range...
p02185 Many Decimal Integers
D: Many Decimal Integers problem Given a string S consisting only of numbers (0-9) and a string T consisting only of numbers and `?`. S and T are the same length. Consider changing each `?` That exists in T to one of the numbers from 0 to 9 to create the string T'consisting of only numbers. At this time, it must be ...
```python #!usr/bin/env python3 from collections import defaultdict,deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for x in sys.stdin.readline(...
p02327 Largest Rectangle
Given a matrix (H × W) which contains only 1 and 0, find the area of the largest rectangle which only contains 0s. Constraints * 1 ≤ H, W ≤ 1,400 Input H W c1,1 c1,2 ... c1,W c2,1 c2,2 ... c2,W : cH,1 cH,2 ... cH,W In the first line, two integers H and W separated by a space character are given. In the following...
```python H, W = map(int, input().split()) height = W * [0] max_area = 0 for _ in range(H): height = [0 if t else height[j]+1 for j, t in enumerate(map(int, input().split()))] height.append(0) stack = [] for i, h in enumerate(height): if stack: if stack[-1][1] == h: c...
p02472 Addition of Big Integers
Addition of Big Integers Given two integers $A$ and $B$, compute the sum, $A + B$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the sum in a line. Constraints * $-1 \times 10^{100000} \leq A, B \leq 10^{100000}$ Sample Input 1 5 8 Sample Output 1 13 S...
```python n, m = map(int, input().split()) print(n + m) ```
1011_A. Stages
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages. There are n stages available. The rock...
```python n,k = list(map(int,input().split())) data = sorted(list(input())) data = list(map(lambda x:ord(x)-ord('a')+1,data)) result = 0 used = 0 idx =0 prev = -2 # print(data) for d in data: if d > prev+1: result+= d prev = d used += 1 if used == k: break if used < k: ...
1036_B. Diagonal Walking v.2
Mikhail walks on a Cartesian plane. He starts at the point (0, 0), and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point (0, 0), he can go to any of the following points in one move: * (1, 0); * (1, 1); * (0, 1); * (-1, 1); * (-1, 0); * (-1, -1);...
```python q = int(input()) for i in range(q): n, m, k = map(int, input().split()) if m >k or n > k: print(-1) else: print(k - (k-n)%2 - (k-m)%2) ```
1059_A. Cashier
Vasya has recently got a job as a cashier at a local store. His day at work is L minutes long. Vasya has already memorized n regular customers, the i-th of which comes after t_{i} minutes after the beginning of the day, and his service consumes l_{i} minutes. It is guaranteed that no customer will arrive while Vasya is...
```python n,l,a = map(int,input().split()) b =[] for i in range(n): b.append([int(e) for e in input().split()]) ans = 0 for i in range(n-1): ans += (b[i+1][0] - b[i][1] - b[i][0])//a if(n > 0): ans += b[0][0]//a ans += (l - b[n-1][1] - b[n-1][0])//a else: ans += l//a print(ans) ```
1080_C. Masha and two friends
Recently, Masha was presented with a chessboard with a height of n and a width of m. The rows on the chessboard are numbered from 1 to n from bottom to top. The columns are numbered from 1 to m from left to right. Therefore, each cell can be specified with the coordinates (x,y), where x is the column number, and y is ...
```python def num_sq(x,y,x2,y2): # b, w a = (abs(x2-x)+1) b = (abs(y2-y)+1) if a % 2 == 0 or b % 2 == 0: return (a*b // 2, a*b // 2) if (x+y) % 2 == 0: num_b = a * b // 2 return (num_b, a * b - num_b) num_w = a * b // 2 return (a * b - num_w, num_w) def pt_in(p1, r1, ...
10_B. Cinema Cashier
All cinema halls in Berland are rectangles with K rows of K seats each, and K is an odd number. Rows and seats are numbered from 1 to K. For safety reasons people, who come to the box office to buy tickets, are not allowed to choose seats themselves. Formerly the choice was made by a cashier, but now this is the respon...
```python __author__ = 'Darren' def solve(): n, k = map(int, input().split()) group = map(int, input().split()) available = [[k, 1][:] for _ in range(k+1)] center = (k + 1) // 2 for m in group: closest, best_row, best_col = 10000, -1, -1 for row in range(1, k+1): col = ...
1121_A. Technogoblet of Fire
Everybody knows that the m-coder Tournament will happen soon. m schools participate in the tournament, and only one student from each school participates. There are a total of n students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. ...
```python n,m,k=map(int,input().split()) p=list(map(int,input().split())) s=list(map(int,input().split())) c=set(map(int,input().split())) d={} for i in range(n): if s[i] not in d: d[s[i]]=[-1] if p[i]>d[s[i]][0]: d[s[i]]=(p[i],i) st=set() for i in d: st.add(d[i][1]+1) #print(c,st) c=c.diffe...
1148_C. Crazy Diamond
You are given a permutation p of integers from 1 to n, where n is an even number. Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type: * take two indices i and j such that 2 ⋅ |i - j| ≥ n and swap p_i and p_j. There is no need to minimize the number of...
```python n = int(input()) p = [*map(int, input().split())] p = [i - 1 for i in p] #print(p) pos = {} ans = [] for i, j in enumerate(p): pos[j] = i def swap(i, j): ans.append((i + 1, j + 1)) pos[p[i]], pos[p[j]] = pos[p[j]], pos[p[i]] p[i], p[j] = p[j], p[i] def do(i): j=pos[i] if j<n//2...
1206_F. Almost All
You are given a tree with n nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied: For every two nodes i, j, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from ...
```python import math n = int(input()) if n == 1: print() else: edge = [list(map(int, input().split())) for i in range(1, n) ] g = {} for x, y in edge: if x not in g: g[x] = [] if y not in g: g[y] = [] g[x].append(y) g[y].appe...
1225_B1. TV Subscriptions (Easy Version)
The only difference between easy and hard versions is constraints. The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the show, the episode of which will be shown in i-th day. The...
```python x = int(input()) for i in range(x): n, k, d = map(int, input().split(' ')) l = map(int, input().split(' ')) l = list(l) ar = [] for j in range(n-d+1): ar.append(len(set(l[j:(j+d)]))) print(min(ar)) ```
1249_D1. Too Many Segments (easy version)
The only difference between easy and hard versions is constraints. You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i. The integer point is called bad...
```python import sys from heapq import * #sys.stdin = open('in', 'r') #n = int(input()) n,k = map(int, input().split()) seg = [] for i in range(n): l, r = map(int, input().split()) seg.append((l, r, i+1)) seg.sort() c = 0 res = [] i = 0 hmin = [] hmax = [] rem = set() while i < n: l,r,si = seg[i] while ...
1267_L. Lexicography
Lucy likes letters. She studied the definition of the lexicographical order at school and plays with it. At first, she tried to construct the lexicographically smallest word out of given letters. It was so easy! Then she tried to build multiple words and minimize one of them. This was much harder! Formally, Lucy want...
```python # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in...
1290_A. Mind Control
You and your n - 1 friends have found an array of integers a_1, a_2, ..., a_n. You have decided to share it in the following way: All n of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for h...
```python t = int(input()) for _ in range(t): ans = 0 n, pos, control = map(int, input().split()) control = min(control, pos - 1) not_control = pos - control - 1 num = n - control - not_control a = list(map(int, input().split())) for i in range(control + 1): tmp = 10 ** 10 + 1 ...
1332_G. No Monotone Triples
Given a sequence of integers a of length n, a tuple (i,j,k) is called monotone triples if * 1 ≤ i<j<k≤ n; * a_i ≤ a_j ≤ a_k or a_i ≥ a_j ≥ a_k is satisfied. For example, a=[5,3,4,5], then (2,3,4) is monotone triples for sequence a while (1,3,4) is not. Bob is given a sequence of integers a of length n in a ...
```python import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from operator import itemgetter import bisect n,q=map(int,input().split()) A=[-1]+list(map(int,input().split())) Q=[list(map(int,input().split()))+[i] for i in range(q)] Q.sort(key=itemgetter(1)) Q_ind=0 ANS1=[-1000,-1000,...
1353_C. Board Moves
You are given a board of size n × n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move...
```python I = input for _ in range(int(I())): n = int(I())+1 s = 0 for i in range(1,n//2): s += 8*i*i print(s) ```
1373_B. 01 Game
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char...
```python from sys import stdin,stdout t=int(stdin.readline().strip()) for _ in range(t): s=stdin.readline().strip() stdout.write(("NET","DA")[min(s.count('0'),s.count('1')) % 2]+"\n") ```
1396_A. Multiples of Length
You are given an array a of n integers. You want to make all elements of a equal to zero by doing the following operation exactly three times: * Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can...
```python n=int(input());vals=list(map(int,input().split())) if n>=2: print(1,n) ans=[-i*n for i in vals] print(*ans) print(2,n) a1=[i*(n-1) for i in vals[1:n]] print(*a1) print(1,1) print(vals[0]*(n-1)) else: print(1,1) print(-vals[0]) print(1,1) print(0) print(1,1) ...
141_C. Queue
In the Main Berland Bank n people stand in a queue at the cashier, everyone knows his/her height hi, and the heights of the other people in the queue. Each of them keeps in mind number ai — how many people who are taller than him/her and stand in queue in front of him. After a while the cashier has a lunch break and t...
```python def solve(arr,n): arr.sort() names = [x[1] for x in arr] counts = [x[0] for x in arr] segments = [] curr_count = counts[0] curr_len = 0 L = 0 for i in range(n): if counts[i]==curr_count: curr_len += 1 else: segments.append((L,i-1)) ...
1438_C. Engineer Artem
Artem is building a new robot. He has a matrix a consisting of n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{i,j} written in it. If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells c...
```python def solve(): input_str = input().split() m, n = int(input_str[0]), int(input_str[1]) nums = [] for i in range(m): nums.append(list(map(int, input().split()))) for i in range(m): for j in range(n): if (i + j) & 1 == 0: if nums[i][j] & 1 == 0:...
1463_B. Find The Array
You are given an array [a_1, a_2, ..., a_n] such that 1 ≤ a_i ≤ 10^9. Let S be the sum of all elements of the array a. Let's call an array b of n integers beautiful if: * 1 ≤ b_i ≤ 10^9 for each i from 1 to n; * for every pair of adjacent integers from the array (b_i, b_{i + 1}), either b_i divides b_{i + 1}, or...
```python for _ in range(int(input())): n = map(int, input().split()) a = list(map(int, input().split())) c = 1 i = 0 while c <= 1000000000: d = 2 * c if c <= a[i] <= d: print(c, end=" ") i += 1 d = 1 if i == len(a): break ...
148_B. Escape
The princess is going to escape the dragon's cave, and she needs to plan it carefully. The princess runs at vp miles per hour, and the dragon flies at vd miles per hour. The dragon will discover the escape after t hours and will chase the princess immediately. Looks like there's no chance to success, but the princess ...
```python vp = int(input()) vd = int(input()) t = int(input()) f = int(input()) c = int(input()) distance = t * vp time = t treasure = 0 if vp == vd: if t == 0: print(1) else: print(0) elif vp > vd: print(0) else: while distance < c: timeadd = distance/(vd - vp) distance ...
1539_D. PriceFixed
Lena is the most economical girl in Moscow. So, when her dad asks her to buy some food for a trip to the country, she goes to the best store — "PriceFixed". Here are some rules of that store: * The store has an infinite number of items of every product. * All products have the same price: 2 rubles per item. * ...
```python n = int(input()) arr = [] for _ in range(n): arr.append(list(map(int, input().split()))) arr.sort(key=lambda x:x[1]) # print(arr) lo, hi = 0, n-1 ans, counter = 0, 0 while lo<=hi: # print(lo, hi, counter) to_buy, req = arr[lo] if counter>=req or to_buy==0: counter += to_buy an...
166_A. Rank List
Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place. You know the rules of comparing the results of two give...
```python n, k = map(int, input().split()) table =[] table_dic = dict() for i in range(n): p, t = map(int, input().split()) table_dic[i + 1] = [p,t] table.append([p, 50 - t]) ranking = sorted(table, key=lambda table: (table[0], table[1]), reverse=True) for i in range(n): ranking[i][1] = 50 - ranking[i...
233_C. Cycles
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been pa...
```python n, k = 0, int(input()) p = [['0'] * 100 for i in range(100)] while k: for i in range(n): if i > k: break p[n][i] = p[i][n] = '1' k -= i n += 1 print(n) for i in range(n): print(''.join(p[i][:n])) ```
259_B. Little Elephant and Magic Square
Little Elephant loves magic squares very much. A magic square is a 3 × 3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15...
```python l=[] for i in range(3): l.append(list(map(int,input().split()))) l[1][1]=(l[1][0]+l[1][2])//2 c=sum(l[1]) l[0][0]=c-(l[0][1]+l[0][2]) l[2][2]=c-(l[2][0]+l[2][1]) for i in range(3): for j in range(3): print(l[i][j],end=" ") print() ```
282_B. Painting Eggs
The Bitlandians are quite weird people. They have very peculiar customs. As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work. The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. h...
```python import sys input = lambda: sys.stdin.readline() n = int(input()) S = 0 ans = '' for i in range(n): a, g = [int(x) for x in input().split(' ')] if abs(S + a) <= 500: S += a ans += 'A' else: S -= g ans += 'G' print(ans) ```
305_A. Strange Addition
Unfortunately, Vasya can only sum pairs of integers (a, b), such that for any decimal place at least one number has digit 0 in this place. For example, Vasya can sum numbers 505 and 50, but he cannot sum 1 and 4. Vasya has a set of k distinct non-negative integers d1, d2, ..., dk. Vasya wants to choose some integers ...
```python n = int(input()) arr = list(map(int,input().split())) t = [] flag = 0 if(0 in arr): t.append(0) if(100 in arr): t.append(100) for i in range(n): if(arr[i]>0 and arr[i]<10): t.append(arr[i]) flag = 1 break for i in range(n): if(arr[i]%10 == 0 and arr[i]>0 and arr[i]<100)...
331_A2. Oh Sweet Beaverette
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me? — Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night? At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcomin...
```python n, t = int(input()), list(map(int, input().split())) a, b = {}, {} for i, j in enumerate(t): if not j in a: a[j] = i else: b[j] = i p = [(a[j], b[j] - 1) for j in b] s = [j if j > 0 else 0 for j in t] u = v = 2 * t[p[0][0]] - 1 for i in range(n - 1): s[i + 1] += s[i] for i, j in p: u = 2 * t[i] + ...
377_A. Maze
Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side. Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any oth...
```python from collections import defaultdict from sys import stdin def put(): return map(int, stdin.readline().split()) def find(): for i in range(n): for j in range(m): if mat[i][j]=='.': return i,j return -1,-1 def dfs(i,j): s = [(i,j)] t = 1 vis[i][j]=1 ...
399_C. Cards
User ainta loves to play with cards. He has a cards containing letter "o" and b cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below. 1. At first, the score is 0. 2. For each block of contiguous "o"s with length x the score increases by x2. 3. F...
```python a, b = map(int, input().split()) sx = lambda p: (a - p + 1) ** 2 + p - 1 sy = lambda q: (b % q) * (1 + b // q) ** 2 + (b // q) ** 2 * (q - b % q) n = min(a, b) if a == 0: print( -b ** 2) print( b * "x" ) elif b <= 1: print( a ** 2 - b ** 2 ) print ( a * "o" + b * "x" ) else: res = - (a ...
421_D. Bug in Code
Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!' The head of the company d...
```python from collections import defaultdict from bisect import bisect_left as lower import sys input = sys.stdin.readline def put(): return map(int, input().split()) try: n,m = put() cnt, mp, ans = [0]*n, defaultdict(), [0]*n for _ in range(n): x,y = put() x,y = x-1,y-1 key = ...
448_B. Suffix Structures
Bizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team. At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), s and t. You need to transform word s into word t". The task looked simple to the guys because they know the suffix...
```python s = input() t = input() ind = 0 for x in t: ind = s.find(x, ind) + 1 if ind <= 0: break if ind > 0 or len(t) == 0: print('automaton') else: ss = list(s) tt = list(t) bb1 = True if len(ss) >= len(tt): for x in tt: bb = False for y in ss: ...
46_C. Hamsters and Tigers
Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together...
```python n=int(input()) s=input() h=0 for i in s: if i=='H':h+=1 r=[] t=0 for i in range(0,n): if s[i]=='H': for b in range((i+1)%n,min(((i+1)%n+h-1),n)): if s[b]=='T': t+=1 if ((i+1)%n+(h-1))>n: for q in range(0,(((i+1)%n+(h-1))%n)): if ...
492_D. Vanya and Computer Game
Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to...
```python n, x, y = map(int, input().split()) for _ in range(n): a = int(input()) c1, c2 = ((a + 1) * x // (x + y)) / x, ((a + 1) * y // (x + y)) / y if c1 == c2: print('Both') elif c1 > c2: print('Vanya') else: print('Vova') ```
56_E. Domino Principle
Vasya is interested in arranging dominoes. He is fed up with common dominoes and he uses the dominoes of different heights. He put n dominoes on the table along one axis, going from left to right. Every domino stands perpendicular to that axis so that the axis passes through the center of its base. The i-th domino has ...
```python from typing import TypeVar, Generic, Callable, List import sys from array import array # noqa: F401 from bisect import bisect_left, bisect_right def input(): return sys.stdin.buffer.readline().decode('utf-8') T = TypeVar('T') class SegmentTree(Generic[T]): __slots__ = ["size", "tree", "identity...
591_C. Median Smoothing
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practi...
```python def main(): n = int(input()) a = [int(i) for i in input().split()] flag = 0 now_begin = 0 kek = 0 ans = [[-1] * 2 for i in range(n)] for i in range(1, n - 1): if a[i] != a[i - 1] and a[i] != a[i + 1]: kek += 1 else: flag = max((kek + 1) // 2,...
613_A. Peter and Snow Blower
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it...
```python import math def dot(v1, v2): return v1[0]*v2[0] + v1[1]*v2[1] def cross(v1, v2): return v1[0]*v2[1] - v1[1]*v2[0] def mag(x,y): return math.sqrt(x**2 + y**2) def main(): PI = 3.141592653589793 mags = [] n, x0, y0 = map(int, input().split()) x, y = x0, y0 for i in rang...
633_A. Ebony and Ivory
Dante is engaged in a fight with "The Savior". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots. For every bullet that hits the shield, Ebony deals a units of damage while Ivory deals b units of dama...
```python a, b, c = map(int, input().split()) h = 0 if c % a == 0: k = c // a else: k = c // a + 1 if c % b == 0: m = c // b else: m = c // b + 1 if c - a*k < 0 and c - b*m < 0 and ((c < 2 * a) and c < 2*b): print('No') else: for i in range(k+1): if (c - a*i) % b == 0 and (h == 0): ...
774_D. Lie or Truth
Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a1, a2, ..., an. While Vasya was walking, his little brother Stepan played with Vasya's cubes and chan...
```python n,l,r = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) if(a[:l - 1] == b[:l - 1] and a[r:] == b[r:]): print("TRUTH") else: print("LIE") ```
799_D. Field expansion
In one of the games Arkady is fond of the game process happens on a rectangular field. In the game process Arkady can buy extensions for his field, each extension enlarges one of the field sizes in a particular number of times. Formally, there are n extensions, the i-th of them multiplies the width or the length (by Ar...
```python def mp(): return map(int,input().split()) def lt(): return list(map(int,input().split())) def pt(x): print(x) def ip(): return input() def it(): return int(input()) def sl(x): return [t for t in x] def spl(x): return x.split() def aj(liste, item): liste.append(item) def bin(x): return "{0:b}".format(x)...
845_B. Luba And The Ticket
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky. The ticket is considered lucky if the sum of first three digits equals to the sum of las...
```python def main(): s = input() print(solver(s)) def solver(s): L1 = [int(x) for x in s[0:3]] L2 = [int(x) for x in s[3:6]] diff = sum(L2) - sum(L1) if diff == 0: return 0 elif diff < 0: L1, L2 = L2, L1 diff = -diff changes = [9 - L1[i] for i in range(3)] + [L2[i] - 0 for i in range(3)] changes.sort...
865_D. Buy Low Sell High
You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you...
```python from heapq import * N = int(input()) price = [int(i) for i in input().split()] total = 0 inf = (10**6) + 1 h = [inf] #Assume we bought and sold optimally for the first k prices. #We adjust our answer for the (k+1)th price that comes up. for p in price: if p > h[0]: total += (p - heappop(h)) ...
913_G. Power Substring
You are given n positive integers a1, a2, ..., an. For every ai you need to find a positive integer ki such that the decimal notation of 2ki contains the decimal notation of ai as a substring among its last min(100, length(2ki)) digits. Here length(m) is the length of the decimal notation of m. Note that you don't ha...
```python import sys #sys.stdout = open('output.txt', 'w') #sys.stdin = open('input.txt', 'r') #for line in sys.stdin: #while 1: # line = sys.stdin.readline() # if line: # print (line,end="") def phi(p,i): if i == 0: return 1 return p**i - p**(i-1) def pwr(x,p,mod): if p == 0: ret...
936_A. Save Energy!
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on. During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The s...
```python from math import ceil k , d , t = [int(x) for x in input().split()] n = ceil(k/d)*d diff = n - k new_k = k+(diff/2) res = (t//new_k)*n if t%new_k <= k : res += t%new_k else : res += k+(t%new_k- k)*2 print(res) ```
p02603 M-SOLUTIONS Programming Contest 2020 - Road to Millionaire
To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives. He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the n...
```python n,*a=map(int,open(0).read().split()) m=1000 for i in range(1,n): if a[i]>a[i-1]: m=m//a[i-1]*a[i]+m%a[i-1] print(m) ```
p02734 AtCoder Beginner Contest 159 - Knapsack for All Segments
Given are a sequence of N integers A_1, A_2, \ldots, A_N and a positive integer S. For a pair of integers (L, R) such that 1\leq L \leq R \leq N, let us define f(L, R) as follows: * f(L, R) is the number of sequences of integers (x_1, x_2, \ldots , x_k) such that L \leq x_1 < x_2 < \cdots < x_k \leq R and A_{x_1}+A_{...
```python import sys input = sys.stdin.readline N,S=map(int,input().split()) A=list(map(int,input().split())) mod=998244353 DP=[0]*(S+1) # 多項式の考え方が分かりやすい. # 多項式を使わないなら, # DP[j] := 終端がiになる区間について, S=jのときのF(*,i)の和 # を更新していくと考えれば良いのかな... DP[0]=1 ANS=0 for a in A: for i in range(S-a,-1,-1): DP[i+a]+=DP[i] ...
p02868 NIKKEI Programming Contest 2019-2 - Shortest Path on a Line
We have N points numbered 1 to N arranged in a line in this order. Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph. The i-th operation is as follows: * The operation uses integers L_i ...
```python from heapq import heappush,heappop N,M=map(int,input().split()) LRC=[list(map(int,input().split())) for i in range(M)] data=[[],[]]+[[[i-1,0]] for i in range(2,N+1)] for L,R,C in LRC: data[L].append([R,C]) dist=[[0,1]] inf=float("inf") flag=[inf]*(N+1) while dist: y,x=heappop(dist) if flag[x]!=inf...
p03003 AtCoder Beginner Contest 130 - Common Subsequence
You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive). In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content? Here the subsequence of A is a sequence obtained by removing zero or ...
```python def main(): e=enumerate n,m,*u=map(int,open(0).read().split()) dp=[[1]*(m+1)for _ in range(n+1)] dpi=dp[0] for i,s in e(u[:n]): dpi1=dp[i+1] for j,t in e(u[n:]): dpi1[j+1]=(dpi[j+1]+dpi1[j]-dpi[j]*(s!=t))%(10**9+7) dpi=dpi1 print(dpi[m]) main() ```
p03143 NIKKEI Programming Contest 2019 - Weights on Vertices and Edges
There is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. Also, each of these vertices and edges has a specified weight. Vertex i has a weight of X_i; Edge i has a weight of Y_i and connects Vertex A_i and B_i. We would like to remove zero o...
```python import sys from collections import deque input = sys.stdin.readline N,M=map(int,input().split()) X=list(map(int,input().split())) EDGE=[list(map(int,input().split())) for i in range(M)] EDGE.sort(key=lambda x:x[2]) EDGELIST=[[] for i in range(N+1)] for i in range(M): x,y,w=EDGE[i] EDGELIST[x].append...
p03287 AtCoder Beginner Contest 105 - Candy Distribution
There are N boxes arranged in a row from left to right. The i-th box from the left contains A_i candies. You will take out the candies from some consecutive boxes and distribute them evenly to M children. Such being the case, find the number of the pairs (l, r) that satisfy the following: * l and r are both integers...
```python n,m=list(map(int,input().split())) a=list(map(int,input().split())) d={0:1} s=0 for i in a: s=(s+i)%m if s in d: d[s]+=1 else: d[s]=1 def f(x): return int(x*(x-1)/2) s=0 for i in d: s+=f(d[i]) print(s) ```
p03603 AtCoder Regular Contest 083 - Bichrome Tree
We have a tree with N vertices. Vertex 1 is the root of the tree, and the parent of Vertex i (2 \leq i \leq N) is Vertex P_i. To each vertex in the tree, Snuke will allocate a color, either black or white, and a non-negative integer weight. Snuke has a favorite integer sequence, X_1, X_2, ..., X_N, so he wants to all...
```python n = int(input()) parents = list(map(int, input().split())) weights = list(map(int, input().split())) children = [[] for _ in range(n)] for i in range(n-1): children[parents[i]-1].append(i+1) def dfs(cur): if children[cur] == []: return (weights[cur], 0) sum = 0 dp = [[False] * (wei...
p03762 AtCoder Beginner Contest 058 - ###
On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis. Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i. Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i. For ever...
```python N,M=map(int,input().split()) X=list(map(int,input().split())) Y=list(map(int,input().split())) mod=10**9+7 x=0 for i in range(N): x+=((i-(N-i-1))*X[i])%mod x%=mod y=0 for j in range(M): y+=((j-(M-j-1))*Y[j])%mod y%=mod print((x*y)%mod) ```
p03932 square869120Contest #3 - Souvenirs
Input The input is given from standard input in the following format. > $H \ W$ $a_{1, 1} \ a_{1, 2} \ \cdots \ a_{1, W}$ $a_{2, 1} \ a_{2, 2} \ \cdots \ a_{2, W}$ $\vdots \ \ \ \ \ \ \ \ \ \ \vdots \ \ \ \ \ \ \ \ \ \ \vdots$ $a_{H, 1} \ a_{H, 2} \ \cdots \ a_{H, W}$ Output * Print the maximum number of souvenirs...
```python H,W = map(int,input().split()) src = [list(map(int,input().split())) for i in range(H)] dp = [[[0 for ex in range(W)] for sx in range(W)] for xy in range(H+W-1)] dp[0][0][0] = src[0][0] for xy in range(H+W-2): n = min(xy+1,H,W,H+W-xy-1) sx0 = max(0,xy-H+1) for sx in range(sx0, sx0+n): for...
p00025 Hit and Blow
Let's play Hit and Blow game. A imagines four numbers and B guesses the numbers. After B picks out four numbers, A answers: * The number of numbers which have the same place with numbers A imagined (Hit) * The number of numbers included (but different place) in the numbers A imagined (Blow) For example, if A imagin...
```python import sys e=iter(map(lambda a:a.split(),sys.stdin)) for a,b in zip(e,e): h=sum([1 for i in range(4)if a[i]==b[i]]) w=4-len(set(a)-set(b))-h print(h,w) ```
p00156 Moats around the Castle
Now, a ninja is planning to sneak into the castle tower from outside the castle. This ninja can easily run on the ground and swim in the moat, but he is not very good at climbing up from the moat, so he wants to enter the moat as few times as possible. Create a program that takes a sketch of the castle as input and ou...
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0156 """ import sys from sys import stdin from collections import deque input = stdin.readline def bfs(field, sx, sy): """ ??????????????°???????????°??????????????§?????????????????? :param field: :param s...
p00313 Secret Investigation
The secret organization AiZu AnalyticS has launched a top-secret investigation. There are N people targeted, with identification numbers from 1 to N. As an AZAS Information Strategy Investigator, you have decided to determine the number of people in your target who meet at least one of the following conditions: * Thos...
```python N = int(input()) U = set([i+1 for i in range(N)]) A = set([int(x) for x in input().split()[1:]]) B = set([int(x) for x in input().split()[1:]]) C = set([int(x) for x in input().split()[1:]]) result = ((U-A) & C) | (B & C) print(len(result)) ```
p00483 Planetary Exploration
After a long journey, the super-space-time immigrant ship carrying you finally discovered a planet that seems to be habitable. The planet, named JOI, is a harsh planet with three types of terrain, "Jungle," "Ocean," and "Ice," as the name implies. A simple survey created a map of the area around the planned residence. ...
```python from itertools import accumulate from operator import add line, row = [int(x) for x in input().split()] k = int(input()) L=[] J=[[0]*(row+1) for _ in range(line+1)] O=[[0]*(row+1) for _ in range(line+1)] I=[[0]*(row+1) for _ in range(line+1)] for _ in range(line): L.append(input()) for i in range(line):...
p00669 K Cards
One day, the teacher came up with the following game. The game uses n cards with one number from 1 to 10 and proceeds as follows. 1. The teacher pastes n cards on the blackboard in a horizontal row so that the numbers can be seen, and declares an integer k (k ≥ 1) to the students. For n cards arranged in a horizontal...
```python from functools import reduce from collections import Counter while True: n, k = map(int, input().split()) if n == 0: break clst = [int(input()) for _ in range(n)] acc = reduce(lambda x, y:x* y, clst[:k]) scores = [acc] for i in range(n - k): acc = acc // clst[i] * clst[i + k] scores.ap...
p00812 Equals are Equals
Mr. Simpson got up with a slight feeling of tiredness. It was the start of another day of hard work. A bunch of papers were waiting for his inspection on his desk in his office. The papers contained his students' answers to questions in his Math class, but the answers looked as if they were just stains of ink. His hea...
```python import sys readline = sys.stdin.readline write = sys.stdout.write from string import digits def convert(S): S = S + "$" cur = 0 def expr(): nonlocal cur res = [] op = '+' while 1: r = fact() if op == '-': for e in r: ...
p01076 Graph Making
Problem There are n vertices that are not connected to any of the vertices. An undirected side is stretched between each vertex. Find out how many sides can be stretched when the diameter is set to d. The diameter represents the largest of the shortest distances between two vertices. Here, the shortest distance is the...
```python # AOJ 1591 Graph Making # Python3 2018.7.13 bal4u n, d = map(int, input().split()) if d == 1: print(n*(n-1)//2) else: print((n-1)+(n-d-1)*n-((n-d-1)*(n+d-2)//2)) ```
p01684 Venn Diagram
Problem Statement Alice is a private teacher. One of her job is to prepare the learning materials for her student. Now, as part of the materials, she is drawing a Venn diagram between two sets $A$ and $B$. Venn diagram is a diagram which illustrates the relationships among one or more sets. For example, a Venn diagra...
```python import sys readline = sys.stdin.readline write = sys.stdout.write from math import pi, sqrt, acos, sin def solve(): EPS = 1e-9 W, H, A, B, C = map(int, readline().split()) if W == 0: return False a = sqrt(A / pi); b = sqrt(B / pi) mx = max(a, b) if 2*mx > min(W, H) - EPS: ...
p01828 M and A
Example Input acmicpc tsukuba Output No
```python def f(s,t): j=0;i=0 while i<len(t) and j<len(s): if t[i]==s[j]:j+=2 i+=1 return j>=len(s) I=input s=I() t=I() print(['No','Yes'][f(s,t) or f(s[1:],t)]) ```
p01963 Separate String
You are given a string $t$ and a set $S$ of $N$ different strings. You need to separate $t$ such that each part is included in $S$. For example, the following 4 separation methods satisfy the condition when $t = abab$ and $S = \\{a, ab, b\\}$. * $a,b,a,b$ * $a,b,ab$ * $ab,a,b$ * $ab,ab$ Your task is to count the n...
```python from collections import defaultdict import sys def solve(): readline = sys.stdin.readline write = sys.stdout.write mod = 10**9 + 9 base = 37 ca = ord('a') N = int(readline()) SS = [readline().strip() for i in range(N)] SS.sort(key = len) T = readline().strip() L = len...
p02250 Multiple String Matching
Determine whether a text T includes a pattern P. Your program should answer for given queries consisting of P_i. Constraints * 1 ≤ length of T ≤ 1000000 * 1 ≤ length of P_i ≤ 1000 * 1 ≤ Q ≤ 10000 * The input consists of alphabetical characters and digits Input In the first line, a text T is given. In the second lin...
```python base = 127 mask = (1 << 32) - 1 def calc_hash(f, pl, tl): dl = tl - pl tmp = set() t = 1 for _ in range(pl): t = (t * base) & mask e = 0 for i in range(pl): e = (e * base + f[i]) & mask for i in range(dl): tmp.add(e) e = (e * base - t * f[i] + f[i + ...
p02398 How Many Divisors?
How Many Divisors? Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b. Constraints * 1 ≤ a, b, c ≤ 10000 * a ≤ b Input Three integers a, b and c are given in a line separated by a single space. Output Print the number of divisors in a line. Example Inp...
```python a, b, c = map(int, input().split()) ans = 0 for i in range(a, b + 1): if c % i == 0: ans += 1 print(ans) ```
1016_C. Vasya And The Mushrooms
Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends...
```python n = int(input()) u1 = list(map(int, input().split())) u2 = list(map(int, input().split())) a1 = u1[:n] a2 = u2[:n] for i in range(1, n): a1[i] += a1[i - 1] a2[i] += a2[i - 1] q1 = [0] * (2 * n) q2 = [0] * (2 * n) for i in range(1, n): q1[i] = u1[i] * (i) + q1[i - 1] q2[i] = u2[i] * (i) + q2[i ...
103_C. Russian Roulette
After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all. Sasha se...
```python #!/usr/bin/env python3 n, k, p = map(int, input().strip().split()) if k == 0: ak = 0 an = n else: ak = k - 1 if n % 2 == 1 else k an = n - (n % 2) ans = '' for i in range(p): v = int(input().rstrip()) if k == 0: print('.', end='') else: if v == n: pri...
1062_D. Fun with Integers
You are given a positive integer n greater or equal to 2. For every pair of integers a and b (2 ≤ |a|, |b| ≤ n), you can transform a into b if and only if there exists an integer x such that 1 < |x| and (a ⋅ x = b or b ⋅ x = a), where |x| denotes the absolute value of x. After such a transformation, your score increas...
```python i = input() i = int(i) v = 0 g = 2 s = 4 while g <= i: while s <= i: v = v + int(s / g * 4) s = s + g g = g + 1 s = g * 2 print(str(v)) ```
1084_C. The Fair Nut and String
The Fair Nut found a string s. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences p_1, p_2, …, p_k, such that: 1. For each i (1 ≤ i ≤ k), s_{p_i} = 'a'. 2. For each i (1 ≤ i < k), there is such j that p_i < j < p_{i + 1} and s...
```python s=input() sss='' for i in s: if i in ['a','b']: sss+=i from itertools import groupby xxx=[''.join(g) for _, g in groupby(sss)] xxx=[len(i)+1 for i in xxx if 'a' in i] ans=1 if len(xxx)==1: print((xxx[0]-1)%1000000007) else: for i in xxx: ans*=i print((ans-1)%1000000007) ``...
1131_E. String Multiplication
Roman and Denis are on the trip to the programming competition. Since the trip was long, they soon got bored, and hence decided to came up with something. Roman invented a pizza's recipe, while Denis invented a string multiplication. According to Denis, the result of multiplication (product) of strings s of length m an...
```python ALPH = 'abcdefghijklmnopqrstuvwxyz' MAX = 10 ** 9 def cnt(s): c = {ch : 0 for ch in ALPH} i = 0 while i < len(s): j = i + 1 while j < len(s) and s[i] == s[j]: j += 1 c[s[i]] = max(c[s[i]], j - i) i = j return c def nxt(c, t): nc = cnt(t) fo...
1152_A. Neko Finds Grapes
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible. The j-th key can be used to unlock the ...
```python n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) aeven = 0 aodd = 0 beven = 0 bodd = 0 for i in range(n): if a[i] % 2 == 0: aeven += 1 else: aodd += 1 for i in range(m): if b[i] % 2 == 0: beven += 1 else: ...
1191_C. Tokitsukaze and Discard Items
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them. These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed o...
```python from collections import deque n,m,k=list(map(int,input().split())) arr=list(map(int,input().split())) d=deque() for i in arr: d.append(i) chances=curr=tot=0 # print("WORKING") while tot<m: # print("S") if (d[0]-curr)%k==0: p=(d[0]-curr)//k else:p=((d[0]-curr)//k)+1 temp=curr w...
1230_A. Dawid and Bags of Candies
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or thro...
```python list1 = list(map(int, input().split())) list1.sort() if list1[0] + list1[3] == list1[1] + list1[2]: print("YES") elif list1[0] + list1[2] +list1[1] == list1[3]: print("YES") else: print("NO") ```
1251_E1. Voting (Easy Version)
The only difference between easy and hard versions is constraints. Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you. There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins....
```python import sys from heapq import * #sys.stdin = open('in', 'r') t = int(input()) for ti in range(t): n = int(input()) a = [] for i in range(n): mi, pi = map(int, input().split()) a.append((mi, -pi)) a.sort() c = 0 h = [] res = 0 for i in reversed(range(n)): ...
1271_C. Shawarma Tent
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes. The main school of the capital is located in (s_x, ...
```python n,x,y=map(int,input().split()) lu=0 ld=0 ru=0 rd=0 u=0 d=0 l=0 r=0 for i in range(n): a,b=map(int,input().split()) if(a<x and b<y): ld+=1 elif(a<x and b>y): lu+=1 elif(a==x and b!=y): if(b>y): u+=1 else: d+=1 elif(a>x and b<y): ...
1294_D. MEX maximizing
Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: * for the array [0, 0, 1, 0, 2] MEX equals to 3 because numbers 0, 1 and 2 are presented in the array and 3 is the minimum non-negative integer not presented in the array; * for the array [1, 2, 3, 4] MEX eq...
```python import os from io import BytesIO, IOBase import sys from collections import defaultdict, deque, Counter from bisect import * from math import sqrt, pi, ceil, log, inf,gcd from itertools import permutations from copy import deepcopy from heapq import * from sys import setrecursionlimit def main(): q, x = m...
1315_D. Recommendations
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications. The latest A/B test suggests that users are reading recommended publications more actively ...
```python # Код программы написал на языке Python 3 import sys from heapq import heappush, heappop def main(): n = int(sys.stdin.readline()) h = sorted(list(zip([int(i) for i in sys.stdin.readline().split()], [int(i) for i in sys.stdin.readline().split()]))) z, w, o, res = [], 0, 0, 0 while o...
1359_D. Yet Another Yet Another Task
Alice and Bob are playing yet another card game. This time the rules are the following. There are n cards lying in a row in front of them. The i-th card has value a_i. First, Alice chooses a non-empty consecutive segment of cards [l; r] (l ≤ r). After that Bob removes a single card j from that segment (l ≤ j ≤ r). Th...
```python import math import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) ans = 0 for i in range(31): s = 0 for j in a: if j <= i: s = max(0, s + j) else: s = 0 ans = max(ans, s - i) print(ans) ```
139_D. Digits Permutations
Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly. Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so o...
```python import itertools def countZeroes(s): ret = 0 for i in s: if i != '0': break ret += 1 return ret def stupid(n): ansMax = 0 bn1 = n bn2 = n for n1 in itertools.permutations(n): for n2 in itertools.permutations(n): val = str(int(''.joi...
1443_A. Kids Seating
Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a ≠ b) will indulge if: 1. gcd(a, b) = 1 or, 2. a divides b or b d...
```python # cook your dish here for _ in range(int(input())): n=int(input()) s=4*n-2 for i in range(n): print(s,end=" ") s-=2 print() ```
1468_J. Road Reform
There are n cities and m bidirectional roads in Berland. The i-th road connects the cities x_i and y_i, and has the speed limit s_i. The road network allows everyone to get from any city to any other city. The Berland Transport Ministry is planning a road reform. First of all, maintaining all m roads is too costly, ...
```python from collections import defaultdict from math import ceil, sqrt, floor from heapq import heappush,heappop import sys inf = float("inf") class DisjointSet: def __init__(self, n): self.n = n self.par = [-1] * n self.nc = n def findParent(self, i): if self.par[i] == -1: return i #no parent yet ...
1493_C. K-beautiful Strings
You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is...
```python #!/usr/bin/python import sys from sys import stdin def solve(N, K, S): if N % K != 0: print(-1) return cnt_dict = {} for s in S: cnt_dict[s] = 0 for s in S: cnt_dict[s] += 1 bea = True for k in cnt_dict: if cnt_dict[k] % K != 0: ...
1543_B. Customising the Track
Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into n sub-tracks. You are given an array a where a_i represents the number of traffic cars in the i-th sub-track. You def...
```python t = int(input()) for T in range(t): n = int(input()) A = [int(i) for i in input().split()] s = sum(A) mean = s//n rem = s%n for i in range(n): if i<rem: A[i] = mean+1 else: A[i] = mean A.sort() cursum = 0 curnums = 0 ans = 0 f...
171_C. A Piece of Cake
How to make a cake you'll never eat. Ingredients. * 2 carrots * 0 calories * 100 g chocolate spread * 1 pack of flour * 1 egg Method. 1. Put calories into the mixing bowl. 2. Take carrots from refrigerator. 3. Chop carrots. 4. Take chocolate spread from refrigerator. 5. Put chocolate spread ...
```python a = input().split() s = 0 for i in range(int(a[0])): s += (i + 1) * int(a[i + 1]) print(s) ```
191_A. Dynasty Puzzles
The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the...
```python from sys import stdin, stdout fst = 97 sze = 26 values = [[0 for i in range(sze)] for j in range(sze)] n = int(stdin.readline()) challengers = [] for i in range(n): s = stdin.readline().strip() challengers.append((ord(s[0]) - fst, ord(s[-1]) - fst)) for i in range(sze): if values[i...
215_A. Bicycle Chain
Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation. We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on t...
```python n = int(input()) a = list(map(int,input().split())) m = int(input()) b = list(map(int,input().split())) count = [] for i in range(n): for j in range(m): if((b[j]/a[i])==int(b[j]/a[i])): count.append(int(b[j]/a[i])) o = max(count) print(count.count(o)) ```
239_A. Two Bags of Potatoes
Valera had two bags of potatoes, the first of these bags contains x (x ≥ 1) potatoes, and the second — y (y ≥ 1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater ...
```python """ author - Sayan Bose Brooklyn 99 is love! """ y, k, n = map(int, input().split()) if n-y == 0: print(-1) else: y1 = y res = [] f, f1 = 0, 0 while y <= n: if not y%k: f = 1 if y-y1: f1 = 1 print(y-y1, end = ' ') if not f: temp = y//k + 1 y = k * temp else: y += k ...
263_D. Cycle in Graph
You've got a undirected graph G, consisting of n nodes. We will consider the nodes of the graph indexed by integers from 1 to n. We know that each node of graph G is connected by edges with at least k other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least k + 1. A simpl...
```python n, m, k = map(int, input().split()) d = {} for _ in range(m): u, v = map(int, input().split()) if u not in d: d[u] = [v] else: d[u].append(v) if v not in d: d[v] = [u] else: d[v].append(u) # print(d) stack = [] not_visited = set(range(1, n+1)) while not_v...
335_B. Palindrome
Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible. Input The only line of the input contains one string s of length n (1 ≤ n ≤ 5·104) c...
```python def p2(a): n = len(a) last = [[0] * 26 for _ in range(n)] last[0][ord(a[0])-97] = 0 for i in range(1, n): for j in range(26): last[i][j] = last[i-1][j] last[i][ord(a[i])-97] = i dp = [''] * n for i in range(n-1, -1, -1): for j in range(n-1, i, -1): k = last[j][ord(a[i])-9...
358_B. Dima and Text Messages
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other. Dima and Inna are using a secret code in their text messages. ...
```python def werify_message(words, message): true_message = ''.join(['<3', '<3'.join(words), '<3']) # index in true_message i = 0 for litera in message: if len(true_message) != i: if litera == true_message[i]: i += 1 else: # Дошли до конца исходн...
381_A. Sereja and Dima
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ...
```python n = int(input("")) cards=list(map(int,input().split())) sereja = 0 dima = 0 temp = 0 turn = 1 while cards != []: nMax=max(cards[0],cards[-1]) if turn==1: temp = sereja + nMax sereja+=nMax turn=2 else: temp = dima + nMax dima+=nMax turn=1 ...
42_A. Guilty — to the kitchen!
It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills. According to the borscht recipe it consists of n ingredients that have to be mixed in propor...
```python n,v=map(int,input().split()) a=[int(i) for i in input().split()] b=[int(i) for i in input().split()] mini=10**9 for i in range(n): mini=min(mini,b[i]/a[i]) sm=0 for i in range(n): sm=sm+mini*a[i] print(min(sm,v)) ```