name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
328_B. Sheldon and Ice Pieces
Do you remember how Kai constructed the word "eternity" using pieces of ice as components? Little Sheldon plays with pieces of ice, each piece has exactly one digit between 0 and 9. He wants to construct his favourite number t. He realized that digits 6 and 9 are very similar, so he can rotate piece of ice with 6 to u...
```python def c(a, b): a = a.replace('6', '9') a = a.replace('2', '5') b = b.replace('6', '9') b = b.replace('2', '5') n = 10000 for i in '01345789': t = a.count(i) if t != 0: n = min(n, b.count(i)//t) return n a = input() b = input() print(c(a, b)) ```
34_C. Page Numbers
«Bersoft» company is working on a new version of its most popular text editor — Bord 2010. Bord, like many other text editors, should be able to print out multipage documents. A user keys a sequence of the document page numbers that he wants to print out (separates them with a comma, without spaces). Your task is to w...
```python A=[int(num) for num in input().split(',')] s_a=sorted(set(A)) prev=None string="" count=0 for i in s_a: if prev is None: prev=i string+=str(prev) count+=1 else: if i-(prev+count)==0: count+=1 else: if count>1: string+='-'+...
396_A. On Number of Decompositions into Multipliers
You are given an integer m as a product of integers a1, a2, ... an <image>. Your task is to find the number of distinct decompositions of number m into the product of n ordered positive integers. Decomposition into n products, given in the input, must also be considered in the answer. As the answer can be very large, ...
```python # Made By Mostafa_Khaled bot = True Mod = 1000000007 MAX = 33000 n = int( input() ) A = list( map( int, input().split() ) ) B = [0] * MAX bePrime = [0] * MAX; primNum = [] C = [] fac=[1] for j in range(1, MAX): fac.append( fac[-1] * j % Mod ) def calc( M, N ): return fac[M] * pow( ...
444_E. DZY Loves Planting
DZY loves planting, and he enjoys solving tree problems. DZY has a weighted tree (connected undirected graph without cycles) containing n nodes (they are numbered from 1 to n). He defines the function g(x, y) (1 ≤ x, y ≤ n) as the longest edge in the shortest path between nodes x and y. Specially g(z, z) = 0 for every...
```python n = int(input()) edges = [[int(x) for x in input().split()] for i in range(n-1)] edges = sorted(edges) use_count = [0]+[int(input()) for i in range(n)] lo,hi = 0,10000 def getpar(par,u): if par[par[u]] == par[u]: return par[u] par[u] = getpar(par,par[u]) return par[u] def unite(par,sz,use,...
467_A. George and Accommodation
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
```python c = 0 for _ in range(int(input())): n = [int(x) for x in input().split()] n,m = n[0],n[1] if m - n >= 2: c += 1 print(c) ```
48_D. Permutations
A permutation 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), (4, 3, 1), (2, 3, 4) are not. There are many tasks on permutations. Today you are going to solve one of them. Let’s imagine that somebody took...
```python def fail(): print(-1) import sys sys.exit() n = int(input()) count = (n + 1) * [ 0 ] assign = n * [ None ] for i, x in enumerate(map(int, input().split())): if x > n: fail() count[x] += 1 assign[i] = count[x] for i in range(2, n): if count[i - 1] < count[i]: fail() print(count[1]) pri...
53_B. Blog Photo
One popular blog site edits the uploaded photos like this. It cuts a rectangular area out of them so that the ratio of height to width (i.e. the height / width quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 (2x for some int...
```python from math import ceil,floor l = [] for i in range(39): l.append(2**i) h,w = map(int,input().split()) h1 = 0 w1 = 0 maxi = 0 for i in l: if i<=w: a = ceil(i*0.8) b = floor(i*1.25) if a<=h<=b: if i*h>=maxi: maxi = i * h h1 = h ...
567_D. One-Dimensional Battle Ships
Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of n square cells (that is, on a 1 × n table). At the beginning of the game Alice puts k ships on the field without telling their positions to Bob. Each ship looks as a 1 × a rectangle (that is, it occupies...
```python import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def solve(): n, k, a = mints() a += 1 m = mint() x = list(mints()) l = 0 r = m + 1 while r - l > 1: c = (l + r) // 2 b = x[:c] b.sort() last = 0 cnt = ...
610_C. Harmony Analysis
The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordinate of every vec...
```python p = [[0]] for i in range(int(input())): p = [t + t for t in p] + [[1 - q for q in t] + t for t in p] for t in p: print(''.join('+*'[q] for q in t)) ```
630_M. Turn
Vasya started working in a machine vision company of IT City. Vasya's team creates software and hardware for identification of people by their face. One of the project's know-how is a camera rotating around its optical axis on shooting. People see an eye-catching gadget — a rotating camera — come up to it to see it be...
```python import math, re, sys, string, operator, functools, fractions, collections sys.setrecursionlimit(10**7) dX= [-1, 1, 0, 0,-1, 1,-1, 1] dY= [ 0, 0,-1, 1, 1,-1,-1, 1] RI=lambda x=' ': list(map(int,input().split(x))) RS=lambda x=' ': input().rstrip().split(x) mod=int(1e9+7) eps=1e-6 ###############################...
659_E. New Reform
Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads. The President of Berland decided to make changes to the road sy...
```python import sys from math import sqrt, gcd, ceil, log # from bisect import bisect, bisect_left from collections import defaultdict, Counter, deque # from heapq import heapify, heappush, heappop input = sys.stdin.readline read = lambda: list(map(int, input().strip().split())) sys.setrecursionlimit(200000) def ma...
682_B. Alyona and Mex
Someone gave Alyona an array containing n positive integers a1, a2, ..., an. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not ...
```python import sys n = int(input()) arr = list(map(int,input().split())) arr.sort() ans = 1 for i in range(1,n+1): if arr[i-1]>=ans: ans+=1 print(ans) ```
705_A. Hulk
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
```python x = int(input()) feelings = '' for _ in range(x): if _ == x - 1: if _ % 2 != 0: feelings = feelings + 'I love it ' else: feelings = feelings + 'I hate it ' else: if _ % 2 != 0: feelings = feelings + 'I love that ' else: feelings = feelings + 'I hate that ' print(feelings) ```
727_D. T-shirts Distribution
The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this si...
```python from math import * from sys import * def conv(s): if s=="S" or s=="S\n": return 1 if s=="M" or s=="M\n": return 2 if s=="L" or s=="L\n": return 3 if s=="XL" or s=="XL\n": return 4 if s=="XXL" or s=="XXL\n": return 5 return 6 def uncon(x): if x==1: return "S" if x==2: return "M" if x=...
771_D. Bear and Company
Bear Limak prepares problems for a programming competition. Of course, it would be unprofessional to mention the sponsor name in the statement. Limak takes it seriously and he is going to change some words. To make it still possible to read, he will try to modify each word as little as possible. Limak has a string s t...
```python # http://codeforces.com/contest/771/problem/D """ DP-solution. For each state (v, k, x, v_is_last_letter) we trial a step along the v, k and x axes and check that dp[future_state] = min(dp[future_state], dp[state] + cost_of_move) Hence this implicitly reults in the one with least cost. V, K, X are arrays th...
796_D. Police Stations
Inzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own. Ruling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be pos...
```python import os, sys, bisect, copy from collections import defaultdict, Counter, deque from functools import lru_cache #use @lru_cache(None) if os.path.exists('in.txt'): sys.stdin=open('in.txt','r') if os.path.exists('out.txt'): sys.stdout=open('out.txt', 'w') # def input(): return sys.stdin.readline() def mapi(a...
888_D. Almost Identity Permutations
A permutation p of size n is an array such that every integer from 1 to n occurs exactly once in this array. Let's call a permutation an almost identity permutation iff there exist at least n - k indices i (1 ≤ i ≤ n) such that pi = i. Your task is to count the number of almost identity permutations for given numbers...
```python import math nk=input().split() n=int(nk[0]) k=int(nk[1]) L=[0]*5 L[1]=1 L[2]=(n*(n-1))//2 L[3]=(n*(n-1)*(n-2))//3 L[4]=(3*n*(n-1)*(n-2)*(n-3))//8 s=0 for i in range(0,k+1): s+=L[i] print(s) ```
911_B. Two Cakes
It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into a pieces, and the second one — into b pieces. Ivan knows that there will be n people at the celebration (including himself), so Ivan has set n plat...
```python #problem 911b n,a,b=list(map(int,input().split())) print(max(min(a//i,b//(n-i)) for i in range(1,n))) ```
95_B. Lucky Numbers
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. Fo...
```python from itertools import permutations as p def ck(num,arr): for i in arr: if i>=num: print(i) return x = input() z = len(x) if z == 1: print(47) elif z == 2 : if int(x) <= 74: arr = [47,74] ck(int(x),arr) else: print(4477) elif z == 3: ...
p02586 AtCoder Beginner Contest 175 - Picking Goods
There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i. Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, ...
```python import sys input = sys.stdin.readline R, C, k = map(int, input().split()) xs = [[0] * C for _ in range(R)] for _ in range(k): r, c, v = map(int, input().split()) xs[r - 1][c - 1] = v dp = [[[0] * (C + 1) for _ in range(R + 1)] for _ in range(4)] for i in range(R): for j in range(C): for ...
p02717 AtCoder Beginner Contest 161 - ABC Swap
We have three boxes A, B, and C, each of which contains an integer. Currently, the boxes A, B, and C contain the integers X, Y, and Z, respectively. We will now do the operations below in order. Find the content of each box afterward. * Swap the contents of the boxes A and B * Swap the contents of the boxes A and C C...
```python X, Y, Z = map(int,input().split()) print(Z, X, Y) ```
p02846 Sumitomo Mitsui Trust Bank Programming Contest 2019 - Interval Running
Takahashi and Aoki are training for long-distance races in an infinitely long straight course running from west to east. They start simultaneously at the same point and moves as follows towards the east: * Takahashi runs A_1 meters per minute for the first T_1 minutes, then runs at A_2 meters per minute for the subse...
```python t = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) x = t[0] * (a[0] - b[0]) y = x + t[1] * (a[1] - b[1]) if x*y > 0: print(0) elif x*y == 0: print('infinity') elif abs(x) % abs(y) == 0: print(2 * (abs(x) // abs(y))) else: print(2 * (abs(x) // abs(y...
p02983 AtCoder Beginner Contest 133 - Remainder Minimization 2019
You are given two non-negative integers L and R. We will choose two integers i and j such that L \leq i < j \leq R. Find the minimum possible value of (i \times j) \mbox{ mod } 2019. Constraints * All values in input are integers. * 0 \leq L < R \leq 2 \times 10^9 Input Input is given from Standard Input in the fol...
```python l,r = map(int,input().split()) r = min(r, l+4038) ans = 2018 for i in range(l,r): for j in range(l+1,r+1): if ans > i*j%2019: ans = i*j%2019 print(ans) ```
p03125 AtCoder Beginner Contest 118 - B +/- A
You are given positive integers A and B. If A is a divisor of B, print A + B; otherwise, print B - A. Constraints * All values in input are integers. * 1 \leq A \leq B \leq 20 Input Input is given from Standard Input in the following format: A B Output If A is a divisor of B, print A + B; otherwise, print B -...
```python a,b = list(map(int,input().split())) print(a+b if b%a == 0 else b-a) ```
p03267 AtCoder Beginner Contest 108 - All Your Paths are Different Lengths
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists. * The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N. * The number o...
```python #解説参照 l=int(input()) r=0 while 2**(r+1)<=l: r+=1 n=r+1 ans=[] for i in range(r): ans.append((i+1,i+2,0)) ans.append((i+1,i+2,2**i)) for t in range(n-1,0,-1): if l-2**(t-1)>=2**r: ans.append((t,n,l-2**(t-1))) l-=2**(t-1) print(n,len(ans)) for a in ans: print(*a) ```
p03425 AtCoder Beginner Contest 089 - March
There are N people. The name of the i-th person is S_i. We would like to choose three people so that the following conditions are met: * The name of every chosen person begins with `M`, `A`, `R`, `C` or `H`. * There are no multiple people whose names begin with the same letter. How many such ways are there to choo...
```python import itertools N = int(input()) # N=10^5 count={} for i in range(N): c = input()[0] count[c] = count.get(c, 0)+1 s = 0 for a,b,c in itertools.combinations("MARCH", 3): s += count.get(a,0)*count.get(b,0)*count.get(c,0) print(s) ```
p03582 CODE FESTIVAL 2017 qual B - Largest Smallest Cyclic Shift
For a string S, let f(S) be the lexicographically smallest cyclic shift of S. For example, if S = `babca`, f(S) = `ababc` because this is the smallest among all cyclic shifts (`babca`, `abcab`, `bcaba`, `cabab`, `ababc`). You are given three integers X, Y, and Z. You want to construct a string T that consists of exact...
```python a,b,c = map(int,input().split()) L = [[0] for _ in range(a)] + [[1] for _ in range(b)] + [[2] for _ in range(c)] while len(L) > 1: L[0] += L.pop() L.sort() print(''.join(('a','b','c')[i] for i in L[0])) ```
p03739 AtCoder Beginner Contest 059 - Sequence
You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one. At least how many operations are necessary to satisfy the following conditions? * For every i (1≤i≤n), the sum of the terms from the 1-st through i-...
```python n=int(input()) a=list(map(int,input().split())) u=0 s=1 x=0 y=0 for i in a: u+=i if s*u<=0: x+=1-s*u u=s s=s*(-1) s=-1 u=0 for i in a: u+=i if s*u<=0: y+=1-s*u u=s s=-1*s print(min(x,y)) ```
p03901 CODE FESTIVAL 2016 Elimination Tournament Round 2 (Parallel) - Takahashi is Missing!
Aoki is in search of Takahashi, who is missing in a one-dimentional world. Initially, the coordinate of Aoki is 0, and the coordinate of Takahashi is known to be x, but his coordinate afterwards cannot be known to Aoki. Time is divided into turns. In each turn, Aoki and Takahashi take the following actions simultaneou...
```python #!/usr/bin/env python3 import math x = int(input()) p = int(input())/100 print(math.ceil(x / 2) / p) ```
p00007 Debt Hell
Your friend who lives in undisclosed country is involved in debt. He is borrowing 100,000-yen from a loan shark. The loan shark adds 5% interest of the debt and rounds it to the nearest 1,000 above week by week. Write a program which computes the amount of the debt in n weeks. Input An integer n (0 ≤ n ≤ 100) is g...
```python import math n = int(input()) a = 100000 for _ in range(n): a *= 1.05 a = 1000 * math.ceil(a / 1000) print(a) ```
p00139 Snakes
In a world, a mysterious snake made of only letters lives. Two types of snakes are currently identified, type A and type B, but there may be other types as well. For class A, after ">'" is followed by one or more "=", "#" comes, and after the same number of "=" as before, "~" (half-width tilde) finish. Class B ends w...
```python import re SNAKE_A = re.compile(r">'(=+)#\1~") SNAKE_B = re.compile(r">\^(Q=)+~~") def answer(regex, string, output): result = regex.fullmatch(string) if result is not None: print(output) else: print("NA") for _ in range(int(input())): snake = input() if snake[1] == ...
p00272 Ticket Sales
Today is the ticket release date for Aizu Entertainment's recommended idol group "Akabeko & Koboushi". There are four types of tickets: S seat 6000 yen A seat 4000 yen B seat 3000 yen C seat 2000 yen You, the sales manager, are excitedly waiting for the launch. Finally on sale. It's selling very well! Shortly after ...
```python for i in range(4): t,n=map(int,input().split()) if t==1: print(f'{6000*n}') elif t==2: print(f'{4000*n}') elif t==3: print(f'{3000*n}') elif t==4: print(f'{2000*n}') ```
p00460 Bingo
problem In one programming contest, it is customary to play a bingo game at a social gathering after the competition. However, the bingo card used in this bingo game is a little special and is created according to the following conditions. * The Bingo card is divided into squares of N rows and N columns, and one posi...
```python import itertools while 1: n,m,s=map(int,input().split()) if n==0:break dp=[[0 for _ in range(s+1)] for _ in range(n*n+1)] dp[0][0]=1 for i,j in itertools.product(range(1,n*n+1),range(s+1)): if j>=i:dp[i][j]+=dp[i-1][j-i]+dp[i][j-i] if j-m>=1:dp[i][j]+=100000-dp[i-1][j-m-1] ...
p00650 The House of Huge Family
Mr. Dango's family has an extremely huge number of members. Once it had about 100 members, and now it has as many as population of a city. It is jokingly guessed that the member might fill this planet in the near future. Mr. Dango's family, the huge family, is getting their new house. Scale of the house is as large as...
```python # AOJ 1065 The House of Huge Family # Python3 2018.7.10 bal4u # UNION-FIND library class UnionSet: def __init__(self, nmax): self.size = [1]*nmax self.id = [i for i in range(nmax+1)] def root(self, i): while i != self.id[i]: self.id[i] = self.id[self.id[i]] i = self.id[i] return i def connec...
p00926 Shopping
Example Input 10 3 3 7 8 9 2 5 Output 23
```python import sys reader=(token for line in sys.stdin for token in line.split()) while 1: try: n=int(next(reader)) m=int(next(reader)) except: break a=[1]*(n+1) for i in range(m): c=int(next(reader))-1 d=int(next(reader))-1 for i in range(c,d): a[i]=3 print(sum(a)) ```
p01059 Gossip
Problem N idols, numbered from 1 to n in order, are lined up in a row. Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1. At time 0, m idols with numbers a1, a2, ..., am have secret i...
```python n, m = map(int, input().split()) a =list(map(int, input().split())) t = max(a[0] - 1, n - a[-1]) for i in range(1, m):t = max(t, (a[i] - a[i - 1]) // 2) print(t) ```
p01496 Bicube
Mary Thomas has a number of sheets of squared paper. Some of squares are painted either in black or some colorful color (such as red and blue) on the front side. Cutting off the unpainted part, she will have eight opened-up unit cubes. A unit cube here refers to a cube of which each face consists of one square. She is...
```python from collections import deque from string import ascii_lowercase, ascii_uppercase, digits import sys readline = sys.stdin.readline write = sys.stdout.write D = [ (1, 5, 2, 3, 0, 4), # 'U' (3, 1, 0, 5, 4, 2), # 'R' (4, 0, 2, 3, 5, 1), # 'D' (2, 1, 5, 0, 4, 3), # 'L' ] p_dice = (0, 0, 0, 1, 1, ...
p01809 Let's Solve Geometric Problems
Let's solve the geometric problem Mr. A is still solving geometric problems today. It is important to be aware of floating point errors when solving geometric problems. Floating-point error is the error caused by the rounding that occurs when representing a number in binary finite decimal numbers. For example, 0.1 in...
```python def gcd(m, n): r = m % n return gcd(n, r) if r else n p, q = map(int, input().split()) q //= gcd(p, q) x = q; y = 1; k = 2 while k*k <= x: if x % k == 0: while x % k == 0: x //= k y *= k k += 1 y *= x print(y) ```
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
```python # ノードをtupleで渡す from collections import defaultdict from heapq import * class MinCostFlow: def __init__(self): self.inf=10**9 self.to = defaultdict(dict) def add_edge(self, u, v, cap, cost): self.to[u][v]=[cap, cost] self.to[v][u]=[0, -cost] # s...source,t...sink,f...