name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
429_C. Guess the Tree
Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food. Iahub asks Iahubina: can you build a rooted tree, such that * each ...
```python def DFS(x): for i in range(x): if(Seen[i][x]): continue if(Rem[i]>=C[x]): if(Rem[i]==C[x] and len(Children[i])==0): continue Rem[i]-=C[x] Parent[x]=i Children[i].append(x) return True for i in range...
451_A. Game With Sticks
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks. An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick. In the grid shown be...
```python n,m = map(int, input().strip().split()) print("Akshat" if min(n,m)%2!=0 else "Malvika") ```
520_E. Pluses everywhere
Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no ...
```python n, k = map(int, input().split()) t = list(map(int, input())) p, d = 1, 10**9 + 7 s = 0 f = [1] * n for i in range(2, n): f[i] = (i * f[i - 1]) % d c = lambda a, b: 0 if a > b else (f[b] * pow(f[a] * f[b -a], d - 2, d)) % d if k: u = [0] * (n + 1) p = [1] * (n + 1) for i in range(n): u[i] = (p[i] * ...
548_B. Mike and Fun
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the ...
```python def score(R) : val = 0 ret = 0 for i in R : if i : val += 1 ret = max(ret, val) else : val = 0 return ret n, m, q = map(int, input().split()) A = [list(map(int, input().split())) for i in range(n)] B = [score(A[i]) for i in range(n)] for _ i...
574_D. Bear and Blocks
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample. Limak will repeat the following operation till everything is destroyed. Block is called internal if i...
```python x=int(input()) mas = list(map(int,input().split(" "))) mas2=[0]*(x) mas2[0]=1 for i in range(1,x): mas2[i]=min(mas[i],mas2[i-1]+1) mas2[-1]=1 for i in range(2,x+1): mas2[-i]=min(mas[-i],mas2[-i+1]+1, mas2[-i]) print(max(mas2)) ```
596_B. Wilbur and Array
Wilbur the pig is tinkering with arrays again. He has the array a1, a2, ..., an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai, ai + 1, ... , an or subtract 1 from all elements ai, ai + 1, ..., an. His goal is to end up with the array b1, b2, ..., bn. Of co...
```python # print("Input n") n = int(input()) # print("Input the integers") a = [int(x) for x in input().split()] answer = abs(a[0]) for i in range(1, n): answer += abs(a[i-1] - a[i]) print(answer) ```
617_D. Polyline
There are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this p...
```python """n=int(input()) x=list(map(int, input().split())) c=0 pro=1 for i in range(n): if x[i]==1: c+=1 if c==1: old=i elif c>1: new=i pro*=(new-old) old=new print(pro) """ a=list(map(int,input().split())) b=list(map(int,input().split())) c...
638_A. Home Numbers
The main street of Berland is a straight line with n houses built along it (n is an even number). The houses are located at both sides of the street. The houses with odd numbers are at one side of the street and are numbered from 1 to n - 1 in the order from the beginning of the street to the end (in the picture: from ...
```python [n, x] = list(map(int, input().split(' '))) answer = int (x % 2 == 0 and (n / 2 - x / 2 + 1) or( (x + 1) / 2)) print(answer) ```
712_A. Memory and Crow
There are n integers b1, b2, ..., bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure: * The crow sets ai initially 0. * The crow then adds bi to ai, subtracts bi + 1, adds the bi + 2 number, and so on until the n'th number. Thus, ai = bi - bi + 1 + bi...
```python n=int(input()) a=input().split() for i in range (n): a[i]=int(a[i]) a.reverse() b=[] b.append(a[0]) for i in range (n-1): b.append(a[i]+a[i+1]) b.reverse() print (" ".join(map(str, b))) ```
757_A. Gotta Catch Em' All!
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbas...
```python from collections import Counter k = Counter("Bulbasaur") r = Counter(input()) print(min([r[c] // k[c] for c in k])) ```
802_F. Marmots (hard)
Your task is the exact same as for the easy version. But this time, the marmots subtract the village's population P from their random number before responding to Heidi's request. Also, there are now villages with as few as a single inhabitant, meaning that <image>. Can you help Heidi find out whether a village follow...
```python for i in range(int(input())): a=list(map(int,input().split())) mx=max(list(map(abs,a))) std=(sum(list(map(lambda x:x*x,a)))/len(a))**0.5 print('poisson'if mx/std>2 else'uniform') ```
825_B. Five-In-a-Row
Alice and Bob play 5-in-a-row game. They have a playing field of size 10 × 10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts. In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins imm...
```python mat=[] n=10 m=10 for i in range(n): s=input() s=list(s) mat.append(s) f=0 def check(mat): for i in range(10): for j in range(10): #horizontal for k in range(5): if (i+k)>=10 or mat[i+k][j]!='X': break else: ...
847_M. Weather Tomorrow
Vasya came up with his own weather forecasting method. He knows the information about the average air temperature for each of the last n days. Assume that the average air temperature for each day is integral. Vasya believes that if the average temperatures over the last n days form an arithmetic progression, where the...
```python n=int(input()) l=list(map(int,input().split())) f=0 for i in range (2,len(l)): if l[i]==l[i-1]+(l[1]-l[0]): pass else: f=1 print(l[n-1]) break if f==0: if (l[n-1])==(l[0]+(n-1)*(l[1]-l[0])): print(l[0]+(n*(l[1]-l[0]))) else: print(l[n-1]) ```
896_B. Ithea Plays With Chtholly
This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. <image> Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right. This game ...
```python import sys n, m, c=map(int, input().split()) a=[] for i in range(n+1): a.append(0) cnt=0 while cnt<n: i=0 x=int(input()) if x*2<=c: i=1 while a[i] and a[i]<=x: i+=1 else: i=n while a[i] and a[i]>=x: i-=1 if a[i]==0: cnt+=...
93_C. Azembler
After the Search Ultimate program that searched for strings in a text failed, Igor K. got to think: "Why on Earth does my program work so slowly?" As he double-checked his code, he said: "My code contains no errors, yet I know how we will improve Search Ultimate!" and took a large book from the shelves. The book read "...
```python n=int(input()) mn=[float('inf')]*256 ans="" done=set() def gen(vals,st): global mn,ans #print(*vals) if('|'.join([str(x) for x in vals]) in done): return done.add('|'.join([str(x) for x in vals])) if(vals[-1]==n): if(len(vals)<mn[n]): mn[n]=len(vals) ...
967_A. Mind the Gap
These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts 1 minute. He was asked to insert one takeoff in the schedule. The takeoff takes 1 minute it...
```python # -*- coding: utf-8 -*- # @Date : 2019-01-30 20:41:28 # @Author : raj lath (oorja.halt@gmail.com) # @Link : link # @Version : 1.0.0 from sys import stdin max_val=int(10e12) min_val=int(-10e12) def read_int() : return int(stdin.readline()) def read_ints() : return [int(x) for x in stdin.readl...
993_A. Two Squares
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect. The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the ...
```python a=list(map(int,input().split())) b=list(map(int,input().split())) a1 = min(a[0::2]) b1 = max(a[0::2]) c1 = min(a[1::2]) d1 = max(a[1::2]) g = sum(b[0::2])/4 h = sum(b[1::2])/4 r = abs(b[0]-g) + abs(b[1]-h) for i in range(a1,b1+1) : for j in range (c1,d1+1) : if abs(i-g) + abs(j-h)<=r : ...
p02627 AtCoder Beginner Contest 171 - αlphabet
An uppercase or lowercase English letter \alpha will be given as input. If \alpha is uppercase, print `A`; if it is lowercase, print `a`. Constraints * \alpha is an uppercase (`A` - `Z`) or lowercase (`a` - `z`) English letter. Input Input is given from Standard Input in the following format: α Output If \alph...
```python c = input() print('A' if ord(c)<96 else 'a') ```
p02758 AtCoder Beginner Contest 158 - Removing Robots
There are N robots numbered 1 to N placed on a number line. Robot i is placed at coordinate X_i. When activated, it will travel the distance of D_i in the positive direction, and then it will be removed from the number line. All the robots move at the same speed, and their sizes are ignorable. Takahashi, who is a misc...
```python import sys input = sys.stdin.readline class SegmentTree(object): def __init__(self, init_array, seg_func=min, seg_func_null=10 ** 9 + 7): self.seg_func = seg_func self.seg_func_null = seg_func_null self.n = 1 while self.n < len(init_array): self.n *= 2 ...
p02893 AtCoder Grand Contest 039 - Division by Two with Something
Given are integers N and X. For each integer k between 0 and X (inclusive), find the answer to the following question, then compute the sum of all those answers, modulo 998244353. * Let us repeat the following operation on the integer k. Operation: if the integer is currently odd, subtract 1 from it and divide it by 2...
```python from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil,...
p03028 M-SOLUTIONS Programming Contest - Random Tournament
We will host a rock-paper-scissors tournament with N people. The participants are called Person 1, Person 2, \ldots, Person N. For any two participants, the result of the match between them is determined in advance. This information is represented by positive integers A_{i,j} ( 1 \leq j < i \leq N ) as follows: * If A...
```python import sys p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def SI(): return sys.stdin.readline()[:-1] def pbit(aa,L): for a in aa:print(format(a,"b").zfill(L)) print() def main(): n=II() aa=[[int(c) for c in SI()] for _ in range(n-1)] #p2D(aa) # 人i...
p03169 Educational DP Contest - Sushi
There are N dishes, numbered 1, 2, \ldots, N. Initially, for each i (1 \leq i \leq N), Dish i has a_i (1 \leq a_i \leq 3) pieces of sushi on it. Taro will perform the following operation repeatedly until all the pieces of sushi are eaten: * Roll a die that shows the numbers 1, 2, \ldots, N with equal probabilities, a...
```python n=int(input()) k=[0,0,0] a,s,d=0,0,0 for i in input().split(): if i=="1":a+=1 elif i=="2":s+=1 else:d+=1 dp=[[ [0]*(n+1) for j in range(n+1)] for i in range(n+1)] for i in range(d+1): for j in range(d+s+1): for k in range(n+1-i-j): su=i+j+k ret=0 if su: ret+=n/su ...
p03314 AtCoder Regular Contest 100 - Colorful Sequences
You are given integers N, K, and an integer sequence A of length M. An integer sequence where each element is between 1 and K (inclusive) is said to be colorful when there exists a contiguous subsequence of length K of the sequence that contains one occurrence of each integer between 1 and K (inclusive). For every co...
```python MOD = 10 ** 9 + 7 n, k, m = map(int, input().split()) a = list(map(int, input().split())) def include_perm(a): for i in range(m - k + 1): seen = [False] * (k + 1) for j in range(i, i + k): if seen[a[j]]: break seen[a[j]] = True else: ...
p03471 AtCoder Beginner Contest 085 - Otoshidama
The commonly used bills in Japan are 10000-yen, 5000-yen and 1000-yen bills. Below, the word "bill" refers to only these. According to Aohashi, he received an otoshidama (New Year money gift) envelope from his grandfather that contained N bills for a total of Y yen, but he may be lying. Determine whether such a situat...
```python n, y = map(int,input().split()) ans = [-1,-1,-1] for i in range(n+1): for j in range(n+1-i): if 10000*i + 5000*j + 1000*(n-i-j) == y: ans = [i,j,n-i-j] print(*ans) ```
p03633 AtCoder Beginner Contest 070 - Multiple Clocks
We have N clocks. The hand of the i-th clock (1≤i≤N) rotates through 360° in exactly T_i seconds. Initially, the hand of every clock stands still, pointing directly upward. Now, Dolphin starts all the clocks simultaneously. In how many seconds will the hand of every clock point directly upward again? Constraints * 1≤...
```python from fractions import gcd from functools import reduce n, *T = map(int, open(0).read().split()) print(reduce(lambda x, y:x*y//gcd(x, y), T)) ```
p03791 Mujin Programming Challenge 2017 - Robot Racing
You are developing frog-shaped robots, and decided to race them against each other. First, you placed N robots onto a number line. These robots are numbered 1 through N. The current coordinate of robot i is x_i. Here, all x_i are integers, and 0 < x_1 < x_2 < ... < x_N. You will repeatedly perform the following opera...
```python input() a=b=1 for r in input().split(): a=a*b%(10**9+7) if b*2<eval(r+'+2'):b+=1 print(a) ```
p03959 CODE FESTIVAL 2016 qual C - Two Alpinists
Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range. The mountain range consists of N mountains, extending from west to east in a straight line as Mt. 1, Mt. 2, ..., Mt. N. Mr. Takahashi traversed the range from the west and Mr. Aoki from the east. The height of Mt. i is h_i...
```python N=int(input()) T = list(map(int, input().split())) A = list(map(int, input().split())) a = 1 if T[0]>A[0] or A[-1]>T[-1] or T[-1]!=A[0]: a*=0 for i in range(1,N-1): if T[i-1]!=T[i]: if T[i]>A[i]: a*=0 break else: a*=1 elif A[i]!=A[i+...
p00051 Differential II
When you enter 8 numbers from 0 to 9, write a program that outputs the difference between the largest integer and the smallest integer that can sort the 8 numbers. The number that can be sorted may start from 0, such as 00135569. Input Given multiple datasets. The number of datasets n (n ≤ 50) is given on the first...
```python n=int(input()) for _ in range(n): c=[i for i in input()] Max=int("".join(sorted(c,reverse=True))) Min=int("".join(sorted(c))) print(Max-Min) ```
p00181 Bookshelf
Taro is addicted to a novel. The novel has n volumes in total, and each volume has a different thickness. Taro likes this novel so much that he wants to buy a bookshelf dedicated to it. However, if you put a large bookshelf in the room, it will be quite small, so you have to devise to make the width of the bookshelf as...
```python import bisect def main(): m,n = list(map(int,input().split())) if n==0: exit() W = [int(input()) for _ in range(n)] w_total = 0 w_sum =[] for w in W: w_total+=w w_sum.append(w_total) def judge(shelf_length): last_val = 0 for i in range(m):...
p00337 Road Planning
Villages were scattered in the Wakamatsu Plain of Aizu. Several settlements are connected by straight roads that allow them to travel to and from each other, and any settlement in the plain can be traced back and forth. Each road has a lengthy maintenance fee, but all the settlements funded the road to maintain it. At...
```python import sys def graham_scan(vertices: list): from math import atan2 from operator import itemgetter vertices.sort(key=itemgetter(1)) base_x, base_y = vertices[0][:2] vertices = sorted(vertices[1:], key=lambda p: atan2(p[1]-base_y, p[0]-base_x)) + vertices[:1] convex = vertices[-1:] +...
p00528 Modern Mansion
Modern Mansion You got lost in a big mansion. This mansion has a structure in which square rooms are arranged in a grid pattern from north, south, east, and west, with M columns in the east-west direction and N rows in the north-south direction, for a total of M x N. The room in the xth column (1 ≤ x ≤ M) from the wes...
```python from heapq import heappush, heappop M, N, K = map(int, input().split()) X = [[] for i in range(M)] Y = [[] for i in range(N)] for i in range(K): x, y = map(int, input().split()); x -= 1; y -= 1 X[x].append((y, i)) Y[y].append((x, i)) G0 = [[] for i in range(K)] G1 = [[] for i in range(K)] for x...
p00695 Get a Rectangular Field
Karnaugh is a poor farmer who has a very small field. He wants to reclaim wasteland in the kingdom to get a new field. But the king who loves regular shape made a rule that a settler can only get a rectangular land as his field. Thus, Karnaugh should get the largest rectangular land suitable for reclamation. The map o...
```python # AOJ 1114: Get a Rectangular Field # Python3 2018.7.8 bal4u s = [[0 for c in range(6)] for r in range(6)] for k in range(int(input())): if k > 0: input() for r in range(5): a = list(map(int, input().split())) for c in range(5): s[r+1][c+1] = s[r+1][c]+a[c] ans = 0; for r in range(1, 6): for c in r...
p00836 Sum of Consecutive prime Numbers
Some positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has three representations 2 + 3 + 5 + 7 + 11 + 13, 11 + 13 + 17, ...
```python def solve(): # making a list of prime numbers primes = [2, 3] for n in range(5, 10000, 2): l = n ** 0.5 for p in primes: if n % p == 0: break if l < p: primes.append(n) break primes = [0] + primes ...
p00968 Digits Are Not Just Characters
Digits Are Not Just Characters Mr. Manuel Majorana Minore made a number of files with numbers in their names. He wants to have a list of the files, but the file listing command commonly used lists them in an order different from what he prefers, interpreting digit sequences in them as ASCII code sequences, not as numb...
```python n = int(input()) ss = [input() for _ in range(n + 1)] sp = [[s[0]] for s in ss] for i, s in enumerate(ss): for j in range(1, len(s)): if s[j - 1].isdigit() != s[j].isdigit(): sp[i].append('') sp[i][-1] += s[j] s0 = sp[0] for s in sp[1:]: p = 0 m = min(len(s0), len(s)) ...
p01100 Gift Exchange Party
Gift Exchange Party A gift exchange party will be held at a school in TKB City. For every pair of students who are close friends, one gift must be given from one to the other at this party, but not the other way around. It is decided in advance the gift directions, that is, which student of each pair receives a gift....
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, M = map(int, readline().split()) if N == M == 0: return False G = [[] for i in range(N)] cs = [0]*N for i in range(M): u, v = map(int, readline().split()) ...
p01552 YAML
YAML (YAML Ain't Markup Language) is one of the formats for expressing an object as a character string. You will be given an object represented by a subset of YAML and a query that specifies the property, so please answer the value of the specified property. Subset of YAML A subset of YAML follows the syntax rules e...
```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+9 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 ...
p01708 Points and Lines
Problem Statement One day, you found an old scroll with strange texts on it. You revealed that the text was actually an expression denoting the position of treasure. The expression consists of following three operations: * From two points, yield a line on which the points lie. * From a point and a line, yield a poin...
```python digits = "-0123456789" def cross_point(P, Q): x0, y0, x1, y1 = P x2, y2, x3, y3 = Q dx0 = x1 - x0; dy0 = y1 - y0 dx1 = x3 - x2; dy1 = y3 - y2 s = (y0-y2)*dx1 - (x0-x2)*dy1 sm = dx0*dy1 - dy0*dx1 if s < 0: s = -s sm = -sm if s == 0: x = x0 y = y0...
p01853 Lie with Mean Value
Problem statement N first-year students of the Faculty of Information Science and Technology of R University take the final exam of the lecture called Programming Exercise 1. The test is a perfect score of m. In other words, the score that one student can get is an integer between 0 and m. Since the teacher in charge...
```python # -*- coding: utf-8 -*- (n,m)=[int(a) for a in input().split()] for i in range(n): if i:print(" ",end="") if i<=n/2: print("0",end="") else: print("{}".format(m),end="") print("") ```
p02275 Counting Sort
Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in ...
```python # 計数ソート # https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/6/ALDS1_6_A # 計算量 O(n+k) import sys input = sys.stdin.buffer.readline n = int(input()) A = [int(i) for i in input().split()] B = [None] * n C = [0] * 10001 for a in A: C[a] += 1 for i in range(10001): C[i] = C[i - 1] + C[i] for j i...
p02422 Transformation
Transformation Write a program which performs a sequence of commands to a given string $str$. The command is one of: * print a b: print from the a-th character to the b-th character of $str$ * reverse a b: reverse from the a-th character to the b-th character of $str$ * replace a b p: replace from the a-th charact...
```python str = input("") q = int(input()) for i in range(q): line = input().split() c = line[0] a = int(line[1]) b = int(line[2]) + 1 if c == 'replace': str = str[:a] + line[3] + str[b:] elif c == 'reverse': str = str[:a] + str[a:b][::-1] + str[b:] else: print(str[...
1011_D. Rocket
This is an interactive problem. Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet...
```python from sys import stdin from math import * from sys import stdout line = stdin.readline().rstrip().split() m = int(line[0]) n = int(line[1]) bits = [] for i in range(n): print(m) stdout.flush() line = stdin.readline().rstrip().split() res = int(line[0]) if res == 0: exit(0) if ...
1036_E. Covered Points
You are given n segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line. Count the number of distinct points with integer coordinates, which are covered by at least one segment. Input The first line contains a sing...
```python import sys from math import gcd class Segment: def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def dx(self): return self.x2 - self.x1 def dy(self): return self.y2 - self.y1 def pt_cnt(self)...
1059_D. Nature Reserve
There is a forest that we model as a plane and live n rare animals. Animal number i has its lair in the point (x_{i}, y_{i}). In order to protect them, a decision to build a nature reserve has been made. The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the f...
```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 ...
10_E. Greedy Change
Billy investigates the question of applying greedy algorithm to different spheres of life. At the moment he is studying the application of greedy algorithm to the problem about change. There is an amount of n coins of different face values, and the coins of each value are not limited in number. The task is to collect t...
```python __author__ = 'Darren' def solve(): n = int(input()) coins = list(map(int, input().split())) def greedy(amount): num = 0 for i in range(n): num += amount // coins[i] amount %= coins[i] return num result = 1 << 31 for i in range(1, n): ...
1121_D. Diana and Liana
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers. The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the tow...
```python def main(): m, k, n, s = map(int, input().split()) a = list(map(int, input().split())) # prevbug: input in a line! b = list(map(int, input().split())) # prevbug: convert to list b_dict = {} for x in b: b_dict.setdefault(x, 0) b_dict[x] += 1 # prevbug: b or b_dict le...
116_C. Party
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: * Employee A is the immediate manag...
```python def findDepth(a, i): depth = 1 nextLevel = a[i][:] while len(nextLevel) > 0: depth += 1 children = nextLevel[:] nextLevel = [] for child in children: nextLevel += a[child] return depth n = int(input()) a = [] for i in range(n): a.appen...
1188_B. Count Pairs
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k. Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p. Input The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime. The se...
```python def check(num1, num2, p, k): v = num1 + num2 v *= num1 * num1 + num2 * num2 v %= p v += p v %= p return v == k % p if __name__ == '__main__': n, p, k = (int(x) for x in input().split()) idx___number = [int(x) for x in input().split()] idx___precount = [((pow(x, 4, p) - k...
1207_C. Gas Pipeline
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consist...
```python import math t = int(input()) for _ in range(t): (n, a, b) = [int(x) for x in input().split()] s = input() #print((n, a, b, s)) gap = math.ceil((2 * a) / b) + 1 #print((a, b, gap)) cost = b state = 0 b2 = 2 * b streak0 = 0 for i in range(n-1): if s[i] == '1': streak0 = 0 else: streak0...
1225_D. Power Products
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100). The second line contains n integers a_1, …, a_n (1 ≤ a_...
```python from collections import defaultdict import sys as _sys def main(): n, k = _read_ints() a = tuple(_read_ints()) result = find_good_pairs_n(a, k) print(result) def _read_line(): result = _sys.stdin.readline() assert result[-1] == "\n" return result[:-1] def _read_ints(): re...
1249_F. Maximum Weight Subset
You are given a tree, which consists of n vertices. Recall that a tree is a connected undirected graph without cycles. <image> Example of a tree. Vertices are numbered from 1 to n. All vertices have weights, the weight of the vertex v is a_v. Recall that the distance between two vertices in the tree is the number o...
```python n, k = map(int, input().split()) a = list(map(int, input().split())) g = {} def dfs(v, p=-1): c = [dfs(child, v) for child in g.get(v, set()) - {p}] c.sort(key=len, reverse=True) r = [] i = 0 while c: if i >= len(c[-1]): c.pop() else: o = max(i, k - i - 1) s = q = 0 for x in c: if le...
1268_C. K Integers
You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. ...
```python import sys input = sys.stdin.buffer.readline # all operations are log(n) class bit: def __init__(self, n): self.n = n+1 self.mx_p = 0 while 1 << self.mx_p < self.n: self.mx_p += 1 self.a = [0]*(self.n) self.tot = 0 def add(self, idx, val): ...
1333_C. Eugene and an array
Eugene likes working with arrays. And today he needs your help in solving one challenging task. An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Let's call a nonempty...
```python import sys import heapq def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def rinput(): return map(int, input().split()) def rlinput(): return list(map(int, input().split())) def YES(flag): if flag: return "YES" return "NO" def main(...
1353_F. Decreasing Heights
You are playing one famous sandbox game with the three-dimensional world. The map of the world can be represented as a matrix of size n × m, where the height of the cell (i, j) is a_{i, j}. You are in the cell (1, 1) right now and want to get in the cell (n, m). You can move only down (from the cell (i, j) to the cell...
```python #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): for _ in range(int(input())): n,m=map(int,input().split()) a=[ [int(x) for x in input().split()] for _ in range(n)] if m>n: b=[ [a[j][i] for j in range(n)] for i in range(m)] ...
1373_E. Sum of Digits
Let f(x) be the sum of digits of a decimal number x. Find the smallest non-negative integer x such that f(x) + f(x + 1) + ... + f(x + k) = n. Input The first line contains one integer t (1 ≤ t ≤ 150) — the number of test cases. Each test case consists of one line containing two integers n and k (1 ≤ n ≤ 150, 0 ≤ k ...
```python def generate_prefix(su): pre = "" if su >= 8: pre += '8' su -= 8 if len(pre) > 0: nu = 9 else: nu = 8 while su > 0: while su >= nu: su -= nu pre += str(nu) nu -= 1 pre = pre[::-1] return pre def get_number(su...
1420_A. Cubes Sorting
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for? Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got ...
```python import sys import bisect input = sys.stdin.readline ins = lambda: input().rstrip() ini = lambda: int(input().rstrip()) inm = lambda: map(int, input().rstrip().split()) inl = lambda: list(map(int, input().split())) out = lambda x, s='\n': print(s.join(map(str, x))) t = ini() for _ in range(t): n = ini() ...
1463_E. Plan of Lectures
Ivan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture — formally, he wants to choose some permutation of integers from 1 to n ...
```python class Node: def __init__(self, value): self.value = value self.next = None self.prev = None def __repr__(self): if not self: return "{}()".format(self.__class__.__name__) return "{}({})".format(self.__class__.__name__, self.value) class LL: def...
148_E. Porcelain
During her tantrums the princess usually smashes some collectable porcelain. Every furious shriek is accompanied with one item smashed. The collection of porcelain is arranged neatly on n shelves. Within each shelf the items are placed in one row, so that one can access only the outermost items — the leftmost or the r...
```python #!/usr/bin/env python3 import os import sys from io import BytesIO, IOBase class FastO: def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(fd, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = lambda b: stream.write(b.encode()) ...
1512_C. A-B Palindrome
You are given a string s consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string s by '0' or '1' so that the string becomes a palindrome and has exactly a characters '0' and exactly b characters '1'. Note that each of the characters '?' is replaced independently fro...
```python import sys input = sys.stdin.readline for _ in range(int(input())): a,b=map(int,input().split()) s=list(input().rstrip()) l=len(s);question=s.count('?') f=0 for i in range(0,l//2): left=s[i];right=s[l-1-i] if left==right: if left=='0':a-=2 elif left=...
208_C. Police Station
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital — number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any d...
```python #build the graph with n cities and m roads #figure out all of the shortest paths from city 1 to city n #best=number of shortest paths (if we have police station at 1 or n) s=list(map(int,input().split())) n=s[0] m=s[1] roads=[] Adj=[] for i in range(0,n+1): roads.append([]) Adj.append([False]*(n+1))...
331_C1. The Great Julya Calendar
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar. The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: "May the Great Beaver bless you! May your chacres open ...
```python def maxx(n): l=[] while(n>0): l.append(n%10) n = int(n/10) return max(l) n =int(input()) j=0 while(n>0): n = n- maxx(n) j+=1 print(j) ```
353_C. Find Maximum
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise. For ...
```python n = int(input()) a = list(map(int, input().split())) s = input() ans = 0 sm = 0 for i in range(n): if s[i] == '1': ans = max(ans + a[i], sm) sm += a[i] print(ans) ```
377_D. Developing Game
Pavel is going to make a game of his dream. However, he knows that he can't make it on his own so he founded a development company and hired n workers of staff. Now he wants to pick n workers from the staff who will be directly responsible for developing a game. Each worker has a certain skill level vi. Besides, each ...
```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...
39_A. C*++ Calculations
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term): * expression :...
```python import re n = int(input()) v = input() f1, f2 = v.count('a++'), v.count('++a') s = [] i = 0 while i < len(v) - 2: if v[i] + v[i + 1] + v[i + 2] == '++a': s.append('b') i += 3 elif v[i] + v[i + 1] + v[i + 2] == 'a++': s.append('a') i += 3 else: if i == len(v) - 2: s.extend(v[i:]) i = len(v)...
424_B. Megacity
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city. The city of Tomsk can be represented as point on the plane with ...
```python import math #t=int(input()) #lst = list(map(int, input().strip().split(' '))) n,s = map(int, input().strip().split(' ')) l=[] for i in range(n): x,y,k = map(int, input().strip().split(' ')) l1=[] l1=[math.sqrt(x*x + y*y),k] l.append(l1) l.sort(key = lambda l: l[0]) #print(l) t=-1 f=0 for i in...
448_E. Divisors
Bizon the Champion isn't just friendly, he also is a rigorous coder. Let's define function f(a), where a is a sequence of integers. Function f(a) returns the following sequence: first all divisors of a1 go in the increasing order, then all divisors of a2 go in the increasing order, and so on till the last element of s...
```python import sys solSaved = {} solSavedPropios = {} def DivisorsN(n): key = solSaved.get(str(n)) if key == None : divisors = [] divisors2 = [] for i in range(1,int(n ** (1/2)) + 1): if n % i == 0 : if abs(i - (n/i)) < 10 ** (-7) : divisors.append(int...
46_F. Hercule Poirot Problem
Today you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books. You are not informed on what crime was committed, when and where the corpse was found and other details. We onl...
```python def solve(n,m,k,edge_list,house_members): room_sets=[i for i in range(n)] valid_move=[True for i in range(n)] room_status=[ [1<<i,0,[]] for i in range(n)] # room_status[i]->informacion de todo otro cuarto,persona y llave alcanzable para el cuarto i # room_status[i][0]->los cuartos alcanzab...
493_B. Vasya and Wrestling
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins. When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins. If the sequences of...
```python n = int(input()) a = [] b = [] for i in range(n): x = int(input()) if i == n-1: num = x if x > 0: a.append(x) else: b.append(abs(x)) sma = sum(a) smb = sum(b) if sma > smb: print("first") elif sma < smb: print("second") else: if a == b: if x > 0: ...
518_A. Vitaly and Strings
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time. During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English l...
```python def f(s): return f(s[:-1])+'a' if s[-1] == 'z'else s[:-1]+chr(ord(s[-1])+1) s = f(input()) print(('No such string', s)[s < input()]) ```
544_A. Set of Strings
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct. Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exi...
```python from sys import * k=int(input()) s=input() ee=set() for i in s: ee.add(i) if k>len(ee): print("NO") exit(0) print("YES") i=1 cur=s[0] num=k-1 ee.discard(s[0]) while i<len(s): if s[i] in ee and num: print(cur) ee.discard(s[i]) num-=1 cur=s[i] else: c...
570_C. Replacement
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this su...
```python import sys n,m = map(int,sys.stdin.readline().split()) arr = list(sys.stdin.readline()) count = cnt = 0 for i in arr: if i=='.': cnt += 1 elif cnt !=0: count += cnt-1 cnt = 0 if cnt!=0: count += cnt-1 i = m while i: x,c = sys.stdin.readline().split() x = int(x)-1 ...
592_A. PawnChess
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess». This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed...
```python __author__ = 'Suvasish' lst = [] a_row = 7 b_row = 0 b_lst = [] a_lst = [] for i in range(0, 8): lst.append(list(input())) # print(lst[i]) if 'W' in lst[i]: a_lst.append(i) if 'B' in lst[i]: b_lst.append(i) b_lst.reverse() # print('AL', a_lst) # print('BL', b_lst) _break = ...
613_D. Kingdom and its Cities
Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible. The kingdom curren...
```python import sys from collections import deque def solve(): sys.setrecursionlimit(10**6) readline = sys.stdin.readline writelines = sys.stdout.writelines N = int(readline()) G = [[] for i in range(N)] for i in range(N-1): u, v = map(int, readline().split()) G[u-1].append(v-1)...
633_D. Fibonacci-ish
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if 1. the sequence consists of at least two elements 2. f0 and f1 are arbitrary 3. fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is...
```python import random, math from copy import deepcopy as dc from bisect import bisect_left, bisect_right from collections import Counter # Function to call the actual solution def solution(li): ma = {} for i in range(len(li)): ma[li[i]] = ma.get(li[i], 0) + 1 # ma1 = dc(ma) ans = 0 # li = list(set(li)) for ...
686_B. Little Robber Girl's Zoo
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places. The robber girl was angry at first, but then she decided to arrange the animals herself. She ...
```python n = int(input()) arr = list(map(int,input().split())) check = 0 while check==0: check = 1 i = 0 while i<n-1: if arr[i]>arr[i+1]: check = 0 print(i+1,i+2) arr[i],arr[i+1] = arr[i+1],arr[i] i += 1 ```
709_A. Juicer
Kolya is going to make fresh orange juice. He has n oranges of sizes a1, a2, ..., an. Kolya will put them in the juicer in the fixed order, starting with orange of size a1, then orange of size a2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly gr...
```python """ IIIIIIIIII OOOOOOOOOOO IIIIIIIIII II OO OO II II OO OO II II OO OO II II OO OO II II OO OO II II OO OO II IIIIIIIIII OOOOOOOOOOO IIIIIIIIII """ n, b, d = map(int, input().split()) m = list(map(int, ...
753_A. Santa Claus and Candies
Santa Claus has n candies, he dreams to give them as gifts to children. What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has. Input The only line contains positive integ...
```python n=int(input()) i=1 a=[] while(n>=i): a.append(i) n-=i i+=1 a[-1]+=n print(len(a)) print(*a) ```
774_G. Perfectionist Arkadiy
Arkadiy has lots square photos with size a × a. He wants to put some of them on a rectangular wall with size h × w. The photos which Arkadiy will put on the wall must form a rectangular grid and the distances between neighboring vertically and horizontally photos and also the distances between outside rows and column...
```python def gcd(x,y): if (x%y==0): return y return gcd(y,x%y) a,h,w=input().split() a=int(a) h=int(h) w=int(w) g=gcd(h+a,w+a) if (g<a or h<a or w<a): print("-1") else: print(g/(g//a)-a) ```
81_B. Sequence Formatting
Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2 ,3,..., 10" will be corrected to...
```python # вводим строку s s, i, v = input() + ' ', 0, ' ' # перебираем строку while i < len(s): # если в строке запятая, поставить пробел после нее if s[i] == ',': v += ', ' # если в строке точки, заменить их на многоточия и пробел перед ними elif s[i] == '.': v += ('' if v[-1] == ' '...
845_E. Fire in the City
The capital of Berland looks like a rectangle of size n × m of the square blocks of same size. Fire! It is known that k + 1 blocks got caught on fire (k + 1 ≤ n·m). Those blocks are centers of ignition. Moreover positions of k of these centers are known and one of these stays unknown. All k + 1 positions are distinct...
```python import sys from collections import Counter from operator import itemgetter from heapq import heappop, heappush n, m, k = map(int, input().split()) points = [list(map(int, line.split())) for line in sys.stdin] pts_sorted_x = sorted(points) pts_sorted_y = sorted(points, key=itemgetter(1, 0)) inf = 10**9+1 OK =...
892_B. Wrath
Hands that shed innocent blood! There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li. You are g...
```python n=int(input()) l=[0]*n r=[0]*n len=list(map(int,input().split())) for i in range(n): a=max(0,i-len[i]) b=max(a,i) #print(' '.join(map(str,[i,a,b]))) l[a]+=1 r[b]+=1 ans=0 t=0 for i in range(n): t+=l[i] t-=r[i] #print('t='+str(t)) if t==0: #print('i='+str(i)) ...
914_B. Conan and Agasa play a Card Game
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it. They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all c...
```python n=int(input()) l=list(map(int,input().split())) dic={} status=True i=0 l.sort() while i<len(l): counter=0 while True: if i<len(l)-1 and l[i+1]==l[i]: i+=1 counter+=1 else: break i+=1 counter+=1 if counter%2==1: status=False ...
962_B. Students in Railway Carriage
There are n consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger. The university team for the Olympiad consists of a student-programmers and b student-athletes. Determine the largest number of students from all a+b students, which you can put in the railway carriage so t...
```python n,a,b = map(int,input().split()) s=a+b ans = 0 for t in map(len, input().split('*')): if a > b: a, b = b, a a -= min(a , (t//2)) b -= min(b , (t - (t//2))) print(s-a-b) ```
p02606 AIsing Programming Contest 2020 - Number of Multiples
How many multiples of d are there among the integers between L and R (inclusive)? Constraints * All values in input are integers. * 1 \leq L \leq R \leq 100 * 1 \leq d \leq 100 Input Input is given from Standard Input in the following format: L R d Output Print the number of multiples of d among the integers b...
```python l, r, d = map(int, input().split()) ans = (r // d) - ((l - 1) // d) print(ans) ```
p02737 AtCoder Grand Contest 043 - Giant Graph
Given are simple undirected graphs X, Y, Z, with N vertices each and M_1, M_2, M_3 edges, respectively. The vertices in X, Y, Z are respectively called x_1, x_2, \dots, x_N, y_1, y_2, \dots, y_N, z_1, z_2, \dots, z_N. The edges in X, Y, Z are respectively (x_{a_i}, x_{b_i}), (y_{c_i}, y_{d_i}), (z_{e_i}, z_{f_i}). Bas...
```python from collections import defaultdict import sys input = lambda: sys.stdin.readline().rstrip() M = 998244353 # < (1 << 30) def mod_inv(a, M=M): x1, y1, z1 = 1, 0, a x2, y2, z2 = 0, 1, M while abs(z1) != 1: d, m = divmod(z2, z1) x1, x2 = x2-d*x1, x1 y1, y2 = y2-d*y1, y1 z1, z2 = m, z1 ...
p02871 Hitachi Hokudai Labo & Hokkaido University Contest 2019-1 - Problem A
Requirements * All inputs are of non-negative integer value. * T_{\text{max}} = 10000 * 200 \leq |V| \leq 400 * 1.5 |V| \leq |E| \leq 2 |V| * 1 \leq u_{i}, v_{i} \leq |V| (1 \leq i \leq |E|) * 1 \leq d_{u_i, v_i} \leq \lceil 4\sqrt{2|V|} \rceil (1 \leq i \leq |E|) * The given graph has no self-loops / multiple edges a...
```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(...
p03006 diverta 2019 Programming Contest 2 - Picking Up
There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i). We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation: * Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates...
```python from collections import defaultdict as ddict d = ddict(int) d[0] = 0 n = int(input()) l = [tuple(map(int, input().split())) for _ in range(n)] l.sort() for i in range(n-1): for j in range(i+1,n): curx = l[j][0] - l[i][0] cury = l[j][1] - l[i][1] d[(curx,cury)] += 1 print(n-max(d.values())) ```
p03146 AtCoder Beginner Contest 116 - Collatz Problem
A sequence a=\\{a_1,a_2,a_3,......\\} is determined as follows: * The first term s is given as input. * Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd. * a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1. Find the minimum integer m that satisfies the following conditio...
```python s=int(input()) a=[] ans=1 while True: a.append(s) if s%2==0: s//=2 else: s=s*3+1 ans+=1 if s in a: print(ans) break ```
p03290 AtCoder Beginner Contest 104 - All Green
A programming competition site AtCode provides algorithmic problems. Each problem is allocated a score based on its difficulty. Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points. These p_1 + … + p_D problems are all of the problems available on AtCode. A user...
```python D,G = map(int,input().split()) PC = [0]+[list(map(int,input().split()))for i in range(D)] def f(p,c): if p==0: return 10**9 m=min(c//(p*100),PC[p][0]) s=100*p*m if m==PC[p][0]: s+=PC[p][1] if s<c: m+=f(p-1,c-s) return min(m,f(p-1,c)) print(f(D,G)) ```
p03606 AtCoder Beginner Contest 073 - Theater
Joisino is working as a receptionist at a theater. The theater has 100000 seats, numbered from 1 to 100000. According to her memo, N groups of audiences have come so far, and the i-th group occupies the consecutive seats from Seat l_i to Seat r_i (inclusive). How many people are sitting at the theater now? Constrai...
```python print(sum(1-eval(s.replace(' ','-'))for s in open(0).readlines()[1:])) ```
p03767 AtCoder Grand Contest 012 - AtCoder Group Contest
There are 3N participants in AtCoder Group Contest. The strength of the i-th participant is represented by an integer a_i. They will form N teams, each consisting of three participants. No participant may belong to multiple teams. The strength of a team is defined as the second largest strength among its members. For ...
```python N = int(input()) A = list(map(int, input().split())) A.sort() print(sum(A[N:3 * N:2])) ```
p03935 square869120Contest #3 - Sum of Fibonacci Sequence
E869120 defined a sequence $a$ like this: * $a_1=a_2=1$, $a_{k+2}=a_{k+1}+a_k \ (k \ge 1)$ He also defined sequences $d_1, d_2, d_3, \dots , d_n$, as the following recurrence relation : * $d_{1, j} = a_j$ * $d_{i, j} = \sum_{k = 1}^j d_{i - 1, k} \ (i \ge 2)$ You are given integers $n$ and $m$. Please calculate...
```python M=998244353 g=lambda a,b:[(a[0]*b[0]+a[1]*b[2])%M,(a[0]*b[1]+a[1]*b[3])%M,(a[2]*b[0]+a[3]*b[2])%M,(a[2]*b[1]+a[3]*b[3])%M] def f(n): e=[1,0,0,1];z=[1,1,1,0] while n: if n%2>0:e=g(e,z) z=g(z,z);n//=2 return e[1] n,m=map(int,input().split());I=[1,1];r=f(m+2*n-2);c=1 for i in range(2,n):I+=[(M-M//i)*I[M%i...
p00028 Mode Value
Your task is to write a program which reads a sequence of integers and prints mode values of the sequence. The mode value is the element which occurs most frequently. Input A sequence of integers ai (1 ≤ ai ≤ 100). The number of integers is less than or equals to 100. Output Print the mode values. If there are se...
```python if __name__ == '__main__': ans = dict() while True: try: n = int(input()) if n not in ans: ans[n] = 1 else: ans[n] += 1 except EOFError: break a = max(ans.values()) A = [] for d in ans: if ans[d] == a: A.append(d) B = sorted(A) for i in B: print(i) ```
p00159 The Best Body
There is BMI (Body Mass Index) as an index showing the degree of obesity. The BMI value is calculated using the following formula. BMI = weight (kg) / (height (m)) 2 The closer the BMI value is to the standard value, the more "ideal body shape" is considered. Therefore, if the standard value of BMI is 22, create a pr...
```python # from sys import exit while(True): N = int(input()) if N == 0: break L = [] for i in range(N): p, h, w = [int(n) for n in input().split()] L.append((p, abs(22- w/((h/100)**2)))) # print(abs(22- w/((h/100)**2))) L = sorted(L, key=lambda x: x[1]) print(L[...
p00316 Investigation of Club Activities
Akira, the student council president of A High School, decided to investigate which club activities the A High School students belong to. A High School has N students numbered 1 to N and M types of club activities numbered 1 to M. There is no limit to the number of people in each club activity, and there can be 0 club ...
```python n, m, k = map(int, input().split()) *parent, = range(n+m) def root(x): if x == parent[x]: return x parent[x] = root(parent[x]) return parent[x] def unite(x, y): px = root(x); py = root(y) if px < py: parent[py] = px else: parent[px] = py for i in range(k): a...
p00486 Walking Santa
At the end of last year, Santa Claus forgot to give Christmas presents to the children in JOI village. Therefore, I decided to deliver the chocolate cake to the children as an apology. The day to deliver is approaching tomorrow, so it's time to come up with a move plan. JOI village is divided into a grid shape by W ro...
```python from bisect import bisect_left as bl INF = 10 ** 20 def main(): w, h = map(int, input().split()) n = int(input()) xlst = [] ylst = [] appx = xlst.append appy = ylst.append for i in range(n): x, y = map(int,input().split()) appx(x) appy(y) sorted_xlst = sorted(xlst) sort...
p00815 Map of Ninja House
An old document says that a Ninja House in Kanazawa City was in fact a defensive fortress, which was designed like a maze. Its rooms were connected by hidden doors in a complicated manner, so that any invader would become lost. Each room has at least two doors. The Ninja House can be modeled by a graph, as shown in Fi...
```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 ...
p00946 Rearranging a Sequence
Example Input 5 3 4 2 5 Output 5 2 4 1 3
```python n, m = map(int, input().split()) E = [int(input()) for i in range(m)] s = set() E.reverse() F = [] for e in E: if e in s: continue s.add(e) F.append(e) for i in range(1, n+1): if i in s: continue F.append(i) *_,=map(print,F) ```
p01213 Repeated Subsequences
You are a treasure hunter traveling around the world. Finally, you’ve got an ancient text indicating the place where the treasure was hidden. The ancient text looks like a meaningless string of characters at first glance. Actually, the secret place is embedded as the longest repeated subsequence of the text. Well, the...
```python def lcs(x, y, pre_lcs, pre_lcs_len): pm = dict((zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ', [0] * 26))) for c in pm: for i, xc in enumerate(x): if c == xc: pm[c] |= (1 << i) V = (1 << len(x)) - 1 rec = [] for yc in y: V = ((V + (V & pm[yc])) | (V...
p01349 Ennichi
A rabbit who came to the fair found that the prize for a game at a store was a carrot cake. The rules for this game are as follows. There is a grid-like field of vertical h squares x horizontal w squares, and each block has at most one block. Each block is a color represented by one of the uppercase letters ('A'-'Z')....
```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 = 998244353 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x i...
p01531 Flick Input
A: Flick input A college student who loves 2D, commonly known as 2D, replaced his long-used Galapagos mobile phone with a smartphone. 2D, who operated the smartphone for the first time, noticed that the character input method was a little different from that of old mobile phones. On smartphones, a method called flick ...
```python flicks = { "T": "a", "L": "i", "U": "u", "R": "e", "D": "o" } buttons = { "1": "", "2": "k", "3": "s", "4": "t", "5": "n", "6": "h", "7": "m", "8": "y", "9": "r", "0": "w" } def get_word(button, flick): if button == "0" and flick == "U": ...