name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
131_C. The World is a Theatre
There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the trou...
```python from sys import stdin, stdout a, b, c = [int(a) for a in stdin.read().split()] ZA = [1, 1] for d in range(2, 31): ZA.append(d * ZA[d - 1]) e = 0 if c - b < 4: d = 4 else: d = c - b while d <= a and d < c: e = e + ZA[a] // ZA[d] // ZA[a - d] * ZA[b] // ZA[c - d] // ZA[b - c + d] d = d + 1 stdout.write(str...
1360_D. Buying Shovels
Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≤ i ≤ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or...
```python from sys import stdin input=lambda : stdin.readline().strip() from math import ceil,sqrt,factorial,gcd for _ in range(int(input())): n,k=map(int,input().split()) if k>=n: print(1) else: l=[] s=int(sqrt(n)) for i in range(2,s+2): if n%i==0 and i<=k: l.append(n//i) t=n//i if t<=k: ...
1380_E. Merging Towers
You have a set of n discs, the i-th disc has radius i. Initially, these discs are split among m towers: each tower contains at least one disc, and the discs in each tower are sorted in descending order of their radii from bottom to top. You would like to assemble one tower containing all of those discs. To do so, you ...
```python import sys inpy = [int(x) for x in sys.stdin.read().split()] n, m = inpy[0], inpy[1] belong = inpy[2: 2 + n] qur = [] for i in range(m - 1): qur.append((inpy[i * 2 + 2 + n], inpy[i * 2 + 3 + n])) contain = [[] for _ in range(m + 1)] res = 0 for i in range(n -1): if belong[i] != belong[i+1]: ...
1400_E. Clear the Multiset
You have a multiset containing several integers. Initially, it contains a_1 elements equal to 1, a_2 elements equal to 2, ..., a_n elements equal to n. You may apply two types of operations: * choose two integers l and r (l ≤ r), then remove one occurrence of l, one occurrence of l + 1, ..., one occurrence of r fro...
```python from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from...
1445_A. Array Rearrangment
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i ≤ x holds for each i (1 ≤ i ≤ n). Input The first line of input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. t blocks follow, each d...
```python y = int(input()) for _ in range(y): q = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split()))[::-1] e = True for i in range(q[0]): if a[i] + b[i] <= q[1]: pass else: print("No") e = False ...
146_A. Lucky Ticket
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. It...
```python n = int(input()) s = input() print('YES' if set(s) <= {'4', '7'} and s[:len(s) // 2].count('4') == s[-(len(s) // 2):].count('4') else 'NO') ```
1495_C. Garden of the Sun
There are many sunflowers in the Garden of the Sun. Garden of the Sun is a rectangular table with n rows and m columns, where the cells of the table are farmlands. All of the cells grow a sunflower on it. Unfortunately, one night, the lightning stroke some (possibly zero) cells, and sunflowers on those cells were burn...
```python import sys, os if os.environ['USERNAME']=='kissz': inp=open('in.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=sys.stdin.readline def debug(*args): pass # SCRIPT STARTS HERE for _ in range(int(inp())): n,m=map(int,inp().split()) R=[] ...
173_A. Rock-Paper-Scissors
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scisso...
```python n = int(input()) a = input() b = input() ai = 0 alen = len(a) bi = 0 blen = len(b) nik = 0 pol = 0 if alen == blen: rnd = alen else: rnd = alen*blen numofrounds = 0 for i in range(n): #print(i,rnd) if i == rnd: numofrounds = n//rnd # print(numofrounds) nik *= numofrounds ...
241_A. Old Peykan
There are n cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as c1, c2, ..., cn. The Old Peykan wants to travel from city c1 to cn using roads. There are (n - 1) one way roads, the i-th road goes from city ci to city ci + 1 and is di kil...
```python # CF 241/A 1300 # S = supply in city i # D = distance from c[i] to c[i + 1] # k = refresh interval # min time to arrive at C[n] where n = m + 1 def f(k, D, S): n = len(D) # travel time is at least the sum of all distances time = sum(D) fuel = 0 best = 0 for i in range(n): ...
289_E. Polo the Penguin and XOR operation
Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive. For permutation p = p0, p1, ..., pn, Polo has defined its beauty — number <image>. Expression <image> means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in al...
```python import sys from math import gcd,sqrt,ceil from collections import defaultdict,Counter,deque from bisect import bisect_left,bisect_right import math from itertools import permutations # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdin = open('input.txt', 'r') # sys.std...
337_B. Routine Problem
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the scre...
```python import sys from fractions import gcd my_file = sys.stdin #my_file = open("input.txt", "r") line = [int(i) for i in my_file.readline().split()] a, b, c, d = line[0], line[1], line[2], line[3] if a/b < c/d: N = (b*c) - (a*d) D = b*c else: N = (a*d)-(b*c) D = a*d dec = gcd(N,D) print(N//dec, en...
383_B. Volcanoes
Iahub got lost in a very big desert. The desert can be represented as a n × n square matrix, where each cell is a zone of the desert. The cell (i, j) represents the cell at row i and column j (1 ≤ i, j ≤ n). Iahub can go from one cell (i, j) only down or right, that is to cells (i + 1, j) or (i, j + 1). Also, there a...
```python __author__ = 'Pavel Mavrin' n, m = [int(x) for x in input().split()] a = [] for i in range(m): a.append([int(x) - 1 for x in input().split()]) a.sort(key=lambda x: x[0] * n + x[1]) a.append([n - 1, n]) d = [[0, 1]] r = 0 i = 0 while i < len(a): if a[i][0] == r: dd = [] j = 0 ...
404_A. Valera and X
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the...
```python n = int(input()) data = [] ghotr = set() other = set() for i in range(n): text = input() for index in range(len(text)): if index == i: ghotr.add(text[index]) elif index == n - i - 1: ghotr.add(text[n-1-i]) else: other....
431_B. Shower Line
Many students live in a dormitory. A dormitory is a whole new world of funny amusements and possibilities but it does have its drawbacks. There is only one shower and there are multiple students who wish to have a shower in the morning. That's why every morning there is a line of five people in front of the dormitory...
```python import sys,math from collections import deque,defaultdict import operator as op from functools import reduce from itertools import permutations #sys.setrecursionlimit(10**6) I=sys.stdin.readline #s="abcdefghijklmnopqrstuvwxyz" """ x_move=[-1,0,1,0,-1,1,1,-1] y_move=[0,1,0,-1,1,1,-1,-1] """ def ii(): re...
476_B. Dreamoon and WiFi
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them. Each command is one of the following two types: 1. Go 1 unit towards the positive direction, denoted as '+' 2. Go 1 unit towards the negative direction, ...
```python import math s1=input() s2=input() c1=0 c2=0 c3=0 for items in s1: if items=="+": c1+=1 if items=="-": c2+=1 for items in s2: if items=="+": c1-=1 if items=="-": c2-=1 if items=="?": c3+=1 if (c2<0): print(0.000) elif (c2>c3): print(0.000)...
49_C. Disposition
Vasya bought the collected works of a well-known Berland poet Petya in n volumes. The volumes are numbered from 1 to n. He thinks that it does not do to arrange the book simply according to their order. Vasya wants to minimize the number of the disposition’s divisors — the positive integers i such that for at least one...
```python print(*range(2, int(input())+1), end=' ') print(1) ```
524_C. The Art of Dealing with ATM
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bi...
```python # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq,bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(1...
54_C. First Digit Law
In the probability theory the following paradox called Benford's law is known: "In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit" (that's the simplest form of the law). Having read about it on Codeforces, the Hedgeho...
```python def num_ones(a,b): '''returns how many nums start with digit 1 in [a,b]''' if a==0: if b==0: return 0 ans=0 b=str(b) for i in range(1,len(b)): ans+=10**(i-1) if b[0]=='1': x=b[1:] if x=='': x=0 ...
599_B. Spongebob and Joke
While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a1, a2, ..., am of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f1, f2, ..., fn of length n an...
```python read = lambda: map(int, input().split()) n, m = read() f = list(read()) b = list(read()) c = [list() for i in range(n + 1)] for i in range(n): c[f[i]].append(i + 1) a = [0] * m ans = 'Possible' for i in range(m): if len(c[b[i]]) == 0: print('Impossible') exit() if len(c[b[i]]) > 1:...
620_A. Professor GukiZ's Robot
Professor GukiZ makes a new robot. The robot are in the point with coordinates (x1, y1) and should go to the point (x2, y2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps...
```python x2,y2=map(int,input().split()) x1,y1=map(int,input().split()) m=min(abs(x1-x2),abs(y2-y1) ) d=max(abs(x1-x2),abs(y2-y1) ) ans = m+d-m print(ans ) ```
63_E. Sweets Game
Karlsson has visited Lillebror again. They found a box of chocolates and a big whipped cream cake at Lillebror's place. Karlsson immediately suggested to divide the sweets fairly between Lillebror and himself. Specifically, to play together a game he has just invented with the chocolates. The winner will get the cake a...
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') lines = [ [0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18], [0, 3, 7], [1, 4, 8, 12], [2, 5, 9, 13, 16], [6, 10, 14, 17], [...
669_C. Little Artem and Matrix
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it. That element can store information about the matrix of integers size n × m. There a...
```python a, b, c = map(int, input().split()) arr = [] mat = [[0 for j in range(b)] for i in range(a)] for i in range(c): arr.append(input()) arr = arr[::-1] for command in arr: arra = [int(i) for i in command.split()] if arra[0] == 1: swp = mat[arra[1] - 1][b - 1] for i in range(b): ...
690_D3. The Wall (hard)
So many wall designs to choose from! Even modulo 106 + 3, it's an enormous number. Given that recently Heidi acquired an unlimited supply of bricks, her choices are endless! She really needs to do something to narrow them down. Heidi is quick to come up with criteria for a useful wall: * In a useful wall, at least ...
```python mod = 10 ** 6 + 3 def prod(a, b): return [[sum([a[i][k] * b[k][j] for k in range(len(b))]) % mod for j in range(len(b[0]))] for i in range(len(a))] c, w, h = map(int, input().split()) a = [[0] * (w + 1) for _ in range(w + 1)] for i in range(w): a[i][i + 1] = 1 for cnt in range(0, w + 1): a...
714_E. Sonya and Problem Wihtout a Legend
Sonya was unable to think of a story for this problem, so here comes the formal description. You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operati...
```python N=int(input()) s=list(map(int,input().split())) for i in range(N):s[i]-=i X=sorted(s) dp=[0]*N for i in s: mi = 7e77 for j in range(N): mi = min(mi, dp[j]) dp[j] = mi + abs(i-X[j]) print(min(dp)) ```
735_B. Urbanization
Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 peo...
```python n, n1, n2 = [int(x) for x in input().split()] d = [int(x) for x in input().split()] d.sort(reverse=True) s1 = 0 s2 = 0 n1, n2 = min(n1, n2), max(n1, n2) for i in range(n1): s1 += d[i] for i in range(n1, n1 + n2): s2 += d[i] ans = s1 / n1 + s2 / n2 print(ans) ```
75_B. Facetook Priority Wall
Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described). This priority factor will be affected by three types of actions: * 1. "X posted on Y's wall" (...
```python from collections import defaultdict u, p = input(), defaultdict(int) for i in range(int(input())): t = input().split() a, k = t[0], t[1][0] if k == 'p': b, d = t[3][: -2], 15 elif k == 'c': b, d = t[3][: -2], 10 else: b, d = t[2][: -2], 5 if a == u: p[b] += d elif b == u: p[a] += d...
780_A. Andryusha and Socks
Andryusha is an orderly boy and likes to keep things in their place. Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the sock...
```python NumOfSocks = int(input()) Socks = [int(x) for x in input().split()] OnTable, maxSocks, tmpMaxSocks = [0] * (NumOfSocks+1), 0, 0 for i in Socks: if not OnTable[i]: OnTable[i] = 1 tmpMaxSocks += 1 else: OnTable[i] = 0 tmpMaxSocks -= 1 if tmpMaxSocks > maxSocks: maxSo...
803_E. Roma and Poker
Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes 1 virtual bourle from the loser. Last evening Roma started to play poker. He decided to spend no more than k virtual bourl...
```python n, k = [int(i) for i in input().split()] s = input() dp = [[False] * 2010 for i in range(1001)] dp[0][0] = True for i in range(n): l = -k + 1 r = k if i == n - 1: l -= 1 r += 1 for b in range(l, r): if s[i] == 'L': dp[i + 1][b] = dp[i][b + 1] elif ...
828_C. String Reconstruction
Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more...
```python from sys import stdin, stdout sze = 10 ** 6 + 1 n = int(stdin.readline()) challengers = [] strings = [] sze = 10 ** 6 + 1 cnt = [[] for i in range(sze)] for i in range(n): s = stdin.readline().strip().split() num = int(s[1]) values = list(map(int, s[2:])) strings.append(s[0]) ...
84_D. Doctor
There are n animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number i in the queue will have to visit his...
```python import sys from array import array # noqa: F401 from collections import deque def input(): return sys.stdin.buffer.readline().decode('utf-8') n, k = map(int, input().split()) a = list(map(int, input().split())) if sum(a) < k: print(-1) exit() ok, ng = 0, 10**9 + 10 while abs(ok - ng) > 1: ...
873_A. Chores
Luba has to do n chores today. i-th chore takes ai units of time to complete. It is guaranteed that for every <image> the condition ai ≥ ai - 1 is met, so the sequence is sorted. Also Luba can work really hard on some chores. She can choose not more than k any chores and do each of them in x units of time instead of a...
```python n, k, x = map(int, input().split()) a = [int(x) for x in input().split()] res = k*x n-=k res+=sum(a[:n]) print(res) ```
898_F. Restoring the Expression
A correct expression of the form a+b=c was written; a, b and c are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits so tha...
```python def modgroup(M = 10**9+7, invn = 0) : exec(f'''class mod{M} : inv = [None] * {invn+1} if {invn+1} >= 2 : inv[1] = 1 for i in range(2, {invn+1}) : inv[i] = (({M} - {M}//i) * inv[{M}%i]) %{M} def __init__(self, n = 0) : self.n = n % {M} __repr__ = lambda self : str(self.n) + '%{M}' __int__ = lambda sel...
91_A. 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 math a, b = input(), input() na = len(a) nb = len(b) dp = [[-1 for _ in range(26)] for _ in range(na+1)] # dp = ([-1 for _ in range(26)],) * (na + 1) for i in range(na - 1, -1, -1): for j in range(26): dp[i][j] = dp[i+1][j] dp[i][ord(a[i]) - 97] = i cp = 0 ans = 1 i = 0 while i < nb: ...
975_D. Ghosts
Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way. There are n ghosts in the universe, they move in the OXY plane, each one of them has its own velocity that does not change in time: \overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarr...
```python import atexit import io import sys # Buffering IO _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) def main(): n, a, b = [int...
995_C. Leaving the Bar
For a vector \vec{v} = (x, y), define |v| = √{x^2 + y^2}. Allen had a bit too much to drink at the bar, which is at the origin. There are n vectors \vec{v_1}, \vec{v_2}, ⋅⋅⋅, \vec{v_n}. Allen will make n moves. As Allen's sense of direction is impaired, during the i-th move he will either move in the direction \vec{v_...
```python import random n = int(input()) V = [tuple(map(int,input().split())) for i in range(n)] dist = lambda x,y:x*x+y*y indices = sorted((dist(*v),i) for i,v in enumerate(V)) result = [0]*n vx,vy = 0,0 for d,i in reversed(indices): x,y = V[i] _,c = min(((dist(vx+x,vy+y),1),(dist(vx-x,vy-y),-1))) vx += c*...
p02642 AtCoder Beginner Contest 170 - Not Divisible
Given is a number sequence A of length N. Find the number of integers i \left(1 \leq i \leq N\right) with the following property: * For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i. Constraints * All values in input are integers. * 1 \leq N \leq 2 \times 10^5 * 1 \leq A_...
```python n,*a=map(int,open(0).read().split()) ma=1001001 nums=[0]*ma for i in a: nums[i]+=1 if nums[i]==1: # 一回だけ出てきた場合 for j in range(i+i,ma,i): nums[j]+=2 ans=nums.count(1) print(ans) ```
p02772 AtCoder Beginner Contest 155 - Papers Please
You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria. According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is...
```python n = input() a = map(int, input().split()) print('APPROVED' if all(ai % 2 == 1 or ai % 3 == 0 or ai % 5 == 0 for ai in a) else 'DENIED') ```
p03042 AtCoder Beginner Contest 126 - YYMM or MMYY
You have a digit sequence S of length 4. You are wondering which of the following formats S is in: * YYMM format: the last two digits of the year and the two-digit representation of the month (example: `01` for January), concatenated in this order * MMYY format: the two-digit representation of the month and the last t...
```python S = int(input()) b=S%100 a=S//100 if 1<=a<=12 and 1<=b<=12: print('AMBIGUOUS') elif 1<=a<=12: print('MMYY') elif 1<=b<=12: print('YYMM') else: print('NA') ```
p03184 Educational DP Contest - Grid 2
There is a grid with H horizontal rows and W vertical columns. Let (i, j) denote the square at the i-th row from the top and the j-th column from the left. In the grid, N Squares (r_1, c_1), (r_2, c_2), \ldots, (r_N, c_N) are wall squares, and the others are all empty squares. It is guaranteed that Squares (1, 1) and ...
```python import sys def prepare(n): fact = [1] * (n + 1) for i in range(1, n + 1): fact[i] = fact[i - 1] * i % MOD inv = [1] * (n + 1) inv[n] = pow(fact[n], MOD - 2, MOD) for i in range(n - 1, 0, -1): inv[i] = inv[i + 1] * (i + 1) % MOD return fact, inv MOD = 10 ** 9 + 7 h, ...
p03331 AtCoder Grand Contest 025 - Digits Sum
Takahashi has two positive integers A and B. It is known that A plus B equals N. Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10). Constraints * 2 ≤ N ≤ 10^5 * N is an integer. Input Input is given from Standard Input in the following format: N Outp...
```python N = sum([int(i) for i in input()]) print('10' if N == 1 else N) ```
p03490 AtCoder Regular Contest 087 - FT Robot
A robot is put at the origin in a two-dimensional plane. Initially, the robot is facing in the positive x-axis direction. This robot will be given an instruction sequence s. s consists of the following two kinds of letters, and will be executed in order from front to back. * `F` : Move in the current direction by dis...
```python import os import sys if os.getenv("LOCAL"): sys.stdin = open("_in.txt", "r") sys.setrecursionlimit(10 ** 9) INF = float("inf") IINF = 10 ** 18 MOD = 10 ** 9 + 7 # MOD = 998244353 S = sys.stdin.buffer.readline().decode().rstrip() X, Y = list(map(int, sys.stdin.buffer.readline().split())) # X 軸と Y 軸は独立に...
p03652 AtCoder Grand Contest 018 - Sports Festival
Takahashi is hosting an sports meet. There are N people who will participate. These people are conveniently numbered 1 through N. Also, there are M options of sports for this event. These sports are numbered 1 through M. Among these options, Takahashi will select one or more sports (possibly all) to be played in the ev...
```python import sys sys.setrecursionlimit(10 ** 7) input = sys.stdin.readline f_inf = float('inf') mod = 10 ** 9 + 7 res = f_inf def resolve(): def dfs(remove): global res if len(remove) == m: return cnt = [0] * m ma = -f_inf target = None for i in ra...
p03808 AtCoder Grand Contest 010 - Boxes
There are N boxes arranged in a circle. The i-th box contains A_i stones. Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation: * Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-...
```python N = int(input()) A = list(map(int, input().split())) s = sum(A) K = s // (N * (N + 1) // 2) if N == 1: print("YES") exit() if s % (N * (N + 1) // 2) != 0: print("NO") exit() d = [0] * (N - 1) for i in range(N - 1): d[i] = A[i + 1] - A[i] - K for i in range(N - 1): if d[i] > 0 or abs(d...
p03976 Kyoto University Programming Contest 2016 - Problem Committee
> Kyoto University Programming Contest is a programming contest voluntarily held by some Kyoto University students. This contest is abbreviated as Kyoto University Programming Contest and called KUPC. > > source: Kyoto University Programming Contest Information The problem-preparing committee met to hold this year's K...
```python from collections import Counter n, k = map(int, input().split()) P = [input()[0] for _ in range(n)] CP = Counter(P) P = list(CP.values()) ans = 0 while len(P) >= k: P.sort(reverse=True) for i in range(k): P[i] -= 1 P = [i for i in P if i > 0] ans += 1 print(ans) ```
p00065 Trading
There is data that records the customer number of the business partner and the trading date on a monthly basis. Please create a program that reads this month's data and last month's data and outputs the customer number of the company with which you have transactions and the number of transactions for two consecutive mo...
```python flag = False cli = [0] * 1001 sen = set() kon = set() while True: try: c, d = map(int, input().split(",")) except: if flag: break flag = True continue if flag: kon.add(c) else: sen.add(c) cli[c] += 1 for i in range(1,1001): ...
p00197 Greatest Common Divisor: Euclidean Algorithm
The greatest common divisor is an indispensable element in mathematics handled on a computer. Using the greatest common divisor can make a big difference in the efficiency of the calculation. One of the algorithms to find the greatest common divisor is "Euclidean algorithm". The flow of the process is shown below. <im...
```python def solve(): from sys import stdin f_i = stdin ans = "" while True: a, b = map(int, f_i.readline().split()) if a == 0 and b == 0: break if a < b: a, b = b, a # Euclidean Algorithm cnt = 1 ...
p00711 Red and Black
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles. Write a program to count the number of black tiles which he can r...
```python from collections import deque y = [-1,0,1,0] x = [0,-1,0,1] def main(): h,w = 0,0 c = [] def check(i,j): return 0<=i and i<h and 0<=j and j<w def bfs(a,b): res = 0 d = deque() d.append([a,b]) f = [[False]*w for _ in range(h)] while len(d): ...
p01413 Quest of Merchant
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well. Today's training is to gain the power of business by running around the city and conducting trade. I want to earn as much money as possible for future training. In this world, roads in ...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, M, W, T = map(int, readline().split()) cur = 0 n_map = {} ws = [0]*M; P = [0]*M for i in range(M): s, v, p = readline().split() n_map[s] = i ws[i] = int(v) P[i] = int(p) ...
p01867 AddMul
Problem statement Jota knows only the characters from `a` to` z` and the addition symbol `+`. Jota has an older sister, Tachiko. In addition to that, Tatsuko knows multiplication `*`, parentheses `(`, `)`, and integers (numbers) between `1` and` 9`. However, I don't know how to use multiple parentheses and how to mult...
```python # -*- coding: utf-8 -*- from collections import Counter N = input() S = input().split('+') dic_chr_num = Counter(S) dic_num_kind = Counter(dic_chr_num.values()) ans = 4 * len(dic_chr_num) - 1 for num, kind in dic_num_kind.items(): if num == 1: ans -= 2 * kind elif kind >= 2: ans -=...
p02004 GuruGuru
You are playing a game called Guru Guru Gururin. In this game, you can move with the vehicle called Gururin. There are two commands you can give to Gururin: 'R' and 'L'. When 'R' is sent, Gururin rotates clockwise by 90 degrees. Otherwise, when 'L' is sent, Gururin rotates counterclockwise by 90 degrees. During the ga...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): S = readline().strip() ans = 0 d = 0; cur = 0 for c in S: if c == "R": if d == cur: cur += 1 d = (d + 1) % 4 if d == 0 and cur == 4: ans +=...
p02289 Priority Queue
A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations: * $insert(S, k)$: insert an element $k$ into the set $S$ * $extractMax(S)$: remove and return the element of $S$ with the largest key Write a program which perfo...
```python #coding:utf-8 #1_9_C import heapq h = [] while True: cmd = input().split() if cmd[0] == "end": break elif cmd[0] == "insert": heapq.heappush(h, -int(cmd[1])) else: print(-heapq.heappop(h)) ```
p02436 Queue
Queue is a container of elements that are inserted and deleted according to FIFO (First In First Out). For $n$ queues $Q_i$ ($i = 0, 1, ..., n-1$), perform a sequence of the following operations. * enqueue($t$, $x$): Insert an integer $x$ to $Q_t$. * front($t$): Report the value which should be deleted next from $Q_t...
```python from collections import deque n,q=map(int,input().split()) qs = [deque() for _ in range(n)] for _ in range(q): op = list(map(int,input().split())) que = qs[op[1]] if op[0] == 0: que.append(op[2]) elif op[0] == 1: if len(que)>0: x = que.popleft() print(x) que.appendleft(x) else: if len(q...
1008_B. Turn the Rectangles
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangle...
```python n=int(input()) l=[] for i in range(n): l.append(list(map(int,input().split()))) val=0 check=1 for j in range(n-1,-1,-1): if(l[j][0]<l[j][1]): if(l[j][0]>=val): val=l[j][0] elif(l[j][1]>=val): val=l[j][1] else: check=0 else: if(l[j][1]>=val): val=l[j][1] elif(l[j][0]>=val): val=l[j]...
1096_G. Lucky Tickets
All bus tickets in Berland have their numbers. A number consists of n digits (n is even). Only k decimal digits d_1, d_2, ..., d_k can be used to form ticket numbers. If 0 is among these digits, then numbers may have leading zeroes. For example, if n = 4 and only digits 0 and 4 can be used, then 0000, 4004, 4440 are va...
```python from math import trunc MOD = 998244353 MODF = float(MOD) SHRT = float(1 << 16) # Using pajenegod's crazy method for multiplication using floating point fmod = lambda x: x - MODF * trunc(x / MODF) mod_prod = lambda a, b: fmod(trunc(a / SHRT) * fmod(b * SHRT) + (a - SHRT * trunc(a / SHRT)) * b) def fpow(a, b)...
1118_A. Water Buying
Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water. There are only two types of water bottles in the nearby shop — 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop. The bottle of the first type costs a burles and the bottle of the se...
```python q=int(input()) for i in range(q): n,a,b=map(int,input().split()) b=min(b,2*a) if(n%2==1): print(((n//2)*b)+a) else: print((n//2)*b) ```
1144_D. Equalize Them All
You are given an array a consisting of n integers. You can perform the following operations arbitrary number of times (possibly, zero): 1. Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i + |a_i - a_j|; 2. Choose a pair of indices (i, j) such that |i-j|=1 (indice...
```python from sys import stdin,stdout from math import gcd,sqrt from collections import deque input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\n') P=lambda x:stdout.write(x) hg=lambda x,y:((y+x-1)//x)*x pw=lambda x:1 if x==1 else 1+pw(x//2) chk=lambda x:chk(x//2) i...
1165_C. Good String
Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and ...
```python n = int(input()) s = input() i,p=0,1 ans = '' while i<(n-1): if p%2 == 1: if s[i] != s[i+1]: ans = ans + s[i] p += 1 else: ans = ans + s[i] p += 1 i += 1 if len(ans)%2 == 1: ans += s[-1] print(len(s)-len(ans)) print(ans) ```
1184_C2. Heidi and the Turing Test (Medium)
The Cybermen solved that first test much quicker than the Daleks. Luckily for us, the Daleks were angry (shocking!) and they destroyed some of the Cybermen. After the fighting stopped, Heidi gave them another task to waste their time on. There are n points on a plane. Given a radius r, find the maximum number of poin...
```python import sys NORM = 2000000 LIMIT = NORM * 2 + 1 class segmentTree: def __init__(self, n): self.n = n self.t = [0] * (n * 2) self.lazy = [0] * n def apply(self, p, value): self.t[p] += value if p < self.n: self.lazy[p] += value def build(self, p): while p > 1: p >>= 1 self.t[p] = m...
1202_E. You Are Given Some Strings...
You are given a string t and n strings s_1, s_2, ..., s_n. All strings consist of lowercase Latin letters. Let f(t, s) be the number of occurences of string s in string t. For example, f('aaabacaa', 'aa') = 3, and f('ababa', 'aba') = 2. Calculate the value of ∑_{i=1}^{n} ∑_{j=1}^{n} f(t, s_i + s_j), where s + t is th...
```python class Node(object): def __init__(self): super(Node, self).__init__() self.next = [-1] * 26 self.trans = [] self.matches = 0 self.leaf = 0 self.link = 0 class AhoCorasick(object): def __init__(self): super(AhoCorasick, self).__init__() se...
121_A. Lucky Sum
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what i...
```python n = (input()).split() l = int(n[0]) r = int(n[1]) a = [] x = [] a.append([]) a[0].append('4') a[0].append('7') for i in range(1,10): a.append([]) for j in a[i-1]: a[i].append('4'+j) a[i].append('7'+j) for j in a[i]: x.append(int(j)) x.append(4) x.append(7) x.sort...
1244_E. Minimizing Difference
You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perfor...
```python g, f = map(int, input().split()); a = sorted(map(int, input().split())) l,j =0,g-1; b= False while(j-l > 0 and f > 0): x = (a[l+1]-a[l])*(l+1)+(a[j]-a[j-1])*(g-j) if x>=f: ans = max(a[j]-a[l]-f//(l+1),0);print(ans);b = True f-=x;l+=1;j-=1 if(b==False): print(0) ```
1264_C. Beautiful Mirrors with queries
Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint ...
```python import sys input = sys.stdin.readline mod = 998244353 #出力の制限 #互いに素なa,bについて、a*x+b*y=1の一つの解 def extgcd(a,b): r = [1,0,a] w = [0,1,b] while w[2]!=1: q = r[2]//w[2] r2 = w w2 = [r[0]-q*w[0],r[1]-q*w[1],r[2]-q*w[2]] r = r2 w = w2 #[x,y] return [w[0],w[1]...
1285_E. Delete a Segment
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the...
```python import io import os from collections import Counter, defaultdict, deque # From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self....
1329_B. Dreamoon Likes Sequences
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as foll...
```python #------------------------------warmup---------------------------- 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...
1349_B. Orac and Medians
Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to th...
```python for _ in range(int(input())): n,k=map(int,input().split()) ar=list(map(int,input().split())) flag=False for i in range(1,n): if(ar[i]>=k and ar[i-1]>=k): flag=True break if(ar[i]>=k and ar[i-2]>=k and i>=2): flag=True break if...
1369_F. BareLee
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determine...
```python def f(s,e): if e%2: return 1-s%2 elif s*2>e: return s%2 else: return g(s,e//2) def g(s,e): if 2*s>e: return 1 else: return f(s,e//2) a=[tuple(map(int,input().split())) for i in range(int(input()))] b=1 for i in a: b1=g(*i)|(f(*i)<<1) b=b1^3 if b==2 else b1 if b==0: print('0 0') exit(0...
1391_E. Pairs of Pairs
You have a simple and connected undirected graph consisting of n nodes and m edges. Consider any way to pair some subset of these n nodes such that no node is present in more than one pair. This pairing is valid if for every pair of pairs, the induced subgraph containing all 4 nodes, two from each pair, has at most ...
```python # Fast IO (only use in integer input) import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline t = int(input()) for _ in range(t): n,m = map(int,input().split()) connectionList = [] for _ in range(n): connectionList.append([]) for _ in range(m): u,v = map(int,in...
1416_B. Make Them Equal
You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array s...
```python t = int(input()) ns = [] for i in range(t): n = int(input()) arr = list(map(int, input().split())) ans = [] sm = sum(arr) if sm % n != 0: ans = -1 else: avg = sm // n for idx, el in enumerate(arr): if idx == 0: continue ...
1433_A. Boring Apartments
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive. Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on. Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone...
```python for x in range(int(input())): a=input() s=(int(a[0])-1)*10 t= len(a) s+=t*(t+1)//2 print(s) ```
1480_B. The Great Hero
The great hero guards the country where Homer lives. The hero has attack power A and initial health value B. There are n monsters in front of the hero. The i-th monster has attack power a_i and initial health value b_i. The hero or a monster is said to be living, if his or its health value is positive (greater than o...
```python import math for t in range(int(input())): a,b,n=map(int,input().split()) attack=list(map(int,input().split())) health=list(map(int,input().split())) val=[] for i in range(n): val+=[[attack[i],health[i]]] val.sort() poss=True for i in range(n): times=math.ceil(va...
1508_A. Binary Literature
A bitstring is a string that contains only the characters 0 and 1. Koyomi Kanou is working hard towards her dream of becoming a writer. To practice, she decided to participate in the Binary Novel Writing Contest. The writing prompt for the contest consists of three bitstrings of length 2n. A valid novel for the contes...
```python import itertools def solve(a, b): if a.count("1") * 2 >= len(a) and b.count("1") * 2 >= len(b): ch = "1" other = "0" else: ch = "0" other = "1" res = [] i = 0 j = 0 ilast = -1 jlast = -1 while i < len(a) and j < len(b): while i < len(a) ...
1534_B. Histogram Ugliness
Little Dormi received a histogram with n bars of height a_1, a_2, …, a_n for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking. To modify the histogram, Little Dormi is able to perform the following operation an arbitrar...
```python t = int(input()) for _ in range(t): n = int(input()) res = 0 a = map(int, input().split()) p = 0 pp = 0 ugly = 0 for k in a: if k > p: ugly += k - p pp = p else: down = max(0, min(p - k, p - pp)) ugly += p - k - down ...
161_D. Distance in Tree
A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactl...
```python ###pyrival template for fast IO import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file....
180_F. Mathematical Analysis Rocks!
Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≤ i ≤ n) has a best friend p[i] (1 ≤ p[i] ≤ n). In fact, each student is a best frie...
```python n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) d={} for i in range(n): d[a[i]]=b[i] for i in range(1,n+1): print(d[i],end=" ") print() ```
204_B. Little Elephant and Cards
The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks...
```python from collections import defaultdict import math n=int(input()) d=defaultdict(int) o=defaultdict(int) for i in range(n): x,y=map(int,input().split()) o[x]+=1 d[x]+=1 if y!=x: d[y]+=1 mi=10**5+1 for i in d: ## print(d[i]) if d[i]>=math.ceil(n/2): mi=min(mi,max(math.ceil(n/...
229_A. Shifts
You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the valu...
```python import sys n, m = map(int, input().split()) mp = ['' for i in range(n)] f = [[0 for j in range(m)] for i in range(n)] for i in range(n): mp[i] = input() if mp[i].find('1') == -1: print(-1) sys.exit() tmp = mp[i][::-1].find('1') + 1 for j in range(m): if mp[i][j] == '1': f[i][j] = 0 else: f[i...
252_D. Playing with Permutations
Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n. A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n), all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha...
```python def Solve(x,L): if(x==k[0]): return L==S if((x,tuple(L)) in Mem): return False if(L==S): return False E=[] for i in range(len(L)): E.append(L[Q[i]-1]) if(Solve(x+1,E)): return True E=[0]*len(L) for i in range(len(L)): E[Q[i]-...
2_B. The least round way
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together a...
```python # Legends Always Come Up with Solution # Author: Manvir Singh import os from io import BytesIO, IOBase import sys from collections import defaultdict, deque, Counter from math import sqrt, pi, ceil, log, inf, gcd, floor from itertools import combinations, permutations from bisect import * from fractions impo...
325_B. Stadium and Games
Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stage...
```python import sys def isqrt(n): l = -1 h = n while l + 1 < h: m = (l + h) // 2 if m * m <= n: l = m else: h = m return l with sys.stdin as fin, sys.stdout as fout: n = int(next(fin)) ans = [] for i in range(64 + 1): a = 2 ** i -...
371_D. Vessels
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the wa...
```python n=int(input()) a=list(map(int,input().split())) vessels=[] ans=[] index=[] for i in range(n): vessels.append([0,a[i]]) index.append(i+1) m=int(input()) for i in range(m): a=input() if a[0]=='1': a,p,x=list(map(int,a.split())) p-=1 tt=set() while p<n and x>0:...
393_A. Nineteen
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string. For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) tw...
```python a=input() n=int(0) ii=int(0) t=int(0) e=int(0) for i in range(len(a)): if a[i] == "n": n+=1 if a[i] == "i": ii+=1 if a[i] == "e": e+=1 if a[i] == "t": t+=1 if n >3: n=int(((n-3)/2))+1 else: n=int(n/3) print(min(n,int(e/3),ii,t)) ```
416_B. Art Union
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1...
```python m,n=map(int,input().split()) a=[] for i in range(m): p=[int(j) for j in input().split()] a.append(p) for j in range(1,m): a[j][0]+=a[j-1][0] for i in range(1,n): a[0][i]+=a[0][i-1] #print(a) for j in range(1,m): a[j][i]+=max(a[j-1][i],a[j][i-1]) #print(a) for i in...
465_A. inc ARG
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in ...
```python n = int(input()) s = input() swaps = 0 k = 0 for i in range(len(s)): if int(s[i]) == 0: k += 1 break k += 1 print(k) ```
566_A. Matching Names
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching ps...
```python import sys class Node: def __init__(self, d): global nodes self.ch = {} self.a = [[], []] self.d = d nodes += [self] nodes = [] pairs = [] res = 0 N = int(sys.stdin.readline()) _input = sys.stdin.readlines() _input = [s[:-1] for s in _input] A = [_input[:N], _inp...
609_D. Gadgets for dollars and pounds
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing. Nura can buy gadgets for n days. For each day you know the exchange rates of dol...
```python from sys import stdin, stdout def ints(): return [int(x) for x in stdin.readline().split()] n, m, k, s = ints() a = ints() b = ints() d_gad = []; p_gad = []; for i in range(m): t, c = ints() if t == 1: d_gad.append([c, i + 1]) else: p_gad.append([c, i + 1]) d_gad.sort() p_gad.sort() mn_dol =...
630_C. Lucky Numbers
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers. Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits. Input The on...
```python x=input() print((2**(int(x)+1))-2) ```
656_G. You're a Professional
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system. You are given user's friends' opinions about a list of items. You are also given a threshold T — the minimal number of "likes" necessary for an item to be r...
```python from functools import reduce f,o,t = map(int, input().split(' ')) res = [0 for i in range(o)] for i in range(f): s = input() for j in range(o): res[j]+=(s[j]=='Y') print(reduce(lambda x,y: x+(y>=t), res,0)) #kitten ```
680_B. Bear and Finding Criminals
There are n cities in Bearland, numbered 1 through n. Cities are arranged in one long row. The distance between cities i and j is equal to |i - j|. Limak is a police officer. He lives in a city a. His job is to catch criminals. It's hard because he doesn't know in which cities criminals are. Though, he knows that ther...
```python from sys import stdin, stdout cnt, number = map(int, stdin.readline().split()) labels = list(map(int, stdin.readline().split())) if labels[number - 1]: ans = 1 else: ans = 0 for i in range(1, min(cnt - number, number - 1) + 1): if labels[number - 1 + i] and labels[number - 1 - i]: ans...
703_A. Mishka and Game
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds n is defined. I...
```python n = int(input()) k = 0 l = 0 for i in range(n): m,c = map(int,input().split()) if m > c: k +=1 elif c > m: l +=1 if k > l: print("Mishka") elif l > k: print("Chris") else: print("Friendship is magic!^^") ```
725_A. Jumping Ball
In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it...
```python n=int(input()) s=input() k=s[0] res=i=0 while i<=n-1 and s[i]==k: i+=1 else: if k=='<': res+=i k='>' i=n-1 while i>=0 and s[i]==k: i-=1 else: res+=n-i-1 print(res) ```
747_A. Display Size
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly n pixels. Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels a and the number of columns of pixels b, so that: * there are exactly n pixels on the d...
```python import math num = int(input()) s = math.sqrt(num) s = int(float(s)) for i in range (s, 0, -1) : if num % i == 0 : print(i) print(int(float(num / i))) break ```
76_D. Plus and xor
Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions ...
```python a, b = int(input()), int(input()) x, y = (a - b) >> 1, (a - b) // 2 + b if a < b or (a + b) & 1 or x & (a - x) != x: print("-1") else: print(x, y) ```
794_A. Bank Robbery
A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes. Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe fro...
```python # Method 1a: Using a list comprehension # a, b, c, d = [int(x) for x in input().split()] # print(a*b*c*d) # Method 1b: Using the map function # a, b, c, d = map(int, input().split()) # print(a*b*c*d) # Method 2a: List comprehension with stdin and stdout # from sys import stdin, stdout # a, b, c, d = [int(x...
860_A. Did you mean...
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them. Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are thr...
```python s = input() n = len(s) if n==1 or n==2: print(s) else: a = ['a','e','i','o','u'] q,w = '','' if s[0] not in a: q = s[0] if s[1] not in a: w = s[1] res = s[:2] for i in range(2,n): e = s[i] if e not in a: if q!='' and w!='': ...
886_F. Symmetric Projections
You are given a set of n points on the plane. A line containing the origin is called good, if projection of the given set to this line forms a symmetric multiset of points. Find the total number of good lines. Multiset is a set where equal elements are allowed. Multiset is called symmetric, if there is a point P on t...
```python from fractions import Fraction import time class Point: def __init__(self, x, y): self.x = x self.y = y def to_tuple(self): return (self.x, self.y) def __repr__(self): return "Point({}, {})".format(self.x, self.y) def __eq__(self, other): return sel...
909_F. AND-permutations
Given an integer N, find two permutations: 1. Permutation p of numbers from 1 to N such that pi ≠ i and pi & i = 0 for all i = 1, 2, ..., N. 2. Permutation q of numbers from 1 to N such that qi ≠ i and qi & i ≠ 0 for all i = 1, 2, ..., N. & is the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_...
```python def test(x, i): i = list(i) ok = True for j in range(x): if (i[j] == j+1 or (i[j]&(j+1) != 0)): ok = False if ok: print(i) def comp(n): return 2**len(bin(n)[2:])-1-n n = int(input()) nn = n if (n%2 == 0): x = [] while (n != 0): #add n to comp(n) to the front of x for i in range(comp(n), n+...
931_C. Laboratory Work
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error. Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each...
```python R = lambda : map(int, input().split()) n = int(input()) v = list(R()) mn = min(v); mx = max(v); from collections import Counter c = Counter(v) if mn==mx or mn==mx-1: print(len(v)); print(" ".join(map(str,v))); exit(); if mn==mx-2 and len(c)==2: c[mn+1]=0 k = sorted(list(c.keys())) ck0 = c[k[0]]; ck...
958_F1. Lightsabers (easy)
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of th...
```python import sys n, m = map(int, input().split()) a = list(map(int, input().split())) k = list(map(int, input().split())) c = 0 s = sum(k) if m==1: if a.count(1)==k[0] or k[0] in a: print("YES") else: print("NO") sys.exit(0) for i in range(n): if i+s-1<=n-1: k0 = [0]*m for j in a[i:i+s]: k0[...
985_C. Liebig's Barrels
You have m = n·k wooden staves. The i-th stave has length ai. You have to assemble n barrels consisting of k staves each, you can use any k staves to construct a barrel. Each stave must belong to exactly one barrel. Let volume vj of barrel j be equal to the length of the minimal stave in it. <image> You want to asse...
```python n, k, l = map(int, input().split()) sl = [int(i) for i in input().split()] vx = min(sl) vy = vx + l fl = sorted([i for i in sl if vx <= i <= vy]) if len(fl) < n: print('0') else: ans = 0 i = 0 um = n while um > 0: ans += fl[i] um -= 1 i = min(i + k, len(fl) - um) ...
p02576 AtCoder Beginner Contest 176 - Takoyaki
Takahashi loves takoyaki - a ball-shaped snack. With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make. How long does it take to make N takoyaki? Constraints * 1 \leq N,X,T \leq 1000 * All values in input are integers. Input Input i...
```python n,x,t=map(int,input().split()) print(abs((-n//x))*t) ```