name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
645_D. Robot Rapping Results Report
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots o...
```python from collections import defaultdict class RobotRapping(): def __init__(self, n, m, battles): self.n, self.m = n, m self.battles = battles def generate_graph(self, k): edge_map = defaultdict(list) rev_map = defaultdict(list) for i in range(k): edge...
672_B. Different is Good
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some num...
```python n = int(input()) s = input() s = set(s) if n<27: print(n - len(s)) else: print('-1') ```
697_D. Puzzles
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city h...
```python import sys input = sys.stdin.readline n = int(input()) par = [-1] + [int(i) - 1 for i in input().split()] child = [[] for i in range(n)] for i in range(1, n): child[par[i]].append(i) size = [1] * n def dfs(): stack = [0] visit = [False] * n while stack: u = stack[-1] if not v...
73_B. Need For Brake
Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game! n racers take part in the championship, which consists of a number of races. After each race racers are a...
```python class Racer: def __init__(self, name, points): self.name = name self.points = points def __str__(self): return '%s %d' % (self.name, self.points) n = int(input()) best = n * [ None ] worst = n * [ None ] for i in range(n): name, points = input().split() points = int(po...
808_A. Lucky Year
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not. You are given current year in Berland. Your task is to find how long...
```python import math a = int(input()) #print(math.log(a)) b = int(10 ** ((math.log(a+1) // math.log(10)))) #print(b) total = b while total <= a: total += b print(str(total-a)) ```
832_B. Petya and Exam
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one.. There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is kno...
```python a=input() s=input() k=int(input()) def qw(c): t=True w=-1 if len(s)>len(c)+1: t=False try: for j in range(len(s)): w+=1 if s[j]=='?': if c[w] not in a: t=False elif s[j]=='*': b=len(c)-len(s)+1 for e in c[j:j+b]: if e in a: t=False w+=b-1 else: if s[j]!=c[w]: ...
877_D. Olya and Energy Drinks
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks. Formally, her room can be represented as a field of n × m cells, each cell of which is empty or littered with cans. Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses...
```python from collections import deque n, m, k = map(int, input().split()) INF = float("inf") d = [[INF] * m for _ in range(n)] t = [[] for i in range(n)] for i in range(n): a = list(input()) t[i] = a sx, sy, gx, gy = map(int, input().split()) sx, sy, gx, gy = sx - 1, sy - 1, gx - 1, gy - 1 def bfs(): q...
900_E. Maximum Questions
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions. Suddenly in the morning, Vasya found that somebody spoiled his string...
```python n = int(input()); s = input(); m = int(input()) a = [0]*(n+2); b = [0]*(n+2); q = [0]*(n+1); dp = [(0, 0)]*(n+2) for i in range(0, n): b[i] = b[i-2]+(s[i] == 'b') a[i] = a[i-2]+(s[i] == 'a') q[i] = q[i-1]+(s[i] == '?') for i in range(n-m, -1, -1): dp[i] = dp[i+1] i_b = 1 if m%2 == 1 else 2 i_a...
923_C. Perfect Security
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the m...
```python def add(x): global tree now = 0 tree[now][2] += 1 for i in range(29, -1, -1): bit = (x>>i)&1 if tree[now][bit]==0: tree[now][bit]=len(tree) tree.append([0, 0, 0]) now = tree[now][bit] tree[now][2] += 1 def find_min(x): global tree ...
979_A. Pizza, Pizza, Pizza!!!
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems. Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to cele...
```python n = int(input()) + 1 if n == 1: print(0) exit() if n % 2 == 0: print(n //2) else: print(n) ```
999_B. Reversing Encryption
A string s of length n can be encrypted by the following algorithm: * iterate over all divisors of n in decreasing order (i.e. from n to 1), * for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d). For example, the above algorithm applied t...
```python l = int(input()) s = list(input()) for i in range(2, l + 1): if l % i > 0: continue s[:i] = s[i - 1::-1] print(''.join(s)) ```
p02664 NOMURA Programming Competition 2020 - Postdocs
For a string S consisting of the uppercase English letters `P` and `D`, let the doctoral and postdoctoral quotient of S be the total number of occurrences of `D` and `PD` in S as contiguous substrings. For example, if S = `PPDDP`, it contains two occurrences of `D` and one occurrence of `PD` as contiguous substrings, s...
```python # B - Postdocs t = input() print(t.replace('?', 'D')) ```
p02793 AtCoder Beginner Contest 152 - Flatten
Given are N positive integers A_1,...,A_N. Consider positive integers B_1, ..., B_N that satisfy the following condition. Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds. Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N. Since the answer can be enormous, print t...
```python N = int(input()) A = [int(a) for a in input().split()] import fractions mod = 10**9+7 t = 1 for a in A: t = a*t//fractions.gcd(a, t) ans = 0 for a in A: ans += t//a print(ans%mod) ```
p02929 Japanese Student Championship 2019 Qualification - Cell Inversion
There are 2N squares arranged from left to right. You are given a string of length 2N representing the color of each of the squares. The color of the i-th square from the left is black if the i-th character of S is `B`, and white if that character is `W`. You will perform the following operation exactly N times: choo...
```python from math import factorial mod = 10 ** 9 + 7 n = int(input()) inp = list(input()) if inp[0] == 'W' or inp[-1] == 'W': print(0) exit(0) arr = ['L'] swap_dict = {'L': 'R', 'R': 'L'} for i in range(1, 2 * n): arr.append(arr[i - 1] if inp[i] != inp[i - 1] else swap_dict[arr[i - 1]]) if arr.count('L') ...
p03065 Tenka1 Programmer Contest 2019 - Polynomial Divisors
You are given a polynomial of degree N with integer coefficients: f(x)=a_Nx^N+a_{N-1}x^{N-1}+...+a_0. Find all prime numbers p that divide f(x) for every integer x. Constraints * 0 \leq N \leq 10^4 * |a_i| \leq 10^9(0\leq i\leq N) * a_N \neq 0 * All values in input are integers. Input Input is given from Standard I...
```python def factors(z): ret = [] for i in range(2, int(z**(1/2))+1): if z%i == 0: ret.append(i) while z%i == 0: z //= i if z != 1: ret.append(z) return ret def eratosthenes(N): if N == 0: return [] from collections import deque ...
p03208 AtCoder Beginner Contest 115 - Christmas Eve
In some other world, today is Christmas Eve. There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters. He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees shoul...
```python N, K = map(int, input().split()) H = [int(input()) for n in range(N)] H.sort() R = [H[i+K-1] - H[i] for i in range(N+1-K)] print(min(R)) ```
p03357 AtCoder Regular Contest 097 - Sorted and Sorted
There are 2N balls, N white and N black, arranged in a row. The integers from 1 through N are written on the white balls, one on each ball, and they are also written on the black balls, one on each ball. The integer written on the i-th ball from the left (1 ≤ i ≤ 2N) is a_i, and the color of this ball is represented by...
```python import sys input = sys.stdin.readline n = int(input()) INF = 10 ** 9 info = [list(input().split()) for i in range(2 * n)] ind = {} for i in range(2 * n): if info[i][0] == "B": info[i] = (0, int(info[i][1])) else: info[i] = (1, int(info[i][1])) ind[info[i][0] * 10 ** 5 + info[i][...
p03515 CODE FESTIVAL 2017 Elimination Tournament Round 3 (Parallel) - Black Cats Deployment
Snuke Festival 2017 will be held in a tree with N vertices numbered 1,2, ...,N. The i-th edge connects Vertex a_i and b_i, and has joyfulness c_i. The staff is Snuke and N-1 black cats. Snuke will set up the headquarters in some vertex, and from there he will deploy a cat to each of the other N-1 vertices. For each v...
```python import sys from operator import itemgetter read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines class UnionFind: def __init__(self, N): self.root = list(range(N + 1)) def __getitem__(self, x): root = self.root while root[x]...
p03833 AtCoder Regular Contest 067 - Yakiniku Restaurants
There are N barbecue restaurants along a street. The restaurants are numbered 1 through N from west to east, and the distance between restaurant i and restaurant i+1 is A_i. Joisino has M tickets, numbered 1 through M. Every barbecue restaurant offers barbecue meals in exchange for these tickets. Restaurant i offers a...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines import itertools INF=10**10 N,M = map(int,readline().split()) A = [0,0]+list(map(int,readline().split())) B = [[INF]*M]+[list(map(int,line.split())) for line in readlines()] for i in range(1...
p03998 AtCoder Beginner Contest 045 - Card Game for Three (ABC Edit)
Alice, Bob and Charlie are playing Card Game for Three, as below: * At first, each of the three players has a deck consisting of some number of cards. Each card has a letter `a`, `b` or `c` written on it. The orders of the cards in the decks cannot be rearranged. * The players take turns. Alice goes first. * If the cu...
```python hands = {char:list(input()) for char in 'abc'} next_hand = 'a' while hands[next_hand]: next_hand = hands[next_hand].pop(0) print(next_hand.upper()) ```
p00086 Patrol
In 1862, the lord of Aizu was ordered to serve as a guardian of Kyoto. The Kyoto Shugoshoku is an important role to protect Kyoto at the end of the Edo period when security has deteriorated. You have to patrol the city by sharing it with the shogunate and other clan. However, when it came time to decide the sharing rou...
```python import sys def is_half_euler_graph(node_list): for node in node_list: isBool = True for dic_key, dic_value in node.items(): if dic_key != 1 and dic_key != 2: if dic_value % 2 != 0: isBool = False break else : ...
p00218 Dividing Students
At Aizu Shingakujuku, students are divided into classes by conducting a proficiency test when they enter the cram school. The test consists of three subjects: Mathematics, English, and Japanese, and students are divided into A, B, and C classes. The level of class A is the highest and then decreases in order. The clas...
```python while True: #繰り返し回数を入力し0であった場合はbreakする num = int(input()) if num == 0: break else: for _ in range(num): a,b,c = map(int,input().split()) #100 点の科目があるまたは数学と英語の平均点が 90 点以上または3 科目の平均点が 80 点以上の場合"A"を出力する if a == 100 or b == 100 or c ...
p00378 Heat Strokes
We have had record hot temperatures this summer. To avoid heat stroke, you decided to buy a quantity of drinking water at the nearby supermarket. Two types of bottled water, 1 and 0.5 liter, are on sale at respective prices there. You have a definite quantity in your mind, but are willing to buy a quantity larger than ...
```python a, b, x = map(int, input().split()) if b * 2 <= a: ans = b * (x // 500 + bool(x % 500)) else: ans = a * (x // 1000) + min(b * ((x % 1000) // 500 + bool((x % 1000) % 500)), a * bool(x % 1000)) print(ans) ```
p00596 Dominoes Arrangement
[0, 0] [0, 1] [1, 1] [0, 2] [1, 2] [2, 2] [0, 3] [1, 3] [2, 3] [3, 3] [0, 4] [1, 4] [2, 4] [3, 4] [4, 4] [0, 5] [1, 5] [2, 5] [3, 5] [4, 5] [5, 5] [0, 6] [1, 6] [2, 6] [3, 6] [4, 6] [5, 6] [6, 6] Consider the standard set of 28 western dominoes as shown in the above figure. Given a subset of the ...
```python import sys def subset(line): l = line.strip().split(" ") a = list(map(int, l)) xy = list(map(lambda x: [x // 10, x % 10], a)) dominos = [[2 if [x, y] in xy and x == y else \ 1 if [x, y] in xy else \ 1 if [y, x] in xy else 0 \ for x in range(0, 7...
p01135 Poor Mail Forwarding
The postal system in the area where Masa lives has changed a bit. In this area, each post office is numbered consecutively from 1 to a different number, and mail delivered to a post office is intended from that post office via several post offices. Delivered to the post office. Mail "forwarding" is only done between sp...
```python def solve(): from sys import stdin f_i = stdin ans = '' while True: n, m = map(int, f_i.readline().split()) if n == 0: break # prep for warshall-floyd algorithm inf = 10000 * 31 + 1 dist = [[inf] * n for i in range(n)] ...
p01593 Earn Big
Problem C: Earn Big A group of N people is trying to challenge the following game to earn big money. First, N participants are isolated from each other. From this point, they are not allowed to contact each other, or to leave any information for other participants. The game organizer leads each participant, one by on...
```python dp=[1]+[0]*1000 n,m=map(int,input().split()) for i in range(n): j=1 while i+j<=n and j<=m:dp[i+j]+=dp[i]/(n-i);j+=1 print('%.10f'%dp[n]) ```
p01750 Hyperrectangle
Sunuke received a d-dimensional hypercube with a side length of l1 × ... × ld as a birthday present. Sunuke placed this rectangular parallelepiped so that the range of the i-th coordinate was 0 or more and li or less, and ate the part that satisfied x1 + ... + xd ≤ s. However, xi represents the i-th coordinate. If the ...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): MOD = 10**9 + 7 D = int(readline()) L = [int(readline()) for i in range(D)] S = int(readline()) dp = [0]*(S+1) dp[S] = 1 for i in range(D): l = L[i] for i in range(l, S+1): dp...
p02169 Count Words
Problem There are $ M $ type characters. Use them to create a string of length $ N $. How many strings are used that have $ K $ or more? Find too much divided by $ 998244353 $. Here, the difference between two strings of length $ N $ is defined as follows. * If the two strings are $ S = S_1S_2 \ ldots S_N $, $ T = T...
```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(...
p02310 Tangent to a Circle
Find the tangent lines between a point $p$ and a circle $c$. Constraints * $-1,000 \leq px, py, cx, cy \leq 1,000$ * $1 \leq r \leq 1,000$ * Distance between $p$ and the center of $c$ is greater than the radius of $c$. Input The input is given in the following format. $px \; py$ $cx \; cy \; r$ $px$ and $py$ repr...
```python import cmath import itertools import math import os import sys from collections import defaultdict 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 PI = cmath.pi TAU = cmath.pi * 2 EPS = 1e-10 ...
p02458 Multi-Set
For a set $S$ of integers, perform a sequence of the following operations. Note that multiple elements can have equivalent values in $S$. * insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation. * find($x$): Report the number of $x$ in $S$. * delete($x$): Delete all $x$ from $S$. ...
```python import bisect import collections def main6(): values = collections.defaultdict(int) element_count = 0 q = int(input()) for _ in range(q): com, *para = map(int, input().split()) if com == 0: values[para[0]] += 1 element_count += 1 print...
1017_D. The Wu
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace. This "personal treasure" is a multis...
```python from sys import stdin def main(): n, m, q = map(int, input().split()) c = sz = 1 << n costs, cnt = [0] * sz, [0] * sz for w in map(int, input().split()): c //= 2 for i in range(c, sz, c * 2): for j in range(i, i + c): costs[j] += w for i, c in ...
1041_A. Heist
There was an electronic store heist last night. All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ...
```python def heist(n,a): return max(a)-min(a)-n+1 n=int(input()) a=list(map(int,input().split())) print(heist(n,a)) ```
1105_C. Ayoub and Lost Array
Ayoub had an array a of integers of size n and this array had two interesting properties: * All the integers in the array were between l and r (inclusive). * The sum of all the elements was divisible by 3. Unfortunately, Ayoub has lost his array, but he remembers the size of the array n and the numbers l and...
```python MOD = 10**9 + 7 n,l,r = map(int,input().split()) dp = [[ 0,0,0]for i in range(n+1)] # In condition l <= x <= r , mod 0,1,2 number count(define a,b,c) a = r//3 - (l - 1)//3 b = (r+1)//3 - (l - 1 + 1)//3 c = (r+2)//3 - (l - 1 + 2)//3 #example #l = 2 , r = 10 #a = 10//3 - 1//3 = 3 - 0 = 3 (3,6,9) #b = 11//...
1153_B. Serval and Toy Bricks
Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny. He has a special interest to create difficult problems for others to solve. This time, with many 1 × 1 × 1 toy bricks, he builds up a 3-dimensional object. We can describe ...
```python import sys, os, re, datetime from collections import * from bisect import * def mat(v, *dims): def submat(i): if i == len(dims)-1: return [v for _ in range(dims[-1])] return [submat(i+1) for _ in range(dims[i])] return submat(0) __cin__ = None def cin(): global __cin__ if __cin...
1175_A. From Hero to Zero
You are given an integer n and an integer k. In one step you can do one of the following moves: * decrease n by 1; * divide n by k if n is divisible by k. For example, if n = 27 and k = 3 you can do the following steps: 27 → 26 → 25 → 24 → 8 → 7 → 6 → 2 → 1 → 0. You are asked to calculate the minimum numbe...
```python import math t=int(input()) for _ in range(t): n,k=map(int,input().split()) count=0 a,b=int(n//k),int(n%k) while n>0: if k>n: a,b=0,int(n%k) else: a,b=math.floor(n//k),int(n%k) n=a if a==0: count+=b else: count+=(b+1) print(count) ```
1231_C. Increasing Matrix
In this problem, a n × m rectangular matrix a is called increasing if, for each row of i, when go from left to right, the values strictly increase (that is, a_{i,1}<a_{i,2}<...<a_{i,m}) and for each column j, when go from top to bottom, the values strictly increase (that is, a_{1,j}<a_{2,j}<...<a_{n,j}). In a given ma...
```python def main(): n, m = map(int, input().split()) l = list(list(map(int, input().split()))[::-1] for _ in range(n))[::-1] for r0, r1 in zip(l, l[1:-1]): for i, a in enumerate(r1[1:-1], 1): if not a: r1[i] = min(r1[i - 1], r0[i]) - 1 print(sum(map(sum, l)) if all(...
1272_E. Nearest Opposite Parity
You are given an array a consisting of n integers. In one move, you can jump from the position i to the position i - a_i (if 1 ≤ i - a_i) or to the position i + a_i (if i + a_i ≤ n). For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that a_j has the ...
```python input() n=map(int,input().split()) n=list(n) ans=len(n)*[-1] a=[] go=[[] for _ in range(len(n))] for i,x in enumerate(n): for y in (x,-x): y+=i if y>=0 and y<len(n): if x%2!=n[y]%2: ans[i]=1 a.append(i) else: go[y].ap...
1295_F. Good Contest
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared n problems; and since the platform is very popular, 998244351 coder from all over the world is going to solve them. For each problem, the authors estimated the number of people who would solve it: fo...
```python import sys from itertools import chain readline = sys.stdin.readline MOD = 998244353 def compress(L): L2 = list(set(L)) L2.sort() C = {v : k for k, v in enumerate(L2)} return L2, C N = int(readline()) LR = [tuple(map(int, readline().split())) for _ in range(N)] LR = [(a-1, b) for a, b in LR...
1338_B. Edge Weight Assignment
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold: * For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_...
```python import sys # try: # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') # except: # pass input = sys.stdin.readline def DFS(i): visited = {i:True} stack = [(i,0)] while len(stack)!=0: tail,depth = stack.pop(-1) flag = True for each in neigh[tail]: if each not in visited:...
1360_A. Minimal Square
Find the minimum area of a square land on which you can place two identical rectangular a × b houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, * You are given two identical rectangles with side lengths a and b (1 ≤ a, b ≤ 100) — positive integers (you are given ...
```python num=int(input("")) i=0 while i<num: a,b=(input("")).split() minimum=min(int(a),int(b)) maximum=max(int(a),int(b)) if minimum*2<maximum: print(maximum**2) else: print((minimum*2)**2) i+=1 ```
1380_B. Universal Solution
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string s = s_1 s_2 ... s_{n} of length n where each letter is either R, S or P. While initializing, the bot is choosing a starting index pos (1 ≤ pos ≤ n), and then it can play any numbe...
```python dic={ 'R':'P', 'P':'S', 'S':'R' } t=int(input()) for _ in range(t): S=input() n=len(S) r,p,s=[0,0,0] for i in range(len(S)): if S[i]=='R': r=r+1 elif S[i]=='P': p=p+1 else: s=s+1 m=max(r,p,s) if r==m: print...
1400_B. RPG Protagonist
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course. You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units. ...
```python # cook your dish here # cook your dish here from sys import stdin,stdout from collections import Counter from itertools import permutations import bisect import math I=lambda: map(int,stdin.readline().split()) I1=lambda: stdin.readline() for _ in range(int(I1())): p,f=I() cs,cw=I() s,w=I() if...
1424_B. Valuable Paper
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper. ...
```python import os import sys from io import BytesIO, IOBase from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in fil...
1469_D. Ceil Divisions
You have an array a_1, a_2, ..., a_n where a_i = i. In one step, you can choose two indices x and y (x ≠ y) and set a_x = \left⌈ (a_x)/(a_y) \right⌉ (ceiling function). Your goal is to make array a consist of n - 1 ones and 1 two in no more than n + 5 steps. Note that you don't have to minimize the number of steps. ...
```python import math def solution() : for tc in range(int(input())) : n = int(input()) ls = [i for i in range(1, n+1)] ans = [] for i in range(n-2, 0, -1) : while math.ceil(ls[n-1] / ls[i]) >= ls[i] : ans.append([n, i+1]) ls[n-1] = math...
1517_E. Group Photo
In the 2050 Conference, some people from the competitive programming community meet together and are going to take a photo. The n people form a line. They are numbered from 1 to n from left to right. Each of them either holds a cardboard with the letter 'C' or a cardboard with the letter 'P'. Let C=\\{c_1,c_2,...,c_m\...
```python import sys,io,os try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline except:Z=lambda:sys.stdin.readline().encode() Y=lambda:map(int,Z().split()) from bisect import bisect M=998244353 def add(a,b): v=a+b if v>=M:v-=M if v<0:v+=M return v def sol(n,a,disp=0): if n<2:return 1 if n<3...
172_C. Bus
There is a bus stop near the university. The lessons are over, and n students come to the stop. The i-th student will appear at the bus stop at time ti (all ti's are distinct). We shall assume that the stop is located on the coordinate axis Ox, at point x = 0, and the bus goes along the ray Ox, that is, towards the po...
```python from collections import defaultdict n, m = map(int, input().split()) r, p = [0] * n, defaultdict(list) i = d = 0 while i < n - m: for j in range(i, i + m): t, x = map(int, input().split()) p[x].append(j) d = max(t, d) y = sorted(p.keys()) for x in y: for j in p[x]: r[j]...
192_D. Demonstration
In the capital city of Berland, Bertown, demonstrations are against the recent election of the King of Berland. Berland opposition, led by Mr. Ovalny, believes that the elections were not fair enough and wants to organize a demonstration at one of the squares. Bertown has n squares, numbered from 1 to n, they are numb...
```python from sys import stdin, stdout n, k = map(int, stdin.readline().split()) value = int(stdin.readline()) prices = list(map(int, stdin.readline().split())) used = {} challengers = prices[:-1] for i in range(n - 1): challengers[i] = (challengers[i], i) challengers.sort(reverse = True) ind = challengers[k -...
216_D. Spider's Web
Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web. <image> There are n main threads going from the center of the web. All main threads are located in one plane and divide it into n equal infinite sectors. The sectors are in...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output....
265_B. Roadside Trees (Simplified Edition)
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts. Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following act...
```python n = int(input()) l = [] for _ in range(n): l.append(int(input())) t = len(l) current = 0 t+=l[0]-current current = l[0] for i in range(1,n): if current<=l[i]: t+=1+l[i]-current current = l[i] else: t += 1+current-l[i] current = l[i] print(t) ```
289_B. Polo the Penguin and Matrix
Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij. In one move the penguin can add or subtract number...
```python n,m,d=map(int,input().split()) x=[] y=[] for i in range(n): a=list(map(int,input().split())) y+=a x.append(a) y.sort() e=y[(0+n*m-1)//2] a=x[0][0]%d count=0 ans=0 for i in x: for j in range(len(i)): if(i[j]%d!=a): pass else: count+=1 ans+=(ma...
314_B. Sereja and Periods
Let's introduce the designation <image>, where x is a string, n is a positive integer and operation " + " is the string concatenation operation. For example, [abc, 2] = abcabc. We'll say that string s can be obtained from string t, if we can remove some characters from string t and obtain string s. For example, string...
```python b, p = map(int, input().split()) s1 = input() s2 = input() cnt = [0] * len(s2) nxt = [0] * len(s2) for i in range(len(s2)): pos = i for j in range(len(s1)): if s1[j] == s2[pos]: pos += 1 if pos == len(s2): cnt[i] += 1 pos = 0 ...
430_D. Working out
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column. Iahub starts with ...
```python n,m=map(int,input().split()) a=[] for i in range(n):a.append(list(map(int,input().split()))) dpa=[[[0,0] for i in range(m+2)] for i in range(n+2)] dpb=[[[0,0] for i in range(m+2)] for i in range(n+2)] ans=0 for i in range(1,n+1): for j in range(1,m+1): dpa[i][j][0]=max(dpa[i-1][j][0],dpa[i][j-1][0])+a[i-1]...
453_A. Little Pony and Expected Maximum
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game. The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, ...
```python def main(): m, n = map(int, input().split()) print(sum((i + 1) * (((i + 1) / m) ** n - (i / m) ** n) for i in range(m))) if __name__ == '__main__': main() ```
523_B. Mean Requests
In this problem you will have to deal with a real algorithm that is used in the VK social network. As in any other company that creates high-loaded websites, the VK developers have to deal with request statistics regularly. An important indicator reflecting the load of the site is the mean number of requests for a cer...
```python __author__ = 'ruckus' n, T, c = input().split() n = int(n) T = int(T) c = float(c) a = list(map(int, input().split())) m = int(input()) q = list(map(int, input().split())) res_a = 0 real = 0 maxi_q = max(q) q_n = 0 for i in range(q[-1]): res_a = (res_a + a[i] / T) / c real += a[i] if i >= T: ...
549_H. Degenerate Matrix
The determinant of a matrix 2 × 2 is defined as follows: <image> A matrix is called degenerate if its determinant is equal to zero. The norm ||A|| of a matrix A is defined as a maximum of absolute values of its elements. You are given a matrix <image>. Consider any degenerate matrix B such that norm ||A - B|| is m...
```python A,B,C,D=map(int,(input()+' '+input()).split());k=max(map(abs,[A+B+C+D,A+B-C-D,A-B+C-D,A-B-C+D]))+1e-9;print(abs(A*D-B*C)/k) ```
576_A. Vasya and Petya's Game
Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number. Petya can ask questions like: "Is the unknown number divisible by number y?". The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no ...
```python def input_ints(): return list(map(int, input().split())) def main(): n = int(input()) ans = [] for x in range(2, n + 1): s = set() xx = x for y in range(2, n + 1): while xx % y == 0: xx /= y s.add(y) if len(s) == 1: ...
598_E. Chocolate Bar
You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar. In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically...
```python d = [0] * 49011 def g(n, m, k): t = 1e9 for i in range(1, m // 2 + 1): for j in range(k + 1): t = min(t, f(n, m - i, k - j) + f(n, i, j)) return n * n + t def f(n, m, k): if n > m: n, m = m, n k = min(k, n * m - k) if k == 0: return 0 if k < 0: return 1e9 ...
61_C. Capture Valerian
It's now 260 AD. Shapur, being extremely smart, became the King of Persia. He is now called Shapur, His majesty King of kings of Iran and Aniran. Recently the Romans declared war on Persia. They dreamed to occupy Armenia. In the recent war, the Romans were badly defeated. Now their senior army general, Philip is captu...
```python n, m = input().split() b = input() if b.isdigit() and int(b) == 0: print(int(b)) elif n == m: print(b) else: n= int(n) st1 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] st2 =['0', '1','2','3','4','5','6','7','8','9','A','B','C','D', 'E', 'F','G','H','I','J','K','L','M','N','O'...
63_B. Settlers' Training
In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either inc...
```python """ Oh, Grantors of Dark Disgrace, Do Not Wake Me Again. """ from collections import Counter n, k = map(int, input().split()) cc = Counter(map(int, input().split())) coins = 0 while cc[k] != n: t = 0 for i in range(1, k): if t+1 <= cc[i]: cc[i] -= 1 cc[i+1] += 1 ...
667_E. Chain Reaction
Group of Berland scientists, with whom you have a close business relationship, makes a research in the area of peaceful nuclear energy. In particular, they found that a group of four nanobots, placed on a surface of a plate, can run a powerful chain reaction under certain conditions. To be precise, researchers introd...
```python import sys sys.stderr = sys.stdout from collections import namedtuple Bot = namedtuple('Bot', ('x', 'y', 'i')) def yxi(bot): return bot.y, bot.x, bot.i def reaction1(B, V): Bv = sorted(B[i] for i in range(4) if V[i]) Bh = sorted((B[i] for i in range(4) if not V[i]), key=yxi) S = [None] *...
714_B. Filya and Homework
Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help. Filya is given an array of non-negative integers a1, a2, ..., an. First, he pick an integer x and then he adds x to some elements of the array (no more than once), subtract x ...
```python n=int(input()) s=set() L=[ int(x) for x in input().split() ] for i in L : s.add(i) if ( len(s) > 3 ) : print("NO") elif (len(s) == 1 or len(s) == 2 ) : print("YES") else : L=[] for i in s : L.append(i) L.sort() a,b,c = L[0], L[1], L[2] if ( b-a == c-b ): print("...
734_E. Anton and Tree
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph. There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white). To c...
```python def main(): n = int(input()) colors = input()[::2] dsu = list(range(n)) edges = [[] for _ in range(n)] for _ in range(n - 1): u, v = map(int, input().split()) u -= 1 v -= 1 if colors[u] == colors[v]: a, b = dsu[u], dsu[v] while a != d...
803_B. Distances to Zero
You are given the array of integer numbers a0, a1, ..., an - 1. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array. Input The first line contains integer n (1 ≤ n ≤ 2·105) — length of the array a. The second line contains...
```python import sys n = int(sys.stdin.readline()) a = sys.stdin.readline().strip().split() def findDistancesToZero(n,a): pos_zero_left = a.index('0') pos_zero_right = a.index('0') pos = 0 positions = '' while pos<n: worked = False while pos<=pos_zero_right: ...
84_A. Toy Army
The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows. There are two armies on the playing field each of which consists of n men (n is always even). The current player sp...
```python n=int(input()) print((n*3)//2) ```
898_C. Phone Numbers
Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers. Vasya decided to organize information about the phone numbers of friends. You will be given n strings — all entries from Vasya's phone books. Each entry starts with a fri...
```python n=int(input()) dic={} for i in range(n): l=list(map(str,input().split())) s1=l[0] if s1 in dic.keys(): dic[l[0]]+=list(set(l[2:])) else: dic[l[0]]=list(set(l[2:])) print(len(dic.keys())) for ix in dic.keys(): l=dic[ix][:] ll=len(l) lln=[1 for i in range(ll)] for...
919_D. Substring
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest. I...
```python from collections import defaultdict import sys from sys import stdin def check(a): for i in a: if i: return True return False def change(x): return ord(x)-ord('a') def solve(): n, m = map(int, stdin.readline().split()) s = input() d = {} for i in range(n): ...
946_C. String Transformation
You are given a string s consisting of |s| small english letters. In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter. Your target is to make some number of ...
```python i = 97 j = 0 s = [x for x in input()] for item in s: if item <= chr(i): s[j] = chr(i) i += 1 if i>122: print("".join(s)) break j += 1 else: print(-1) ```
975_A. Aramic script
In Aramic language words can only represent objects. Words in Aramic have special properties: * A word is a root if it does not contain the same letter more than once. * A root and all its permutations represent the same object. * The root x of a word y is the word that contains all letters that appear in y ...
```python n=int(input()) s=input() a=s.split(" ") visited=[] for i in range(len(a)): visited.append(0) arr=[] for g in range(len(a)): aux=[] for h in range(26): aux.append(0) arr.append(aux) for x in range(len(a)): for y in range(len(a[x])): if(arr[x][ord(a[x][y])-97]==0): arr[x][ord(a[x][y])-97]+=1 ...
994_F. Compute Power
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume. You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task ca...
```python # Codeforces Round #488 by NEAR (Div. 2) import collections from functools import cmp_to_key #key=cmp_to_key(lambda x,y: 1 if x not in y else -1 ) import math import sys def getIntList(): return list(map(int, input().split())) import bisect def makePair(z): return [(z[i], z[i+1]) for i in ...
p02769 AtCoder Beginner Contest 156 - Roaming
There is a building with n rooms, numbered 1 to n. We can move from any room to any other room in the building. Let us call the following event a move: a person in some room i goes to another room j~ (i \neq j). Initially, there was one person in each room in the building. After that, we know that there were exactl...
```python n,k=map(int,input().split()) mod=10**9+7 lim=n fcl=[1]*(lim+1) for i in range(1,lim+1): fcl[i]=(fcl[i-1]*i)%mod def comb(x,y,p): return ((fcl[x]*pow(fcl[y],p-2,p))%p*pow(fcl[x-y],p-2,p))%p ans=0 for i in range(min(n,k+1)): ans+=comb(n-1,n-i-1,mod)*comb(n,i,mod) ans%=mod print(ans) ```
p02904 AtCoder Grand Contest 038 - Sorting a Segment
Snuke has a permutation (P_0,P_1,\cdots,P_{N-1}) of (0,1,\cdots,N-1). Now, he will perform the following operation exactly once: * Choose K consecutive elements in P and sort them in ascending order. Find the number of permutations that can be produced as P after the operation. Constraints * 2 \leq N \leq 200000...
```python n, k = map(int,input().split()) P = list(map(int,input().split())) # for i in range(n-k+1): # pp = P[i:i+k] # pp.sort() # print(P[:i] + pp + P[i+k:]) A = [] B = [] VA = [0] * n VB = [0] * n import heapq for i in range(k): heapq.heappush(A, P[i]) # 最小値用 heapq.heappush(B, -P[i]) # 最大値用 ...
p03039 AtCoder Beginner Contest 127 - Cell Distance
We have a grid of squares with N rows and M columns. Let (i, j) denote the square at the i-th row from the top and j-th column from the left. We will choose K of the squares and put a piece on each of them. If we place the K pieces on squares (x_1, y_1), (x_2, y_2), ..., and (x_K, y_K), the cost of this arrangement is...
```python n,m,k=map(int,input().split()) mod=10**9+7 f=[1] for i in range(2*10**5+7):f+=[f[-1]*(i+1)%mod] def comb(a,b):return f[a]*pow(f[b],mod-2,mod)*pow(f[a-b],mod-2,mod)%mod ans=0 for i in range(1,n): ans+=(i*(n-i)*m**2)*(comb(n*m-2,k-2)) ans%=mod for i in range(1,m): ans+=(i*(m-i)*n**2)*(comb(n*m-2,k-2)) a...
p03180 Educational DP Contest - Grouping
There are N rabbits, numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Rabbit i and j is described by an integer a_{i, j}. Here, a_{i, i} = 0 for each i (1 \leq i \leq N), and a_{i, j} = a_{j, i} for each i and j (1 \leq i, j \leq N). Taro is dividing the N rabbits into some number of...
```python N = int(input()) a = [list(map(int, input().split())) for _ in range(N)] score = [0]*(1<<N) for S in range(1<<N): for i in range(N): if (S>>i)&1: for j in range(i+1, N): if (S>>j)&1: score[S] += a[i][j] dp = [-10**18]*(1<<N) dp[0] = 0 for S in...
p03328 AtCoder Beginner Contest 099 - Stone Monument
In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter. It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not cov...
```python a, b = map(int, input().split()) print(((b-a)*((b-a)+1))//2 - b) ```
p03484 AtCoder Regular Contest 088 - Christmas Tree
Takahashi has decided to make a Christmas Tree for the Christmas party in AtCoder, Inc. A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i. He would like to make one as follows: * Specify two non-negative integers A and B. * Pr...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from bisect import bisect_left, bisect_right N = int(readline()) m = map(int,read().split()) AB = zip(m,m) graph = [[] for _ in range(N+1)] for a,b in AB: graph[a].append(b) graph[b]....
p03649 AtCoder Regular Contest 079 - Decrease (Judge ver.)
We have a sequence of length N consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes N-1 or smaller. (The operation is the same as the one in Problem D.) * Determine the largest element in the sequence (if there is more than...
```python import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) A.sort(reverse=True) count = 0 B = [A[0]] for i in range(N-1): a = A[i+1]+count C = [] for b in B: x = (b-a)//(N+1) C.append(x) s = sum(C) count += s new_B = [] for i, b in ...
p03805 AtCoder Beginner Contest 054 - One-stroke Path
You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and vi...
```python import itertools n,m = map(int,input().split()) ab = [] count = 0 for i in range(m): ab.append(set(map(int,input().split()))) ns = [i for i in range(1,n+1)] ptn = [i for i in list(itertools.permutations(ns)) if i[0]==1] for i in ptn: first = i[0] for s in range(1,n): if {first,i[s]} not in ab: ...
p03973 CODE FESTIVAL 2016 qual B - Greedy customers
N people are waiting in a single line in front of the Takahashi Store. The cash on hand of the i-th person from the front of the line is a positive integer A_i. Mr. Takahashi, the shop owner, has decided on the following scheme: He picks a product, sets a positive integer P indicating its price, and shows this product...
```python n = int(input()) a = [] for i in range(n): a0 = int(input()) a.append(a0) ans = 0 key = "b" count = 1 m = 0 for i in range(n): if key == "a": if a[i] == count: count += 1 elif a[i] > count: if a[i]%count == 0: ans += a[i]//count - 1 ...
p00062 What is the Bottommost?
Consider creating the following number pattern. 4 8 2 3 1 0 8 3 7 6 2 0 5 4 1 8 1 0 3 2 5 9 5 9 9 1 3 7 4 4 4 8 0 4 1 8 8 2 8 4 9 6 0 0 2 5 6 0 2 1 6 2 7 8 Five This pattern follows the rules below. A B C In the sequence of numbers, C is the ones digit of A + B. For example 9 5 Four Now, the ones digit of 9...
```python while True: try: L = [int(x) for x in list(input())] except: break T =[] while len(L) > 1: for i in range(len(L)-1): T.append( (L[i] + L[i+1])%10 ) L = T[:] T = [] print(L[0]) ```
p00193 Convenience Store
Convenience store Deven Eleven is planning to open its first store in Aizuwakamatsu City to expand its business. There are already many other convenience stores in Aizuwakamatsu, so the place to open a new store is likely to be the key to success. Under the premise that "customers use the convenience store closest to t...
```python import sys def generate_next_hexes(x, y): hexes = [(x, y - 1), (x, y + 1), (x - 1, y), (x + 1, y)] if y % 2: hexes += [(x - 1, y - 1), (x - 1, y + 1)] else: hexes += [(x + 1, y - 1), (x + 1, y + 1)] return hexes def update_map(hex_map, hexes): num_updated_hexes = 0 di...
p00544 Russian Flag
problem President K decided to make a flag for IOI 2016 in Russia. Chairman K first took out the old flag from the warehouse. This flag is divided into squares of N rows and M columns, and each square is painted in one of white, blue, and red. Chairman K is trying to repaint some of the squares on this flag to make i...
```python #C inf = float("inf") N,M = map(int,input().split()) flag = [list(str(input())) for i in range(N)] WBR = [] for i in range(N): w = flag[i].count("W") b = flag[i].count("B") r = flag[i].count("R") WBR.append([w,b,r]) ans = inf for w in range(N-2): for b in range(N-1): if ...
p00708 Building a Space Station
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task. The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessar...
```python # http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1127 # クラスカル or プリム法 import math class UnionFind: def __init__(self, n): self.n = n # 各要素の親要素の番号を格納するリスト # 根がルートの時は、グループの要素数を格納 最初は全て根で要素数1 self.parents = [-1] * n # 再帰 groupの根を返す # 経路圧縮あり def find(s...
p00979 Fast Forwarding
Fast Forwarding Mr. Anderson frequently rents video tapes of his favorite classic films. Watching the films so many times, he has learned the precise start times of his favorite scenes in all such films. He now wants to find how to wind the tape to watch his favorite scene as quickly as possible on his video player. ...
```python #!/usr/bin/python3 import os import sys def main(): T = read_int() print(solve(T)) def solve(T): if T <= 3: return T sec = 1 T -= 1 f = 3 while T >= 2 * f: T -= 2 * f f *= 3 sec += 2 if T >= f: T -= f sec += 1 else: ...
p01111 Skyscraper MinatoHarukas
Skyscraper "MinatoHarukas" Mr. Port plans to start a new business renting one or more floors of the new skyscraper with one giga floors, MinatoHarukas. He wants to rent as many vertically adjacent floors as possible, because he wants to show advertisement on as many vertically adjacent windows as possible. The rent fo...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01410 Dangerous Tower
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 dexterity that never mistypes by carefully stacking blocks. Since there are many building blocks, let's build a tall tower. There are N blocks, and the i-th (...
```python import sys readline = sys.stdin.readline write = sys.stdout.write from heapq import heappush, heappop class MinCostFlow: INF = 10**18 def __init__(self, N): self.N = N self.G = [[] for i in range(N)] def add_edge(self, fr, to, cap, cost): forward = [to, cap, cost, None] ...
p01726 Almost Same Substring
The unlucky Ikta-kun has rewritten the important character string T that he had to a different character string T'by the virus. It is known that the virus has rewritten one letter of T to a different letter. That is, T and T'are different by exactly one character. In order to restore T, Ikta prepared a document S in wh...
```python import string import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): s0 = "^" + string.ascii_uppercase + string.ascii_lowercase *S, = map(s0.index, readline().strip()); N = len(S) *T, = map(s0.index, readline().strip()); M = len(T) base = 59; mod = 10**9 + 9 pw = ...
p02000 Bumpy Array
problem Given the sequence $ A $ of length $ N $. The $ i $ item in $ A $ is $ A_i $. You can do the following for this sequence: * $ 1 \ leq i \ leq N --Choose the integer i that is 1 $. Swap the value of $ A_i $ with the value of $ A_ {i + 1} $. Find the minimum number of operations required to make $ A $ a sequ...
```python n = int(input()) a = list(map(int, input().split())) ans = n s = 0 b = [0 for i in range(n)] for i in range(n): b[i] = a[i] for i in range(1,n): if i%2 == 1: if b[i] > b[i-1]: flag = True if i < n-1: if b[i-1] > b[i+1] and b[i+1] < b[i]: ...
p02145 Shiritori
Problem Here is a list of strings. Let's take a break and play with shiritori. Shiritori is performed according to the following rules. 1. First of all, select one of your favorite strings from the list and exclude that string from the list. 2. Next, select one character string from the list in which the last charact...
```python import sys, re from collections import deque, defaultdict, Counter from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement from operator import itemgetter, mul from copy import deepcopy f...
p02286 Treap
A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain t...
```python from random import random from collections import deque from copy import deepcopy import sys input = sys.stdin.readline class Treap: def __init__(self, iterable=None): # vertex = [left, right, key, priority, #descendants, sum of descendants] self.root = None if iterable: self._con...
p02433 List
For a dynamic list $L$ of integers, perform a sequence of the following operations. $L$ has a special element called END at the end of the list and an element of $L$ is indicated by a cursor. * insert($x$): Insert $x$ before the element indicated by the cursor. After this operation, the cursor points the inserted elem...
```python q = int(input()) A = [0 for i in range(1500000)] A[0] = 'end' cursor = 0 head = [0 for i in range(1500000)] head_len = 0 def insert(x): global cursor cursor += 1 A[cursor] = x def move(d): global cursor, head, head_len if d >= 0: head[head_len-1+d+(1): head_len-1+(1):-1] = A[cursor-d+1:cursor+1] else...
1006_C. Three Parts of the Array
You are given an array d_1, d_2, ..., d_n consisting of n integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, em...
```python x = int(input()) v = list(map(int,input().strip().split()))[:x] i = 0 j = x-1 s1 = 0 s2 = 0 ans = 0 while(i<=j): if(s2<s1): s2+=v[j] j=j-1 else: s1+=v[i] i=i+1 if(s1==s2): ans=s1 print(ans) ```
102_B. Sum of Digits
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-di...
```python num = input() c = 0 while(len(num) != 1): num = str(sum(int(i) for i in num)) c += 1 print(c) ```
1051_B. Relatively Prime Pairs
You are given a set of all integers from l to r inclusive, l < r, (r - l + 1) ≤ 3 ⋅ 10^5 and (r - l) is always odd. You want to split these numbers into exactly (r - l + 1)/(2) pairs in such a way that for each pair (i, j) the greatest common divisor of i and j is equal to 1. Each number should appear in exactly one o...
```python l,r=map(int,input().split()) print('YES') for i in range((r-l+1)//2): print(l+i*2,l+i*2+1) ```
1073_C. Vasya and Robot
Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell (0, 0). Robot can perform the following four kinds of operations: * U — move from (x, y) to (x, y + 1); * D — move from (x, y) to (x, y - 1); * L — move from (x, y) to (x - 1, y); * R — move from (x, y) to (x + 1,...
```python # -*- coding: utf-8 -*- """ created by shhuan at 2018/11/3 11:30 search for minimum steps, consider binary search """ N = int(input()) ops = [x for x in input()] X, Y = map(int, input().split()) dd = abs(X) + abs(Y) lops = len(ops) if dd > lops or (lops - dd) % 2 != 0: print(-1) exit(0) [ll, ...
1095_C. Powers Of Two
A positive integer x is called a power of two if it can be represented as x = 2^y, where y is a non-negative integer. So, the powers of two are 1, 2, 4, 8, 16, .... You are given two positive integers n and k. Your task is to represent n as the sum of exactly k powers of two. Input The only line of the input contain...
```python import math n,k=[int(x) for x in input().split()] s=k arr= [1 for i in range(k)] i = k - 1 while(i >= 0): while (s+ arr[i] <= n): s += arr[i] arr[i] *= 2 i -= 1 if (s != n): print("NO") else: print("YES") for i in range(0, k, 1): print(arr[i], end = ' ') '''n=i...
1114_D. Flood Fill
You are given a line of n colored squares in a row, numbered from 1 to n from left to right. The i-th square initially has the color c_i. Let's say, that two squares i and j belong to the same connected component if c_i = c_j, and c_i = c_k for all k satisfying i < k < j. In other words, all squares on the segment fro...
```python def run_length_compress(string): string = string + ["."] n = len(string) begin = 0 end = 1 cnt = 1 ans = [] while True: if end >= n: break if string[begin] == string[end]: end += 1 cnt += 1 else: ans.append(...
1163_A. Eating Soup
The three friends, Kuro, Shiro, and Katie, met up again! It's time for a party... What the cats do when they unite? Right, they have a party. Since they wanted to have as much fun as possible, they invited all their friends. Now n cats are at the party, sitting in a circle and eating soup. The rules are simple: anyone...
```python n , m = map(int,input().split()) import math if n==m: print(0) elif m==0: print(1) elif m==1: print(1) else: if n%2==0: if n//2==m: print(n//2) elif m>n//2: print(n-m) else: print(m) else: if math.ceil(n//2)==m or math.flo...
1183_F. Topforces Strikes Back
One important contest will take place on the most famous programming platform (Topforces) very soon! The authors have a pool of n problems and should choose at most three of them into this contest. The prettiness of the i-th problem is a_i. The authors have to compose the most pretty contest (in other words, the cumul...
```python from sys import stdin from itertools import tee def input(): return stdin.readline() def remove_divisors(x, xs): return [y for y in xs if y%xs != 0] q = int(input()) for _ in range(q): n = int(input()) aas = list(set(map(int,input().split()))) aas.sort(reverse=True) # if len(aas) >...
1201_A. Important Exam
A class of students wrote a multiple-choice test. There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points....
```python def get_ints(): return list(map(int, input().split())) N, M = get_ints() a = [input() for i in range(N)] s = get_ints() ans=0 for i in range(M): d = {} for row in a: c = ord(row[i])-65 if c in d: d[c]+=1 else: d[c]=1 ans += max(d.values())*s[i]...
1243_A. Maximum Square
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i × 1 (that is, the width is 1 and the height is a_i). Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will...
```python n=int(input()) for _ in range(n): i=int(input()) ar=sorted(list(map(int,input().split())))[::-1] mx=0 for e in range(i): mx=max(mx,min(e+1,ar[e])) print(mx) ```