name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
628_B. New Skateboard
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which...
```python from sys import stdin, stdout def main(): s = stdin.readline().rstrip() count = 0 for i, e in enumerate(s): if int(e) % 4 == 0: count += 1 if i >= 1: if int(s[i - 1: i + 1]) % 4 == 0: count += i stdout.write(f'{count}\n') if __name__ ...
652_C. Foe Pairs
You are given a permutation p of length n. Also you are given m foe pairs (ai, bi) (1 ≤ ai, bi ≤ n, ai ≠ bi). Your task is to count the number of different intervals (x, y) (1 ≤ x ≤ y ≤ n) that do not contain any foe pairs. So you shouldn't count intervals (x, y) that contain at least one foe pair in it (the position...
```python import sys # TLE without n, m = map(int, input().split()) pos = [None] * (n + 1) for i, a in enumerate(map(int, input().split())): pos[a] = i z = [300005] * (n + 1) for pr in sys.stdin.read().splitlines(): x, y = map(int, pr.split()) if pos[x] > pos[y]: x, y = y, x z[pos[x]] = min(z[...
678_A. Johny Likes Numbers
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k. Input The only line contains two integers n and k (1 ≤ n, k ≤ 109). Output Print the smallest integer x > n, so it is divisible by the number k. Examples Input 5 3 Output 6...
```python a,b=map(int,input().split()) print(((a//b)+1)*b) ```
700_A. As Fast As Possible
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k pe...
```python import sys import math data = sys.stdin.read() data = data.split(' ') n = int(data[0]) l = int(data[1]) w = int(data[2]) v = int(data[3]) k = int(data[4]) z = math.ceil(n/k) top = l/w - l/(2*w*z) + l/(2*v*z) bot = 1 + v/(2*w*z) - 1/(2*z) print(top/bot) ```
722_C. Destroying Array
You are given an array consisting of n non-negative integers a1, a2, ..., an. You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed. After each element is destroyed you have to find out the segment ...
```python class DSU: def __init__(self, n): self.par = list(range(n)) self.arr = list(map(int, input().split())) self.siz = [1] * n self.sht = [0] * n self.max = 0 def find(self, n): nn = n while nn != self.par[nn]: nn = self.par[nn] wh...
744_A. Hongcow Builds A Nation
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries. The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world. There is at most one...
```python class Union: def __init__(self, n): self.ancestors = [i for i in range(n+1)] self.size = [0]*(n+1) def get_root(self, node): if self.ancestors[node] == node: return node self.ancestors[node] = self.get_root(self.ancestors[node]) return self.ancesto...
791_B. Bear and Friendship Condition
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures). There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves. Let A-B denote that membe...
```python n , m = map(int,input().split()) g = [[] for i in range(n + 1 )] e = 0 vx = 0 for i in range(m): a , b = map(int,input().split()) g[a].append(b) g[b].append(a) vis = [False for i in range(n + 1 )] def dfs(node): global vx , e stack = [node] while(stack): node = stack.pop()...
837_F. Prefix Sums
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m). You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Als...
```python n, k = map(int, input().split(" ")) l = map(int, input().split(" ")) v = [] for x in l: if x != 0 or v: v.append(x) def bruteforce(v, k): ret = 0 while True: accm = 0 for i in range(len(v)): if v[i] >= k: return ret accm += v[i] v[i] = ...
858_B. Which floor?
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are o...
```python n, m = map(int, input().split()) a = [tuple(map(int, input().split())) for i in range(m)] ans = set() for i in range(1, 101): can = True for k, f in a: if (k + i - 1) // i != f: can = False break if can: ans.add((n + i - 1) // i) if len(ans) == 1: print(...
883_H. Palindromic Cut
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits. He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, s...
```python n = int(input()) string = input() char = [] charPair = [] charImpair = [] for car in string: if car not in char: z = string.count(car) while z>1: charPair.append(car) z-=2 if(z==1): charImpair.append(car) char.append(car) if len(charImpair) ==0 : String1 = '' for x in charPair: String1+=...
907_C. Shockers
Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for eac...
```python N = int(input()) letters = set() for c in range(ord('a'), ord('z') + 1): letters.add(chr(c)) tmp = set() do_count = False count = 0 for n in range(N): act, val = input().split() if act == '.': for c in val: if c in letters: letters.remove(c) if act == '...
957_B. Mystical Mosaic
There is a rectangular grid of n rows of m initially-white cells each. Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and...
```python def findInArray(c, arr): ind = [] for i in range(len(arr)): if arr[i] == c: ind.append(i) return ind def solve(): numRows,numCols = map(int, input().strip().split()) mat = [[0]*numCols for _ in range(numRows)] for i in range(numRows): mat[i] = list(input().strip()) rows = [0] * numRows col...
982_B. Bus of Characters
In the Bus of Characters there are n rows of seat, each having 2 seats. The width of both seats in the i-th row is w_i centimeters. All integers w_i are distinct. Initially the bus is empty. On each of 2n stops one passenger enters the bus. There are two types of passengers: * an introvert always chooses a row whe...
```python import heapq n=int(input()) w=[int(x) for x in input().split()] us={w[i]:i+1 for i in range(n)} w.sort() p=input() order="" i=0 seats=[] for x in p: if x=="0": y=w[i] order+=str(us[y])+" " heapq.heappush(seats,-y) i+=1; else: m=heapq.heappop(seats) order...
p02559 AtCoder Library Practice Contest - Fenwick Tree
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types. * `0 p x`: a_p \gets a_p + x * `1 l r`: Print \sum_{i = l}^{r - 1}{a_i}. Constraints * 1 \leq N, Q \leq 500,000 * 0 \leq a_i, x \leq 10^9 * 0 \leq p < N * 0 \leq l_i < r_i \leq N * All values in Input are integer. I...
```python class BinaryIndexedTree: # a[i] = [0] * n def __init__(self, n): self.size = n self.data = [0] * (n+1) # return sum(a[0:i]) def cumulative_sum(self, i): ans = 0 while i > 0: ans += self.data[i] i -= i & -i return ans # a[i] ...
p02690 AtCoder Beginner Contest 166 - I hate Factorization
Give a pair of integers (A, B) such that A^5-B^5 = X. It is guaranteed that there exists such a pair for the given integer X. Constraints * 1 \leq X \leq 10^9 * X is an integer. * There exists a pair of integers (A, B) satisfying the condition in Problem Statement. Input Input is given from Standard Input in the fo...
```python x=int(input()) for a in range(999): for b in range(-a, a): if a**5 - b**5 == x: print(a, b) exit() ```
p02819 AtCoder Beginner Contest 149 - Next Prime
Find the minimum prime number greater than or equal to X. Constraints * 2 \le X \le 10^5 * All values in input are integers. Input Input is given from Standard Input in the following format: X Output Print the minimum prime number greater than or equal to X. Examples Input 20 Output 23 Input 2 Outpu...
```python X=int(input()) for i in range(X,10**6): Flag=True for j in range(2,X): if i%j==0: Flag=False break if Flag==True: print(i) break ```
p02955 AtCoder Beginner Contest 136 - Max GCD
We have a sequence of N integers: A_1, A_2, \cdots, A_N. You can perform the following operation between 0 and K times (inclusive): * Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element. Compute the maximum possible pos...
```python N,K = map(int,input().split()) A = list(map(int,input().split())) S = sum(A) ans = 0 for i in range(1,int(S**0.5)+1): if S%i != 0: continue for j in range(2): d = i if j else S//i B = sorted(map(lambda a:a%d,A)) C = [0] for k in range(N): ...
p03091 AtCoder Grand Contest 032 - Three Circuits
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. Edge i connects Vertex a_i and b_i bidirectionally. Determine if three circuits (see Notes) can be formed using each of the edges exactly once. Constraints * A...
```python # -*- coding: utf-8 -*- def solve(): N, M = map(int, input().split()) F = [list() for _ in range(N+1)] D = [int() for _ in range(N+1)] for _ in range(M): a, b = map(int, input().split()) D[a] += 1 D[b] += 1 F[a].append(b) F[b].append(a) E = [0 for ...
p03388 AtCoder Beginner Contest 093 - Worst Case
10^{10^{10}} participants, including Takahashi, competed in two programming contests. In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th. The score of a participant is the product of his/her ranks in the two contests. Process the following Q queries: * In the i-th query, you are ...
```python # 5,10とする # 片方は7位以下 # (7,7) (6,8) (5,-) (4,9) (3,11) (2,12) (1,13) # (8,6) (9,5) (10,4) (11,3) (12,2) (13,1) # 5,12とする # (7,8) - (1,14) except 5 # (8,7) - (14,1) Q = int(input()) AB = [[int(x) for x in input().split()] for _ in range(Q)] for a,b in AB: if a > b: a,b = b,a answer = 0 x = int((a*b)*...
p03553 AtCoder Regular Contest 085 - MUL
We have N gemstones labeled 1 through N. You can perform the following operation any number of times (possibly zero). * Select a positive integer x, and smash all the gems labeled with multiples of x. Then, for each i, if the gem labeled i remains without getting smashed, you will receive a_i yen (the currency of ...
```python def edmonds_karp(s, t, C): import copy import collections r = copy.deepcopy(c) maxf = 0 while True: q, found = collections.deque(), False q.append(([S], 10 ** 15)) while len(q) > 0 and not found: p, minf = q.popleft() for to, flow in r[p[-1...
p03708 AtCoder Grand Contest 015 - A or...or B Problem
Nukes has an integer that can be represented as the bitwise OR of one or more integers between A and B (inclusive). How many possible candidates of the value of Nukes's integer there are? Constraints * 1 ≤ A ≤ B < 2^{60} * A and B are integers. Input The input is given from Standard Input in the following format: ...
```python import sys def solve(): a = int(input()) b = int(input()) if a == b: print(1) return t = a ^ b N = len(bin(t)) - 2 t = 1 << N a = a & (t - 1) b = b & (t - 1) blen = len(bin(b)) - 2 sb = b & (2**(blen - 1) - 1) if sb == 0: sblen = 0 ...
p03862 AtCoder Beginner Contest 048 - Boxes and Candies
There are N boxes arranged in a row. Initially, the i-th box from the left contains a_i candies. Snuke can perform the following operation any number of times: * Choose a box containing at least one candy, and eat one of the candies in the chosen box. His objective is as follows: * Any two neighboring boxes conta...
```python n, x = map(int, input().split()) a = [0] + list(map(int, input().split())) ans = 0 for i in range(n): if a[i] + a[i+1] > x: diff = (a[i] + a[i+1]) - x ans += diff a[i+1] -= diff print(ans) ```
p04028 AtCoder Regular Contest 059 - Unhappy Hacking
Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the `0` key, the `1` key and the backspace key. To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this stri...
```python n = int(input()) s = input() MOD = 10 ** 9 + 7 # dp[i][j] # i回目のキーを押し終えたときに、文字列の長さがjになるときの通り数 dp = [[0] * (n + 1) for i in range(n + 1)] dp[0][0] = 1 for i in range(n): for j in range(n + 1): # Bを押したとき dp[i + 1][max(j - 1, 0)] += dp[i][j] dp[i + 1][max(j - 1, 0)] %= MOD i...
p00111 Doctor's Memorable Codes
Hiroshi:? D-C'KOPUA Peter: What's wrong, Dr. David? I'm used to shouting something I don't understand, but I'm not even writing it today. Hiroshi: Here. <image> Peter: What? This table ... oh, there was something like this in the qualifying question. Replacing characters using a table reduces the number of charact...
```python import sys def cv1(c): o=ord(c) if 65<=o<=90: return format(o-65,"05b") elif o==32: return "11010" elif o==46: return "11011" elif o==44: return "11100" elif o==45: return "11101" elif o==39: return "11110" elif o==63: ret...
p00245 Time Sale
Better things, cheaper. There is a fierce battle at the time sale held in some supermarkets today. "LL-do" here in Aizu is one such supermarket, and we are holding a slightly unusual time sale to compete with other chain stores. In a general time sale, multiple products are cheaper at the same time, but at LL-do, the t...
```python from heapq import heappush, heappop from string import digits import sys readline = sys.stdin.readline write = sys.stdout.write dd = ((-1, 0), (0, -1), (1, 0), (0, 1)) INF = 10**9 while 1: X, Y = map(int, readline().split()) if X == Y == 0: break MP = [readline().split() for i in range(Y)...
p00426 Cup
There are n cups of different sizes and three trays (bon festivals) A, B, and C, and these cups are placed on top of each of the three trays in a pile. However, in any tray, the smallest cup in the tray is on the bottom, the second smallest cup is on top, and the third smallest cup is on top, in ascending order. .. For...
```python def biggest_cup(s,v): try: return s.index(v) except ValueError: return 127 def neighbors(s): a = biggest_cup(s,0) b = biggest_cup(s,1) c = biggest_cup(s,2) if b > a: t = list(s) t[a] = 1 yield tuple(t) elif b < a: t = list(s) ...
p00621 Sleeping Cats
Jack loved his house very much, because his lovely cats take a nap on the wall of his house almost every day. Jack loved cats very much. Jack decided to keep an observation diary of the cats as a free study during the summer vacation. After observing for a while, he noticed an interesting feature of the cats. The fen...
```python while 1: W, Q = map(int, input().split()) if W == Q == 0: break A = [0]*W for i in range(Q): s, *qs = input().split() if s == 's': x, w = map(int, qs) su = sum(A[:w-1]) k = -1 for i in range(W-w+1): su += A...
p00897 Long Distance Taxi
A taxi driver, Nakamura, was so delighted because he got a passenger who wanted to go to a city thousands of kilometers away. However, he had a problem. As you may know, most taxis in Japan run on liquefied petroleum gas (LPG) because it is cheaper than gasoline. There are more than 50,000 gas stations in the country, ...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+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 ...
p01030 Changing Grids
Background Mr. A and Mr. B are enthusiastic about the game "Changing Grids". This game is for two players, with player 1 forming the stage and player 2 challenging the stage and aiming for the goal. Now, A and B have played this game several times, but B has never won because of A's winning streak. So you decided to ...
```python from heapq import heappush, heappop h, w = map(int, input().split()) def get_area(): mp = ["#" * (w + 2)] for _ in range(h): mp.append("#" + input() + "#") mp.append("#" * (w + 2)) return mp areas = [get_area()] times = {} n = int(input()) for i in range(n): times[int(input())...
p01300 Eleven Lover
Edward Leven loves multiples of eleven very much. When he sees a number, he always tries to find consecutive subsequences (or substrings) forming multiples of eleven. He calls such subsequences as 11-sequences. For example, he can find an 11-sequence 781 in a number 17819. He thinks a number which has many 11-sequence...
```python while(True): s = input() m = len(s) if s == "0": quit() dp = [[0 for j in range(11)] for i in range(m)] for i in range(m): n = int(s[i]) if n == 0: tmp = dp[i-1][1:] tmp.reverse() dp[i] = [dp[i-1][0]]+tmp else: ...
p01781 Cube Coloring
Example Input 2 2 2 0 0 0 5 Output 1 3 3 1 0
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): X, Y, Z, A, B, C, N = map(int, readline().split()) S = [0]*max(2*(X+Y+Z+1), 2*N+2) for k in range(N): S[k] = k*(k+1)//2 for k in range(N, X+Y+Z+1): S[k] = k*(k+1)//2 + S[k-N] def calc(k, x, y, ...
p01916 Alphabet Block
A: Alphabet block Wakana Nakawa loves palindromes. Because my name is also a palindrome. Wakana got a set with some alphabet blocks. An alphabet block is a block in which one lowercase alphabet is written for each block, and you can create your favorite character string by changing the order of the blocks and combini...
```python import collections print(sum([v%2 for v in collections.Counter(input()).values()])//2) ```
p02054 Skewering
C: Skewering problem One day, when Homura was playing with blocks, Tempura came. Homura decided to play with blocks with Tempura. There is a rectangular parallelepiped of A \ times B \ times C, which is made by stacking A \ times B \ times C blocks of cubic blocks with a side length of 1 without any gaps. Each side ...
```python A,B,C=map(int,input().split()) ANS=0 for i in [A,B,C]: if i%2==1: ANS+=1 if ANS>=2: print("Hom") else: print("Tem") ```
p02350 RMQ and RUQ
Write a program which manipulates a sequence A = {a0, a1, . . . , an−1} with the following operations: * update(s, t, x): change as, as+1, ..., at to x. * find(s, t): report the minimum element in as, as+1, ..., at. Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1. Constraints * 1 ≤ n ≤ 100000...
```python import math from collections import deque class SegmentTree: __slots__ = ["rank", "elem_size", "tree_size", "tree", "lazy", "default_value"] def __init__(self, a: list, default: int): self.default_value = default real_size = len(a) self.rank = math.ceil(math.log2(real_size))...
1000_E. We Need More Bosses
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location. Of course, some passages should be...
```python import sys from array import array # noqa: F401 def readline(): return sys.stdin.buffer.readline().decode('utf-8') def build_bridge_tree(v_count, edge_count, adj, edge_index): from collections import deque preorder = [0] parent, order, low = [0]+[-1]*v_count, [0]+[-1]*(v_count-1), [0]*v_coun...
106_B. Choosing Laptop
Vasya is choosing a laptop. The shop has n laptops to all tastes. Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties. If all three properties of a laptop are strictly less than those properties ...
```python from sys import stdin,stdout from heapq import heapify,heappush,heappop,heappushpop from collections import defaultdict as dd, deque as dq,Counter as C from bisect import bisect_left as bl ,bisect_right as br from itertools import combinations as cmb,permutations as pmb from math import factorial as f ,ceil,g...
1091_A. New Year and the Christmas Ornament
Alice and Bob are decorating a Christmas Tree. Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments. In Bob's opinion, a Christmas Tree will be beautiful if: * the number of blue ornaments used is greater b...
```python y,b,r=map(int,input().split()) l,m,n=(1,2,3) while(l!=y and m!=b and n!=r): l+=1 m+=1 n+=1 s=l+m+n print(s) ```
110_D. Lucky Probability
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the in...
```python #!/usr/bin/env python3 vl, vr, pl, pr, k = map(int, input().split()) lucky = [4, 7] sz = 0 for i in range(1, 9): base = 10 ** i psz, sz = sz, len(lucky) for j in [4 * base, 7 * base]: for pos in range(psz, sz): lucky.append(j + lucky[pos]) ans = 0 for i in range(0, len(lucky)...
113_A. Grammar Lessons
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: * There are three parts of sp...
```python s=input().split() if(len(s)==1): if(s[0].endswith("lios") or s[0].endswith("etr") or s[0].endswith("liala") or s[0].endswith("etra") or s[0].endswith("inites") or s[0].endswith("initis")): print("YES") else: print("NO") elif(s[0].endswith("lios") or s[0].endswith("etr")): n=len...
1157_G. Inverse of Rows and Columns
You are given a binary matrix a of size n × m. A binary matrix is a matrix where each element is either 0 or 1. You may perform some (possibly zero) operations with this matrix. During each operation you can inverse the row of this matrix or a column of this matrix. Formally, inverting a row is changing all values in ...
```python import sys input = sys.stdin.readline n,m=map(int,input().split()) A=[list(map(int,input().split())) for i in range(n)] for i in range(m): #一行目をi-1まで0にする ANSR=[0]*n ANSC=[0]*m for j in range(i): if A[0][j]==1: ANSC[j]=1 for j in range(i,m): if A[0][j]==0: ...
1198_E. Rectangle Painting 2
There is a square grid of size n × n. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs min(h, w) to color a rectangle of size h × w. You are to make all cells white for minimum total cost. The square is large, so...
```python import sys from collections import defaultdict class MaxFlow(object): def __init__(self): self.edges = defaultdict(lambda: defaultdict(lambda: 0)) def add_edge(self, u, v, capacity=float('inf')): self.edges[u][v] = capacity def bfs(self, s, t): open_q = [s] visi...
1215_D. Ticket Game
Monocarp and Bicarp live in Berland, where every bus ticket consists of n digits (n is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even. Monocarp and Bicarp have decided to play a game with this tic...
```python 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.mode self.write = self...
1238_F. The Maximum Subtree
Assume that you have k one-dimensional segments s_1, s_2, ... s_k (each segment is denoted by two integers — its endpoints). Then you can build the following graph on these segments. The graph consists of k vertexes, and there is an edge between the i-th and the j-th vertexes (i ≠ j) if and only if the segments s_i and...
```python import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n = int(input()) ab = [list(map(int,input().split())) for i in range(n-1)] graph = [[] for i in range(n+1)] deg = [0]*(n+1) for a,b in ab: graph[a].append(b) graph[b].append(a) deg[a] += 1 deg[b] += 1 pnt = [...
1257_A. Two Rival Students
You are the gym teacher in the school. There are n students in the row. And there are two rivalling students among them. The first one is in position a, the second in position b. Positions are numbered from 1 to n from left to right. Since they are rivals, you want to maximize the distance between them. If students a...
```python t = int(input()) for i in range(t): n, x, a, b = map(int, input().split(' ')) if((a==n and b==1)or(b==n and a==1)): print(n-1) elif x==0: print(abs(b-a)) else: ans=x+abs(b-a) if(ans>=n): print(n-1) else: print(ans) ...
1280_B. Beingawesomeism
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r × c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomei...
```python """ This template is made by Satwik_Tiwari. python programmers can use this template :)) . """ #=============================================================================================== #importing some useful libraries. import sys import bisect import heapq from math import * from collections ...
1300_A. Non-zero
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≤ i ≤ n) and do a_i := a_i + 1. If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T...
```python import sys input = lambda: sys.stdin.readline().rstrip() t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) cnt = 0 for i in range(n): if a[i]==0: a[i] += 1 cnt += 1 if sum(a)==0: cnt += 1 print(cnt) ```
1324_B. Yet Another Palindrome Problem
You are given an array a consisting of n integers. Your task is to determine if a has some subsequence of length at least 3 that is a palindrome. Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c...
```python #!/usr/bin/env python import sys def main(): t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().strip().split())) d = dict() didbreak = False for i in range(n): if a[i] not in d: d[a[i]] = [1, i] ...
1343_A. Candies
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >...
```python import math if __name__ == "__main__": n = int(input()) for i in range(n): m = int(input()) res = 1 test = 0 while(m > 2**res -1): res += 1 if m% (2**res -1) == 0: test = m//(2**res -1) break x = test ...
1365_B. Trouble Sort
Ashish has n elements arranged in a line. These elements are represented by two integers a_i — the value of the element and b_i — the type of the element (there are only two possible types: 0 and 1). He wants to sort the elements in non-decreasing values of a_i. He can perform the following operation any number of t...
```python for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) if(sum(b)==0 or sum(b)==n): b = sorted(a) print('Yes' if a==b else 'No') else: print('Yes') ```
1385_B. Restore the Permutation by Merger
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not. There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc...
```python n=int(input()) b=[] for i in range(n): x=int(input()) a=[int(i) for i in input().split()] d={} for j in range(len(a)): if a[j] in d: d[a[j]]+=1 else: d[a[j]]=1 b.append(list(d.keys())) for i in range(len(b)): for j in range(len(b[i])): print(b[i][j],end=" ") print() ...
1450_F. The Struggling Contestant
To help those contestants who struggle a lot in contests, the headquarters of Codeforces are planning to introduce Division 5. In this new division, the tags of all problems will be announced prior to the round to help the contestants. The contest consists of n problems, where the tag of the i-th problem is denoted by...
```python import sys,io,os;Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline o=[] for _ in range(int(Z())): n=int(Z());a=[*map(int,Z().split())] cn=p=a[0];pn=d=0;e=[0]*n;b=[0]*n;c=[0]*n for i in range(n): if a[i]==p: if pn: if pn!=p:b[pn-1]+=1 else:e[p...
1474_D. Cleaning
During cleaning the coast, Alice found n piles of stones. The i-th pile has a_i stones. Piles i and i + 1 are neighbouring for all 1 ≤ i ≤ n - 1. If pile i becomes empty, piles i - 1 and i + 1 doesn't become neighbouring. Alice is too lazy to remove these stones, so she asked you to take this duty. She allowed you to...
```python ''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineering College ''' from os import path from io import BytesIO, IOBase import sys from heapq import heappush,heappop from functools import cmp_to_key as ctk from collections import deque,Counter,defaultdict as dd from bisect import ...
14_A. Letter
A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world...
```python n,m = map(int, input().split()) data = [] for i in range(n): data.append(list(input())) boundary = [-1,-1,-1,-1] for i in range(n): for j in range(m): if data[i][j] == '*': if boundary[0]>j or boundary[0]==-1: boundary[0] = j if boundary[1]<j or bounda...
177_E1. Space Voyage
The Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit n planets. For planet i ai is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and bi is the number of citizens on the planet. The Smart Beaver is going to bring som...
```python n, c = map(int, input().split()) a = [] b = [] for i in range(n): aa, bb = map(int, input().split()) a.append(aa) b.append(bb) def all_zero(): for aa in a: if aa > 0: return False return True def days(x): c = 0 for aa, bb in zip(a, b): c += 1 + aa*x//bb return...
199_A. Hexadecimal's theorem
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers. Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ...
```python import sys s=sys.stdin.readline().strip() s=int(s) def fabo(a): f0=0 f1=1 f2=1 while f2<a: f0=f1 f1=f2 f2=f1+f0 if a==f2: return print(f1,f0,0) else: pass if s==0: print(0,0,0) if s==1: print(0,0,1) else: fabo...
222_B. Cosmic Tables
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in...
```python import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write i...
245_H. Queries for Number of Palindromes
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes. String s[l... r] = slsl + 1... sr ...
```python import os import sys from io import BytesIO, IOBase def main(): # n, k = map(int, input().split()) # s = input() s=input() n=len(s) palin = [[0 for _ in range(n)] for _ in range(n)] dp = [[0 for _ in range(n)] for _ in range(n)] for sz in range(n): for i in range(n - sz): ...
271_A. Beautiful Year
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
```python from collections import Counter n=int(input()) n1=n+1 while(True): s=list(str(n1)) c=Counter(s) if(len(c)==len(s)): print("".join(s)) break n1=n1+1 ```
294_C. Shaass and Lights
There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is alrea...
```python from math import factorial import re in1 = [int(x) for x in re.split("\\s", input())] in2 = [int(x) for x in re.split("\\s", input())] in2.append(0) in2.append(in1[0]+1) in2.sort() lights = [] for x in range(len(in2)-1): lights.append(in2[x+1]-in2[x]-1) lightsTotal = sum(lights) possTotal = factorial...
318_A. Even Odds
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin...
```python n, m = map(int, input().split()) print((m * 2) - 1 if m <= n - (n//2) else (m - (n - (n // 2))) * 2) # UBCF # CodeForcesian # ♥ # تو شرایطی که همه درگیر خودشون و کاراشون شدن من بدون اینکه متوجه شم درگیرت شدم ```
342_A. Xenia and Divisors
Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held: * a < b < c; * a divides b, b divides c. Naturally, Xenia wants...
```python n = int(input()) // 3 x = input() c1 = x.count('1') c2 = x.count('2') c3 = x.count('3') c4 = x.count('4') c6 = x.count('6') if c1 != n or c2 < c4 or c1 != c2 + c3 or c1 != c4 + c6: print(-1) exit() print('1 2 4\n' * c4 + '1 3 6\n' * c3 + '1 2 6\n' * (n - c4 - c3)) ```
365_C. Matrix
You have a string of decimal digits s. Let's define bij = si·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle. A rectangle in a matrix is a group of four integers (x, y, z, t) (x ≤ y, z ≤ t). The elements of the r...
```python def divisors(x): def f(y, q): t = -len(r) while not y % q: y //= q for i in range(t, 0): r.append(r[t] * q) return y r, p = [1], 7 x = f(f(f(x, 2), 3), 5) while x >= p * p: for s in 4, 2, 4, 2, 4, 6, 2, 6: if ...
389_B. Fox and Cross
Fox Ciel has a board with n rows and n columns. So, the board consists of n × n cells. Each cell contains either a symbol '.', or a symbol '#'. A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks. <image> Ciel wants to draw several ...
```python n=int(input()) L=[input() for i in range(n)] L1=[[0 for i in range(n)] for j in range(n)] try : for i in range(n) : for j in range(n) : if L[i][j]=="#" and L1[i][j]==0 : if L1[i+1][j]==L1[i+2][j]==L1[i+1][j+1]==L1[i+1][j-1]==0 and L[i+1][j]==L[i+2][j]==L[i+1][j+1]==L[i+...
409_E. Dome
<image> Input The input contains a single floating-point number x with exactly 6 decimal places (0 < x < 5). Output Output two integers separated by a single space. Each integer should be between 1 and 10, inclusive. If several solutions exist, output any of them. Solution will exist for all tests. Examples Input...
```python import sys from math import sqrt, pi X = float(input()) def rad_len(a, h, c): x = c * a/2 # y = c * sqrt((a / 2)**2 + h**2) y = c * h return sqrt((x - a/2)**2 + (y - 0)**2) def get_max_radius(a, h): lo = 0.0 hi = 1.0 while abs(lo - hi) > 1e-9: # print(lo, hi, rad_len(a,...
482_A. Diverse Permutation
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn. Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k d...
```python s = input() arr = s.split() n = int(arr[0]) k = int(arr[1]) print(1,end='') i = 2 while i in range(2,k+1): if i % 2 == 0: print('',n - i//2 + 1,end='') else: print('',(i+1)//2,end='') i = i + 1 if k % 2 == 0: x = n - k//2 i = k while i in range(k,n): print('',x,end='') x = x - 1 i = i + 1 el...
529_E. 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 n_k = input() n_k = n_k.split(" ") n = int(n_k[0]) k = int(n_k[1]) ais = input() ais = ais.split(" ") q = int(input()) pares = {} for a in ais: a = int(a) for i in range(k): p = int((i+1)*a) if (p not in pares) or (i+1 < pares[p]): pares[p] = i+1 m = 1000000000 for i...
555_B. Case of Fugitive
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: ...
```python #!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses...
581_A. Vasya the Hipster
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and ...
```python a,b=map(int,input().split()) countd=0 counts=0 while a>0 or b>0: if a>0 and b>0: countd=countd+1 a=a-1 b=b-1 elif a>=2 and b==0: counts=counts+1 a=a-2 elif a==0 and b>=2: counts=counts+1 b=b-2 else: a=0 b=0 print(countd,co...
625_C. K-special Tables
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects. Alis is among these collectors. Right now she wants to get one of k-special tables. In case you for...
```python n, k = [int(x) for x in input().split(' ')] ans = 0 y = n*(k-1)+1 x = 1 barr = [] for i in range(n): arr = [] for j in range(k-1): arr.append(x) x += 1 for j in range(k-1, n): arr.append(y) y += 1 ans += arr[k-1] barr.append(' '.join(map(str, arr))) print(an...
71_B. Progress Bar
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar. A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from t...
```python from math import floor n, k, t = map(int, input().split()) l = [0 for i in range(n)] g = t / 100 * n gl = floor(g) for i in range(gl): l[i] = k if gl < n: l[gl] = floor((g - gl) * k) for item in l: print(item, end = ' ') ```
764_C. Timofey and a tree
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some verte...
```python def main(): n = int(input()) pairs = [] for i in range(n-1): a, b = list(map(int, input().split())) pairs.append([a-1, b-1]) colors = list(map(int, input().split())) bad_pairs_count = 0 bad_points_counts = {0:0} for a,b in pairs: if colors[a] != colors[b]: bad_pairs_count += 1 def add(x)...
854_C. Planning
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is e...
```python from heapq import heappush,heappop,heapify n,k=map(int,input().split()) *l,=map(int,input().split()) q=[(-l[i],i)for i in range(k)] heapify(q) a=[0]*n s=0 for i in range(k,n) : heappush(q,(-l[i],i)) x,j=heappop(q) s-=x*(i-j) a[j]=i+1 for i in range(n,n+k) : x,j=heappop(q) s-=x*(i-j) ...
879_A. Borya's Diagnosis
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the...
```python # -*- coding: utf-8 -*- if __name__ == '__main__': n = int(input()) r = 0 while n > 0: s, d = list(map(int, input().split())) r = max(r + 1, s) if (r - s) % d != 0: r += d - (r - s) % d n -= 1 print(r) ```
902_C. Hashing Trees
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of tree...
```python h = int(input()) a = list(map(int, input().split())) p, c, f = 0, 0, False s1, s2 = [], [] for i in a: for j in range(i): s1.append(c) if j==i-1 and not f and p>=2 and i>=2: f = True s2.append(c-1) else: s2.append(c) p = i c += i print('p...
952_G. Puzzling Language
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck). The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usua...
```python # python3 WIDTH = 300 assert WIDTH >= 256 def add(n): if n == 1: add(2) add(255) elif n: print('.' * WIDTH) print('X' * (n - 1) + '.' * (WIDTH - n) + 'X') print('X' * WIDTH) def print_mem2(): print('.' * WIDTH) print('XX' + '.' * (WIDTH - 2)) pr...
99_D. Help King
This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive. Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, ...
```python from math import gcd def PRINT(a, b) : print(str(int(a)) + "/" + str(int(b))) def solve(n) : pre = 0 while(n > 1 and (n % 2 == 0)) : pre = pre + 1 n = n // 2 if(n == 1) : PRINT(pre, 1) return arr = [] ...
p02541 ACL Contest 1 - Sum is Multiple
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists. Constraints * 1 \leq N \leq 10^{15} * All values in input are integers. Input Input is given from Standard Input in the following format: ...
```python from itertools import product def main(): n = int(input()) n_copy = n if n == 1: print(1) exit() if n % 2 == 0: ans = 2 * n - 1 n *= 2 else: ans = n - 1 factors = [] for p in range(2, n): if p * p > n: if n > 1: ...
p02673 AtCoder Grand Contest 044 - Random Pawn
You are playing a game and your goal is to maximize your expected gain. At the beginning of the game, a pawn is put, uniformly at random, at a position p\in\\{1,2,\dots, N\\}. The N positions are arranged on a circle (so that 1 is between N and 2). The game consists of turns. At each turn you can either end the game, ...
```python from bisect import bisect_right def det(p1, p2, p3): area = (p2[0] - p1[0])*(p3[1] - p1[1]) - (p2[1] - p1[1])*(p3[0] - p1[0]) return area > 0 def convex_hull(pts): pts = sorted(pts) n = len(pts) extsize = 0 extpts = [] for i in range(n): while extsize > 1: i...
p02801 AtCoder Beginner Contest 151 - Next Alphabet
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order. Constraints * C is a lowercase English letter that is not `z`. Input Input is given from Standard Input in the following format: C Output Print the letter that follows C in alphabetical order. Example...
```python a = input() b = chr(ord(a)+1) print(b) ```
p02937 AtCoder Beginner Contest 138 - Strings of Impurity
Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists. * Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i chara...
```python s=input() t=input() ans=0 s_inx=0 t_inx=0 s_l=len(s) t_l=len(t) c=0 while t_inx<=t_l-1: try: temp_inx=s[s_inx:].index(t[t_inx]) s_inx+=temp_inx+1 t_inx+=1 c=0 except: c+=1 s_inx=0 ans+=s_l if c==2: print(-1) exit() else: ans+=s_inx print(ans) ```
p03074 AtCoder Beginner Contest 124 - Handstand
N people are arranged in a row from left to right. You are given a string S of length N consisting of `0` and `1`, and a positive integer K. The i-th person from the left is standing on feet if the i-th character of S is `0`, and standing on hands if that character is `1`. You will give the following direction at mo...
```python n, k = map(int, input().split()) s = input() l = [0] * (k * 2 + 1) c = '1' p = 0 ret = 0 for i in range(len(s)): if s[i] != c: ret = max(ret, i - l[p]) l.append(i) if c == '1': l.pop(0) l.pop(0) c = s[i] ret = max(ret, n - l[p]) print(ret) ```
p03216 Dwango Programming Contest V - k-DMC
In Dwango Co., Ltd., there is a content distribution system named 'Dwango Media Cluster', and it is called 'DMC' for short. The name 'DMC' sounds cool for Niwango-kun, so he starts to define DMC-ness of a string. Given a string S of length N and an integer k (k \geq 3), he defines the k-DMC number of S as the number o...
```python import sys def input(): return sys.stdin.readline().strip() N = int(input()) S = input() Q = int(input()) k = list(map(int, input().split())) DM_total = [(0,0,0)] C_list = [] for i in range(N): if S[i] == "D": DM_total.append((DM_total[-1][0] + 1, DM_total[-1][1], DM_total[-1][2])) elif S[i] == "M": ...
p03365 AtCoder Grand Contest 023 - Painting Machines
There are N squares lining up in a row, numbered 1 through N from left to right. Initially, all squares are white. We also have N-1 painting machines, numbered 1 through N-1. When operated, Machine i paints Square i and i+1 black. Snuke will operate these machines one by one. The order in which he operates them is rep...
```python N = int(input()) - 1 LARGE = 10**9+7 def ex_euclid(x, y): c0, c1 = x, y a0, a1 = 1, 0 b0, b1 = 0, 1 while c1 != 0: m = c0 % c1 q = c0 // c1 c0, c1 = c1, m a0, a1 = a1, (a0 - q * a1) b0, b1 = b1, (b0 - q * b1) return c0, a0, b0 # precompute fa...
p03523 CODE FESTIVAL 2017 Final - AKIBA
You are given a string S. Takahashi can insert the character `A` at any position in this string any number of times. Can he change S into `AKIHABARA`? Constraints * 1 \leq |S| \leq 50 * S consists of uppercase English letters. Input Input is given from Standard Input in the following format: S Output If it i...
```python import re s = input() t = ['KIHBR','AKIHBR','KIHABR','KIHBAR','KIHBRA','AKIHABR','AKIHBAR','AKIHBRA','KIHABAR','KIHABRA','KIHBARA','AKIHABAR','AKIHABRA','AKIHBARA','AKIHABARA'] if s in t: print('YES') else: print('NO') ```
p03688 AtCoder Grand Contest 016 - Colorful Hats
There are N cats. We number them from 1 through N. Each of the cats wears a hat. Cat i says: "there are exactly a_i different colors among the N - 1 hats worn by the cats except me." Determine whether there exists a sequence of colors of the hats that is consistent with the remarks of the cats. Constraints * 2 ≤ N ...
```python N = int(input()) hat = list(map(int, input().split())) hat.sort() min, max = hat[0], hat[N - 1] count_min = 0 count_max = N if max - min > 1: print("No") elif max == min: if max <= N // 2 or max == N-1: print("Yes") else: print("No") else: for i in range(N): if hat[i] <...
p03841 AtCoder Grand Contest 008 - K-th K
You are given an integer sequence x of length N. Determine if there exists an integer sequence a that satisfies all of the following conditions, and if it exists, construct an instance of a. * a is N^2 in length, containing N copies of each of the integers 1, 2, ..., N. * For each 1 ≤ i ≤ N, the i-th occurrence of the...
```python # #    ⋀_⋀  #   (・ω・) # ./ U ∽ U\ # │* 合 *│ # │* 格 *│ # │* 祈 *│ # │* 願 *│ # │*   *│ #  ̄ # import sys sys.setrecursionlimit(10**6) input=sys.stdin.readline from math import floor,sqrt,factorial,hypot,log #log2ないyp from heapq import heappop, heappush, heappushpop from collections import Count...
p04008 AtCoder Grand Contest 004 - Teleporter
There are N towns in Snuke Kingdom, conveniently numbered 1 through N. Town 1 is the capital. Each town in the kingdom has a Teleporter, a facility that instantly transports a person to another place. The destination of the Teleporter of town i is town a_i (1≤a_i≤N). It is guaranteed that one can get to the capital fr...
```python #d tree #code自体はあっている。ただ、そもそもアルゴリズムが違う。 #下から調べていかないと最適でない。 #Right Answer. import sys sys.setrecursionlimit(2 * 10 ** 5 + 10) n,k = [int(i) for i in input().split()] a = [int(i)-1 for i in input().split()] #this is directed tree so every node is not reached yet #return the depth from its lowest bottom ...
p00094 Calculation of Area
Have you ever heard of the unit "○○ tsubo" that expresses the area of ​​land? Since ancient times, one samurai has said the area for making rice to eat in a day. There is a land of a [m] x b [m]. Enter a and b and create a program that outputs the tsubo area S [tsubo] of the land. 1 tsubo = 3.305785 [m2], and a and b ...
```python a, b = (int(x) for x in input().split()) s = a*b S = s/3.305785 print('{0:.6f}'.format(S)) ```
p00226 Hit and Blow
Taro and Hanako decided to play hit-and-blow. The hit-and-blow rules are as follows. * Separated into questioners and respondents. * The questioner decides a 4-digit number (correct answer) that does not include duplicate numbers. * Respondents guess the 4-digit number (answer). * For the answer, the questioner gives ...
```python while 1: x,y = map(list,input().split()) if x == ['0'] and y== ['0']: break h = b = 0 for i in range(len(x)): if x[i] == y[i]: h += 1 elif y[i] in x: b += 1 print ('%d %d' % (h,b)) ```
p00388 Design of a Mansion
Our master carpenter is designing a condominium called Bange Hills Mansion. The condominium is constructed by stacking up floors of the same height. The height of each floor is designed so that the total height of the stacked floors coincides with the predetermined height of the condominium. The height of each floor ca...
```python H, A, B = map(int, input().split()) ans = 0 for k in range(A, B+1): if H % k == 0: ans += 1 print(ans) ```
p00604 Cheating on ICPC
Peter loves any kinds of cheating. A week before ICPC, he broke into Doctor's PC and sneaked a look at all the problems that would be given in ICPC. He solved the problems, printed programs out, and brought into ICPC. Since electronic preparation is strictly prohibited, he had to type these programs again during the co...
```python while True: try: n=int(input()) A=sorted(list(map(int,input().split()))) S=0 K=0 for i in range(n): S+=A[i]*(n-i) print(S) except EOFError: break ```
p00741 How Many Islands?
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map. <image> Figure B-1: A marine area map You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two ar...
```python from collections import deque import sys sys.setrecursionlimit(10**6) def dfs(x,y): c[x][y] = 0 for dx in range(-1,2): for dy in range(-1,2): nx = x + dx ny = y + dy if 0 <= nx < h and 0 <= ny < w and c[nx][ny] == 1: dfs(nx,ny) while...
p00880 Malfatti Circles
The configuration of three circles packed inside a triangle such that each circle is tangent to the other two circles and to two of the edges of the triangle has been studied by many mathematicians for more than two centuries. Existence and uniqueness of such circles for an arbitrary triangle are easy to prove. Many me...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): x1, y1, x2, y2, x3, y3 = map(int, readline().split()) if x1 == y1 == x2 == y2 == x3 == y3 == 0: return False d12 = ((x1-x2)**2 + (y1-y2)**2)**.5 d23 = ((x2-x3)**2 + (y2-y3)**2)**.5 d31 = ((x3-x1)**2 + (y...
p01143 Princess's Gamble
Princess'Gamble Princess gambling English text is not available in this practice contest. One day, a brave princess in a poor country's tomboy broke the walls of her room, escaped from the castle, and entered the gambling hall where horse racing and other gambling were held. However, the princess who had never gambl...
```python while True: n, m, p = map(int, input().split()) if n == 0: break players = [int(input()) for _ in range(n)] gold_div = sum(players) * (100 - p) winner = players[m - 1] print(int(gold_div / winner) if winner > 0 else 0) ```
p01452 10-Year-Old Dynamic Programming
<image> One evening. As usual, when you were watching TV in the living room, my sister in fifth grade offered me a consultation. When I listened to the story, I couldn't understand the math problem that was presented at school today, so I want you to teach me how to solve it. The question that bothers my sister is, "...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+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 ...
p01602 Parentheses
() Problem Statement There is a string S. Initially, S is an empty string. Perform the following processing in order of n. * Add x_i p_i (=" (" or") ") to the end of S. After processing, determine if S is a well-balanced string. "The string is balanced" is defined as follows. * The empty string is well-balanced...
```python n = int(input()) s = 0 f = 0 for i in range(n): p,x = input().split() x = int(x) if p == "(": s += x else: s -= x if s < 0: f = 1 if f or s != 0: print("NO") else: print("YES") ```
p01898 Taking a Seat
A: Taking a Seat-Taking a Seat- story Mr. A entered the classroom at the examination site to take an examination. However, Mr. A is a very nervous type. Therefore, depending on the situation, there may be seats that Mr. A does not want to sit in. Therefore, Mr. A decided to find out how many seats he could sit on bas...
```python m,n = map(int,input().split()) seat = [list(input()) for i in range(m)] dummy = ["0" for i in range(n+2)] for i in range(m): seat[i].insert(0,"0") seat[i].append("0") seat.insert(0,dummy) seat.append(dummy) for i in range(1,m + 1): for j in range(1,n + 1): if seat[i][j] == "o": ...
p02178 Walking
problem There are $ N $ islands numbered from $ 1 $ to $ N $. Each island has $ N-1 $ bridges, allowing any $ 2 $ island to move to each other across several bridges. Each bridge has durability, and the durability of the $ i $ th bridge given the input is $ w_i $. There are $ 1 $ treasures on each island, and you can ...
```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(...
p02321 Huge Knapsack Problem
You have N items that you want to put them into a knapsack. Item i has value vi and weight wi. You want to find a subset of items to put such that: * The total value of the items is as large as possible. * The items have combined weight at most W, that is capacity of the knapsack. Find the maximum total value of i...
```python from bisect import bisect_right def main(): N,W = map(int, input().split()) wv = [] for _ in range(N): v,w = map(int, input().split()) wv.append([w,v]) d1 = [[0,0]] d2 = [[0,0]] half = N // 2 for i in range(half): w,v = wv[i] size = len(d1) ...
p02466 Set Symmetric Difference
Find the symmetric difference of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$. Constraints * $1 \leq n, m \leq 200,000$ * $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$ * $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$ Input The input is given in the following format. $n$ $a_0 \; ...
```python n = int(input()) a = set(map(int, input().split())) m = int(input()) b = set(map(int, input().split())) s_union = a | b s_intersection = a & b ans = s_union - s_intersection if ans: print(*sorted(ans), sep="\n") ```