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 use as 9 (and vice versa). Similary, 2 and 5 work the same. There is no other pair of digits with similar effect. He called this effect "Digital Mimicry".
Sheldon favourite number is t. He wants to have as many instances of t as possible. How many instances he can construct using the given sequence of ice pieces. He can use any piece at most once.
Input
The first line contains integer t (1 ≤ t ≤ 10000). The second line contains the sequence of digits on the pieces. The length of line is equal to the number of pieces and between 1 and 200, inclusive. It contains digits between 0 and 9.
Output
Print the required number of instances.
Examples
Input
42
23454
Output
2
Input
169
12118999
Output
1
Note
This problem contains very weak pretests. | ```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 write a part of the program, responsible for «standardization» of this sequence. Your program gets the sequence, keyed by the user, as input. The program should output this sequence in format l1-r1,l2-r2,...,lk-rk, where ri + 1 < li + 1 for all i from 1 to k - 1, and li ≤ ri. The new sequence should contain all the page numbers, keyed by the user, and nothing else. If some page number appears in the input sequence several times, its appearances, starting from the second one, should be ignored. If for some element i from the new sequence li = ri, this element should be output as li, and not as «li - li».
For example, sequence 1,2,3,1,1,2,6,6,2 should be output as 1-3,6.
Input
The only line contains the sequence, keyed by the user. The sequence contains at least one and at most 100 positive integer numbers. It's guaranteed, that this sequence consists of positive integer numbers, not exceeding 1000, separated with a comma, doesn't contain any other characters, apart from digits and commas, can't end with a comma, and the numbers don't contain leading zeroes. Also it doesn't start with a comma or contain more than one comma in a row.
Output
Output the sequence in the required format.
Examples
Input
1,2,3,1,1,2,6,6,2
Output
1-3,6
Input
3,2,1
Output
1-3
Input
30,20,10
Output
10,20,30 | ```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+='-'+str(prev+count-1)+','+str(i)
else:
string+=','+str(i)
count=1
prev=i
if count>1:
string+='-'+str(prev+count-1)
print(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, print it modulo 1000000007 (109 + 7).
Input
The first line contains positive integer n (1 ≤ n ≤ 500). The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Output
In a single line print a single number k — the number of distinct decompositions of number m into n ordered multipliers modulo 1000000007 (109 + 7).
Examples
Input
1
15
Output
1
Input
3
1 1 2
Output
3
Input
2
5 7
Output
4
Note
In the second sample, the get a decomposition of number 2, you need any one number out of three to equal 2, and the rest to equal 1.
In the third sample, the possible ways of decomposing into ordered multipliers are [7,5], [5,7], [1,35], [35,1].
A decomposition of positive integer m into n ordered multipliers is a cortege of positive integers b = {b1, b2, ... bn} such that <image>. Two decompositions b and c are considered different, if there exists index i such that bi ≠ ci. | ```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( fac[N] * fac[M-N] % Mod, Mod-2,Mod ) % Mod
for j in range(2, MAX):
if bePrime[j] == 0:
primNum.append( j )
i = j
while i < MAX:
bePrime[i] = 1
i = i + j
for x in A:
tmp = x
for j in primNum:
while tmp % j == 0:
tmp /= j
B[j] += 1
if tmp > 1:
C.append( tmp )
ans = 1
for j in range(2,MAX):
if B[j] > 0:
ans = ans * calc( n + B[j] -1 , n - 1 ) % Mod
l = len( C )
for j in range(0, l ):
num= 0;
for k in range(0, l ):
if C[k] == C[j]:
num = num + 1
if k > j:
num = 0
break
if num > 0:
ans = ans * calc( n + num -1, n - 1 ) % Mod
print( str( ans % Mod ) )
# Made By Mostafa_Khaled
``` |
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 z.
For every integer sequence p1, p2, ..., pn (1 ≤ pi ≤ n), DZY defines f(p) as <image>.
DZY wants to find such a sequence p that f(p) has maximum possible value. But there is one more restriction: the element j can appear in p at most xj times.
Please, find the maximum possible f(p) under the described restrictions.
Input
The first line contains an integer n (1 ≤ n ≤ 3000).
Each of the next n - 1 lines contains three integers ai, bi, ci (1 ≤ ai, bi ≤ n; 1 ≤ ci ≤ 10000), denoting an edge between ai and bi with length ci. It is guaranteed that these edges form a tree.
Each of the next n lines describes an element of sequence x. The j-th line contains an integer xj (1 ≤ xj ≤ n).
Output
Print a single integer representing the answer.
Examples
Input
4
1 2 1
2 3 2
3 4 3
1
1
1
1
Output
2
Input
4
1 2 1
2 3 2
3 4 3
4
4
4
4
Output
3
Note
In the first sample, one of the optimal p is [4, 3, 2, 1]. | ```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,u,v):
u = getpar(par,u)
v = getpar(par,v)
par[u] = v
sz[v] += sz[u]
use[v] += use[u]
def solve(fp):
par = [i for i in range(n+1)]
sz = [1 for i in range(n+1)]
use = [use_count[i] for i in range(n+1)]
for edge in edges:
if edge[2] < fp:
unite(par,sz,use,edge[0],edge[1])
total_use = sum(use_count)
for i in range(n+1):
p = getpar(par,i)
if(p == i):
if(total_use - use[p] < sz[p]):
return False
return True
while lo < hi:
mid = (lo+hi+1)//2
if solve(mid):
lo = mid
else:
hi = mid-1
print(lo)
``` |
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 in it and the room can accommodate qi people in total (pi ≤ qi). Your task is to count how many rooms has free place for both George and Alex.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of rooms.
The i-th of the next n lines contains two integers pi and qi (0 ≤ pi ≤ qi ≤ 100) — the number of people who already live in the i-th room and the room's capacity.
Output
Print a single integer — the number of rooms where George and Alex can move in.
Examples
Input
3
1 1
2 2
3 3
Output
0
Input
3
1 10
0 10
10 10
Output
2 | ```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 several permutations (perhaps, with a different number of elements), wrote them down consecutively as one array and then shuffled the resulting array. The task is to restore the initial permutations if it is possible.
Input
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains the mixed array of n integers, divided with a single space. The numbers in the array are from 1 to 105.
Output
If this array can be split into several permutations so that every element of the array belongs to exactly one permutation, print in the first line the number of permutations. The second line should contain n numbers, corresponding to the elements of the given array. If the i-th element belongs to the first permutation, the i-th number should be 1, if it belongs to the second one, then its number should be 2 and so on. The order of the permutations’ numbering is free.
If several solutions are possible, print any one of them. If there’s no solution, print in the first line - 1.
Examples
Input
9
1 2 3 1 2 1 4 2 5
Output
3
3 1 2 1 2 2 2 3 2
Input
4
4 3 2 1
Output
1
1 1 1 1
Input
4
1 2 2 3
Output
-1
Note
In the first sample test the array is split into three permutations: (2, 1), (3, 2, 1, 4, 5), (1, 2). The first permutation is formed by the second and the fourth elements of the array, the second one — by the third, the fifth, the sixth, the seventh and the ninth elements, the third one — by the first and the eigth elements. Clearly, there are other splitting variants possible. | ```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])
print(' '.join(map(str, assign)))
``` |
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 integer x). If those rules don't indicate the size of the cut are clearly, then the way with which the cut part possesses the largest area is chosen. Of course, both sides of the cut area should be integer. If there are several answers to this problem, you should choose the answer with the maximal height.
Input
The first line contains a pair of integers h and w (1 ≤ h, w ≤ 109) which are the height and width of the uploaded photo in pixels.
Output
Print two integers which are the height and width of the cut area.
Examples
Input
2 1
Output
1 1
Input
2 2
Output
2 2
Input
5 5
Output
5 4 | ```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
w1 = i
elif b<h:
if i*b>=maxi:
maxi = i * b
h1 = b
w1 = i
elif a<h:
if i*a>=maxi:
maxi = i * a
h1 = a
w1 = i
h2 = 0
w2 = 0
w,h = h,w
maxi = 0
for i in l:
if i<=w:
a = ceil(i/(1.25))
b = floor(i/(0.8))
if i<=w:
a = ceil(i*0.8)
b = floor(i*1.25)
if a<=h<=b:
if i*h>=maxi:
maxi = i * h
h2 = h
w2 = i
elif b<h:
if i*b>=maxi:
maxi = i * b
h2 = b
w2 = i
elif a<h:
if i*a>=maxi:
maxi = i * a
h2 = a
w2 = i
w2,h2 = h2,w2
if h1*w1>h2*w2:
print(h1,w1)
elif h1*w1 == h2*w2:
if h1>h2:
print(h1,w1)
else:
print(h2,w2)
else:
print(h2,w2)
``` |
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 a sequence of a consecutive squares of the field). The ships cannot intersect and even touch each other.
After that Bob makes a sequence of "shots". He names cells of the field and Alice either says that the cell is empty ("miss"), or that the cell belongs to some ship ("hit").
But here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a "miss".
Help Bob catch Alice cheating — find Bob's first move, such that after it you can be sure that Alice cheated.
Input
The first line of the input contains three integers: n, k and a (1 ≤ n, k, a ≤ 2·105) — the size of the field, the number of the ships and the size of each ship. It is guaranteed that the n, k and a are such that you can put k ships of size a on the field, so that no two ships intersect or touch each other.
The second line contains integer m (1 ≤ m ≤ n) — the number of Bob's moves.
The third line contains m distinct integers x1, x2, ..., xm, where xi is the number of the cell where Bob made the i-th shot. The cells are numbered from left to right from 1 to n.
Output
Print a single integer — the number of such Bob's first move, after which you can be sure that Alice lied. Bob's moves are numbered from 1 to m in the order the were made. If the sought move doesn't exist, then print "-1".
Examples
Input
11 3 3
5
4 8 6 1 11
Output
3
Input
5 1 3
2
1 5
Output
-1
Input
5 1 3
1
3
Output
1 | ```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 = 0
for i in b:
if i != last:
cnt += (i-last) // a
last = i
cnt += (n+1-last)//a
if cnt < k:
r = c
else:
l = c
if r == m + 1:
r = -1
print(r)
solve()
``` |
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 vector is 1 or - 1 and any two vectors are orthogonal. Just as a reminder, two vectors in n-dimensional space are considered to be orthogonal if and only if their scalar product is equal to zero, that is:
<image>.
Danil quickly managed to come up with the solution for this problem and the teacher noticed that the problem can be solved in a more general case for 2k vectors in 2k-dimensinoal space. When Danil came home, he quickly came up with the solution for this problem. Can you cope with it?
Input
The only line of the input contains a single integer k (0 ≤ k ≤ 9).
Output
Print 2k lines consisting of 2k characters each. The j-th character of the i-th line must be equal to ' * ' if the j-th coordinate of the i-th vector is equal to - 1, and must be equal to ' + ' if it's equal to + 1. It's guaranteed that the answer always exists.
If there are many correct answers, print any.
Examples
Input
2
Output
++**
+*+*
++++
+**+
Note
Consider all scalar products in example:
* Vectors 1 and 2: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( + 1) + ( - 1)·( - 1) = 0
* Vectors 1 and 3: ( + 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) + ( - 1)·( + 1) = 0
* Vectors 1 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( - 1) + ( - 1)·( + 1) = 0
* Vectors 2 and 3: ( + 1)·( + 1) + ( - 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) = 0
* Vectors 2 and 4: ( + 1)·( + 1) + ( - 1)·( - 1) + ( + 1)·( - 1) + ( - 1)·( + 1) = 0
* Vectors 3 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( + 1)·( - 1) + ( + 1)·( + 1) = 0 | ```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 better, look into it. And the camera takes their photo at that time. What could be better for high quality identification?
But not everything is so simple. The pictures from camera appear rotated too (on clockwise camera rotation frame the content becomes rotated counter-clockwise). But the identification algorithm can work only with faces that are just slightly deviated from vertical.
Vasya was entrusted to correct the situation — to rotate a captured image so that image would be minimally deviated from vertical. Requirements were severe. Firstly, the picture should be rotated only on angle divisible by 90 degrees to not lose a bit of information about the image. Secondly, the frames from the camera are so huge and FPS is so big that adequate rotation speed is provided by hardware FPGA solution only. And this solution can rotate only by 90 degrees clockwise. Of course, one can apply 90 degrees turn several times but for the sake of performance the number of turns should be minimized.
Help Vasya implement the program that by the given rotation angle of the camera can determine the minimum number of 90 degrees clockwise turns necessary to get a picture in which up direction deviation from vertical is minimum.
The next figure contains frames taken from an unrotated camera, then from rotated 90 degrees clockwise, then from rotated 90 degrees counter-clockwise. Arrows show direction to "true up".
<image>
The next figure shows 90 degrees clockwise turn by FPGA hardware.
<image>
Input
The only line of the input contains one integer x ( - 1018 ≤ x ≤ 1018) — camera angle in degrees. Positive value denotes clockwise camera rotation, negative — counter-clockwise.
Output
Output one integer — the minimum required number of 90 degrees clockwise turns.
Examples
Input
60
Output
1
Input
-60
Output
3
Note
When the camera is rotated 60 degrees counter-clockwise (the second example), an image from it is rotated 60 degrees clockwise. One 90 degrees clockwise turn of the image result in 150 degrees clockwise total rotation and deviation from "true up" for one turn is 150 degrees. Two 90 degrees clockwise turns of the image result in 240 degrees clockwise total rotation and deviation from "true up" for two turns is 120 degrees because 240 degrees clockwise equal to 120 degrees counter-clockwise. Three 90 degrees clockwise turns of the image result in 330 degrees clockwise total rotation and deviation from "true up" for three turns is 30 degrees because 330 degrees clockwise equal to 30 degrees counter-clockwise.
From 60, 150, 120 and 30 degrees deviations the smallest is 30, and it it achieved in three 90 degrees clockwise turns. | ```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
#################################################
x=RI()[0]
x%=360
if x>180:
x=x-360
ans=0
val=abs(x)
for i in range(1,4):
x-=90
if x<-180:
x=360+x
if abs(x)<val:
val=abs(x)
ans=i
print(ans)
``` |
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 system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).
In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.
Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.
Input
The first line of the input contains two positive integers, n and m — the number of the cities and the number of roads in Berland (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000).
Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the numbers of the cities connected by the i-th road.
It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.
Output
Print a single integer — the minimum number of separated cities after the reform.
Examples
Input
4 3
2 1
1 3
4 3
Output
1
Input
5 5
2 1
1 3
2 3
2 5
4 3
Output
0
Input
6 5
1 2
2 3
4 5
4 6
5 6
Output
1
Note
In the first sample the following road orientation is allowed: <image>, <image>, <image>.
The second sample: <image>, <image>, <image>, <image>, <image>.
The third sample: <image>, <image>, <image>, <image>, <image>. | ```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 main():
n, m = read()
adj = defaultdict(list)
visited = defaultdict(int)
# visited
for i in range(m):
x, y = read()
adj[x].append(y)
adj[y].append(x)
def dfs(ver):
parent = defaultdict(int)
stk = [(ver,0)]
visited[ver] = 1
parent[ver] = 0
while stk:
node, par = stk.pop()
for child in adj[node]:
if child == par:continue
elif not visited[child]:
visited[child] = 1
parent[child] = node
stk.append((child, node))
elif parent[child] != node:
return(0)
return(1)
ans = 0
for i in range(1, n+1):
if not visited[i]:
ans += dfs(i)
# print(i, visited)
print(ans)
#
if __name__ == "__main__":
main()
``` |
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 apply any operation to the array at all.
Formally, after applying some operations Alyona will get an array of n positive integers b1, b2, ..., bn such that 1 ≤ bi ≤ ai for every 1 ≤ i ≤ n. Your task is to determine the maximum possible value of mex of this array.
Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in the Alyona's array.
The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array.
Output
Print one positive integer — the maximum possible value of mex of the array after Alyona applies some (possibly none) operations.
Examples
Input
5
1 3 3 3 6
Output
5
Input
2
2 1
Output
3
Note
In the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.
To reach the answer to the second sample case one must not decrease any of the array elements. | ```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, second one is love, third one is hate and so on...
For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.
Please help Dr. Banner.
Input
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
Output
Print Dr.Banner's feeling in one line.
Examples
Input
1
Output
I hate it
Input
2
Output
I hate that I love it
Input
3
Output
I hate that I love that I hate it | ```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 size.
During the registration, the organizers asked each of the n participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him.
Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size:
* the size he wanted, if he specified one size;
* any of the two neibouring sizes, if he specified two sizes.
If it is possible, the program should find any valid distribution of the t-shirts.
Input
The first line of the input contains six non-negative integers — the number of t-shirts of each size. The numbers are given for the sizes S, M, L, XL, XXL, XXXL, respectively. The total number of t-shirts doesn't exceed 100 000.
The second line contains positive integer n (1 ≤ n ≤ 100 000) — the number of participants.
The following n lines contain the sizes specified by the participants, one line per participant. The i-th line contains information provided by the i-th participant: single size or two sizes separated by comma (without any spaces). If there are two sizes, the sizes are written in increasing order. It is guaranteed that two sizes separated by comma are neighboring.
Output
If it is not possible to present a t-shirt to each participant, print «NO» (without quotes).
Otherwise, print n + 1 lines. In the first line print «YES» (without quotes). In the following n lines print the t-shirt sizes the orginizers should give to participants, one per line. The order of the participants should be the same as in the input.
If there are multiple solutions, print any of them.
Examples
Input
0 1 0 1 1 0
3
XL
S,M
XL,XXL
Output
YES
XL
M
XXL
Input
1 1 2 0 1 1
5
S
M
S,M
XXL,XXXL
XL,XXL
Output
NO | ```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==3:
return "L"
if x==4:
return "XL"
if x==5:
return "XXL"
return "XXXL"
s=[]
m=[]
l=[]
xl=[]
xxl=[]
sp,mp,lp,xp,xxp=0,0,0,0,0
t=[0]
t+=[int(z) for z in stdin.readline().split()]
n=int(stdin.readline())
ans=[0]*n
#print(t)
for i in range(n):
e=[conv(z) for z in stdin.readline().split(",")]
#print(e)
if len(e)==1:
ans[i]=e[0]
t[e[0]]-=1
if t[e[0]]<0:
print("NO")
exit(0)
else:
if e[0]==1:
s.append(i)
if e[0]==2:
m.append(i)
if e[0]==3:
l.append(i)
if e[0]==4:
xl.append(i)
if e[0]==5:
xxl.append(i)
while len(s)!=sp and t[1]:
ans[s[sp]]=1
sp+=1
t[1]-=1
while len(s)!=sp and t[2]:
ans[s[sp]]=2
sp+=1
t[2]-=1
if len(s)!=sp:
print("NO")
exit(0)
while len(m)!=mp and t[2]:
ans[m[mp]]=2
mp+=1
t[2]-=1
while len(m)!=mp and t[3]:
ans[m[mp]]=3
mp+=1
t[3]-=1
if len(m)!=mp:
print("NO")
exit(0)
while len(l)!=lp and t[3]:
ans[l[lp]]=3
lp+=1
t[3]-=1
while len(l)!=lp and t[4]:
ans[l[lp]]=4
lp+=1
t[4]-=1
if len(l)!=lp:
print("NO")
exit(0)
while len(xl)!=xp and t[4]:
ans[xl[xp]]=4
xp+=1
t[4]-=1
while len(xl)!=xp and t[5]:
ans[xl[xp]]=5
xp+=1
t[5]-=1
if len(xl)!=xp:
print("NO")
exit(0)
while len(xxl)!=xxp and t[5]:
ans[xxl[xxp]]=5
xxp+=1
t[5]-=1
while len(xxl)!=xxp and t[6]:
ans[xxl[xxp]]=6
xxp+=1
t[6]-=1
if len(xxl)!=xxp:
print("NO")
exit(0)
res=[uncon(z) for z in ans]
print("YES")
for i in res:
print(i)
``` |
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 that consists of uppercase English letters. In one move he can swap two adjacent letters of the string. For example, he can transform a string "ABBC" into "BABC" or "ABCB" in one move.
Limak wants to obtain a string without a substring "VK" (i.e. there should be no letter 'V' immediately followed by letter 'K'). It can be easily proved that it's possible for any initial string s.
What is the minimum possible number of moves Limak can do?
Input
The first line of the input contains an integer n (1 ≤ n ≤ 75) — the length of the string.
The second line contains a string s, consisting of uppercase English letters. The length of the string is equal to n.
Output
Print one integer, denoting the minimum possible number of moves Limak can do, in order to obtain a string without a substring "VK".
Examples
Input
4
VKVK
Output
3
Input
5
BVVKV
Output
2
Input
7
VVKEVKK
Output
3
Input
20
VKVKVVVKVOVKVQKKKVVK
Output
8
Input
5
LIMAK
Output
0
Note
In the first sample, the initial string is "VKVK". The minimum possible number of moves is 3. One optimal sequence of moves is:
1. Swap two last letters. The string becomes "VKKV".
2. Swap first two letters. The string becomes "KVKV".
3. Swap the second and the third letter. The string becomes "KKVV". Indeed, this string doesn't have a substring "VK".
In the second sample, there are two optimal sequences of moves. One is "BVVKV" → "VBVKV" → "VVBKV". The other is "BVVKV" → "BVKVV" → "BKVVV".
In the fifth sample, no swaps are necessary. | ```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 that contain the number of occurences of v, k, x at the i'th
index of s.
"""
def cost_of_move(state, ss_ind):
"""
eg. ss = s[0:K.index(k+1)]
Note: ss includes the i+1'th occurence of letter I. We hence want
ss = s[0:ss_ind-1]
And then we cound the number of occurences of V, K, X in this substring.
However, we don't need ss now - this info is contained in lists V, K, X.
"""
curr_v, curr_k, curr_x = state
cost = sum([max(0, V[ss_ind-1] - curr_v), max(0, K[ss_ind-1] - curr_k),
max(0, X[ss_ind-1] - curr_x)])
return cost
if __name__ == "__main__":
n = int(input())
s = input()
V = [s[0:i].count('V') for i in range(n+1)]
K = [s[0:i].count('K') for i in range(n+1)]
X = [(i - V[i] - K[i]) for i in range(n+1)]
# Initialising
n_v, n_k, n_x = V[n], K[n], X[n]
dp = [[[[float('Inf') for vtype in range(2)] for x in range(n_x+1)]
for k in range(n_k+1)] for v in range(n_v+1)]
dp[0][0][0][0] = 0
for v in range(n_v + 1):
for k in range(n_k + 1):
for x in range(n_x + 1):
for vtype in range(2):
orig = dp[v][k][x][vtype]
if v < n_v:
dp[v+1][k][x][1] = min(dp[v+1][k][x][vtype],
orig + cost_of_move([v, k, x], V.index(v+1)))
if k < n_k and vtype == 0:
dp[v][k+1][x][0] = min(dp[v][k+1][x][0],
orig + cost_of_move([v, k, x], K.index(k+1)))
if x < n_x:
dp[v][k][x+1][0] = min(dp[v][k][x+1][0],
orig + cost_of_move([v, k, x], X.index(x+1)))
print(min(dp[n_v][n_k][n_x]))
``` |
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 possible to reach a police station by traveling at most d kilometers along the roads.
<image>
There are n cities in the country, numbered from 1 to n, connected only by exactly n - 1 roads. All roads are 1 kilometer long. It is initially possible to travel from a city to any other city using these roads. The country also has k police stations located in some cities. In particular, the city's structure satisfies the requirement enforced by the previously mentioned law. Also note that there can be multiple police stations in one city.
However, Zane feels like having as many as n - 1 roads is unnecessary. The country is having financial issues, so it wants to minimize the road maintenance cost by shutting down as many roads as possible.
Help Zane find the maximum number of roads that can be shut down without breaking the law. Also, help him determine such roads.
Input
The first line contains three integers n, k, and d (2 ≤ n ≤ 3·105, 1 ≤ k ≤ 3·105, 0 ≤ d ≤ n - 1) — the number of cities, the number of police stations, and the distance limitation in kilometers, respectively.
The second line contains k integers p1, p2, ..., pk (1 ≤ pi ≤ n) — each denoting the city each police station is located in.
The i-th of the following n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities directly connected by the road with index i.
It is guaranteed that it is possible to travel from one city to any other city using only the roads. Also, it is possible from any city to reach a police station within d kilometers.
Output
In the first line, print one integer s that denotes the maximum number of roads that can be shut down.
In the second line, print s distinct integers, the indices of such roads, in any order.
If there are multiple answers, print any of them.
Examples
Input
6 2 4
1 6
1 2
2 3
3 4
4 5
5 6
Output
1
5
Input
6 3 2
1 5 6
1 2
1 3
1 4
1 5
5 6
Output
2
4 5
Note
In the first sample, if you shut down road 5, all cities can still reach a police station within k = 4 kilometers.
In the second sample, although this is the only largest valid set of roads that can be shut down, you can print either 4 5 or 5 4 in the second line. | ```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(arg=0): return map(int if arg==0 else str,input().split())
#------------------------------------------------------------------
n,k,d = mapi()
plc = list(mapi())
gr = defaultdict(list)
for i in range(1,n):
u,v = mapi()
gr[u].append([v,i])
gr[v].append([u,i])
q = deque()
for i in plc:
q.append((i,0))
vis = {}
res = [0]*(n+1)
while q:
tmp,par = q.popleft()
if tmp in vis:
continue
vis[tmp] = 1
for item in gr[tmp]:
if item[0] != par:
if item[0] in vis:
res[item[1]] = 1
else:
q.append((item[0],tmp))
cnt = 0
ans = []
for i in range(1,n+1):
if res[i]==1:
cnt+=1
ans.append(i)
print(cnt)
print(*ans)
``` |
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 n and k.
Input
The first line contains two integers n and k (4 ≤ n ≤ 1000, 1 ≤ k ≤ 4).
Output
Print the number of almost identity permutations for given n and k.
Examples
Input
4 1
Output
1
Input
4 2
Output
7
Input
5 3
Output
31
Input
5 4
Output
76 | ```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 plates for the cakes. Now he is thinking about how to distribute the cakes between the plates. Ivan wants to do it in such a way that all following conditions are met:
1. Each piece of each cake is put on some plate;
2. Each plate contains at least one piece of cake;
3. No plate contains pieces of both cakes.
To make his guests happy, Ivan wants to distribute the cakes in such a way that the minimum number of pieces on the plate is maximized. Formally, Ivan wants to know the maximum possible number x such that he can distribute the cakes according to the aforementioned conditions, and each plate will contain at least x pieces of cake.
Help Ivan to calculate this number x!
Input
The first line contains three integers n, a and b (1 ≤ a, b ≤ 100, 2 ≤ n ≤ a + b) — the number of plates, the number of pieces of the first cake, and the number of pieces of the second cake, respectively.
Output
Print the maximum possible number x such that Ivan can distribute the cake in such a way that each plate will contain at least x pieces of cake.
Examples
Input
5 2 3
Output
1
Input
4 7 10
Output
3
Note
In the first example there is only one way to distribute cakes to plates, all of them will have 1 cake on it.
In the second example you can have two plates with 3 and 4 pieces of the first cake and two plates both with 5 pieces of the second cake. Minimal number of pieces is 3. | ```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. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.
One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n.
Input
The only line contains a positive integer n (1 ≤ n ≤ 10100000). This number doesn't have leading zeroes.
Output
Output the least super lucky number that is more than or equal to n.
Examples
Input
4500
Output
4747
Input
47
Output
47 | ```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:
print(4477)
elif z == 4:
if int(x) <= 7744:
arr4 = sorted([int("".join(i)) for i in p("4477")])
ck(int(x),arr4)
else:
print(444777)
elif z == 5:
print(444777)
elif z == 6:
if int(x) <= 777444:
arr6 = sorted([int("".join(i)) for i in p("444777")])
ck(int(x),arr6)
else:
print(44447777)
elif z ==7:
print(44447777)
elif z==8:
if int(x)<=77774444:
arr8 = sorted([int("".join(i)) for i in p("44447777")])
ck(int(x),arr8)
else:
print(4444477777)
else:
print(4444477777)
``` |
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, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).
He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.
Find the maximum possible sum of the values of items he picks up.
Constraints
* 1 \leq R, C \leq 3000
* 1 \leq K \leq \min(2 \times 10^5, R \times C)
* 1 \leq r_i \leq R
* 1 \leq c_i \leq C
* (r_i, c_i) \neq (r_j, c_j) (i \neq j)
* 1 \leq v_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K
Output
Print the maximum possible sum of the values of items Takahashi picks up.
Examples
Input
2 2 3
1 1 3
2 1 4
1 2 5
Output
8
Input
2 5 5
1 1 3
2 4 20
1 2 1
1 3 4
1 4 2
Output
29
Input
4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10
Output
142 | ```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 k in range(2, -1, -1):
dp[k + 1][i][j] = max(dp[k + 1][i][j], dp[k][i][j] + xs[i][j])
for k in range(4):
dp[k][i][j + 1] = max(dp[k][i][j + 1], dp[k][i][j])
dp[0][i + 1][j] = max(dp[0][i + 1][j], dp[k][i][j])
ans = 0
for k in range(4):
ans = max(ans, dp[k][R - 1][C - 1])
print(ans)
``` |
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
Constraints
* 1 \leq X,Y,Z \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y Z
Output
Print the integers contained in the boxes A, B, and C, in this order, with space in between.
Examples
Input
1 2 3
Output
3 1 2
Input
100 100 100
Output
100 100 100
Input
41 59 31
Output
31 41 59 | ```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 subsequent T_2 minutes, and alternates between these two modes forever.
* Aoki runs B_1 meters per minute for the first T_1 minutes, then runs at B_2 meters per minute for the subsequent T_2 minutes, and alternates between these two modes forever.
How many times will Takahashi and Aoki meet each other, that is, come to the same point? We do not count the start of the run. If they meet infinitely many times, report that fact.
Constraints
* 1 \leq T_i \leq 100000
* 1 \leq A_i \leq 10^{10}
* 1 \leq B_i \leq 10^{10}
* A_1 \neq B_1
* A_2 \neq B_2
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
T_1 T_2
A_1 A_2
B_1 B_2
Output
Print the number of times Takahashi and Aoki will meet each other.
If they meet infinitely many times, print `infinity` instead.
Examples
Input
1 2
10 10
12 4
Output
1
Input
100 1
101 101
102 1
Output
infinity
Input
12000 15700
3390000000 3810000000
5550000000 2130000000
Output
113 | ```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)) + 1)
``` |
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 following format:
L R
Output
Print the minimum possible value of (i \times j) \mbox{ mod } 2019 when i and j are chosen under the given condition.
Examples
Input
2020 2040
Output
2
Input
4 5
Output
20 | ```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 - A.
Examples
Input
4 12
Output
16
Input
8 20
Output
12
Input
1 1
Output
2 | ```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 of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1 | ```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 choose three people, disregarding order?
Note that the answer may not fit into a 32-bit integer type.
Constraints
* 1 \leq N \leq 10^5
* S_i consists of uppercase English letters.
* 1 \leq |S_i| \leq 10
* S_i \neq S_j (i \neq j)
Input
Input is given from Standard Input in the following format:
N
S_1
:
S_N
Output
If there are x ways to choose three people so that the given conditions are met, print x.
Examples
Input
5
MASHIKE
RUMOI
OBIRA
HABORO
HOROKANAI
Output
2
Input
4
ZZ
ZZZ
Z
ZZZZZZZZZZ
Output
0
Input
5
CHOKUDAI
RNG
MAKOTO
AOKI
RINGO
Output
7 | ```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 exactly X `a`s, exactly Y `b`s, and exactly Z `c`s. If there are multiple such strings, you want to choose one that maximizes f(T) lexicographically.
Compute the lexicographically largest possible value of f(T).
Constraints
* 1 \leq X + Y + Z \leq 50
* X, Y, Z are non-negative integers.
Input
Input is given from Standard Input in the following format:
X Y Z
Output
Print the answer.
Examples
Input
2 2 0
Output
abab
Input
1 1 1
Output
acb | ```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-th term is not zero.
* For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.
Constraints
* 2 ≤ n ≤ 10^5
* |a_i| ≤ 10^9
* Each a_i is an integer.
Input
Input is given from Standard Input in the following format:
n
a_1 a_2 ... a_n
Output
Print the minimum necessary count of operations.
Examples
Input
4
1 -3 1 0
Output
4
Input
5
3 -6 4 -5 7
Output
0
Input
6
-1 4 3 2 -5 4
Output
8 | ```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 simultaneously:
* Let the current coordinate of Aoki be a, then Aoki moves to a coordinate he selects from a-1, a and a+1.
* Let the current coordinate of Takahashi be b, then Takahashi moves to the coordinate b-1 with probability of p percent, and moves to the coordinate b+1 with probability of 100-p percent.
When the coordinates of Aoki and Takahashi coincide, Aoki can find Takahashi. When they pass by each other, Aoki cannot find Takahashi.
Aoki wants to minimize the expected number of turns taken until he finds Takahashi. Find the minimum possible expected number of turns.
Constraints
* 1 ≦ x ≦ 1,000,000,000
* 1 ≦ p ≦ 100
* x and p are integers.
Input
The input is given from Standard Input in the following format:
x
p
Output
Print the minimum possible expected number of turns. The output is considered correct if the absolute or relative error is at most 10^{-6}.
Examples
Input
3
100
Output
2.0000000
Input
6
40
Output
7.5000000
Input
101
80
Output
63.7500000 | ```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 given in a line.
Output
Print the amout of the debt in a line.
Example
Input
5
Output
130000 | ```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 with "~~" after "> ^" followed by one or more "Q =".
Example of type A:>'==== # ==== ~>'== # == ~
Example of B type:> ^ Q = Q = Q = Q = ~~> ^ Q = Q = ~~
Receives a snake as character string data, determines what kind it is, and outputs "A" for type A, "B" for type B, and "NA" for other types. Please create a program to do.
Input
The input is given in the following format:
n
S1
S2
::
Sn
The number of snakes identified on the first line n (1 ≤ n ≤ 10000), and the following n lines contain the i-th snake string Si (200 characters or less, without spaces) on each line. Is given to.
Output
Print the i-th snake type A, B or NA on line i.
Example
Input
3
>'======#======~
>^Q=Q=Q=Q=Q=Q=Q=Q=Q=~~
>'===#====~
Output
A
B
NA | ```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] == "'":
answer(SNAKE_A, snake, "A")
else:
answer(SNAKE_B, snake, "B")
``` |
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 the launch, I received a table summarizing the orders up to that point. Each row of the table shows the type and number of tickets sold so far. However, the ticket types do not always appear in the order of S, A, B, C. Create a program to find the sales amount for each row in this table.
input
Input data is given in the following format.
t1 n1
t2 n2
t3 n3
t4 n4
The input consists of 4 lines. Line i is given the integer ti (1 ≤ ti ≤ 4) for the ticket type and the integer ni (0 ≤ ni ≤ 10000) for the number of tickets. The integers 1, 2, 3, and 4 representing the ticket types represent S seats, A seats, B seats, and C seats, respectively. Numbers from 1 to 4 always appear once as values for t1, t2, t3, and t4, but they are not always given in the order of 1, 2, 3, 4.
output
Output the sales amount for each line.
Example
Input
3 10
1 4
4 1
2 5
Output
30000
24000
2000
20000 | ```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 positive integer is written in each square. All those integers are different.
* The integer written in the square is 1 or more and M or less.
* The sum of N × N integers written on the Bingo card is S.
* When looking at any column, the integers are arranged in ascending order from top to bottom.
* The integer in every square is larger than any integer in the column to the left of that square.
The following is an example of a Bingo card when N = 5, M = 50, S = 685.
<image>
I want to make as many bingo cards as possible that meet the above conditions for the social gathering. However, you must not make more than one same card. Create a program that outputs the remainder of the maximum number of Bingo cards that can be created divided by 100000.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input consists of one line, which contains the size of the bingo card N (1 ≤ N ≤ 7), the upper limit of the integers written in the square M (1 ≤ M ≤ 2000), and the bingo card. Three positive integers representing the sum of integers S (1 ≤ S ≤ 3000) are written separated by blanks. However, you can make one or more bingo cards that meet the conditions for any given input data.
When N, M, S is 0, it indicates the end of input. The number of data sets does not exceed 5.
output
For each dataset, divide the maximum number of Bingo cards that can be created by 100000 and output the remainder on one line.
Examples
Input
3 9 45
3 100 50
5 50 685
0 0 0
Output
1
7
74501
Input
None
Output
None | ```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]
dp[i][j]%=100000
print(dp[n*n][s])
``` |
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 that of town.
They all had warm and gracious personality and were close each other. However, in this year the two members of them became to hate each other. Since the two members had enormous influence in the family, they were split into two groups.
They hope that the two groups don't meet each other in the new house. Though they are in the same building, they can avoid to meet each other by adjusting passageways.
Now, you have a figure of room layout. Your task is written below.
You have to decide the two groups each room should belong to. Besides you must make it impossible that they move from any rooms belonging to one group to any rooms belonging to the other group. All of the rooms need to belong to exactly one group. And any group has at least one room.
To do the task, you can cancel building passageway. Because the house is under construction, to cancel causes some cost. You'll be given the number of rooms and information of passageway. You have to do the task by the lowest cost.
Please answer the lowest cost.
By characteristics of Mr. Dango's family, they move very slowly. So all passageways are escalators. Because of it, the passageways are one-way.
Constraints
* 2 ≤ n ≤ 100
* -10,000 ≤ Ci ≤ 10,000
* Y1 ... Ym can't be duplicated integer by each other.
Input
The input consists of multiple datasets. Each dataset is given in the following format.
n m
X1 Y1 C1
...
Xm Ym Cm
All numbers in each datasets are integers. The integers in each line are separated by a space.
The first line of each datasets contains two integers. n is the number of rooms in the house, m is the number of passageways in the house. Each room is indexed from 0 to n-1.
Each of following m lines gives the details of the passageways in the house. Each line contains three integers. The first integer Xi is an index of the room, the starting point of the passageway. The second integer Yi is an index of the room, the end point of the passageway. The third integer Ci is the cost to cancel construction of the passageway. The passageways, they are escalators, are one-way. The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset, print the lowest cost in a line. You may assume that the all of integers of both the answers and the input can be represented by 32 bits signed integers.
Example
Input
3 2
0 1 2
1 2 1
2 1
0 1 100
2 1
0 1 0
2 1
0 1 -1
0 0
Output
1
100
0
-1 | ```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 connected(self, p, q): return self.root(p) == self.root(q)
def unite(self, p, q):
i, j = self.root(p), self.root(q)
if i == j: return
if self.size[i] < self.size[j]:
self.id[i] = j
self.size[j] += self.size[i]
else:
self.id[j] = i
self.size[i] += self.size[j]
# UNION-FIND library
while True:
n, m = map(int, input().split())
if n == 0: break
u = UnionSet(n)
ans, tbl = 0, []
for i in range(m):
x, y, c = map(int, input().split())
if c < 0: ans += c
else: tbl.append((c, x, y))
tbl.sort(reverse=True)
for c, x, y in tbl:
if not u.connected(x, y):
if n > 2:
n -= 1
u.unite(x, y)
else: ans += c
print(ans)
``` |
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 information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | ```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 going to build those eight unit cubes with the front side exposed and then a bicube with them. A bicube is a cube of the size 2 × 2 × 2, consisting of eight unit cubes, that satisfies the following conditions:
* faces of the unit cubes that comes to the inside of the bicube are all black;
* each face of the bicube has a uniform colorful color; and
* the faces of the bicube have colors all different.
Your task is to write a program that reads the specification of a sheet of squared paper and decides whether a bicube can be built with the eight unit cubes resulting from it.
Input
The input contains the specification of a sheet. The first line contains two integers H and W, which denote the height and width of the sheet (3 ≤ H, W ≤ 50). Then H lines follow, each consisting of W characters. These lines show the squares on the front side of the sheet. A character represents the color of a grid: alphabets and digits ('A' to 'Z', 'a' to 'z', '0' to '9') for colorful squares, a hash ('#') for a black square, and a dot ('.') for an unpainted square. Each alphabet or digit denotes a unique color: squares have the same color if and only if they are represented by the same character.
Each component of connected squares forms one opened-up cube. Squares are regarded as connected when they have a common edge; those just with a common vertex are not.
Output
Print "Yes" if a bicube can be built with the given sheet; "No" otherwise.
Examples
Input
3 40
.a....a....a....a....f....f....f....f...
#bc#.#cd#.#de#.#eb#.#cb#.#dc#.#ed#.#be#.
.#....#....#....#....#....#....#....#...
Output
Yes
Input
3 40
.a....a....a....a....f....f....f....f...
bc#.#cd#.#de#.#eb#.#cb#.#dc#.#ed#.#be#.
.#....#....#....#....#....#....#....#...
Output
Yes
Input
5 35
.a....a....a....a....f....f....f...
bc#.#cd#.#de#.#eb#.#cb#.#dc#.#ed#.
.#..f.#....#....#....#....#....#...
..e##..............................
.b#................................
Output
Yes
Input
3 40
.a....a....a....a....f....f....f....f...
bc#.#cd#.#de#.#eb#.#cb#.#dc#.#ed#.#eb#.
.#....#....#....#....#....#....#....#...
Output
No | ```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, 2, 2, 3)*3
ss = digits + ascii_uppercase + ascii_lowercase
L = len(ss)
def rotate_dice(L, k):
return [L[e] for e in D[k]]
def enumerate_dice(L0):
L = L0[:]
for k in p_dice:
yield L
L[:] = (L[e] for e in D[k])
def dice_graph(L0 = [0, 1, 2, 3, 4, 5]):
DA = list(map(tuple, enumerate_dice(L0)))
DM = {tuple(e): i for i, e in enumerate(DA)}
G = [list(DM[tuple(rotate_dice(ds, i))] for i in range(4)) for ds in DA]
return DA, G
def solve():
H, W = map(int, readline().split())
S = [readline().strip() for i in range(H)]
DA, DG = dice_graph()
dd = ((0, -1), (1, 0), (0, 1), (-1, 0))
DS = []
used = [[0]*W for i in range(H)]
for i in range(H):
for j in range(W):
if S[i][j] == '.' or used[i][j]:
continue
D = [0]*6
que = deque([(j, i, 0)])
used[i][j] = 1
while que:
x, y, k = que.popleft()
v = DA[k][0]
c = S[y][x]
if c == '#':
D[v] = L
else:
D[v] = ss.index(c)
for e, (dx, dy) in enumerate(dd):
nx = x + dx; ny = y + dy
if not 0 <= nx < W or not 0 <= ny < H or S[ny][nx] == '.' or used[ny][nx]:
continue
used[ny][nx] = 1
que.append((nx, ny, DG[k][e]))
if D.count(L) != 3:
continue
for e in enumerate_dice(D):
if e[3] == e[4] == e[5] == L:
if e[0] != e[1] and e[1] != e[2] and e[2] != e[0]:
DS.append(e[:3])
break
P = [
[0, 3, 4],
[0, 2, 3],
[0, 1, 2],
[0, 4, 1],
[3, 2, 5],
[2, 1, 5],
[1, 4, 5],
[4, 3, 5],
]
DS.sort()
M = len(DS)
def dfs(i, used, used_c, state):
if i == 8:
return 1
ps = P[i]
s = [0]*3
for j in range(M):
if used[j]:
continue
used[j] = 1
d = DS[j]
for b in range(3):
for k in range(3):
p = ps[k]
if state[p] == -1:
if used_c[d[-b+k]]:
break
else:
if state[p] != d[-b+k]:
break
else:
for k in range(3):
p = ps[k]
if state[p] == -1:
used_c[d[-b+k]] = 1
s[k], state[p] = state[p], d[-b+k]
if dfs(i+1, used, used_c, state):
return 1
for k in range(3):
p = ps[k]
state[p] = s[k]
if state[p] == -1:
used_c[d[-b+k]] = 0
used[j] = 0
return 0
if M >= 8 and dfs(0, [0]*M, [0]*L, [-1]*6):
write("Yes\n")
else:
write("No\n")
solve()
``` |
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 decimal is an infinite decimal number of 0.00011001100110011 ... in binary, but an error occurs when rounding this to a finite number of digits.
Positive integers p and q are given in decimal notation. Find the b-ary system (b is an integer greater than or equal to 2) so that the rational number p / q can be expressed as a decimal number with a finite number of digits. If there are more than one, output the smallest one.
Constraints
* 0 <p <q <10 ^ 9
Input Format
Input is given from standard input in the following format.
p q
Output Format
Print the answer in one line.
Sample Input 1
1 2
Sample Output 1
2
1/2 is binary 0.1
Sample Input 2
21 30
Sample Output 2
Ten
21/30 is 0.7 in decimal
Example
Input
1 2
Output
2 | ```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...flow
# これが本体
def cal(self,s,t,f):
min_cost=0
pot=defaultdict(int)
while f:
dist = {}
pre_u={} # 最短距離の遷移元の頂点
# ダイクストラで最短距離を求める
hp=[]
heappush(hp,(0,s))
dist[s]=0
while hp:
d,u=heappop(hp)
if d>dist[u]:continue
for v,[cap,cost] in self.to[u].items():
if cap==0:continue
nd=dist[u]+cost+pot[u]-pot[v]
dist.setdefault(v, self.inf)
if nd>=dist[v]:continue
dist[v]=nd
pre_u[v]=u
heappush(hp,(nd,v))
# sinkまで届かなかったら不可能ということ
if t not in dist:return -1
# ポテンシャルを更新する
for u,d in dist.items():pot[u]+=d
# パスs-t上で最小の容量=流す量を求める
u=t
min_cap=f
while u!=s:
u,v=pre_u[u],u
min_cap=min(min_cap,self.to[u][v][0])
# フローから流す量を減らし、コストを加える
f-=min_cap
min_cost+=min_cap*pot[t]
# パスs-tの容量を更新する
u=t
while u!=s:
u,v=pre_u[u],u
self.to[u][v][0]-=min_cap
self.to[v][u][0]+=min_cap
return min_cost
def main():
n,m,f=map(int,input().split())
mc=MinCostFlow()
for _ in range(m):
u,v,c,d=map(int,input().split())
mc.add_edge(u,v,c,d)
print(mc.cal(0,n-1,f))
main()
``` |
Subsets and Splits