index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
1,500 | 8 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.
Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy:
* Each piece should contain at least l numbers.
* The difference between the maximal and the minimal number on the piece should be at most s.
Please help Alexandra to find the minimal number of pieces meeting the condition above.
Input
The first line contains three space-separated integers n, s, l (1 β€ n β€ 105, 0 β€ s β€ 109, 1 β€ l β€ 105).
The second line contains n integers ai separated by spaces ( - 109 β€ ai β€ 109).
Output
Output the minimal number of strip pieces.
If there are no ways to split the strip, output -1.
Examples
Input
7 2 2
1 3 1 2 4 1 2
Output
3
Input
7 2 2
1 100 1 100 1 100 1
Output
-1
Note
For the first sample, we can split the strip into 3 pieces: [1, 3, 1], [2, 4], [1, 2].
For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | def split(a,n,s,l):
pieces = []
i = 1
tmpmin = a[0]
tmpmax = a[0]
tmppc = [a[0]]
while i<n:
if abs(a[i]-tmpmin)<=s and abs(a[i]-tmpmax)<=s:
tmppc.append(a[i])
if a[i]<tmpmin: tmpmin=a[i]
elif a[i]>tmpmax: tmpmax = a[i]
else:
pieces.append(tmppc)
tmppc = [a[i]]
tmpmin = a[i]
tmpmax = a[i]
i += 1
pieces.append(tmppc)
fail = False
for j in range(len(pieces)):
if len(pieces[j])<l:
if j>0:
prevpc = pieces[j-1]
minj = min(pieces[j])
maxj = max(pieces[j])
while len(pieces[j])<l:
tmp = prevpc.pop()
if abs(tmp-minj)<=s and abs(tmp-maxj)<=s:
pieces[j].insert(0,tmp)
if tmp<minj: minj=tmp
elif tmp>maxj: maxj=tmp
else:
return -1
if len(prevpc)<l:
return -1
else:
return -1
return len(pieces)
n,s,l = [int(s) for s in input().split()]
a = [int(s) for s in input().split()]
res = split(a,n,s,l)
if res<0:
a.reverse()
res = split(a,n,s,l)
print(res)
| {
"input": [
"7 2 2\n1 100 1 100 1 100 1\n",
"7 2 2\n1 3 1 2 4 1 2\n"
],
"output": [
"-1\n",
"3\n"
]
} |
1,501 | 7 | Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1, m), then goes down 2 rows to (3, m), then goes left to (3, 1) and so on.
Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').
Consider sample tests in order to understand the snake pattern.
Input
The only line contains two integers: n and m (3 β€ n, m β€ 50).
n is an odd number.
Output
Output n lines. Each line should contain a string consisting of m characters. Do not output spaces.
Examples
Input
3 3
Output
###
..#
###
Input
3 4
Output
####
...#
####
Input
5 3
Output
###
..#
###
#..
###
Input
9 9
Output
#########
........#
#########
#........
#########
........#
#########
#........
######### | def main():
n,m=map(int,input().split())
a='#'*m
b='.'*(m-1)+'#'
c=a
d='#'*1+'.'*(m-1)
for i in range(n):
print(a)
a,b,c,d=b,c,d,a
main()
| {
"input": [
"9 9\n",
"5 3\n",
"3 3\n",
"3 4\n"
],
"output": [
"#########\n........#\n#########\n#........\n#########\n........#\n#########\n#........\n#########\n",
"###\n..#\n###\n#..\n###\n",
"###\n..#\n###\n",
"####\n...#\n####\n"
]
} |
1,502 | 8 | Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
<image>
The problem is:
You are given a lucky number n. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
If we sort all lucky numbers in increasing order, what's the 1-based index of n?
Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.
Input
The first and only line of input contains a lucky number n (1 β€ n β€ 109).
Output
Print the index of n among all lucky numbers.
Examples
Input
4
Output
1
Input
7
Output
2
Input
77
Output
6 | def main():
s = input()
ans = 1
for c in s:
ans = ans * 2 + (c == '7')
print(ans - 1)
main() | {
"input": [
"4\n",
"77\n",
"7\n"
],
"output": [
"1",
"6",
"2"
]
} |
1,503 | 7 | Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special β it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.
The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.
Input
The first line of input contains two integers n and s (1 β€ n β€ 100, 1 β€ s β€ 1000) β the number of passengers and the number of the top floor respectively.
The next n lines each contain two space-separated integers fi and ti (1 β€ fi β€ s, 1 β€ ti β€ 1000) β the floor and the time of arrival in seconds for the passenger number i.
Output
Print a single integer β the minimum amount of time in seconds needed to bring all the passengers to floor 0.
Examples
Input
3 7
2 1
3 8
5 2
Output
11
Input
5 10
2 77
3 33
8 21
9 12
10 64
Output
79
Note
In the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:
1. Move to floor 5: takes 2 seconds.
2. Pick up passenger 3.
3. Move to floor 3: takes 2 seconds.
4. Wait for passenger 2 to arrive: takes 4 seconds.
5. Pick up passenger 2.
6. Go to floor 2: takes 1 second.
7. Pick up passenger 1.
8. Go to floor 0: takes 2 seconds.
This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds. | from operator import add
def main():
n, s = map(int, input().split())
print(max(max(add(*map(int, input().split())) for _ in range(n)), s))
if __name__ == '__main__':
main()
| {
"input": [
"5 10\n2 77\n3 33\n8 21\n9 12\n10 64\n",
"3 7\n2 1\n3 8\n5 2\n"
],
"output": [
"79\n",
"11\n"
]
} |
1,504 | 12 | Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells.
Vova's character can learn new spells during the game. Every spell is characterized by two values xi and yi β damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage x and mana cost y for z seconds, then he will deal xΒ·z damage and spend yΒ·z mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously.
Also Vova can fight monsters. Every monster is characterized by two values tj and hj β monster kills Vova's character in tj seconds and has hj health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones.
Vova's character kills a monster, if he deals hj damage to it in no more than tj seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in tj seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight.
You have to write a program which can answer two types of queries:
* 1 x y β Vova's character learns new spell which deals x damage per second and costs y mana per second.
* 2 t h β Vova fights the monster which kills his character in t seconds and has h health points.
Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game.
For every query of second type you have to determine if Vova is able to win the fight with corresponding monster.
Input
The first line contains two integer numbers q and m (2 β€ q β€ 105, 1 β€ m β€ 1012) β the number of queries and the amount of mana at the beginning of every fight.
i-th of each next q lines contains three numbers ki, ai and bi (1 β€ ki β€ 2, 1 β€ ai, bi β€ 106).
Using them you can restore queries this way: let j be the index of the last query of second type with positive answer (j = 0 if there were none of these).
* If ki = 1, then character learns spell with x = (ai + j) mod 106 + 1, y = (bi + j) mod 106 + 1.
* If ki = 2, then you have to determine if Vova is able to win the fight against monster with t = (ai + j) mod 106 + 1, h = (bi + j) mod 106 + 1.
Output
For every query of second type print YES if Vova is able to win the fight with corresponding monster and NO otherwise.
Example
Input
3 100
1 4 9
2 19 49
2 19 49
Output
YES
NO
Note
In first example Vova's character at first learns the spell with 5 damage and 10 mana cost per second. Next query is a fight with monster which can kill character in 20 seconds and has 50 health points. Vova kills it in 10 seconds (spending 100 mana). Next monster has 52 health, so Vova can't deal that much damage with only 100 mana. | #!/usr/bin/env python3
# solution after hint
# (instead of best hit/mana spell store convex hull of spells)
# O(n^2) instead of O(n log n)
[q, m] = map(int, input().strip().split())
qis = [tuple(map(int, input().strip().split())) for _ in range(q)]
mod = 10**6
j = 0
spell_chull = [(0, 0)] # lower hull _/
def is_right(xy0, xy1, xy):
(x0, y0) = xy0
(x1, y1) = xy1
(x, y) = xy
return (x0 - x) * (y1 - y) >= (x1 - x) * (y0 - y)
def in_chull(x, y):
i = 0
if x > spell_chull[-1][0]:
return False
while spell_chull[i][0] < x:
i += 1
if spell_chull[i][0] == x:
return spell_chull[i][1] <= y
else:
return is_right(spell_chull[i - 1], spell_chull[i], (x, y))
def add_spell(x, y):
global spell_chull
if in_chull(x, y):
return
i_left = 0
while i_left < len(spell_chull) - 1 and not is_right(spell_chull[i_left + 1], spell_chull[i_left], (x, y)):
i_left += 1
i_right = i_left + 1
while i_right < len(spell_chull) - 1 and is_right(spell_chull[i_right + 1], spell_chull[i_right], (x, y)):
i_right += 1
if i_right == len(spell_chull) - 1 and x >= spell_chull[-1][0]:
i_right += 1
spell_chull = spell_chull[:i_left + 1] + [(x, y)] + spell_chull[i_right:]
for i, qi in enumerate(qis):
(k, a, b) = qi
x = (a + j) % mod + 1
y = (b + j) % mod + 1
if k == 1:
add_spell(x, y)
else: #2
if in_chull(y / x, m / x):
print ('YES')
j = i + 1
else:
print ('NO')
| {
"input": [
"3 100\n1 4 9\n2 19 49\n2 19 49\n"
],
"output": [
"YES\nNO\n"
]
} |
1,505 | 9 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x β 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 β€ n β€ 2Β·105, 2 β€ x β€ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 β€ a, b β€ n) β edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4 | from sys import stdin
from collections import deque
def bfs(G, s):
Q = deque()
Q.append(s)
infinite = 10 ** 6
d = [infinite]*n
d[s] = 0
while Q:
u = Q.popleft()
for v in graph[u]:
if d[v] == infinite:
d[v] = d[u] + 1
Q.append(v)
return d
n, x = map(int, stdin.readline().split())
x = x - 1
graph = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int, stdin.readline().split())
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
d_Alice = bfs(graph, 0)
d_Bob = bfs(graph, x)
resp = d_Alice[x]
for i,v in enumerate(graph):
if len(v) == 1 and d_Alice[i] > d_Bob[i]:
resp = max(resp, d_Alice[i])
print(2*resp)
| {
"input": [
"4 3\n1 2\n2 3\n2 4\n",
"5 2\n1 2\n2 3\n3 4\n2 5\n"
],
"output": [
"4",
"6"
]
} |
1,506 | 8 | Daenerys Targaryen has an army consisting of k groups of soldiers, the i-th group contains ai soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has n rows, each of them has 8 seats. We call two seats neighbor, if they are in the same row and in seats {1, 2}, {3, 4}, {4, 5}, {5, 6} or {7, 8}.
<image> A row in the airplane
Daenerys Targaryen wants to place her army in the plane so that there are no two soldiers from different groups sitting on neighboring seats.
Your task is to determine if there is a possible arranging of her army in the airplane such that the condition above is satisfied.
Input
The first line contains two integers n and k (1 β€ n β€ 10000, 1 β€ k β€ 100) β the number of rows and the number of groups of soldiers, respectively.
The second line contains k integers a1, a2, a3, ..., ak (1 β€ ai β€ 10000), where ai denotes the number of soldiers in the i-th group.
It is guaranteed that a1 + a2 + ... + ak β€ 8Β·n.
Output
If we can place the soldiers in the airplane print "YES" (without quotes). Otherwise print "NO" (without quotes).
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
2 2
5 8
Output
YES
Input
1 2
7 1
Output
NO
Input
1 2
4 4
Output
YES
Input
1 4
2 2 1 2
Output
YES
Note
In the first sample, Daenerys can place the soldiers like in the figure below:
<image>
In the second sample, there is no way to place the soldiers in the plane since the second group soldier will always have a seat neighboring to someone from the first group.
In the third example Daenerys can place the first group on seats (1, 2, 7, 8), and the second group an all the remaining seats.
In the fourth example she can place the first two groups on seats (1, 2) and (7, 8), the third group on seats (3), and the fourth group on seats (5, 6). | import sys
def r():
return list(map(int, input().split()))
n, k = map(int, input().split())
a = r()
cnt4 = n
cnt2 = 2*n
cnt1 = 0
for i in range(k):
x = min((a[i]+1)//4, cnt4)
cnt4 -= x
a[i] = max(0, a[i]-4*x)
cnt2 += cnt4
cnt1 += cnt4
for i in range(k):
x = min(a[i]//2, cnt2)
cnt2 -= x
a[i] = max(0, a[i]-2*x)
cnt1 += cnt2
for i in range(k):
cnt1 -= a[i]
if (cnt1 < 0):
print('NO')
else:
print('YES')
| {
"input": [
"2 2\n5 8\n",
"1 2\n7 1\n",
"1 4\n2 2 1 2\n",
"1 2\n4 4\n"
],
"output": [
"YES\n",
"NO\n",
"YES\n",
"YES\n"
]
} |
1,507 | 10 | Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 β€ i β€ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 β€ n β€ 200000) β the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 β€ ai β€ 109), where ai is the number of balls with color i.
Output
Print one number β the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 β to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 β to the second box. Penalty is 5.
Total penalty is 19. | from heapq import *
n=int(input())
a=list(map(int,input().split()))
s=0
if len(a)%2==0:
a=[0]+a
n+=1
def sc(a,s=0):
heapify(a)
for i in range ((n-1)//2):
k=heappop(a)+heappop(a)+heappop(a)
s+=k
heappush(a,k)
print(s)
sc(a)
| {
"input": [
"3\n1 2 3\n",
"4\n2 3 4 5\n"
],
"output": [
"6\n",
"19\n"
]
} |
1,508 | 12 | Roy and Biv have a set of n points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.
They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).
However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.
Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).
Help them compute the minimum cost way to choose edges to satisfy the above constraints.
Input
The first line will contain an integer n (1 β€ n β€ 300 000), the number of points.
The next n lines will contain two tokens pi and ci (pi is an integer, 1 β€ pi β€ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.
Output
Print a single integer, the minimum cost way to solve the problem.
Examples
Input
4
1 G
5 R
10 B
15 G
Output
23
Input
4
1 G
2 R
3 B
10 G
Output
12
Note
In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively. | def F1():
n = int(input())
ans = 0
allc = 0
bigr = 0
bigb = 0
lastr = -1
lastb = -1
lastg = -(1 << 60)
for i in range(n):
x = input().split()
pos, col = int(x[0]), x[1]
if col == 'R' or col == 'G':
if lastr != -1:
bigr = max(bigr, pos - lastr)
allc += pos - lastr
lastr = pos
if col == 'B' or col == 'G':
if lastb != -1:
bigb = max(bigb, pos - lastb)
allc += pos - lastb
lastb = pos
if col == 'G':
ans += allc + min(0, - bigr - bigb + pos - lastg)
lastr = lastb = lastg = pos
bigr = bigb = allc = 0
ans += allc
print(ans)
if __name__=='__main__':
F1()
| {
"input": [
"4\n1 G\n2 R\n3 B\n10 G\n",
"4\n1 G\n5 R\n10 B\n15 G\n"
],
"output": [
"12",
"23"
]
} |
1,509 | 11 | A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains n ski junctions, numbered from 1 to n. Initially the junctions aren't connected in any way.
In the constructing process m bidirectional ski roads will be built. The roads are built one after another: first the road number 1 will be built, then the road number 2, and so on. The i-th road connects the junctions with numbers ai and bi.
Track is the route with the following properties:
* The route is closed, that is, it begins and ends in one and the same junction.
* The route contains at least one road.
* The route doesn't go on one road more than once, however it can visit any junction any number of times.
Let's consider the ski base as a non-empty set of roads that can be divided into one or more tracks so that exactly one track went along each road of the chosen set. Besides, each track can consist only of roads from the chosen set. Ski base doesn't have to be connected.
Two ski bases are considered different if they consist of different road sets.
After building each new road the Walrusland government wants to know the number of variants of choosing a ski base based on some subset of the already built roads. The government asks you to help them solve the given problem.
Input
The first line contains two integers n and m (2 β€ n β€ 105, 1 β€ m β€ 105). They represent the number of junctions and the number of roads correspondingly. Then on m lines follows the description of the roads in the order in which they were built. Each road is described by a pair of integers ai and bi (1 β€ ai, bi β€ n, ai β bi) β the numbers of the connected junctions. There could be more than one road between a pair of junctions.
Output
Print m lines: the i-th line should represent the number of ways to build a ski base after the end of construction of the road number i. The numbers should be printed modulo 1000000009 (109 + 9).
Examples
Input
3 4
1 3
2 3
1 2
1 2
Output
0
0
1
3
Note
Let us have 3 junctions and 4 roads between the junctions have already been built (as after building all the roads in the sample): 1 and 3, 2 and 3, 2 roads between junctions 1 and 2. The land lot for the construction will look like this:
<image>
The land lot for the construction will look in the following way:
<image>
We can choose a subset of roads in three ways:
<image>
In the first and the second ways you can choose one path, for example, 1 - 2 - 3 - 1. In the first case you can choose one path 1 - 2 - 1. | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
class UnionFind(object):
__slots__ = ['nodes']
def __init__(self, n: int):
self.nodes = [-1] * n
def find(self, x: int) -> int:
if self.nodes[x] < 0:
return x
else:
self.nodes[x] = self.find(self.nodes[x])
return self.nodes[x]
def unite(self, x: int, y: int) -> bool:
root_x, root_y, nodes = self.find(x), self.find(y), self.nodes
if root_x != root_y:
if nodes[root_x] > nodes[root_y]:
root_x, root_y = root_y, root_x
nodes[root_x] += nodes[root_y]
nodes[root_y] = root_x
return root_x != root_y
if __name__ == '__main__':
n, m = map(int, input().split())
uf = UnionFind(n + 10)
ans = [0] * m
x = 1
mod = 10**9 + 9
for i, (u, v) in enumerate(map(int, input().split()) for _ in range(m)):
if not uf.unite(u, v):
x = x * 2 % mod
ans[i] = (x - 1) % mod
sys.stdout.buffer.write('\n'.join(map(str, ans)).encode('utf-8'))
| {
"input": [
"3 4\n1 3\n2 3\n1 2\n1 2\n"
],
"output": [
"0\n0\n1\n3\n"
]
} |
1,510 | 9 | Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted β the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.
Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:
Define the score of X to be the sum of the elements of X modulo p.
Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:
* Each part contains at least 1 element of A, and each part consists of contiguous elements of A.
* The two parts do not overlap.
* The total sum S of the scores of those two parts is maximized. This is the encryption code.
Output the sum S, which is the encryption code.
Input
The first line of the input contains two space-separated integer N and p (2 β€ N β€ 100 000, 2 β€ p β€ 10 000) β the number of elements in A, and the modulo for computing scores, respectively.
The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].
Output
Output the number S as described in the problem statement.
Examples
Input
4 10
3 4 7 2
Output
16
Input
10 12
16 3 24 13 9 8 7 5 12 12
Output
13
Note
In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of <image>.
In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <image>. | import math
def func(n,k,a):
s=sum(a)
ms=0
x=0
for i in range(n):
cs=(x%k)+(s%k)
x+=a[i]
s-=a[i]
ms=max(ms,cs)
return ms
for _ in range(1):
n,k=list(map(int,input().split()))
a=list(map(int,input().split()))
print(func(n,k,a)) | {
"input": [
"4 10\n3 4 7 2\n",
"10 12\n16 3 24 13 9 8 7 5 12 12\n"
],
"output": [
"16",
"13"
]
} |
1,511 | 8 | Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.
There are n flowers in a row in the exhibition. Sonya can put either a rose or a lily in the i-th position. Thus each of n positions should contain exactly one flower: a rose or a lily.
She knows that exactly m people will visit this exhibition. The i-th visitor will visit all flowers from l_i to r_i inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.
Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.
Input
The first line contains two integers n and m (1β€ n, mβ€ 10^3) β the number of flowers and visitors respectively.
Each of the next m lines contains two integers l_i and r_i (1β€ l_iβ€ r_iβ€ n), meaning that i-th visitor will visit all flowers from l_i to r_i inclusive.
Output
Print the string of n characters. The i-th symbol should be Β«0Β» if you want to put a rose in the i-th position, otherwise Β«1Β» if you want to put a lily.
If there are multiple answers, print any.
Examples
Input
5 3
1 3
2 4
2 5
Output
01100
Input
6 3
5 6
1 4
4 6
Output
110010
Note
In the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions;
* in the segment [1β¦3], there are one rose and two lilies, so the beauty is equal to 1β
2=2;
* in the segment [2β¦4], there are one rose and two lilies, so the beauty is equal to 1β
2=2;
* in the segment [2β¦5], there are two roses and two lilies, so the beauty is equal to 2β
2=4.
The total beauty is equal to 2+2+4=8.
In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions;
* in the segment [5β¦6], there are one rose and one lily, so the beauty is equal to 1β
1=1;
* in the segment [1β¦4], there are two roses and two lilies, so the beauty is equal to 2β
2=4;
* in the segment [4β¦6], there are two roses and one lily, so the beauty is equal to 2β
1=2.
The total beauty is equal to 1+4+2=7. | def i_ints():
return map(int, input().split())
n, m = i_ints()
print(("01"*n)[:n])
| {
"input": [
"6 3\n5 6\n1 4\n4 6\n",
"5 3\n1 3\n2 4\n2 5\n"
],
"output": [
"010101",
"01010"
]
} |
1,512 | 8 | Let s(x) be sum of digits in decimal representation of positive integer x. Given two integers n and m, find some positive integers a and b such that
* s(a) β₯ n,
* s(b) β₯ n,
* s(a + b) β€ m.
Input
The only line of input contain two integers n and m (1 β€ n, m β€ 1129).
Output
Print two lines, one for decimal representation of a and one for decimal representation of b. Both numbers must not contain leading zeros and must have length no more than 2230.
Examples
Input
6 5
Output
6
7
Input
8 16
Output
35
53
Note
In the first sample, we have n = 6 and m = 5. One valid solution is a = 6, b = 7. Indeed, we have s(a) = 6 β₯ n and s(b) = 7 β₯ n, and also s(a + b) = s(13) = 4 β€ m. | def f(l):
n,m = l #1129
return ['5'*282,'4'*281+'5']
l = list(map(int,input().split()))
[print(r) for r in f(l)]
| {
"input": [
"8 16\n",
"6 5\n"
],
"output": [
"11111111\n88888889",
"111111\n888889"
]
} |
1,513 | 9 | Ivan wants to play a game with you. He picked some string s of length n consisting only of lowercase Latin letters.
You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from 1 to n-1), but he didn't tell you which strings are prefixes and which are suffixes.
Ivan wants you to guess which of the given 2n-2 strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!
Input
The first line of the input contains one integer number n (2 β€ n β€ 100) β the length of the guessed string s.
The next 2n-2 lines are contain prefixes and suffixes, one per line. Each of them is the string of length from 1 to n-1 consisting only of lowercase Latin letters. They can be given in arbitrary order.
It is guaranteed that there are exactly 2 strings of each length from 1 to n-1. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length n.
Output
Print one string of length 2n-2 β the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The i-th character of this string should be 'P' if the i-th of the input strings is the prefix and 'S' otherwise.
If there are several possible answers, you can print any.
Examples
Input
5
ba
a
abab
a
aba
baba
ab
aba
Output
SPPSPSPS
Input
3
a
aa
aa
a
Output
PPSS
Input
2
a
c
Output
PS
Note
The only string which Ivan can guess in the first example is "ababa".
The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.
In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | def solve(c):
d=''
s=set()
for e in a:
if c.startswith(e) and len(e) not in s:
d+='P'
s.add(len(e))
elif c.endswith(e) and -len(e) not in s:
d+='S'
s.add(-len(e))
else:return True
print(d)
return False
n=int(input())
a,b=[],[]
for i in range(n+n-2):
a.append(input())
if len(a[-1])==n-1:b.append(a[-1])
if solve(b[0]+b[1][-1]):solve(b[1]+b[0][-1]) | {
"input": [
"3\na\naa\naa\na\n",
"5\nba\na\nabab\na\naba\nbaba\nab\naba\n",
"2\na\nc\n"
],
"output": [
"PPSS",
"SPPSPSPS",
"PS"
]
} |
1,514 | 7 | We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other consonant. Multiple changes can be made.
In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.
Given the names of two superheroes, determine if the superhero with name s can be transformed to the Superhero with name t.
Input
The first line contains the string s having length between 1 and 1000, inclusive.
The second line contains the string t having length between 1 and 1000, inclusive.
Both strings s and t are guaranteed to be different and consist of lowercase English letters only.
Output
Output "Yes" (without quotes) if the superhero with name s can be transformed to the superhero with name t and "No" (without quotes) otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
a
u
Output
Yes
Input
abc
ukm
Output
Yes
Input
akm
ua
Output
No
Note
In the first sample, since both 'a' and 'u' are vowels, it is possible to convert string s to t.
In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string s to t. | def process(s):
return [c in 'aeiou' for c in s]
s1 = input()
s2 = input()
print('Yes' if process(s1) == process(s2) else 'No') | {
"input": [
"akm\nua\n",
"a\nu\n",
"abc\nukm\n"
],
"output": [
"No\n",
"YES\n",
"YES\n"
]
} |
1,515 | 10 | Let s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 β€ l β€ |s| - |t| + 1 that t = s_l s_{l+1} β¦ s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l.
For example, let s = "1010111". A string t = "010" is an unique substring of s, because l = 2 is the only one suitable number. But, for example t = "10" isn't a unique substring of s, because l = 1 and l = 3 are suitable. And for example t ="00" at all isn't a substring of s, because there is no suitable l.
Today Vasya solved the following problem at the informatics lesson: given a string consisting of symbols "0" and "1", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him.
You are given 2 positive integers n and k, such that (n mod 2) = (k mod 2), where (x mod 2) is operation of taking remainder of x by dividing on 2. Find any string s consisting of n symbols "0" or "1", such that the length of its minimal unique substring is equal to k.
Input
The first line contains two integers n and k, separated by spaces (1 β€ k β€ n β€ 100 000, (k mod 2) = (n mod 2)).
Output
Print a string s of length n, consisting of symbols "0" and "1". Minimal length of the unique substring of s should be equal to k. You can find any suitable string. It is guaranteed, that there exists at least one such string.
Examples
Input
4 4
Output
1111
Input
5 3
Output
01010
Input
7 3
Output
1011011
Note
In the first test, it's easy to see, that the only unique substring of string s = "1111" is all string s, which has length 4.
In the second test a string s = "01010" has minimal unique substring t ="101", which has length 3.
In the third test a string s = "1011011" has minimal unique substring t ="110", which has length 3. | import os
import sys
def log(*args, **kwargs):
if os.environ.get('CODEFR'):
print(*args, **kwargs)
n, k = tuple(map(int, input().split()))
s = '0'*((n-k)//2) + '1'
for i in range(n):
print(s[i % len(s)], end='')
print()
| {
"input": [
"4 4\n",
"7 3\n",
"5 3\n"
],
"output": [
"1111",
"0010010",
"01010"
]
} |
1,516 | 10 | Misha was interested in water delivery from childhood. That's why his mother sent him to the annual Innovative Olympiad in Irrigation (IOI). Pupils from all Berland compete there demonstrating their skills in watering. It is extremely expensive to host such an olympiad, so after the first n olympiads the organizers introduced the following rule of the host city selection.
The host cities of the olympiads are selected in the following way. There are m cities in Berland wishing to host the olympiad, they are numbered from 1 to m. The host city of each next olympiad is determined as the city that hosted the olympiad the smallest number of times before. If there are several such cities, the city with the smallest index is selected among them.
Misha's mother is interested where the olympiad will be held in some specific years. The only information she knows is the above selection rule and the host cities of the first n olympiads. Help her and if you succeed, she will ask Misha to avoid flooding your house.
Input
The first line contains three integers n, m and q (1 β€ n, m, q β€ 500 000) β the number of olympiads before the rule was introduced, the number of cities in Berland wishing to host the olympiad, and the number of years Misha's mother is interested in, respectively.
The next line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ m), where a_i denotes the city which hosted the olympiad in the i-th year. Note that before the rule was introduced the host city was chosen arbitrarily.
Each of the next q lines contains an integer k_i (n + 1 β€ k_i β€ 10^{18}) β the year number Misha's mother is interested in host city in.
Output
Print q integers. The i-th of them should be the city the olympiad will be hosted in the year k_i.
Examples
Input
6 4 10
3 1 1 1 2 2
7
8
9
10
11
12
13
14
15
16
Output
4
3
4
2
3
4
1
2
3
4
Input
4 5 4
4 4 5 1
15
9
13
6
Output
5
3
3
3
Note
In the first example Misha's mother is interested in the first 10 years after the rule was introduced. The host cities these years are 4, 3, 4, 2, 3, 4, 1, 2, 3, 4.
In the second example the host cities after the new city is introduced are 2, 3, 1, 2, 3, 5, 1, 2, 3, 4, 5, 1. | #!/usr/bin/env python
import operator as op
import os
import sys
from bisect import bisect_left, bisect_right, insort
from functools import reduce
from io import BytesIO, IOBase
from itertools import chain, repeat, starmap
def main():
input = sys.stdin.buffer.readline
n, m, q = map(int, input().split())
a = [int(x) for x in input().split()]
counter = [0] * m
for ai in a:
counter[ai - 1] += 1
count_order = sorted(range(m), key=lambda x: counter[x])
years = [0] * m
for i in range(m - 1):
diff = counter[count_order[i + 1]] - counter[count_order[i]]
years[i + 1] = years[i] + diff * (i + 1)
max_k = max(counter) * m - sum(counter)
k = [int(input()) - n for _ in range(q)]
k_order = sorted(range(q), key=lambda x: k[x])
sortedlist = SortedList()
res, idx = [0] * q, 0
for i in range(q):
ki = k[k_order[i]]
if ki > max_k:
res[k_order[i]] = ((ki - max_k - 1) % m) + 1
else:
while years[idx] < ki:
sortedlist.add(count_order[idx])
idx += 1
ki -= years[idx - 1] + 1
ki %= idx
res[k_order[i]] = sortedlist[ki] + 1
print(*res, sep='\n')
class SortedList():
"""Sorted list is a sorted mutable sequence."""
DEFAULT_LOAD_FACTOR = 500
def __init__(self, iterable=None):
"""Initialize sorted list instance."""
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self.update(iterable)
def add(self, value):
"""Add `value` to sorted list."""
_lists = self._lists
_maxes = self._maxes
if _maxes:
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_maxes[pos] = value
else:
insort(_lists[pos], value)
self._expand(pos)
else:
_lists.append([value])
_maxes.append(value)
self._len += 1
def _expand(self, pos):
"""Split sublists with length greater than double the load-factor."""
_load = self._load
_lists = self._lists
_index = self._index
if len(_lists[pos]) > (_load << 1):
_maxes = self._maxes
_lists_pos = _lists[pos]
half = _lists_pos[_load:]
del _lists_pos[_load:]
_maxes[pos] = _lists_pos[-1]
_lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
"""Update sorted list by adding all values from `iterable`."""
_lists = self._lists
_maxes = self._maxes
values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort()
self.clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load))
_maxes.extend(sublist[-1] for sublist in _lists)
self._len = len(values)
del self._index[:]
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_maxes = self._maxes
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return False
_lists = self._lists
idx = bisect_left(_lists[pos], value)
return _lists[pos][idx] == value
def remove(self, value):
"""Remove `value` from sorted list if it is a member."""
_maxes = self._maxes
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > (self._load >> 1):
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
def _loc(self, pos, idx):
"""Convert an index pair (lists index, sublist index) into a single
index number that corresponds to the position of the value in the
sorted list."""
if not pos:
return idx
_index = self._index
if not _index:
self._build_index()
total = 0
pos += self._offset
while pos:
if not pos & 1:
total += _index[pos - 1]
pos = (pos - 1) >> 1
return total + idx
def _pos(self, idx):
"""Convert an index into an index pair (lists index, sublist index)
that can be used to access the corresponding lists position."""
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError('list index out of range')
elif idx >= self._len:
raise IndexError('list index out of range')
if idx < len(self._lists[0]):
return 0, idx
_index = self._index
if not _index:
self._build_index()
pos = 0
child = 1
len_index = len(_index)
while child < len_index:
index_child = _index[child]
if idx < index_child:
pos = child
else:
idx -= index_child
pos = child + 1
child = (pos << 1) + 1
return (pos - self._offset, idx)
def _build_index(self):
"""Build a positional index for indexing the sorted list."""
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(op.add, zip(head, tail)))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 1 << (len(row1) - 1).bit_length()
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(op.add, zip(head, tail)))
tree.append(row)
reduce(list.__iadd__, reversed(tree), self._index)
self._offset = size * 2 - 1
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return self.clear()
elif self._len <= 8 * (stop - start):
values = self.__getitem__(slice(None, start))
if stop < self._len:
values += self.__getitem__(slice(stop, None))
self.clear()
return self.update(values)
indices = range(start, stop, step)
if step > 0:
indices = reversed(indices)
_pos, _delete = self._pos, self._delete
for index in indices:
pos, idx = _pos(index)
_delete(pos, idx)
else:
pos, idx = self._pos(index)
self._delete(pos, idx)
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
_lists = self._lists
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return reduce(list.__iadd__, self._lists, [])
start_pos, start_idx = self._pos(start)
if stop == self._len:
stop_pos = len(_lists) - 1
stop_idx = len(_lists[stop_pos])
else:
stop_pos, stop_idx = self._pos(stop)
if start_pos == stop_pos:
return _lists[start_pos][start_idx:stop_idx]
prefix = _lists[start_pos][start_idx:]
middle = _lists[(start_pos + 1):stop_pos]
result = reduce(list.__iadd__, middle, prefix)
result += _lists[stop_pos][:stop_idx]
return result
if step == -1 and start > stop:
result = self.__getitem__(slice(stop + 1, start + 1))
result.reverse()
return result
indices = range(start, stop, step)
return list(self.__getitem__(index) for index in indices)
else:
if self._len:
if index == 0:
return _lists[0][0]
elif index == -1:
return _lists[-1][-1]
else:
raise IndexError('list index out of range')
if 0 <= index < len(_lists[0]):
return _lists[0][index]
len_last = len(_lists[-1])
if -len_last < index < 0:
return _lists[-1][len_last + index]
pos, idx = self._pos(index)
return _lists[pos][idx]
def __iter__(self):
"""Return an iterator over the sorted list."""
return chain.from_iterable(self._lists)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return chain.from_iterable(map(reversed, reversed(self._lists)))
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def bisect_left(self, value):
"""Return an index to insert `value` in the sorted list."""
pos = bisect_left(self._maxes, value)
return self._len if pos == len(self._maxes) else self._loc(pos, bisect_left(self._lists[pos], value))
def bisect_right(self, value):
"""Return an index to insert `value` in the sorted list."""
pos = bisect_right(self._maxes, value)
return self._len if pos == len(self._maxes) else self._loc(pos, bisect_right(self._lists[pos], value))
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
return 0
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
pos_right = bisect_right(_maxes, value)
if pos_right == len(_maxes):
return self._len - self._loc(pos_left, idx_left)
idx_right = bisect_right(_lists[pos_right], value)
if pos_left == pos_right:
return idx_right - idx_left
right = self._loc(pos_right, idx_right)
left = self._loc(pos_left, idx_left)
return right - left
def __copy__(self):
"""Return a shallow copy of the sorted list."""
return self.__class__(self)
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
if not self._len:
raise IndexError('pop index out of range')
_lists = self._lists
if 0 <= index < len(_lists[0]):
val = _lists[0][index]
self._delete(0, index)
return val
len_last = len(_lists[-1])
if -len_last < index < 0:
pos = len(_lists) - 1
loc = len_last + index
val = _lists[pos][loc]
self._delete(pos, loc)
return val
pos, idx = self._pos(index)
val = _lists[pos][idx]
self._delete(pos, idx)
return val
def index(self, value, start=0, stop=None):
"""Return first index of value in sorted list."""
_len = self._len
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
if _lists[pos_left][idx_left] != value:
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
left = self._loc(pos_left, idx_left)
if start <= left:
if left <= stop:
return left
else:
if start <= self.bisect_right(value) - 1:
return start
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
"""Return new sorted list containing all values in both sequences."""
values = reduce(list.__iadd__, self._lists, [])
values.extend(other)
return self.__class__(values)
__radd__ = __add__
def __iadd__(self, other):
"""Update sorted list with values from `other`."""
self.update(other)
return self
def __mul__(self, num):
"""Return new sorted list with `num` shallow copies of values."""
values = reduce(list.__iadd__, self._lists, []) * num
return self.__class__(values)
__rmul__ = __mul__
def __imul__(self, num):
"""Update the sorted list with `num` shallow copies of values."""
values = reduce(list.__iadd__, self._lists, []) * num
self.clear()
self.update(values)
return self
def __make_cmp(seq_op):
"Make comparator method."
def comparer(self, other):
"Compare method for sorted list and sequence."
self_len = self._len
len_other = len(other)
if self_len != len_other:
if seq_op is op.eq:
return False
if seq_op is op.ne:
return True
for alpha, beta in zip(self, other):
if alpha != beta:
return seq_op(alpha, beta)
return seq_op(self_len, len_other)
comparer.__name__ = '__{0}__'.format(seq_op.__name__)
return comparer
__eq__ = __make_cmp(op.eq)
__ne__ = __make_cmp(op.ne)
__lt__ = __make_cmp(op.lt)
__gt__ = __make_cmp(op.gt)
__le__ = __make_cmp(op.le)
__ge__ = __make_cmp(op.ge)
__make_cmp = staticmethod(__make_cmp)
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(reduce(list.__iadd__, self._lists, []))
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
| {
"input": [
"4 5 4\n4 4 5 1\n15\n9\n13\n6\n",
"6 4 10\n3 1 1 1 2 2\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n"
],
"output": [
"5\n3\n3\n3\n",
"4\n3\n4\n2\n3\n4\n1\n2\n3\n4\n"
]
} |
1,517 | 9 | Yet another education system reform has been carried out in Berland recently. The innovations are as follows:
An academic year now consists of n days. Each day pupils study exactly one of m subjects, besides, each subject is studied for no more than one day. After the lessons of the i-th subject pupils get the home task that contains no less than ai and no more than bi exercises. Besides, each subject has a special attribute, the complexity (ci). A school can make its own timetable, considering the following conditions are satisfied:
* the timetable should contain the subjects in the order of the complexity's strict increasing;
* each day, except for the first one, the task should contain either k times more exercises, or more by k compared to the previous day (more formally: let's call the number of home task exercises in the i-th day as xi, then for each i (1 < i β€ n): either xi = k + xi - 1 or xi = kΒ·xi - 1 must be true);
* the total number of exercises in all home tasks should be maximal possible.
All limitations are separately set for each school.
It turned out that in many cases ai and bi reach 1016 (however, as the Berland Minister of Education is famous for his love to half-measures, the value of bi - ai doesn't exceed 100). That also happened in the Berland School β256. Nevertheless, you as the school's principal still have to work out the timetable for the next academic year...
Input
The first line contains three integers n, m, k (1 β€ n β€ m β€ 50, 1 β€ k β€ 100) which represent the number of days in an academic year, the number of subjects and the k parameter correspondingly. Each of the following m lines contains the description of a subject as three integers ai, bi, ci (1 β€ ai β€ bi β€ 1016, bi - ai β€ 100, 1 β€ ci β€ 100) β two limitations to the number of exercises on the i-th subject and the complexity of the i-th subject, correspondingly. Distinct subjects can have the same complexity. The subjects are numbered with integers from 1 to m.
Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is preferred to use the cin stream or the %I64d specificator.
Output
If no valid solution exists, print the single word "NO" (without the quotes). Otherwise, the first line should contain the word "YES" (without the quotes) and the next n lines should contain any timetable that satisfies all the conditions. The i + 1-th line should contain two positive integers: the number of the subject to study on the i-th day and the number of home task exercises given for this subject. The timetable should contain exactly n subjects.
Examples
Input
4 5 2
1 10 1
1 10 2
1 10 3
1 20 4
1 100 5
Output
YES
2 8
3 10
4 20
5 40
Input
3 4 3
1 3 1
2 4 4
2 3 3
2 2 2
Output
NO | class Subject:
def __init__(self, id, low, high, complexity):
self.id = id
self.low = low
self.high = high
self.complexity = complexity
self.day_links = [ {} for i in range(high - low + 1) ]
def add_link(self, link):
day = link.day
links = self.day_links[link.weight - self.low]
if day not in links or links[day].total < link.total:
links[day] = link
class Link:
def __init__(self, subject, weight, total, day, previous):
self.subject = subject
self.weight = weight
self.total = total
self.day = day
self.previous = previous
class Group:
def __init__(self, complexity):
self.complexity = complexity
self.subjects = []
need_day, num_subjects, more = map(int, input().split())
groups = {}
for i in range(num_subjects):
subject = Subject(i + 1, *list(map(int, input().split())))
if subject.complexity not in groups:
groups[subject.complexity] = Group(subject.complexity)
groups[subject.complexity].subjects.append(subject)
groups = sorted(groups.values(), key = lambda group: group.complexity)
num_groups = len(groups)
best_link = None
for pos, group in enumerate(groups):
if num_groups - pos >= need_day:
for subject in group.subjects:
for weight in range(subject.low, subject.high + 1):
subject.add_link(Link(subject, weight, weight, 1, None))
for subject in group.subjects:
for i, links in enumerate(subject.day_links):
weight = subject.low + i
for day, link in links.items():
if day == need_day:
if not best_link or best_link.total < link.total:
best_link = link
continue
for next_weight in [ weight + more, weight * more ]:
max_pos = num_groups + day - need_day
for next_pos in range(pos + 1, max_pos + 1):
for next_subject in groups[next_pos].subjects:
if next_weight < next_subject.low:
continue
if next_weight > next_subject.high:
continue
next_subject.add_link(Link(
next_subject, next_weight,
next_weight + link.total, day + 1, link))
if best_link:
print('YES')
schedule = need_day * [ None ]
link = best_link
while link:
subject = link.subject
subject.weight = link.weight
schedule[link.day - 1] = subject
link = link.previous
for subject in schedule:
print(subject.id, subject.weight)
import sys
sys.exit()
else:
print('NO')
| {
"input": [
"4 5 2\n1 10 1\n1 10 2\n1 10 3\n1 20 4\n1 100 5\n",
"3 4 3\n1 3 1\n2 4 4\n2 3 3\n2 2 2\n"
],
"output": [
"YES\n1 8\n2 10\n4 20\n5 40\n",
"NO\n"
]
} |
1,518 | 7 | You play your favourite game yet another time. You chose the character you didn't play before. It has str points of strength and int points of intelligence. Also, at start, the character has exp free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by 1 or raise intelligence by 1).
Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is strictly greater than the resulting intelligence).
Calculate the number of different character builds you can create (for the purpose of replayability) if you must invest all free points. Two character builds are different if their strength and/or intellect are different.
Input
The first line contains the single integer T (1 β€ T β€ 100) β the number of queries. Next T lines contain descriptions of queries β one per line.
This line contains three integers str, int and exp (1 β€ str, int β€ 10^8, 0 β€ exp β€ 10^8) β the initial strength and intelligence of the character and the number of free points, respectively.
Output
Print T integers β one per query. For each query print the number of different character builds you can create.
Example
Input
4
5 3 4
2 1 0
3 5 5
4 10 6
Output
3
1
2
0
Note
In the first query there are only three appropriate character builds: (str = 7, int = 5), (8, 4) and (9, 3). All other builds are either too smart or don't use all free points.
In the second query there is only one possible build: (2, 1).
In the third query there are two appropriate builds: (7, 6), (8, 5).
In the fourth query all builds have too much brains. |
def solve():
n = int(input())
for _ in range(n):
s, i, e = map(int, input().split())
n_s = s + e
if n_s > i:
print(min(e + 1, n_s -(n_s + i)//2))
else:
print('0')
solve() | {
"input": [
"4\n5 3 4\n2 1 0\n3 5 5\n4 10 6\n"
],
"output": [
"3\n1\n2\n0\n"
]
} |
1,519 | 12 | It's the year 5555. You have a graph, and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.
Given a connected graph with n vertices, you can choose to either:
* find an independent set that has exactly ββ{n}β vertices.
* find a simple cycle of length at least ββ{n}β.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.
Input
The first line contains two integers n and m (5 β€ n β€ 10^5, n-1 β€ m β€ 2 β
10^5) β the number of vertices and edges in the graph.
Each of the next m lines contains two space-separated integers u and v (1 β€ u,v β€ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print "1", followed by a line containing ββ{n}β distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
6 6
1 3
3 4
4 2
2 6
5 6
5 1
Output
1
1 6 4
Input
6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
Output
2
4
1 5 2 4
Input
5 4
1 2
1 3
2 4
2 5
Output
1
3 4 5
Note
In the first sample:
<image>
Notice that you can solve either problem, so printing the cycle 2-4-3-1-5-6 is also acceptable.
In the second sample:
<image>
Notice that if there are multiple answers you can print any, so printing the cycle 2-5-6, for example, is acceptable.
In the third sample:
<image> | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
e = [tuple(map(int, input().split())) for _ in range(m)]
g = [[] for _ in range(n + 1)]
for u, v in e:
g[u].append(v)
g[v].append(u)
req = 1
while req * req < n:
req += 1
def dfs():
dep = [0] * (n + 1)
par = [0] * (n + 1)
st = [1]
st2 = []
while st:
u = st.pop()
if dep[u]:
continue
st2.append(u)
dep[u] = dep[par[u]] + 1
for v in g[u]:
if not dep[v]:
par[v] = u
st.append(v)
elif dep[u] - dep[v] + 1 >= req:
cyc = []
while u != par[v]:
cyc.append(u)
u = par[u]
return (None, cyc)
mk = [0] * (n + 1)
iset = []
while st2:
u = st2.pop()
if not mk[u]:
iset.append(u)
for v in g[u]:
mk[v] = 1
return (iset[:req], None)
iset, cyc = dfs()
if iset:
print(1)
print(*iset)
else:
print(2)
print(len(cyc))
print(*cyc)
| {
"input": [
"6 6\n1 3\n3 4\n4 2\n2 6\n5 6\n5 1\n",
"6 8\n1 3\n3 4\n4 2\n2 6\n5 6\n5 1\n1 4\n2 5\n",
"5 4\n1 2\n1 3\n2 4\n2 5\n"
],
"output": [
"2\n6\n5 6 2 4 3 1 \n",
"2\n6\n5 6 2 4 3 1\n",
"1\n3 4 5\n"
]
} |
1,520 | 11 | You are given two arrays a_1, a_2, ... , a_n and b_1, b_2, ... , b_m. Array b is sorted in ascending order (b_i < b_{i + 1} for each i from 1 to m - 1).
You have to divide the array a into m consecutive subarrays so that, for each i from 1 to m, the minimum on the i-th subarray is equal to b_i. Note that each element belongs to exactly one subarray, and they are formed in such a way: the first several elements of a compose the first subarray, the next several elements of a compose the second subarray, and so on.
For example, if a = [12, 10, 20, 20, 25, 30] and b = [10, 20, 30] then there are two good partitions of array a:
1. [12, 10, 20], [20, 25], [30];
2. [12, 10], [20, 20, 25], [30].
You have to calculate the number of ways to divide the array a. Since the number can be pretty large print it modulo 998244353.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2 β
10^5) β the length of arrays a and b respectively.
The second line contains n integers a_1, a_2, ... , a_n (1 β€ a_i β€ 10^9) β the array a.
The third line contains m integers b_1, b_2, ... , b_m (1 β€ b_i β€ 10^9; b_i < b_{i+1}) β the array b.
Output
In only line print one integer β the number of ways to divide the array a modulo 998244353.
Examples
Input
6 3
12 10 20 20 25 30
10 20 30
Output
2
Input
4 2
1 3 3 7
3 7
Output
0
Input
8 2
1 2 2 2 2 2 2 2
1 2
Output
7 | n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
def solve():
M = 998244353
res = 1
i = n - 1
j = m - 1
while j >= 0 and res:
count = 0
while i >= 0 and a[i] >= b[j]:
if count > 0:
count += 1
elif a[i] == b[j]:
count = 1
i -= 1
if j == 0:
count = min(count, 1)
if i>=0:
count = 0
res *= count
res %= M
j -= 1
return res
print(solve()) | {
"input": [
"6 3\n12 10 20 20 25 30\n10 20 30\n",
"8 2\n1 2 2 2 2 2 2 2\n1 2\n",
"4 2\n1 3 3 7\n3 7\n"
],
"output": [
"2",
"7",
"0"
]
} |
1,521 | 8 | This problem is split into two tasks. In this task, you are required to find the minimum possible answer. In the task Village (Maximum) you are required to find the maximum possible answer. Each task is worth 50 points.
There are N houses in a certain village. A single villager lives in each of the houses. The houses are connected by roads. Each road connects two houses and is exactly 1 kilometer long. From each house it is possible to reach any other using one or several consecutive roads. In total there are N-1 roads in the village.
One day all villagers decided to move to different houses β that is, after moving each house should again have a single villager living in it, but no villager should be living in the same house as before. We would like to know the smallest possible total length in kilometers of the shortest paths between the old and the new houses for all villagers.
<image>
Example village with seven houses
For example, if there are seven houses connected by roads as shown on the figure, the smallest total length is 8 km (this can be achieved by moving 1 β 6, 2 β 4, 3 β 1, 4 β 2, 5 β 7, 6 β 3, 7 β 5).
Write a program that finds the smallest total length of the shortest paths in kilometers and an example assignment of the new houses to the villagers.
Input
The first line contains an integer N (1 < N β€ 10^5). Houses are numbered by consecutive integers 1, 2, β¦, N.
Then N-1 lines follow that describe the roads. Each line contains two integers a and b (1 β€ a, b β€ N, a β b) denoting that there is a road connecting houses a and b.
Output
In the first line output the smallest total length of the shortest paths in kilometers.
In the second line describe one valid assignment of the new houses with the smallest total length: N space-separated distinct integers v_1, v_2, β¦, v_N. For each i, v_i is the house number where the villager from the house i should move (v_i β i). If there are several valid assignments, output any of those.
Scoring
Subtasks:
1. (6 points) N β€ 10
2. (19 points) N β€ 1 000
3. (25 points) No further constraints
Examples
Input
4
1 2
2 3
3 4
Output
4
2 1 4 3
Input
7
4 2
5 7
3 4
6 3
1 3
4 5
Output
8
3 4 6 2 7 1 5 | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline()
# ------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# import heapq as hq
# import bisect as bs
# from collections import deque as dq
# from collections import defaultdict as dc
# from math import ceil,floor,sqrt
# from collections import Counter
n = N()
dic = [set() for _ in range(n+1)]
dic2 = [[] for _ in range(n+1)]
for _ in range(n-1):
u,v = RL()
dic[u].add(v)
dic[v].add(u)
now = [1]
father,gress,leaf = [0]*(n+1),[0]*(n+1),[]
for i in range(2,n+1):
gress[i] = len(dic[i])-1
if gress[i]==0:
leaf.append(i)
while now:
node = now.pop()
dic[node].discard(father[node])
for child in dic[node]:
father[child] = node
now.append(child)
res = 0
ans = [0]*(n+1)
while leaf:
p = leaf.pop()
f = father[p]
if not dic2[p]:
dic2[f].append(p)
else:
t = len(dic2[p])
res+=t*2
while t>2:
t-=2
a,b = dic2[p].pop(),dic2[p].pop()
ans[a] = b
ans[b] = a
if t==1:
a = dic2[p].pop()
ans[a] = p
ans[p] = a
else:
a,b = dic2[p].pop(),dic2[p].pop()
ans[a] = p
ans[p] = b
ans[b] = a
gress[f]-=1
if gress[f]==0:
leaf.append(f)
p = 1
if not dic2[p]:
res+=2
m = dic[p].pop()
b = ans[m]
a = ans[b]
if a!=m:
ans[a] = b
ans[m] = p
ans[p] = m
else:
ans[p] = m
ans[m] = b
ans[b] = p
else:
t = len(dic2[p])
res+=t*2
while t>2:
t-=2
a,b = dic2[p].pop(),dic2[p].pop()
ans[a] = b
ans[b] = a
if t==1:
a = dic2[p].pop()
ans[a] = p
ans[p] = a
else:
a,b = dic2[p].pop(),dic2[p].pop()
ans[a] = p
ans[p] = b
ans[b] = a
print(res)
print_list(ans[1:]) | {
"input": [
"4\n1 2\n2 3\n3 4\n",
"7\n4 2\n5 7\n3 4\n6 3\n1 3\n4 5\n"
],
"output": [
"4\n2 1 4 3 ",
"8\n6 4 1 2 7 3 5 "
]
} |
1,522 | 11 | You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it. | import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**4)
M, N = map(int, input().split())
NN = N + M
e = [-1] * NN
def find(x):
if e[x] < 0: return x
e[x] = find(e[x])
return e[x]
def join(a, b):
a, b = find(a), find(b)
if a == b: return False
if e[a] > e[b]: a, b = b, a
e[a] += e[b]
e[b] = a
return True
A = list(map(int, input().split()))
B = list(map(int, input().split()))
E = []
cost = 0
for i in range(M):
_, *X = map(lambda s: int(s)-1, input().split())
for j in X:
cost += A[i] + B[j]
E.append((i, M + j, A[i] + B[j]))
E.sort(key=lambda v: -v[2])
for a, b, c in E:
if join(a, b):
cost -= c
print(cost)
| {
"input": [
"7 8\n3 6 7 9 10 7 239\n8 1 9 7 10 2 6 239\n3 2 1 3\n2 4 1\n3 1 3 7\n2 4 3\n5 3 4 5 6 7\n2 5 7\n1 8\n",
"3 2\n1 2 3\n4 5\n2 1 2\n2 1 2\n2 1 2\n"
],
"output": [
"66\n",
"11\n"
]
} |
1,523 | 9 | You are given a string s, consisting of brackets of two types: '(', ')', '[' and ']'.
A string is called a regular bracket sequence (RBS) if it's of one of the following types:
* empty string;
* '(' + RBS + ')';
* '[' + RBS + ']';
* RBS + RBS.
where plus is a concatenation of two strings.
In one move you can choose a non-empty subsequence of the string s (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.
What is the maximum number of moves you can perform?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Each of the next t lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print a single integer β the maximum number of moves you can perform on a given string s.
Example
Input
5
()
[]()
([)]
)]([
)[(]
Output
1
2
2
0
1
Note
In the first example you can just erase the whole string.
In the second example you can first erase the brackets on positions 1 and 2: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.
In the third example you can first erase the brackets on positions 1 and 3: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.
In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.
In the fifth example you can erase the brackets on positions 2 and 4: ")[(]" and get ")(" as a result. You can erase nothing from it. | def calc(s, x, y):
bal, cnt = 0, 0
for c in s:
if c == y:
if bal > 0:
bal -= 1
cnt += 1
elif c == x:
bal += 1
return cnt
for _ in range(int(input())):
s = input()
print(calc(s, '(', ')') + calc(s, '[', ']')) | {
"input": [
"5\n()\n[]()\n([)]\n)]([\n)[(]\n"
],
"output": [
"\n1\n2\n2\n0\n1\n"
]
} |
1,524 | 7 | You are given two integers n and k.
You should create an array of n positive integers a_1, a_2, ..., a_n such that the sum (a_1 + a_2 + ... + a_n) is divisible by k and maximum element in a is minimum possible.
What is the minimum possible maximum element in a?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The first and only line of each test case contains two integers n and k (1 β€ n β€ 10^9; 1 β€ k β€ 10^9).
Output
For each test case, print one integer β the minimum possible maximum element in array a such that the sum (a_1 + ... + a_n) is divisible by k.
Example
Input
4
1 5
4 3
8 8
8 17
Output
5
2
1
3
Note
In the first test case n = 1, so the array consists of one element a_1 and if we make a_1 = 5 it will be divisible by k = 5 and the minimum possible.
In the second test case, we can create array a = [1, 2, 1, 2]. The sum is divisible by k = 3 and the maximum is equal to 2.
In the third test case, we can create array a = [1, 1, 1, 1, 1, 1, 1, 1]. The sum is divisible by k = 8 and the maximum is equal to 1. | from math import ceil
def answer():
v=ceil(n/k)
return ceil((v*k)/n)
for T in range(int(input())):
n,k=map(int,input().split())
print(answer())
| {
"input": [
"4\n1 5\n4 3\n8 8\n8 17\n"
],
"output": [
"\n5\n2\n1\n3\n"
]
} |
1,525 | 8 | You are given an integer x. Can you make x by summing up some number of 11, 111, 1111, 11111, β¦? (You can use any number among them any number of times).
For instance,
* 33=11+11+11
* 144=111+11+11+11
Input
The first line of input contains a single integer t (1 β€ t β€ 10000) β the number of testcases.
The first and only line of each testcase contains a single integer x (1 β€ x β€ 10^9) β the number you have to make.
Output
For each testcase, you should output a single string. If you can make x, output "YES" (without quotes). Otherwise, output "NO".
You can print each letter of "YES" and "NO" in any case (upper or lower).
Example
Input
3
33
144
69
Output
YES
YES
NO
Note
Ways to make 33 and 144 were presented in the statement. It can be proved that we can't present 69 this way. | def result(x):
r1=(x-(x%11)*111)
if r1>=0 and r1%11==0 :
return "YES"
else:
return "NO"
return None
t=int(input())
for i in range(0,t):
x=int(input())
print(result(x)) | {
"input": [
"3\n33\n144\n69\n"
],
"output": [
"\nYES\nYES\nNO\n"
]
} |
1,526 | 7 | Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
Input
The input contains three positive integer numbers in the first line: n, m and a (1 β€ n, m, a β€ 109).
Output
Write the needed number of flagstones.
Examples
Input
6 6 4
Output
4 | def dj(n,m,k):
return
n,m,k = map(int,input().split())
print(-n//k*(-m//k)) | {
"input": [
"6 6 4\n"
],
"output": [
"4\n"
]
} |
1,527 | 8 | You've got an array a, consisting of n integers: a1, a2, ..., an. Your task is to find a minimal by inclusion segment [l, r] (1 β€ l β€ r β€ n) such, that among numbers al, al + 1, ..., ar there are exactly k distinct numbers.
Segment [l, r] (1 β€ l β€ r β€ n; l, r are integers) of length m = r - l + 1, satisfying the given property, is called minimal by inclusion, if there is no segment [x, y] satisfying the property and less then m in length, such that 1 β€ l β€ x β€ y β€ r β€ n. Note that the segment [l, r] doesn't have to be minimal in length among all segments, satisfying the given property.
Input
The first line contains two space-separated integers: n and k (1 β€ n, k β€ 105). The second line contains n space-separated integers a1, a2, ..., an β elements of the array a (1 β€ ai β€ 105).
Output
Print a space-separated pair of integers l and r (1 β€ l β€ r β€ n) such, that the segment [l, r] is the answer to the problem. If the sought segment does not exist, print "-1 -1" without the quotes. If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2 2 3
Output
1 2
Input
8 3
1 1 2 2 3 3 4 5
Output
2 5
Input
7 4
4 7 7 4 7 4 7
Output
-1 -1
Note
In the first sample among numbers a1 and a2 there are exactly two distinct numbers.
In the second sample segment [2, 5] is a minimal by inclusion segment with three distinct numbers, but it is not minimal in length among such segments.
In the third sample there is no segment with four distinct numbers. | def s(n,k):
ss = dict()
a = list(map(int,input().split()))
res = 0
for i in range(n):
if a[i] in ss:
ss[a[i]] += 1
else:
ss[a[i]] = 1
if len(ss) == k:
res = i
break
else:
return (-1,-1)
for i in range(n):
if ss[a[i]] == 1:
return (i+1, res+1)
ss[a[i]] -= 1
print(*s(*map(int,input().split()))) | {
"input": [
"7 4\n4 7 7 4 7 4 7\n",
"4 2\n1 2 2 3\n",
"8 3\n1 1 2 2 3 3 4 5\n"
],
"output": [
"-1 -1\n",
"1 2",
"2 5"
]
} |
1,528 | 7 | Dima's got a staircase that consists of n stairs. The first stair is at height a1, the second one is at a2, the last one is at an (1 β€ a1 β€ a2 β€ ... β€ an).
Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width wi and height hi. Dima throws each box vertically down on the first wi stairs of the staircase, that is, the box covers stairs with numbers 1, 2, ..., wi. Each thrown box flies vertically down until at least one of the two following events happen:
* the bottom of the box touches the top of a stair;
* the bottom of the box touches the top of a box, thrown earlier.
We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width wi cannot touch the stair number wi + 1.
You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of stairs in the staircase. The second line contains a non-decreasing sequence, consisting of n integers, a1, a2, ..., an (1 β€ ai β€ 109; ai β€ ai + 1).
The next line contains integer m (1 β€ m β€ 105) β the number of boxes. Each of the following m lines contains a pair of integers wi, hi (1 β€ wi β€ n; 1 β€ hi β€ 109) β the size of the i-th thrown box.
The numbers in the lines are separated by spaces.
Output
Print m integers β for each box the height, where the bottom of the box will be after landing. Print the answers for the boxes in the order, in which the boxes are given in the input.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5
1 2 3 6 6
4
1 1
3 1
1 1
4 3
Output
1
3
4
6
Input
3
1 2 3
2
1 1
3 1
Output
1
3
Input
1
1
5
1 2
1 10
1 10
1 10
1 10
Output
1
3
13
23
33
Note
The first sample are shown on the picture.
<image> | def main():
n, res = int(input()), []
l = list(map(int, input().split()))
for _ in range(int(input())):
w, h = map(int, input().split())
m = max(l[0], l[w - 1])
res.append(m)
l[0] = m + h
print('\n'.join(map(str, res)))
if __name__ == '__main__':
main()
| {
"input": [
"1\n1\n5\n1 2\n1 10\n1 10\n1 10\n1 10\n",
"3\n1 2 3\n2\n1 1\n3 1\n",
"5\n1 2 3 6 6\n4\n1 1\n3 1\n1 1\n4 3\n"
],
"output": [
"1\n3\n13\n23\n33\n",
"1\n3\n",
"1\n3\n4\n6\n"
]
} |
1,529 | 9 | Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 β€ li β€ ri β€ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di.
Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 β€ xi β€ yi β€ m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array.
Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.
Input
The first line contains integers n, m, k (1 β€ n, m, k β€ 105). The second line contains n integers: a1, a2, ..., an (0 β€ ai β€ 105) β the initial array.
Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 β€ li β€ ri β€ n), (0 β€ di β€ 105).
Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1 β€ xi β€ yi β€ m).
The numbers in the lines are separated by single spaces.
Output
On a single line print n integers a1, a2, ..., an β the array after executing all the queries. Separate the printed numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
Examples
Input
3 3 3
1 2 3
1 2 1
1 3 2
2 3 4
1 2
1 3
2 3
Output
9 18 17
Input
1 1 1
1
1 1 1
1 1
Output
2
Input
4 3 6
1 2 3 4
1 2 1
2 3 2
3 4 4
1 2
1 3
2 3
1 2
1 3
2 3
Output
5 18 31 20 | #import sys; sys.stdin = open("TF.txt")
R = lambda: list(map(int,input().split()))
def modif(lst):
lst[0]-=1
lst[1]-=1
return lst
n,m,k = R()
a = R()
op = [modif(R()) for i in range(m)]
b = [0]*(n)
cnt = [0]*(m)
for i in range(k):
l,r = R()
l-=1;r-=1
cnt[l] += 1
try: cnt[r+1] -= 1
except: pass
q = [0]*(m)
toadd = 0
for i,v in enumerate(cnt):
toadd += v
q[i] += toadd
for i,v in enumerate(q):
b[op[i][0]] += op[i][2] * v
try: b[op[i][1]+1] -= op[i][2] * v
except: pass
toadd = 0
for i,v in enumerate(b):
toadd += v
a[i] += toadd
print(*a) | {
"input": [
"4 3 6\n1 2 3 4\n1 2 1\n2 3 2\n3 4 4\n1 2\n1 3\n2 3\n1 2\n1 3\n2 3\n",
"1 1 1\n1\n1 1 1\n1 1\n",
"3 3 3\n1 2 3\n1 2 1\n1 3 2\n2 3 4\n1 2\n1 3\n2 3\n"
],
"output": [
"5 18 31 20\n",
"2\n",
"9 18 17\n"
]
} |
1,530 | 7 | Professor Vasechkin is studying evolution of worms. Recently he put forward hypotheses that all worms evolve by division. There are n forms of worms. Worms of these forms have lengths a1, a2, ..., an. To prove his theory, professor needs to find 3 different forms that the length of the first form is equal to sum of lengths of the other two forms. Help him to do this.
Input
The first line contains integer n (3 β€ n β€ 100) β amount of worm's forms. The second line contains n space-separated integers ai (1 β€ ai β€ 1000) β lengths of worms of each form.
Output
Output 3 distinct integers i j k (1 β€ i, j, k β€ n) β such indexes of worm's forms that ai = aj + ak. If there is no such triple, output -1. If there are several solutions, output any of them. It possible that aj = ak.
Examples
Input
5
1 2 3 5 7
Output
3 2 1
Input
5
1 8 1 5 1
Output
-1 | def twonums(n,l):
for i in range(n):
for j in range(i+1,n):
t= l[i]+l[j]
if t in l:
return [l.index(t)+1,j+1, i+1]
return [-1]
n= int(input())
l= list(map(int , input().split()))
print(*twonums(n,l))
| {
"input": [
"5\n1 2 3 5 7\n",
"5\n1 8 1 5 1\n"
],
"output": [
"3 1 2",
"-1\n"
]
} |
1,531 | 7 | Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.
Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own.
<image>
Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
Input
The first line of the input contains an integer n (1 β€ n β€ 100000) β the number of magnets. Then n lines follow. The i-th line (1 β€ i β€ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
Output
On the single line of the output print the number of groups of magnets.
Examples
Input
6
10
10
10
01
10
10
Output
3
Input
4
01
01
10
10
Output
2
Note
The first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.
The second testcase has two groups, each consisting of two magnets. | def main():
n = int(input())
a = input()
pr = a
k = 1
for i in range(1, n):
a = input()
if a != pr:
k += 1
pr = a
print(k)
main()
| {
"input": [
"4\n01\n01\n10\n10\n",
"6\n10\n10\n10\n01\n10\n10\n"
],
"output": [
"2\n",
"3\n"
]
} |
1,532 | 9 | Let's call an array consisting of n integer numbers a1, a2, ..., an, beautiful if it has the following property:
* consider all pairs of numbers x, y (x β y), such that number x occurs in the array a and number y occurs in the array a;
* for each pair x, y must exist some position j (1 β€ j < n), such that at least one of the two conditions are met, either aj = x, aj + 1 = y, or aj = y, aj + 1 = x.
Sereja wants to build a beautiful array a, consisting of n integers. But not everything is so easy, Sereja's friend Dima has m coupons, each contains two integers qi, wi. Coupon i costs wi and allows you to use as many numbers qi as you want when constructing the array a. Values qi are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array a of n elements. After that he takes wi rubles from Sereja for each qi, which occurs in the array a. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay.
Help Sereja, find the maximum amount of money he can pay to Dima.
Input
The first line contains two integers n and m (1 β€ n β€ 2Β·106, 1 β€ m β€ 105). Next m lines contain pairs of integers. The i-th line contains numbers qi, wi (1 β€ qi, wi β€ 105).
It is guaranteed that all qi are distinct.
Output
In a single line print maximum amount of money (in rubles) Sereja can pay.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
Output
5
Input
100 3
1 2
2 1
3 1
Output
4
Input
1 2
1 1
2 100
Output
100
Note
In the first sample Sereja can pay 5 rubles, for example, if Dima constructs the following array: [1, 2, 1, 2, 2]. There are another optimal arrays for this test.
In the third sample Sereja can pay 100 rubles, if Dima constructs the following array: [2]. | import itertools
def f(n):
return n * (n - 1) / 2 + 1 if n % 2 else n * (n - 1) / 2 + n / 2
n, m = map(int, input().split())
table = sorted([int(input().split()[1]) for _ in range(m)], reverse = True)
ans = 1
while f(ans) <= n:
ans += 1
ans -= 1
print(list(itertools.accumulate(table))[min(ans - 1, m - 1)])
| {
"input": [
"100 3\n1 2\n2 1\n3 1\n",
"1 2\n1 1\n2 100\n",
"5 2\n1 2\n2 3\n"
],
"output": [
"4\n",
"100\n",
"5\n"
]
} |
1,533 | 7 | You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic check.
Web-developers of the company Q assume that a password is complex enough, if it meets all of the following conditions:
* the password length is at least 5 characters;
* the password contains at least one large English letter;
* the password contains at least one small English letter;
* the password contains at least one digit.
You are given a password. Please implement the automatic check of its complexity for company Q.
Input
The first line contains a non-empty sequence of characters (at most 100 characters). Each character is either a large English letter, or a small English letter, or a digit, or one of characters: "!", "?", ".", ",", "_".
Output
If the password is complex enough, print message "Correct" (without the quotes), otherwise print message "Too weak" (without the quotes).
Examples
Input
abacaba
Output
Too weak
Input
X12345
Output
Too weak
Input
CONTEST_is_STARTED!!11
Output
Correct | def f(t): return len(t) > 4 and any('0'<= i <= '9' for i in t) and any('a' <= i <= 'z' for i in t) and any('A' <= i <= 'Z' for i in t)
print('Correct' if f(input()) else 'Too weak') | {
"input": [
"X12345\n",
"CONTEST_is_STARTED!!11\n",
"abacaba\n"
],
"output": [
"Too weak\n",
"Correct\n",
"Too weak\n"
]
} |
1,534 | 8 | Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment.
Find all integer solutions x (0 < x < 109) of the equation:
x = bΒ·s(x)a + c,
where a, b, c are some predetermined constant values and function s(x) determines the sum of all digits in the decimal representation of number x.
The teacher gives this problem to Dima for each lesson. He changes only the parameters of the equation: a, b, c. Dima got sick of getting bad marks and he asks you to help him solve this challenging problem.
Input
The first line contains three space-separated integers: a, b, c (1 β€ a β€ 5; 1 β€ b β€ 10000; - 10000 β€ c β€ 10000).
Output
Print integer n β the number of the solutions that you've found. Next print n integers in the increasing order β the solutions of the given equation. Print only integer solutions that are larger than zero and strictly less than 109.
Examples
Input
3 2 8
Output
3
10 2008 13726
Input
1 2 -18
Output
0
Input
2 2 -1
Output
4
1 31 337 967 | def solve(r):
summ=0
for i in str(abs(r)):summ+=int(i)
return summ
a,b,c=map(int,input().split())
ans=[]
for i in range(1,82):
r=(b*(i**a))+c
if r>0 and r<10**9 and solve(r)==i:ans.append(r)
print(len(ans))
print(*ans)
| {
"input": [
"3 2 8\n",
"2 2 -1\n",
"1 2 -18\n"
],
"output": [
"3\n10 2008 13726\n",
"4\n1 31 337 967\n",
"0\n\n"
]
} |
1,535 | 7 | Let's denote as <image> the number of bits set ('1' bits) in the binary representation of the non-negative integer x.
You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l β€ x β€ r, and <image> is maximum possible. If there are multiple such numbers find the smallest of them.
Input
The first line contains integer n β the number of queries (1 β€ n β€ 10000).
Each of the following n lines contain two integers li, ri β the arguments for the corresponding query (0 β€ li β€ ri β€ 1018).
Output
For each query print the answer in a separate line.
Examples
Input
3
1 2
2 4
1 10
Output
1
3
7
Note
The binary representations of numbers from 1 to 10 are listed below:
110 = 12
210 = 102
310 = 112
410 = 1002
510 = 1012
610 = 1102
710 = 1112
810 = 10002
910 = 10012
1010 = 10102 | def get(l, r):
while l | (l + 1) <= r:
l |= (l + 1)
return l
q = int(input())
for i in range(q):
l, r = map(int, input().split())
print(get(l, r))
| {
"input": [
"3\n1 2\n2 4\n1 10\n"
],
"output": [
"1\n3\n7\n"
]
} |
1,536 | 7 | Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2 Γ 2 square consisting of black pixels is formed.
Pasha has made a plan of k moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers i and j, denoting respectively the row and the column of the pixel to be colored on the current move.
Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2 Γ 2 square consisting of black pixels is formed.
Input
The first line of the input contains three integers n, m, k (1 β€ n, m β€ 1000, 1 β€ k β€ 105) β the number of rows, the number of columns and the number of moves that Pasha is going to perform.
The next k lines contain Pasha's moves in the order he makes them. Each line contains two integers i and j (1 β€ i β€ n, 1 β€ j β€ m), representing the row number and column number of the pixel that was painted during a move.
Output
If Pasha loses, print the number of the move when the 2 Γ 2 square consisting of black pixels is formed.
If Pasha doesn't lose, that is, no 2 Γ 2 square consisting of black pixels is formed during the given k moves, print 0.
Examples
Input
2 2 4
1 1
1 2
2 1
2 2
Output
4
Input
2 3 6
2 3
2 2
1 3
2 2
1 2
1 1
Output
5
Input
5 3 7
2 3
1 2
1 1
4 1
3 1
5 3
3 2
Output
0 | R=lambda:map(int,input().split())
n,m,k=R()
N=1024
g=[[0]*N for _ in range(N)]
def T(r,c):
return g[r][c] and g[r+1][c] and g[r][c+1] and g[r+1][c+1]
for i in range(k):
r,c=R()
g[r][c]=1
if T(r-1,c-1) or T(r-1,c) or T(r,c-1) or T(r,c):
print(i+1)
break
else:
print(0)
| {
"input": [
"2 2 4\n1 1\n1 2\n2 1\n2 2\n",
"5 3 7\n2 3\n1 2\n1 1\n4 1\n3 1\n5 3\n3 2\n",
"2 3 6\n2 3\n2 2\n1 3\n2 2\n1 2\n1 1\n"
],
"output": [
"4",
"0",
"5"
]
} |
1,537 | 8 | Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.
It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows:
* Pasha can boil the teapot exactly once by pouring there at most w milliliters of water;
* Pasha pours the same amount of water to each girl;
* Pasha pours the same amount of water to each boy;
* if each girl gets x milliliters of water, then each boy gets 2x milliliters of water.
In the other words, each boy should get two times more water than each girl does.
Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.
Input
The first line of the input contains two integers, n and w (1 β€ n β€ 105, 1 β€ w β€ 109) β the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters.
The second line of the input contains the sequence of integers ai (1 β€ ai β€ 109, 1 β€ i β€ 2n) β the capacities of Pasha's tea cups in milliliters.
Output
Print a single real number β the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.
Examples
Input
2 4
1 1 1 1
Output
3
Input
3 18
4 4 4 2 2 2
Output
18
Input
1 5
2 3
Output
4.5
Note
Pasha also has candies that he is going to give to girls but that is another task... | def f():
[n,w] = list(map(int,input().split(' ')))
a = list(map(int,input().split(' ')))
a.sort()
print(format(min(min(a[0],a[n]/2)*3*n,w),'.20f'))
f() | {
"input": [
"1 5\n2 3\n",
"2 4\n1 1 1 1\n",
"3 18\n4 4 4 2 2 2\n"
],
"output": [
"4.5\n",
"3.0\n",
"18.0\n"
]
} |
1,538 | 11 | Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2Β·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 β€ n β€ 100 000, 1 β€ k β€ 109).
The second line contains n integers, a1, a2, ... an (1 β€ ai β€ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other. | G_EVEN = {0:0, 1:1, 2:2}
G_ODD = {0:0, 1:1, 2:0, 3:1}
def grundy(k, ai):
if k % 2:
if ai <= 3:
return G_ODD[ai]
elif ai % 2:
return 0
else:
p = 0
j = ai
while not j & 1:
p += 1
j >>= 1
if j == 3:
return 2 if p % 2 else 1
else:
return 1 if p % 2 else 2
return 1 + p % 2
else:
if ai <= 2:
return G_EVEN[ai]
else:
return ~ai & 1
def nim_sum(ns):
s = 0
for ni in ns:
s ^= ni
return s
def winner(k, a):
return bool(nim_sum(grundy(k, ai) for ai in a))
if __name__ == '__main__':
n, k = map(int, input().split())
a = list(map(int, input().split()))
print("Kevin" if winner(k, a) else "Nicky")
| {
"input": [
"1 2\n3\n",
"2 1\n3 4\n"
],
"output": [
"Nicky\n",
"Kevin\n"
]
} |
1,539 | 7 | Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)?
Input
The first line of the input contains two integers s and x (2 β€ s β€ 1012, 0 β€ x β€ 1012), the sum and bitwise xor of the pair of positive integers, respectively.
Output
Print a single integer, the number of solutions to the given conditions. If no solutions exist, print 0.
Examples
Input
9 5
Output
4
Input
3 3
Output
2
Input
5 2
Output
0
Note
In the first sample, we have the following solutions: (2, 7), (3, 6), (6, 3), (7, 2).
In the second sample, the only solutions are (1, 2) and (2, 1). | def o(s,x):
d=s-x
if x<<1 & d or d%2 or d<0: return 0
return 2**(bin(x).count('1'))-(0 if d else 2)
s,x=map(int,input().split())
print(o(s,x)) | {
"input": [
"5 2\n",
"9 5\n",
"3 3\n"
],
"output": [
"0",
"4",
"2"
]
} |
1,540 | 7 | Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not connected to a charger) or charges by 1 percent (if connected to a charger).
Game continues while both joysticks have a positive charge. Hence, if at the beginning of minute some joystick is charged by 1 percent, it has to be connected to a charger, otherwise the game stops. If some joystick completely discharges (its charge turns to 0), the game also stops.
Determine the maximum number of minutes that game can last. It is prohibited to pause the game, i. e. at each moment both joysticks should be enabled. It is allowed for joystick to be charged by more than 100 percent.
Input
The first line of the input contains two positive integers a1 and a2 (1 β€ a1, a2 β€ 100), the initial charge level of first and second joystick respectively.
Output
Output the only integer, the maximum number of minutes that the game can last. Game continues until some joystick is discharged.
Examples
Input
3 5
Output
6
Input
4 4
Output
5
Note
In the first sample game lasts for 6 minute by using the following algorithm:
* at the beginning of the first minute connect first joystick to the charger, by the end of this minute first joystick is at 4%, second is at 3%;
* continue the game without changing charger, by the end of the second minute the first joystick is at 5%, second is at 1%;
* at the beginning of the third minute connect second joystick to the charger, after this minute the first joystick is at 3%, the second one is at 2%;
* continue the game without changing charger, by the end of the fourth minute first joystick is at 1%, second one is at 3%;
* at the beginning of the fifth minute connect first joystick to the charger, after this minute the first joystick is at 2%, the second one is at 1%;
* at the beginning of the sixth minute connect second joystick to the charger, after this minute the first joystick is at 0%, the second one is at 2%.
After that the first joystick is completely discharged and the game is stopped. | [a,b] = list(map(int,input().split(' ')))
if a < b:
a, b = b, a
def f(a, b):
if a < b:
a, b = b, a
return a//2 if a < 3 else (a-1)//2 + f(b + (a-1)//2, a-(a-1)//2*2)
print(f(a,b))
| {
"input": [
"4 4\n",
"3 5\n"
],
"output": [
"5\n",
"6\n"
]
} |
1,541 | 10 | Anton and Dasha like to play different games during breaks on checkered paper. By the 11th grade they managed to play all the games of this type and asked Vova the programmer to come up with a new game. Vova suggested to them to play a game under the code name "dot" with the following rules:
* On the checkered paper a coordinate system is drawn. A dot is initially put in the position (x, y).
* A move is shifting a dot to one of the pre-selected vectors. Also each player can once per game symmetrically reflect a dot relatively to the line y = x.
* Anton and Dasha take turns. Anton goes first.
* The player after whose move the distance from the dot to the coordinates' origin exceeds d, loses.
Help them to determine the winner.
Input
The first line of the input file contains 4 integers x, y, n, d ( - 200 β€ x, y β€ 200, 1 β€ d β€ 200, 1 β€ n β€ 20) β the initial coordinates of the dot, the distance d and the number of vectors. It is guaranteed that the initial dot is at the distance less than d from the origin of the coordinates. The following n lines each contain two non-negative numbers xi and yi (0 β€ xi, yi β€ 200) β the coordinates of the i-th vector. It is guaranteed that all the vectors are nonzero and different.
Output
You should print "Anton", if the winner is Anton in case of both players play the game optimally, and "Dasha" otherwise.
Examples
Input
0 0 2 3
1 1
1 2
Output
Anton
Input
0 0 2 4
1 1
1 2
Output
Dasha
Note
In the first test, Anton goes to the vector (1;2), and Dasha loses. In the second test Dasha with her first move shifts the dot so that its coordinates are (2;3), and Anton loses, as he has the only possible move β to reflect relatively to the line y = x. Dasha will respond to it with the same move and return the dot in position (2;3). | from sys import stdin
x,y,n,d = [int(x) for x in stdin.readline().split()]
d = d**2
v = []
for vec in range(n):
v.append([int(x) for x in stdin.readline().split()])
found = {}
def winner(x,y,v,d):
if x**2 + y**2 > d:
return 1
if (x,y) in found:
return found[(x,y)]
for a,b in v:
if winner(x+a,y+b,v,d) == 0:
found[(x,y)] = 1
return 1
found[(x,y)] = 0
return 0
if winner(x,y,v,d):
print('Anton')
else:
print('Dasha')
| {
"input": [
"0 0 2 4\n1 1\n1 2\n",
"0 0 2 3\n1 1\n1 2\n"
],
"output": [
"Dasha\n",
"Anton\n"
]
} |
1,542 | 7 | Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized a Γ b squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents how many groups of black squares there are in corresponding row or column, and the integers themselves represents the number of consecutive black squares in corresponding group (you can find more detailed explanation in Wikipedia <https://en.wikipedia.org/wiki/Japanese_crossword>).
Adaltik decided that the general case of japanese crossword is too complicated and drew a row consisting of n squares (e.g. japanese crossword sized 1 Γ n), which he wants to encrypt in the same way as in japanese crossword.
<image> The example of encrypting of a single row of japanese crossword.
Help Adaltik find the numbers encrypting the row he drew.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100) β the length of the row. The second line of the input contains a single string consisting of n characters 'B' or 'W', ('B' corresponds to black square, 'W' β to white square in the row that Adaltik drew).
Output
The first line should contain a single integer k β the number of integers encrypting the row, e.g. the number of groups of black squares in the row.
The second line should contain k integers, encrypting the row, e.g. corresponding to sizes of groups of consecutive black squares in the order from left to right.
Examples
Input
3
BBW
Output
1
2
Input
5
BWBWB
Output
3
1 1 1
Input
4
WWWW
Output
0
Input
4
BBBB
Output
1
4
Input
13
WBBBBWWBWBBBW
Output
3
4 1 3
Note
The last sample case correspond to the picture in the statement. | from sys import stdin
def read():
return stdin.readline().strip()
read()
a=[len(i) for i in read().split('W') if i]
print(len(a), *a)
| {
"input": [
"3\nBBW\n",
"5\nBWBWB\n",
"4\nWWWW\n",
"13\nWBBBBWWBWBBBW\n",
"4\nBBBB\n"
],
"output": [
"1\n2\n",
"3\n1 1 1\n",
"0\n\n",
"3\n4 1 3\n",
"1\n4\n"
]
} |
1,543 | 10 | Just to remind, girls in Arpa's land are really nice.
Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 β€ i < k, and a1 = x and ak = y.
<image>
Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it.
Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.
Input
The first line contains integers n, m and w (1 β€ n β€ 1000, <image>, 1 β€ w β€ 1000) β the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited.
The second line contains n integers w1, w2, ..., wn (1 β€ wi β€ 1000) β the weights of the Hoses.
The third line contains n integers b1, b2, ..., bn (1 β€ bi β€ 106) β the beauties of the Hoses.
The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 β€ xi, yi β€ n, xi β yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct.
Output
Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.
Examples
Input
3 1 5
3 2 5
2 4 2
1 2
Output
6
Input
4 2 11
2 4 6 6
6 4 2 1
1 2
2 3
Output
7
Note
In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.
In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. | R = lambda: map(int, input().split())
n, m, w = R()
ws = list(R())
bs = list(R())
anc = [-1] * n
def get(x):
if anc[x] < 0:
return x
anc[x] = get(anc[x])
return anc[x]
def join(x1, x2):
x1, x2 = get(x1), get(x2)
if x1 != x2:
anc[x1] = x2
for i in range(m):
x1, x2 = R()
join(x1 - 1, x2 - 1)
gps = [list() for i in range(n)]
for i in range(n):
gps[get(i)].append(i)
gps = [x for x in gps if x]
dp = [[0] * (w + 1) for i in range(len(gps) + 1)]
for i in range(len(gps)):
tw = sum(ws[x] for x in gps[i])
tb = sum(bs[x] for x in gps[i])
for j in range(w + 1):
dp[i][j] = max(tb + dp[i - 1][j - tw] if tw <= j else 0, dp[i - 1][j])
for k in gps[i]:
dp[i][j] = max(dp[i][j], (dp[i - 1][j - ws[k]] + bs[k] if ws[k] <= j else 0))
print(dp[len(gps) - 1][w]) | {
"input": [
"4 2 11\n2 4 6 6\n6 4 2 1\n1 2\n2 3\n",
"3 1 5\n3 2 5\n2 4 2\n1 2\n"
],
"output": [
"7\n",
"6\n"
]
} |
1,544 | 7 | While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.
Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.
A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
Input
The first line contains string a, and the second line β string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
Output
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
Examples
Input
abcd
defgh
Output
5
Input
a
a
Output
-1
Note
In the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a. | def main():
a, b = input(), input()
print(max(len(a), len(b)) if a != b else -1)
if __name__ == '__main__':
main()
| {
"input": [
"abcd\ndefgh\n",
"a\na\n"
],
"output": [
"5\n",
"-1\n"
]
} |
1,545 | 11 | Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass.
Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well.
Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type.
Input
The first line contains two integers n, k (0 β€ n β€ 1000, 1 β€ k β€ 106) β carbon dioxide concentration the friends want and the number of Coke types.
The second line contains k integers a1, a2, ..., ak (0 β€ ai β€ 1000) β carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration.
Output
Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible.
Examples
Input
400 4
100 300 450 500
Output
2
Input
50 2
100 25
Output
3
Note
In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>.
In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>. | from collections import deque
MAX_A = 1000
def main():
n, k = map(int, input().split())
a = set(int(x) - n for x in input().split())
visited = [False] * (2 * MAX_A + 1)
visited[n] = True
Q = deque()
Q.append((n, 0))
result = None
while Q:
u, l = Q.popleft()
l += 1
for ai in a:
v = u + ai
if v == n:
result = l
break
if 0 <= v < len(visited) and not visited[v]:
visited[v] = True
Q.append((v, l))
if result is not None:
break
if result is None:
result = -1
print(result)
if __name__ == '__main__':
# import sys
# sys.stdin = open("E.txt")
main()
| {
"input": [
"50 2\n100 25\n",
"400 4\n100 300 450 500\n"
],
"output": [
"3",
"2"
]
} |
1,546 | 8 | Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.
Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day ki products will be put up for sale and exactly li clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.
For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale ki products and Noora has chosen this day for sell-out, shelves of the shop would keep 2Β·ki products. Consequently, there is an opportunity to sell two times more products on days of sell-out.
Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.
Input
The first line contains two integers n and f (1 β€ n β€ 105, 0 β€ f β€ n) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out.
Each line of the following n subsequent lines contains two integers ki, li (0 β€ ki, li β€ 109) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.
Output
Print a single integer denoting the maximal number of products that shop can sell.
Examples
Input
4 2
2 1
3 5
2 3
1 5
Output
10
Input
4 1
0 2
0 3
3 5
0 6
Output
5
Note
In the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2, 6, 2, 2] respectively. So on the first day shop will sell 1 product, on the second β 5, on the third β 2, on the fourth β 2. In total 1 + 5 + 2 + 2 = 10 product units.
In the second example it is possible to sell 5 products, if you choose third day for sell-out. | inf = list(map(int,input().split()))
n,f=inf[0],inf[1]
arr = [0]*n
res = 0
for i in range(n):
arr[i] = list(map(int,input().split()))
res += min(arr[i])
def func(x):
return min(2*x[0],x[1])-min(x)
arr = sorted(arr,key = func,reverse=True)[:f]
for x in arr:
res += min(2*x[0],x[1])-min(x)
print(res) | {
"input": [
"4 1\n0 2\n0 3\n3 5\n0 6\n",
"4 2\n2 1\n3 5\n2 3\n1 5\n"
],
"output": [
"5",
"10"
]
} |
1,547 | 7 | Masha and Grisha like studying sets of positive integers.
One day Grisha has written a set A containing n different integers ai on a blackboard. Now he asks Masha to create a set B containing n different integers bj such that all n2 integers that can be obtained by summing up ai and bj for all possible pairs of i and j are different.
Both Masha and Grisha don't like big numbers, so all numbers in A are from 1 to 106, and all numbers in B must also be in the same range.
Help Masha to create the set B that satisfies Grisha's requirement.
Input
Input data contains multiple test cases. The first line contains an integer t β the number of test cases (1 β€ t β€ 100).
Each test case is described in the following way: the first line of the description contains one integer n β the number of elements in A (1 β€ n β€ 100).
The second line contains n integers ai β the elements of A (1 β€ ai β€ 106).
Output
For each test first print the answer:
* NO, if Masha's task is impossible to solve, there is no way to create the required set B.
* YES, if there is the way to create the required set. In this case the second line must contain n different positive integers bj β elements of B (1 β€ bj β€ 106). If there are several possible sets, output any of them.
Example
Input
3
3
1 10 100
1
1
2
2 4
Output
YES
1 2 3
YES
1
YES
1 2 | from random import randint
def solve():
n, a = int(input()), list(map(int, input().split()))
bb, ab = set(), set()
while True:
b = randint(1, 1000000)
for i in a:
if i + b in ab:
break
else:
bb.add(b)
if len(bb) == n:
break
for i in a:
ab.add(b + i)
print('YES')
print(' '.join(map(str, bb)))
T = int(input())
for i in range(T):
solve() | {
"input": [
"3\n3\n1 10 100\n1\n1\n2\n2 4\n"
],
"output": [
"YES\n1 2 3\nYES\n1\nYES\n1 2\n"
]
} |
1,548 | 7 | There is an automatic door at the entrance of a factory. The door works in the following way:
* when one or several people come to the door and it is closed, the door immediately opens automatically and all people immediately come inside,
* when one or several people come to the door and it is open, all people immediately come inside,
* opened door immediately closes in d seconds after its opening,
* if the door is closing and one or several people are coming to the door at the same moment, then all of them will have enough time to enter and only after that the door will close.
For example, if d = 3 and four people are coming at four different moments of time t1 = 4, t2 = 7, t3 = 9 and t4 = 13 then the door will open three times: at moments 4, 9 and 13. It will close at moments 7 and 12.
It is known that n employees will enter at moments a, 2Β·a, 3Β·a, ..., nΒ·a (the value a is positive integer). Also m clients will enter at moments t1, t2, ..., tm.
Write program to find the number of times the automatic door will open. Assume that the door is initially closed.
Input
The first line contains four integers n, m, a and d (1 β€ n, a β€ 109, 1 β€ m β€ 105, 1 β€ d β€ 1018) β the number of the employees, the number of the clients, the moment of time when the first employee will come and the period of time in which the door closes.
The second line contains integer sequence t1, t2, ..., tm (1 β€ ti β€ 1018) β moments of time when clients will come. The values ti are given in non-decreasing order.
Output
Print the number of times the door will open.
Examples
Input
1 1 3 4
7
Output
1
Input
4 3 4 2
7 9 11
Output
4
Note
In the first example the only employee will come at moment 3. At this moment the door will open and will stay open until the moment 7. At the same moment of time the client will come, so at first he will enter and only after it the door will close. Thus the door will open one time. | BigNum = 10 ** 20
n, m, a, d = map(int, input().split(' '))
ts = [0] + list(map(int, input().split(' '))) + [BigNum]
def empsInRange(l, r):
em1 = l // a + 1
em2 = r // a
return (em1, min(em2, n))
empDoorGroup = d // a + 1
def moveEmps(emps, last):
em1, em2 = emps
if em1 > em2:
return last, 0
if em1 * a <= last + d:
gr1 = (last + d - em1 * a) // a
em1 += 1 + gr1
if em1 > em2:
return last, 0
doorGroups = (em2 - em1 + 1 + empDoorGroup - 1) // empDoorGroup
last = (em1 + empDoorGroup * (doorGroups - 1)) * a
return last, doorGroups
res = 0
last = -BigNum
for i in range(1, len(ts)):
#print(i, ' ------------ ')
emps = empsInRange(ts[i - 1], ts[i])
#print(ts[i-1], ts[i], emps, last)
last, inc = moveEmps(emps, last)
#print('last:', last, ' inc:', inc)
res += inc
if ts[i] < BigNum and last + d < ts[i]:
res += 1
last = ts[i]
#print('temp res:', res)
print(res)
| {
"input": [
"1 1 3 4\n7\n",
"4 3 4 2\n7 9 11\n"
],
"output": [
"1\n",
"4\n"
]
} |
1,549 | 7 | Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for each incorrect guess he receives an electric shock too. The show ends when Valentin guesses the selected letter correctly.
Valentin can't keep in mind everything, so he could guess the selected letter much later than it can be uniquely determined and get excessive electric shocks. Excessive electric shocks are those which Valentin got after the moment the selected letter can be uniquely determined. You should find out the number of excessive electric shocks.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of actions Valentin did.
The next n lines contain descriptions of his actions, each line contains description of one action. Each action can be of one of three types:
1. Valentin pronounced some word and didn't get an electric shock. This action is described by the string ". w" (without quotes), in which "." is a dot (ASCII-code 46), and w is the word that Valentin said.
2. Valentin pronounced some word and got an electric shock. This action is described by the string "! w" (without quotes), in which "!" is an exclamation mark (ASCII-code 33), and w is the word that Valentin said.
3. Valentin made a guess about the selected letter. This action is described by the string "? s" (without quotes), in which "?" is a question mark (ASCII-code 63), and s is the guess β a lowercase English letter.
All words consist only of lowercase English letters. The total length of all words does not exceed 105.
It is guaranteed that last action is a guess about the selected letter. Also, it is guaranteed that Valentin didn't make correct guesses about the selected letter before the last action. Moreover, it's guaranteed that if Valentin got an electric shock after pronouncing some word, then it contains the selected letter; and also if Valentin didn't get an electric shock after pronouncing some word, then it does not contain the selected letter.
Output
Output a single integer β the number of electric shocks that Valentin could have avoided if he had told the selected letter just after it became uniquely determined.
Examples
Input
5
! abc
. ad
. b
! cd
? c
Output
1
Input
8
! hello
! codeforces
? c
. o
? d
? h
. l
? e
Output
2
Input
7
! ababahalamaha
? a
? b
? a
? b
? a
? h
Output
0
Note
In the first test case after the first action it becomes clear that the selected letter is one of the following: a, b, c. After the second action we can note that the selected letter is not a. Valentin tells word "b" and doesn't get a shock. After that it is clear that the selected letter is c, but Valentin pronounces the word cd and gets an excessive electric shock.
In the second test case after the first two electric shocks we understand that the selected letter is e or o. Valentin tries some words consisting of these letters and after the second word it's clear that the selected letter is e, but Valentin makes 3 more actions before he makes a correct hypothesis.
In the third example the selected letter can be uniquely determined only when Valentin guesses it, so he didn't get excessive electric shocks. | import string
def toset(x):
res = set()
for i in x:
res.add(i)
return res
l = toset(string.ascii_lowercase)
n = int(input())
pig = False
ans = 0
for _ in range(n - 1):
if(len(l) == 1):
pig = True
ch, x = input().split()
if(ch == '.'):
for i in x:
if(i in l):
l.remove(i)
elif(ch == '!'):
if(pig):
ans += 1
l = set.intersection(toset(x), l)
else:
if(pig):
ans += 1
if(x in l):
l.remove(x)
print (ans)
| {
"input": [
"8\n! hello\n! codeforces\n? c\n. o\n? d\n? h\n. l\n? e\n",
"7\n! ababahalamaha\n? a\n? b\n? a\n? b\n? a\n? h\n",
"5\n! abc\n. ad\n. b\n! cd\n? c\n"
],
"output": [
"2",
"0",
"1"
]
} |
1,550 | 9 | A camera you have accidentally left in a desert has taken an interesting photo. The photo has a resolution of n pixels width, and each column of this photo is all white or all black. Thus, we can represent the photo as a sequence of n zeros and ones, where 0 means that the corresponding column is all white, and 1 means that the corresponding column is black.
You think that this photo can contain a zebra. In this case the whole photo should consist of several (possibly, only one) alternating black and white stripes of equal width. For example, the photo [0, 0, 0, 1, 1, 1, 0, 0, 0] can be a photo of zebra, while the photo [0, 0, 0, 1, 1, 1, 1] can not, because the width of the black stripe is 3, while the width of the white stripe is 4. Can the given photo be a photo of zebra or not?
Input
The first line contains a single integer n (1 β€ n β€ 100 000) β the width of the photo.
The second line contains a sequence of integers a1, a2, ..., an (0 β€ ai β€ 1) β the description of the photo. If ai is zero, the i-th column is all black. If ai is one, then the i-th column is all white.
Output
If the photo can be a photo of zebra, print "YES" (without quotes). Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
9
0 0 0 1 1 1 0 0 0
Output
YES
Input
7
0 0 0 1 1 1 1
Output
NO
Input
5
1 1 1 1 1
Output
YES
Input
8
1 1 1 0 0 0 1 1
Output
NO
Input
9
1 1 0 1 1 0 1 1 0
Output
NO
Note
The first two examples are described in the statements.
In the third example all pixels are white, so the photo can be a photo of zebra.
In the fourth example the width of the first stripe is equal to three (white color), the width of the second stripe is equal to three (black), and the width of the third stripe is equal to two (white). Thus, not all stripes have equal length, so this photo is not a photo of zebra. | def solve():
n = int(input())
p = [int(x) for x in (input().split())]
c = dict()
cnt = 0
for i in range(n):
if i == 0:
cnt += 1
continue
if p[i] == p[i - 1]:
cnt += 1
if p[i] != p[i - 1]:
c[cnt] = 1
cnt = 1
if i == n - 1:
c[cnt] = 1
if len(c) < 2:
print('YES')
else:
print('NO')
solve() | {
"input": [
"9\n1 1 0 1 1 0 1 1 0\n",
"8\n1 1 1 0 0 0 1 1\n",
"7\n0 0 0 1 1 1 1\n",
"9\n0 0 0 1 1 1 0 0 0\n",
"5\n1 1 1 1 1\n"
],
"output": [
"No\n",
"No\n",
"No\n",
"Yes\n",
"Yes\n"
]
} |
1,551 | 7 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.
At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.
Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.
Input
The first line contains two integers hh and mm (00 β€ hh β€ 23, 00 β€ mm β€ 59) β the time of Andrew's awakening.
The second line contains four integers H, D, C and N (1 β€ H β€ 105, 1 β€ D, C, N β€ 102).
Output
Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if <image>.
Examples
Input
19 00
255 1 100 1
Output
25200.0000
Input
17 41
1000 6 15 11
Output
1365.0000
Note
In the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.
In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | hh, mm = map(int, input().split())
H,D,C,N = map(int, input().split())
def ceildiv(a, b):
return -(-a // b)
left = max(20*60 - hh*60-mm,0)
B = ceildiv(H + D*left,N)*C*0.8
C = ceildiv(H,N)*C*1.0
print(min(B,C)) | {
"input": [
"19 00\n255 1 100 1\n",
"17 41\n1000 6 15 11\n"
],
"output": [
"25200.0\n",
"1365\n"
]
} |
1,552 | 9 | Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. | def main():
n = int(input())
deg = [0] * n
for i in range(n - 1):
u, v = map(int, input().split())
deg[u - 1] += 1
deg[v - 1] += 1
count = 0
ans = 0
e = []
for i in range(n):
if (deg[i] > 2):
count += 1
ans = i
if (deg[i] == 1):
e.append(i)
if (count > 1):
print("No")
else:
print("Yes")
print(deg[ans])
for el in e:
if (el != ans):
print(ans + 1, el + 1)
main() | {
"input": [
"6\n1 2\n2 3\n3 4\n2 5\n3 6\n",
"4\n1 2\n2 3\n3 4\n",
"5\n1 2\n1 3\n1 4\n1 5\n"
],
"output": [
"No\n",
"Yes\n1\n1 4\n",
"Yes\n4\n1 2\n1 3\n1 4\n1 5\n"
]
} |
1,553 | 9 | As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.
Elections are coming. You know the number of voters and the number of parties β n and m respectively. For each voter you know the party he is going to vote for. However, he can easily change his vote given a certain amount of money. In particular, if you give i-th voter c_i bytecoins you can ask him to vote for any other party you choose.
The United Party of Berland has decided to perform a statistical study β you need to calculate the minimum number of bytecoins the Party needs to spend to ensure its victory. In order for a party to win the elections, it needs to receive strictly more votes than any other party.
Input
The first line of input contains two integers n and m (1 β€ n, m β€ 3000) β the number of voters and the number of parties respectively.
Each of the following n lines contains two integers p_i and c_i (1 β€ p_i β€ m, 1 β€ c_i β€ 10^9) β the index of this voter's preferred party and the number of bytecoins needed for him to reconsider his decision.
The United Party of Berland has the index 1.
Output
Print a single number β the minimum number of bytecoins needed for The United Party of Berland to win the elections.
Examples
Input
1 2
1 100
Output
0
Input
5 5
2 100
3 200
4 300
5 400
5 900
Output
500
Input
5 5
2 100
3 200
4 300
5 800
5 900
Output
600
Note
In the first sample, The United Party wins the elections even without buying extra votes.
In the second sample, The United Party can buy the votes of the first and the fourth voter. This way The Party gets two votes, while parties 3, 4 and 5 get one vote and party number 2 gets no votes.
In the third sample, The United Party can buy the votes of the first three voters and win, getting three votes against two votes of the fifth party. | import sys
import os
def solve(m, candidates):
n = len(candidates)
candidates.sort(key=lambda x: x[1])
party = dict()
granted = 0
for i in range(len(candidates)):
p = candidates[i][0]
c = candidates[i][1]
if p == 1:
granted += 1
continue
if p in party:
party[p].append((i, c))
else:
party[p] = [(i, c)]
result = None
for t in range(1, n // 2 + 2):
total = 0
chosen = set()
for k, v in party.items():
if len(v) >= t:
for i in range(len(v) + 1 - t):
chosen.add(v[i][0])
total += v[i][1]
for i in range(n):
if len(chosen) + granted >= t:
break
if i not in chosen and candidates[i][0] != 1:
chosen.add(i)
total += candidates[i][1]
if result is None:
result = total
else:
result = min(result, total)
return result
def main():
n, m = map(int, input().split())
candidates = []
for i in range(n):
p, c = map(int, input().split())
candidates.append((p, c))
print(solve(m, candidates))
if __name__ == '__main__':
main() | {
"input": [
"1 2\n1 100\n",
"5 5\n2 100\n3 200\n4 300\n5 800\n5 900\n",
"5 5\n2 100\n3 200\n4 300\n5 400\n5 900\n"
],
"output": [
"0\n",
"600\n",
"500\n"
]
} |
1,554 | 10 | Maksim has n objects and m boxes, each box has size exactly k. Objects are numbered from 1 to n in order from left to right, the size of the i-th object is a_i.
Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above. If he has no empty boxes and there is at least one object not in some box then Maksim cannot pack the chosen set of objects.
Maksim wants to know the maximum number of objects he can pack by the algorithm above. To reach this target, he will throw out the leftmost object from the set until the remaining set of objects can be packed in boxes he has. Your task is to say the maximum number of objects Maksim can pack in boxes he has.
Each time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change).
Input
The first line of the input contains three integers n, m, k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ 10^9) β the number of objects, the number of boxes and the size of each box.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ k), where a_i is the size of the i-th object.
Output
Print the maximum number of objects Maksim can pack using the algorithm described in the problem statement.
Examples
Input
5 2 6
5 2 1 4 2
Output
4
Input
5 1 4
4 2 3 4 1
Output
1
Input
5 3 3
1 2 3 1 1
Output
5
Note
In the first example Maksim can pack only 4 objects. Firstly, he tries to pack all the 5 objects. Distribution of objects will be [5], [2, 1]. Maxim cannot pack the next object in the second box and he has no more empty boxes at all. Next he will throw out the first object and the objects distribution will be [2, 1], [4, 2]. So the answer is 4.
In the second example it is obvious that Maksim cannot pack all the objects starting from first, second, third and fourth (in all these cases the distribution of objects is [4]), but he can pack the last object ([1]).
In the third example Maksim can pack all the objects he has. The distribution will be [1, 2], [3], [1, 1]. | def get_input_list():
return list(map(int, input().split()))
n, m, k = get_input_list()
a = get_input_list()
b = 0
c = k
i = n - 1
r = 0
while True:
if c < a[i]:
b += 1
if b == m:
break
c = k
c -= a[i]
r += 1
i -= 1
if i < 0:
break
print(r)
| {
"input": [
"5 3 3\n1 2 3 1 1\n",
"5 1 4\n4 2 3 4 1\n",
"5 2 6\n5 2 1 4 2\n"
],
"output": [
"5",
"1",
"4"
]
} |
1,555 | 8 | Recently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list.
For example, if x=4 and y=6 then the given list can be any permutation of the list [1, 2, 4, 1, 2, 3, 6]. Some of the possible lists are: [1, 1, 2, 4, 6, 3, 2], [4, 6, 1, 1, 2, 3, 2] or [1, 6, 3, 2, 4, 1, 2].
Your problem is to restore suitable positive integer numbers x and y that would yield the same list of divisors (possibly in different order).
It is guaranteed that the answer exists, i.e. the given list of divisors corresponds to some positive integers x and y.
Input
The first line contains one integer n (2 β€ n β€ 128) β the number of divisors of x and y.
The second line of the input contains n integers d_1, d_2, ..., d_n (1 β€ d_i β€ 10^4), where d_i is either divisor of x or divisor of y. If a number is divisor of both numbers x and y then there are two copies of this number in the list.
Output
Print two positive integer numbers x and y β such numbers that merged list of their divisors is the permutation of the given list of integers. It is guaranteed that the answer exists.
Example
Input
10
10 2 8 1 2 4 1 20 4 5
Output
20 8 | def div(a):
d = max(a)
for i in range(2,d+1):
if d%i == 0:
a.remove(i)
print(d,max(a))
n = int(input())
a = list(map(int,input().split()))
div(a)
| {
"input": [
"10\n10 2 8 1 2 4 1 20 4 5\n"
],
"output": [
"20 8\n"
]
} |
1,556 | 9 | Bob is decorating his kitchen, more precisely, the floor. He has found a prime candidate for the tiles he will use. They come in a simple form factor β a square tile that is diagonally split into white and black part as depicted in the figure below.
<image>
The dimension of this tile is perfect for this kitchen, as he will need exactly w Γ h tiles without any scraps. That is, the width of the kitchen is w tiles, and the height is h tiles. As each tile can be rotated in one of four ways, he still needs to decide on how exactly he will tile the floor. There is a single aesthetic criterion that he wants to fulfil: two adjacent tiles must not share a colour on the edge β i.e. one of the tiles must have a white colour on the shared border, and the second one must be black.
<image> The picture on the left shows one valid tiling of a 3 Γ 2 kitchen. The picture on the right shows an invalid arrangement, as the bottom two tiles touch with their white parts.
Find the number of possible tilings. As this number may be large, output its remainder when divided by 998244353 (a prime number).
Input
The only line contains two space separated integers w, h (1 β€ w,h β€ 1 000) β the width and height of the kitchen, measured in tiles.
Output
Output a single integer n β the remainder of the number of tilings when divided by 998244353.
Examples
Input
2 2
Output
16
Input
2 4
Output
64 | def main():
w,h = map(int,input().split())
print(pow(2,w+h,998244353))
main()
| {
"input": [
"2 4\n",
"2 2\n"
],
"output": [
"64\n",
"16\n"
]
} |
1,557 | 9 | n robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous!
Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the location of each robot: the world you live in can be modeled as an infinite coordinate plane, and the i-th robot is currently located at the point having coordinates (x_i, y_i). Furthermore, you may send exactly one command to all of the robots. The command should contain two integer numbers X and Y, and when each robot receives this command, it starts moving towards the point having coordinates (X, Y). The robot stops its movement in two cases:
* either it reaches (X, Y);
* or it cannot get any closer to (X, Y).
Normally, all robots should be able to get from any point of the coordinate plane to any other point. Each robot usually can perform four actions to move. Let's denote the current coordinates of the robot as (x_c, y_c). Then the movement system allows it to move to any of the four adjacent points:
1. the first action allows it to move from (x_c, y_c) to (x_c - 1, y_c);
2. the second action allows it to move from (x_c, y_c) to (x_c, y_c + 1);
3. the third action allows it to move from (x_c, y_c) to (x_c + 1, y_c);
4. the fourth action allows it to move from (x_c, y_c) to (x_c, y_c - 1).
Unfortunately, it seems that some movement systems of some robots are malfunctioning. For each robot you know which actions it can perform, and which it cannot perform.
You want to send a command so all robots gather at the same point. To do so, you have to choose a pair of integer numbers X and Y so that each robot can reach the point (X, Y). Is it possible to find such a point?
Input
The first line contains one integer q (1 β€ q β€ 10^5) β the number of queries.
Then q queries follow. Each query begins with one line containing one integer n (1 β€ n β€ 10^5) β the number of robots in the query. Then n lines follow, the i-th of these lines describes the i-th robot in the current query: it contains six integer numbers x_i, y_i, f_{i, 1}, f_{i, 2}, f_{i, 3} and f_{i, 4} (-10^5 β€ x_i, y_i β€ 10^5, 0 β€ f_{i, j} β€ 1). The first two numbers describe the initial location of the i-th robot, and the following four numbers describe which actions the i-th robot can use to move (f_{i, j} = 1 if the i-th robot can use the j-th action, and f_{i, j} = 0 if it cannot use the j-th action).
It is guaranteed that the total number of robots over all queries does not exceed 10^5.
Output
You should answer each query independently, in the order these queries appear in the input.
To answer a query, you should do one of the following:
* if it is impossible to find a point that is reachable by all n robots, print one number 0 on a separate line;
* if it is possible to find a point that is reachable by all n robots, print three space-separated integers on the same line: 1 X Y, where X and Y are the coordinates of the point reachable by all n robots. Both X and Y should not exceed 10^5 by absolute value; it is guaranteed that if there exists at least one point reachable by all robots, then at least one of such points has both coordinates not exceeding 10^5 by absolute value.
Example
Input
4
2
-1 -2 0 0 0 0
-1 -2 0 0 0 0
3
1 5 1 1 1 1
2 5 0 1 0 1
3 5 1 0 0 0
2
1337 1337 0 1 1 1
1336 1337 1 1 0 1
1
3 5 1 1 1 1
Output
1 -1 -2
1 2 5
0
1 -100000 -100000 | # x = [int(x) for x in input().split()]
q = int(input())
def solve():
n = int(input())
min_x, max_x, min_y, max_y = -100000,100000,-100000,100000
for _ in range(n):
x,y,f1,f2,f3,f4 = [int(x) for x in input().split()]
if f1 == 0:
min_x = max(min_x, x)
if f2 == 0:
max_y = min(max_y, y)
if f3 == 0:
max_x = min(max_x, x)
if f4 == 0:
min_y = max(min_y, y)
if min_x > max_x or min_y > max_y:
print(0)
else:
print(1, min_x, min_y)
for _ in range(q):
solve() | {
"input": [
"4\n2\n-1 -2 0 0 0 0\n-1 -2 0 0 0 0\n3\n1 5 1 1 1 1\n2 5 0 1 0 1\n3 5 1 0 0 0\n2\n1337 1337 0 1 1 1\n1336 1337 1 1 0 1\n1\n3 5 1 1 1 1\n"
],
"output": [
"1 -1 -2\n1 2 5\n0\n1 -100000 -100000\n"
]
} |
1,558 | 10 | The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := β(a_i)/(2)β).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the i-th element of a.
Output
Print one integer β the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0 | def main():
(n, m), d = map(int, input().split()), {}
for i in map(int, input().split()):
t = 0
while i:
d.setdefault(i, [1000000000]).append(t)
i >>= 1
t += 1
print(min(sum(sorted(v)[:m]) for v in d.values()))
if __name__ == '__main__':
main()
| {
"input": [
"5 3\n1 2 3 3 3\n",
"5 3\n1 2 3 4 5\n",
"5 3\n1 2 2 4 5\n"
],
"output": [
"0\n",
"2\n",
"1\n"
]
} |
1,559 | 10 | As the name of the task implies, you are asked to do some work with segments and trees.
Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices.
You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique β there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends.
Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one.
For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not.
Determine if the resulting graph is a tree or not.
Input
The first line contains a single integer n (1 β€ n β€ 5 β
10^5) β the number of segments.
The i-th of the next n lines contain the description of the i-th segment β two integers l_i and r_i (1 β€ l_i < r_i β€ 2n).
It is guaranteed that all segments borders are pairwise distinct.
Output
Print "YES" if the resulting graph is a tree and "NO" otherwise.
Examples
Input
6
9 12
2 11
1 3
6 10
5 7
4 8
Output
YES
Input
5
1 3
2 4
5 9
6 8
7 10
Output
NO
Input
5
5 8
3 6
2 9
7 10
1 4
Output
NO
Note
The graph corresponding to the first example:
<image>
The graph corresponding to the second example:
<image>
The graph corresponding to the third example:
<image> | import sys
input = sys.stdin.readline
def main():
N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)]
A = [None]*(2*N+1)
for i, (l, r) in enumerate(LR):
A[l] = i
A[r] = i
graph = [[] for _ in range(N)]
num_of_edge = 0
q = []
for n in range(1, 2*N+1):
p = A[n]
if LR[p][0] == n:
q.append(p)
else:
tmp = []
while True:
np = q.pop()
if np == p:
break
else:
tmp.append(np)
while tmp:
np = tmp.pop()
q.append(np)
num_of_edge += 1
graph[np].append(p)
graph[p].append(np)
if num_of_edge > N:
return False
if num_of_edge != N-1:
return False
q = [0]
checked = [False]*N
checked[0] = True
while q:
qq = []
for p in q:
for np in graph[p]:
if not checked[np]:
checked[np] = True
qq.append(np)
q = qq
for p in range(N):
if not checked[p]:
return False
return True
if __name__ == "__main__":
print("YES" if main() else "NO") | {
"input": [
"5\n5 8\n3 6\n2 9\n7 10\n1 4\n",
"5\n1 3\n2 4\n5 9\n6 8\n7 10\n",
"6\n9 12\n2 11\n1 3\n6 10\n5 7\n4 8\n"
],
"output": [
"NO\n",
"NO\n",
"YES\n"
]
} |
1,560 | 7 | Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 β€ n β€ 10^5).
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | def main():
n = int(input().strip())
A = [int(s) for s in input().strip().split()]
for i in range(31, -1, -1):
if sum((a >> i) & 1 for a in A) == 1:
break
for j, a in enumerate(A):
if (a >> i) & 1:
break
result = [A[j]] + A[:j] + A[j + 1:]
print(" ".join(str(x) for x in result))
main()
| {
"input": [
"1\n13\n",
"4\n4 0 11 6\n"
],
"output": [
"13\n",
"11 4 0 6\n"
]
} |
1,561 | 11 | Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.
Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense modifier b_j and is worth cb_j coins.
After choosing his equipment Roma can proceed to defeat some monsters. There are p monsters he can try to defeat. Monster k has defense x_k, attack y_k and possesses z_k coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster k can be defeated with a weapon i and an armor set j if a_i > x_k and b_j > y_k. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.
Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.
Help Roma find the maximum profit of the grind.
Input
The first line contains three integers n, m, and p (1 β€ n, m, p β€ 2 β
10^5) β the number of available weapons, armor sets and monsters respectively.
The following n lines describe available weapons. The i-th of these lines contains two integers a_i and ca_i (1 β€ a_i β€ 10^6, 1 β€ ca_i β€ 10^9) β the attack modifier and the cost of the weapon i.
The following m lines describe available armor sets. The j-th of these lines contains two integers b_j and cb_j (1 β€ b_j β€ 10^6, 1 β€ cb_j β€ 10^9) β the defense modifier and the cost of the armor set j.
The following p lines describe monsters. The k-th of these lines contains three integers x_k, y_k, z_k (1 β€ x_k, y_k β€ 10^6, 1 β€ z_k β€ 10^3) β defense, attack and the number of coins of the monster k.
Output
Print a single integer β the maximum profit of the grind.
Example
Input
2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
Output
1 | from bisect import bisect_right
from operator import itemgetter
# quick input by @pajenegod
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
class SegmTree:
def __init__(self, size):
N = 1
h = 0
while N < size:
N <<= 1
h += 1
self.N = N
self.h = h
self.t = [0] * (2 * N)
self.d = [0] * N
def apply(self, p, value):
self.t[p] += value
if (p < self.N):
self.d[p] += value
def build(self, p):
t = self.t
d = self.d
while p > 1:
p >>= 1
t[p] = max(t[p<<1], t[p<<1|1]) + d[p]
def rebuild(self):
t = self.t
for p in reversed(range(1, self.N)):
t[p] = max(t[p<<1], t[p<<1|1])
def push(self, p):
d = self.d
for s in range(self.h, 0, -1):
i = p >> s
if d[i] != 0:
self.apply(i<<1, d[i])
self.apply(i<<1|1, d[i])
d[i] = 0
def inc(self, l, r, value):
if l >= r:
return
l += self.N
r += self.N
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l, value)
l += 1
if r & 1:
r -= 1
self.apply(r, value)
l >>= 1
r >>= 1
self.build(l0)
self.build(r0 - 1)
def query(self, l, r):
if l >= r:
return -float('inf')
t = self.t
l += self.N
r += self.N
self.push(l)
self.push(r - 1)
res = -float('inf')
while l < r:
if l & 1:
res = max(res, t[l])
l += 1
if r & 1:
r -= 1
res = max(t[r], res)
l >>= 1
r >>= 1
return res
n, m, p = map(int, input().split())
weapon = []
for _ in range(n):
a, ca = map(int, input().split())
weapon.append((a, ca))
defense = []
for _ in range(m):
b, cb = map(int, input().split())
defense.append((b, cb))
monster = []
for _ in range(p):
x, y, z = map(int, input().split())
monster.append((x, y, z))
weapon.sort(key=itemgetter(0))
defense.sort(key=itemgetter(0))
monster.sort(key=itemgetter(0))
st = SegmTree(m)
N = st.N
t = st.t
for i, (b, cb) in enumerate(defense):
t[i + N] = -cb
st.rebuild()
i = 0
maxScore = -float('inf')
for a, ca in weapon:
st.inc(0, m, -ca)
while i < p and monster[i][0] < a:
x, y, z = monster[i]
goodDef = bisect_right(defense, (y + 1, 0))
st.inc(goodDef, m, z)
i += 1
currScore = st.query(0, m)
maxScore = max(maxScore, currScore)
st.inc(0, m, ca)
print(maxScore)
| {
"input": [
"2 3 3\n2 3\n4 7\n2 4\n3 2\n5 11\n1 2 4\n2 1 6\n3 4 6\n"
],
"output": [
"1\n"
]
} |
1,562 | 10 | Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 β€ n β€ 5 β
10^5) and m (0 β€ m β€ 5 β
10^5) β the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a β b; 1 β€ a, b β€ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, β¦, t_n, i-th of them denotes desired topic number of the i-th blog (1 β€ t_i β€ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, β¦, p_n (1 β€ p_i β€ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2. | import os,io
from sys import stdout
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def main():
I = lambda : list(map(int,input().split()));n,m = I();g=[[] for i in range(n)]
for i in range(m):a,b = I();g[a-1].append(b-1);g[b-1].append(a-1)
rc = I();c=[i for i in range(1,n+1)];c.sort(key = lambda x : rc[x-1]);mcol=[1]*n;f=1
for i in range(n):
x=c[i]-1;i=x
if rc[x]==mcol[i]:
for j in g[i]:
if mcol[j]==mcol[i]:
mcol[j]+=1
if rc[j]<mcol[j]:break
else:f=0;c=[-1];break
stdout.write(' '.join(str(i) for i in c))
main() | {
"input": [
"5 3\n1 2\n2 3\n4 5\n2 1 2 2 1\n",
"3 3\n1 2\n2 3\n3 1\n1 1 1\n",
"3 3\n1 2\n2 3\n3 1\n2 1 3\n"
],
"output": [
"2 5 1 3 4 ",
"-1\n",
"2 1 3 "
]
} |
1,563 | 11 | In the game of Mastermind, there are two players β Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.
When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers x and y.
The first integer x is the number of indices where Bob's guess correctly matches Alice's code. The second integer y is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, y is the maximum number of indices he could get correct.
For example, suppose n=5, Alice's code is [3,1,6,1,2], and Bob's guess is [3,1,1,2,5]. At indices 1 and 2 colors are equal, while in the other indices they are not equal. So x=2. And the two codes have the four colors 1,1,2,3 in common, so y=4.
<image> Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. x is the number of solid lines, and y is the total number of lines.
You are given Bob's guess and two values x and y. Can you find one possibility of Alice's code so that the values of x and y are correct?
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains three integers n,x,y (1β€ nβ€ 10^5, 0β€ xβ€ yβ€ n) β the length of the codes, and two values Alice responds with.
The second line of each test case contains n integers b_1,β¦,b_n (1β€ b_iβ€ n+1) β Bob's guess, where b_i is the i-th color of the guess.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, on the first line, output "YES" if there is a solution, or "NO" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).
If the answer is "YES", on the next line output n integers a_1,β¦,a_n (1β€ a_iβ€ n+1) β Alice's secret code, where a_i is the i-th color of the code.
If there are multiple solutions, output any.
Example
Input
7
5 2 4
3 1 1 2 5
5 3 4
1 1 2 1 2
4 0 4
5 5 3 3
4 1 4
2 3 2 3
6 1 2
3 2 1 1 1 1
6 2 4
3 3 2 1 1 1
6 2 6
1 1 3 2 1 1
Output
YES
3 1 6 1 2
YES
3 1 1 1 2
YES
3 3 5 5
NO
YES
4 4 4 4 3 1
YES
3 1 3 1 7 7
YES
2 3 1 1 1 1
Note
The first test case is described in the statement.
In the second test case, x=3 because the colors are equal at indices 2,4,5. And y=4 because they share the colors 1,1,1,2.
In the third test case, x=0 because there is no index where the colors are the same. But y=4 because they share the colors 3,3,5,5.
In the fourth test case, it can be proved that no solution exists. | from collections import defaultdict
from heapq import heapify, heappop, heappush
def solve():
n, s, y = map(int, input().split());a = input().split();d = defaultdict(list)
for i, x in enumerate(a):d[x].append(i)
for i in range(1, n + 2):
e = str(i)
if e not in d:break
q = [(-len(d[x]), x) for x in d.keys()];heapify(q);ans,p = [0] * n,[]
for i in range(s):
l, x = heappop(q);ans[d[x].pop()] = x;l += 1
if l:heappush(q, (l, x))
while q:l, x = heappop(q);p.extend(d[x])
if p:
h = (n - s) // 2;y = n - y;q = p[h:] + p[:h]
for x, z in zip(p, q):
if a[x] == a[z]:
if y:ans[x] = e;y -= 1
else:print("NO");return
else:ans[x] = a[z]
for i in range(n - s):
if y and ans[p[i]] != e:ans[p[i]] = e;y -= 1
print("YES");print(' '.join(ans))
for t in range(int(input())):solve() | {
"input": [
"7\n5 2 4\n3 1 1 2 5\n5 3 4\n1 1 2 1 2\n4 0 4\n5 5 3 3\n4 1 4\n2 3 2 3\n6 1 2\n3 2 1 1 1 1\n6 2 4\n3 3 2 1 1 1\n6 2 6\n1 1 3 2 1 1\n"
],
"output": [
"YES\n5 1 1 4 2 \nYES\n3 1 1 1 2 \nYES\n3 3 5 5 \nNO\nYES\n4 4 4 4 3 1 \nYES\n2 1 4 4 1 1 \nYES\n2 3 1 1 1 1 \n"
]
} |
1,564 | 11 | Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it.
There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_i energy. When atom i is excited, it will give A_i energy. You can excite any number of atoms (including zero).
These atoms also form a peculiar one-way bond. For each i, (1 β€ i < N), if atom i is excited, atom E_i will also be excited at no cost. Initially, E_i = i+1. Note that atom N cannot form a bond to any atom.
Mr. Chanek must change exactly K bonds. Exactly K times, Mr. Chanek chooses an atom i, (1 β€ i < N) and changes E_i to a different value other than i and the current E_i. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve!
note: You must first change exactly K bonds before you can start exciting atoms.
Input
The first line contains two integers N K (4 β€ N β€ 10^5, 0 β€ K < N), the number of atoms, and the number of bonds that must be changed.
The second line contains N integers A_i (1 β€ A_i β€ 10^6), which denotes the energy given by atom i when on excited state.
The third line contains N integers D_i (1 β€ D_i β€ 10^6), which denotes the energy needed to excite atom i.
Output
A line with an integer that denotes the maximum number of energy that Mr. Chanek can get.
Example
Input
6 1
5 6 7 8 10 2
3 5 6 7 1 10
Output
35
Note
An optimal solution to change E_5 to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35.
Another possible way is to change E_3 to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4, 5, 6). The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10 + 2) - (6 + 7) = 25 which is not optimal. | import math
N, K = map(int, input().split())
A = list(map(int, input().split()))
D = list(map(int, input().split()))
def get_suffix_sums():
suffix_sums = [0 for i in range(N)]
suffix_sums[N - 1] = A[N - 1]
for i in range(N - 2, -1, -1):
suffix_sums[i] = suffix_sums[i + 1] + A[i]
return suffix_sums
def get_sum_minus_minimum_and_second_minimum():
total_sum = 0
minimum = math.inf
second_minimum = math.inf
for i in range(len(A)):
total_sum += A[i]
x = D[i]
if x <= minimum:
second_minimum = minimum
minimum = x
elif x <= second_minimum:
second_minimum = x
return total_sum - (minimum + second_minimum)
if K == 0:
result = 0
suffix_sums = get_suffix_sums()
for i in range(N):
result = max(result, suffix_sums[i] - D[i])
print(result)
elif K == 1:
# exciting only one atom within the first N - 1
# 1. either 0 or
# 2. excite the min cost one, change E_{N - 1} to be 1, and excite N if
# it is favorable
# 3. excite some atom i in [2, N] (change E_1, doesn't matter to what)
# 4. excite 1, skip the smallest element in A other than 1
result = max(0, sum(A[:-1]) - min(D[:-1])) + max(0, A[-1] - D[-1])
suffix_sums = get_suffix_sums()
for i in range(1, N):
result = max(result, suffix_sums[i] - D[i])
result = max(result, suffix_sums[0] - min(A[1:]) - D[0])
# exciting two atoms within the first N - 1
result = max(result, get_sum_minus_minimum_and_second_minimum())
print(result)
else:
# 0 or excite one within the first N - 1 or excite only the last one
print(max(0, sum(A) - min(D[:-1]), A[-1] - D[-1]))
| {
"input": [
"6 1\n5 6 7 8 10 2\n3 5 6 7 1 10\n"
],
"output": [
"35\n"
]
} |
1,565 | 9 | You have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i.
You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: β W/2β β€ C β€ W.
Output the list of items you will put into the knapsack or determine that fulfilling the conditions is impossible.
If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights of items in the knapsack.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 10^4). Description of the test cases follows.
The first line of each test case contains integers n and W (1 β€ n β€ 200 000, 1β€ W β€ 10^{18}).
The second line of each test case contains n integers w_1, w_2, ..., w_n (1 β€ w_i β€ 10^9) β weights of the items.
The sum of n over all test cases does not exceed 200 000.
Output
For each test case, if there is no solution, print a single integer -1.
If there exists a solution consisting of m items, print m in the first line of the output and m integers j_1, j_2, ..., j_m (1 β€ j_i β€ n, all j_i are distinct) in the second line of the output β indices of the items you would like to pack into the knapsack.
If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights items in the knapsack.
Example
Input
3
1 3
3
6 2
19 8 19 69 9 4
7 12
1 1 1 17 1 1 1
Output
1
1
-1
6
1 2 3 5 6 7
Note
In the first test case, you can take the item of weight 3 and fill the knapsack just right.
In the second test case, all the items are larger than the knapsack's capacity. Therefore, the answer is -1.
In the third test case, you fill the knapsack exactly in half. | import operator
import math
def inlt():
return(list(map(int,input().split())))
T = int(input())
def solve(w, n, W):
indices, w_sorted = zip(*sorted(enumerate(w), key=operator.itemgetter(1)))
C = 0
res = []
for i in reversed(range(n)):
if w_sorted[i] > W:
continue
if C + w_sorted[i] <= W:
res.append(indices[i] + 1)
C += w_sorted[i]
if C >= math.ceil(W / 2):
break
if math.ceil(W / 2) <= C <= W:
return res
else:
return []
for t in range(T):
n, W = inlt()
w = inlt()
res = solve(w, n, W)
if len(res) == 0:
print(-1)
else:
print(len(res))
print(*res) | {
"input": [
"3\n1 3\n3\n6 2\n19 8 19 69 9 4\n7 12\n1 1 1 17 1 1 1\n"
],
"output": [
"1\n1 \n-1\n6\n1 2 3 5 6 7 \n"
]
} |
1,566 | 9 | Polycarp found under the Christmas tree an array a of n elements and instructions for playing with it:
* At first, choose index i (1 β€ i β€ n) β starting position in the array. Put the chip at the index i (on the value a_i).
* While i β€ n, add a_i to your score and move the chip a_i positions to the right (i.e. replace i with i + a_i).
* If i > n, then Polycarp ends the game.
For example, if n = 5 and a = [7, 3, 1, 2, 3], then the following game options are possible:
* Polycarp chooses i = 1. Game process: i = 1 \overset{+7}{\longrightarrow} 8. The score of the game is: a_1 = 7.
* Polycarp chooses i = 2. Game process: i = 2 \overset{+3}{\longrightarrow} 5 \overset{+3}{\longrightarrow} 8. The score of the game is: a_2 + a_5 = 6.
* Polycarp chooses i = 3. Game process: i = 3 \overset{+1}{\longrightarrow} 4 \overset{+2}{\longrightarrow} 6. The score of the game is: a_3 + a_4 = 3.
* Polycarp chooses i = 4. Game process: i = 4 \overset{+2}{\longrightarrow} 6. The score of the game is: a_4 = 2.
* Polycarp chooses i = 5. Game process: i = 5 \overset{+3}{\longrightarrow} 8. The score of the game is: a_5 = 3.
Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case contains one integer n (1 β€ n β€ 2 β
10^5) β the length of the array a.
The next line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β elements of the array a.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case, output on a separate line one number β the maximum score that Polycarp can get by playing the game on the corresponding array according to the instruction from the statement. Note that Polycarp chooses any starting position from 1 to n in such a way as to maximize his result.
Example
Input
4
5
7 3 1 2 3
3
2 1 4
6
2 1000 2 3 995 1
5
1 1 1 1 1
Output
7
6
1000
5
Note
The first test case is explained in the statement.
In the second test case, the maximum score can be achieved by choosing i = 1.
In the third test case, the maximum score can be achieved by choosing i = 2.
In the fourth test case, the maximum score can be achieved by choosing i = 1. |
def fucker():
n=int(input())
a=[int(x) for x in input().split()]
for i in range(n-1, -1,-1):
if (a[i]<(n-i)):
a[i]+=a[i+a[i]]
print(max(a))
t=int(input())
for _ in range(0, t):
fucker() | {
"input": [
"4\n5\n7 3 1 2 3\n3\n2 1 4\n6\n2 1000 2 3 995 1\n5\n1 1 1 1 1\n"
],
"output": [
"\n7\n6\n1000\n5\n"
]
} |
1,567 | 10 | You have a malfunctioning microwave in which you want to put some bananas. You have n time-steps before the microwave stops working completely. At each time-step, it displays a new operation.
Let k be the number of bananas in the microwave currently. Initially, k = 0. In the i-th operation, you are given three parameters t_i, x_i, y_i in the input. Based on the value of t_i, you must do one of the following:
Type 1: (t_i=1, x_i, y_i) β pick an a_i, such that 0 β€ a_i β€ y_i, and perform the following update a_i times: k:=β (k + x_i) β.
Type 2: (t_i=2, x_i, y_i) β pick an a_i, such that 0 β€ a_i β€ y_i, and perform the following update a_i times: k:=β (k β
x_i) β.
Note that x_i can be a fractional value. See input format for more details. Also, β x β is the smallest integer β₯ x.
At the i-th time-step, you must apply the i-th operation exactly once.
For each j such that 1 β€ j β€ m, output the earliest time-step at which you can create exactly j bananas. If you cannot create exactly j bananas, output -1.
Input
The first line contains two space-separated integers n (1 β€ n β€ 200) and m (2 β€ m β€ 10^5).
Then, n lines follow, where the i-th line denotes the operation for the i-th timestep. Each such line contains three space-separated integers t_i, x'_i and y_i (1 β€ t_i β€ 2, 1β€ y_iβ€ m).
Note that you are given x'_i, which is 10^5 β
x_i. Thus, to obtain x_i, use the formula x_i= \dfrac{x'_i} {10^5}.
For type 1 operations, 1 β€ x'_i β€ 10^5 β
m, and for type 2 operations, 10^5 < x'_i β€ 10^5 β
m.
Output
Print m integers, where the i-th integer is the earliest time-step when you can obtain exactly i bananas (or -1 if it is impossible).
Examples
Input
3 20
1 300000 2
2 400000 2
1 1000000 3
Output
-1 -1 1 -1 -1 1 -1 -1 -1 3 -1 2 3 -1 -1 3 -1 -1 -1 3
Input
3 20
1 399999 2
2 412345 2
1 1000001 3
Output
-1 -1 -1 1 -1 -1 -1 1 -1 -1 3 -1 -1 -1 3 -1 2 -1 3 -1
Note
In the first sample input, let us see how to create 16 number of bananas in three timesteps. Initially, k=0.
* In timestep 1, we choose a_1=2, so we apply the type 1 update β k := β(k+3)β β two times. Hence, k is now 6.
* In timestep 2, we choose a_2=0, hence value of k remains unchanged.
* In timestep 3, we choose a_3=1, so we are applying the type 1 update k:= β(k+10)β once. Hence, k is now 16.
It can be shown that k=16 cannot be reached in fewer than three timesteps with the given operations.
In the second sample input, let us see how to create 17 number of bananas in two timesteps. Initially, k=0.
* In timestep 1, we choose a_1=1, so we apply the type 1 update β k := β(k+3.99999)β β once. Hence, k is now 4.
* In timestep 2, we choose a_2=1, so we apply the type 2 update β k := β(kβ
4.12345)β β once. Hence, k is now 17.
It can be shown that k=17 cannot be reached in fewer than two timesteps with the given operations. | b = 10**5
def f(t,x,k):
if t==1:
return (x + k*b + b-1) // b
else:
return (x * k + b - 1) // b
n, m = map(int,input().split())
res = [-1]*(m+1)
res[0] = 0
for i in range(1,n+1):
t, x, y = map(int,input().split())
for k in range(m+1):
if res[k] in (-1,i): continue
for _ in range(y):
k = f(t,x,k)
if k > m or res[k] > -1: break
res[k] = i
res.pop(0)
print(*res) | {
"input": [
"3 20\n1 399999 2\n2 412345 2\n1 1000001 3\n",
"3 20\n1 300000 2\n2 400000 2\n1 1000000 3\n"
],
"output": [
"\n-1 -1 -1 1 -1 -1 -1 1 -1 -1 3 -1 -1 -1 3 -1 2 -1 3 -1 \n",
"\n-1 -1 1 -1 -1 1 -1 -1 -1 3 -1 2 3 -1 -1 3 -1 -1 -1 3 \n"
]
} |
1,568 | 9 | We will consider the numbers a and b as adjacent if they differ by exactly one, that is, |a-b|=1.
We will consider cells of a square matrix n Γ n as adjacent if they have a common side, that is, for cell (r, c) cells (r, c-1), (r, c+1), (r-1, c) and (r+1, c) are adjacent to it.
For a given number n, construct a square matrix n Γ n such that:
* Each integer from 1 to n^2 occurs in this matrix exactly once;
* If (r_1, c_1) and (r_2, c_2) are adjacent cells, then the numbers written in them must not be adjacent.
Input
The first line contains one integer t (1 β€ t β€ 100). Then t test cases follow.
Each test case is characterized by one integer n (1 β€ n β€ 100).
Output
For each test case, output:
* -1, if the required matrix does not exist;
* the required matrix, otherwise (any such matrix if many of them exist).
The matrix should be outputted as n lines, where each line contains n integers.
Example
Input
3
1
2
3
Output
1
-1
2 9 7
4 6 3
1 8 5 | import math
t = int(input())
def get_answer(n):
if n == 1:
print(1)
elif n == 2:
print(-1)
else:
N = n ** 2
for i in range(n):
a = [0] * n
for j in range(n):
a[j] = 1 + (i * (n - 1) + j * n) % N
print(*a)
for _ in range(t):
n = int(input())
get_answer(n)
| {
"input": [
"3\n1\n2\n3\n"
],
"output": [
"\n1\n-1\n2 9 7\n4 6 3\n1 8 5\n"
]
} |
1,569 | 7 | Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | def f(a,bad):
i=0
retain=0
while i<len(a):
c={}
while i<len(a)-1 and (a[i+1]==a[i]or a[i+1]==bad.get(a[i],None)):
c[a[i]]=c.get(a[i],0)+1
i+=1
c[a[i]] = c.get(a[i], 0) + 1
retain+=max(c.items(),key=lambda s:s[1])[1]
i+=1
return len(a)-retain
a=list(input())
n=int(input())
bad={}
for i in range(n):
l=list(input())
bad[l[0]]=l[1]
bad[l[1]]=l[0]
print(f(a,bad)) | {
"input": [
"ababa\n1\nab\n",
"codeforces\n2\ndo\ncs\n"
],
"output": [
"2\n",
"1\n"
]
} |
1,570 | 7 | You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 β€ p1 < p2 < ... < pk β€ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA | def main():
a, res = ' ', []
for b in reversed(input()):
if a <= b:
a = b
res.append(a)
print(''.join(reversed(res)))
if __name__ == '__main__':
main()
| {
"input": [
"ababba\n",
"abbcbccacbbcbaaba\n"
],
"output": [
"bbba\n",
"cccccbba\n"
]
} |
1,571 | 7 | Jabber ID on the national Berland service Β«BabberΒ» has a form <username>@<hostname>[/resource], where
* <username> β is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters Β«_Β», the length of <username> is between 1 and 16, inclusive.
* <hostname> β is a sequence of word separated by periods (characters Β«.Β»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive.
* <resource> β is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters Β«_Β», the length of <resource> is between 1 and 16, inclusive.
The content of square brackets is optional β it can be present or can be absent.
There are the samples of correct Jabber IDs: [email protected], [email protected]/contest.
Your task is to write program which checks if given string is a correct Jabber ID.
Input
The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive.
Output
Print YES or NO.
Examples
Input
[email protected]
Output
YES
Input
[email protected]/contest.icpc/12
Output
NO | def w(s):
return s.isalnum() and len(s) <= 16
def v(s):
i1, i2 = s.find('@'), s.rfind('/')
if i1 == -1 or (i2 > -1 and i1 > i2):
return False
elif not w(s[:i1]) or (i2 > -1 and not w(s[i2 + 1:])):
return False
else:
return all(w(x) for x in s[i1 + 1:(i2 if i2 > -1 else len(s))].split('.'))
print('YES' if v(input().replace('_', 'a')) else 'NO') | {
"input": [
"[email protected]\n",
"[email protected]/contest.icpc/12\n"
],
"output": [
"YES\n",
"NO\n"
]
} |
1,572 | 7 | Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.
From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k β₯ 0) units. A magical box v can be put inside a magical box u, if side length of v is strictly less than the side length of u. In particular, Emuskald can put 4 boxes of side length 2k - 1 into one box of side length 2k, or as in the following figure:
<image>
Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes.
Input
The first line of input contains an integer n (1 β€ n β€ 105), the number of different sizes of boxes Emuskald has. Each of following n lines contains two integers ki and ai (0 β€ ki β€ 109, 1 β€ ai β€ 109), which means that Emuskald has ai boxes with side length 2ki. It is guaranteed that all of ki are distinct.
Output
Output a single integer p, such that the smallest magical box that can contain all of Emuskaldβs boxes has side length 2p.
Examples
Input
2
0 3
1 5
Output
3
Input
1
0 4
Output
1
Input
2
1 10
2 2
Output
3
Note
Picture explanation. If we have 3 boxes with side length 2 and 5 boxes with side length 1, then we can put all these boxes inside a box with side length 4, for example, as shown in the picture.
In the second test case, we can put all four small boxes into a box with side length 2. | def main():
n = int(input())
m = b = 0
for k, a in sorted(tuple(map(int, input().split())) for _ in range(n)):
if k - m > 15:
b = 1 if b else 0
else:
r = 4 ** (k - m)
b = (b + r - 1) // r
if b < a:
b = a
m = k
if b == 1:
k += 1
else:
r = 1
while r < b:
r *= 4
k += 1
print(k)
if __name__ == '__main__':
main()
| {
"input": [
"2\n0 3\n1 5\n",
"1\n0 4\n",
"2\n1 10\n2 2\n"
],
"output": [
"3",
"1",
"3"
]
} |
1,573 | 9 | The problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively.
Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separated by dots. For example, the record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In this problem an arbitrary group of four 8-bit numbers is a correct IP address.
Having worked as an administrator for some time, Polycarpus learned that if you know the IP address, you can use the subnet mask to get the address of the network that has this IP addess.
The subnet mask is an IP address that has the following property: if we write this IP address as a 32 bit string, that it is representable as "11...11000..000". In other words, the subnet mask first has one or more one bits, and then one or more zero bits (overall there are 32 bits). For example, the IP address 2.0.0.0 is not a correct subnet mask as its 32-bit record looks as 00000010000000000000000000000000.
To get the network address of the IP address, you need to perform the operation of the bitwise "and" of the IP address and the subnet mask. For example, if the subnet mask is 255.192.0.0, and the IP address is 192.168.1.2, then the network address equals 192.128.0.0. In the bitwise "and" the result has a bit that equals 1 if and only if both operands have corresponding bits equal to one.
Now Polycarpus wants to find all networks to which his IP addresses belong. Unfortunately, Polycarpus lost subnet mask. Fortunately, Polycarpus remembers that his IP addresses belonged to exactly k distinct networks. Help Polycarpus find the subnet mask, such that his IP addresses will belong to exactly k distinct networks. If there are several such subnet masks, find the one whose bit record contains the least number of ones. If such subnet mask do not exist, say so.
Input
The first line contains two integers, n and k (1 β€ k β€ n β€ 105) β the number of IP addresses and networks. The next n lines contain the IP addresses. It is guaranteed that all IP addresses are distinct.
Output
In a single line print the IP address of the subnet mask in the format that is described in the statement, if the required subnet mask exists. Otherwise, print -1.
Examples
Input
5 3
0.0.0.1
0.1.1.2
0.0.2.1
0.1.1.0
0.0.2.3
Output
255.255.254.0
Input
5 2
0.0.0.1
0.1.1.2
0.0.2.1
0.1.1.0
0.0.2.3
Output
255.255.0.0
Input
2 1
255.0.0.1
0.0.0.2
Output
-1 | def f(t):
a, b, c, d = map(int, t.split('.'))
return d + (c << 8) + (b << 16) + (a << 24)
def g(x):
p = [0] * 4
for i in range(4):
p[3 - i] = str(x % 256)
x //= 256
return '.'.join(p)
n, k = map(int, input().split())
t = [f(input()) for i in range(n)]
p = [0] * n
x = 1 << 31
for i in range(32):
for j, y in enumerate(t):
if y & x: p[j] += x
if len(set(p)) >= k: break
x >>= 1
print(-1 if len(set(p)) != k else g((1 << 32) - x)) | {
"input": [
"5 3\n0.0.0.1\n0.1.1.2\n0.0.2.1\n0.1.1.0\n0.0.2.3\n",
"2 1\n255.0.0.1\n0.0.0.2\n",
"5 2\n0.0.0.1\n0.1.1.2\n0.0.2.1\n0.1.1.0\n0.0.2.3\n"
],
"output": [
"255.255.254.0\n",
"-1\n",
"255.255.0.0\n"
]
} |
1,574 | 7 | In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing".
For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).
It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again.
Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative.
As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.
We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.
Input
The first line contains three integers n, m, k (1 β€ m β€ n β€ 1000, 0 β€ k β€ 106) β total amount of Valerie's teeth, amount of tooth rows and amount of crucians in Valerie's portion for dinner. Then follow n lines, each containing two integers: r (1 β€ r β€ m) β index of the row, where belongs the corresponding tooth, and c (0 β€ c β€ 106) β its residual viability.
It's guaranteed that each tooth row has positive amount of teeth.
Output
In the first line output the maximum amount of crucians that Valerie can consume for dinner.
Examples
Input
4 3 18
2 3
1 2
3 6
2 3
Output
11
Input
2 2 13
1 13
2 12
Output
13 | # 33A
from sys import stdin
__author__ = 'artyom'
def read_int_ary():
return map(int, stdin.readline().strip().split())
n, m, k = read_int_ary()
rows = [1000001] * m
for i in range(n):
r, c = read_int_ary()
rows[r - 1] = min(rows[r - 1], c)
print(min(sum(rows), k)) | {
"input": [
"2 2 13\n1 13\n2 12\n",
"4 3 18\n2 3\n1 2\n3 6\n2 3\n"
],
"output": [
"13\n",
"11\n"
]
} |
1,575 | 9 | Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decreasing order.
for (int i = 1; i < n; i = i + 1)
{
int j = i;
while (j > 0 && a[j] < a[j - 1])
{
swap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1]
j = j - 1;
}
}
Petya uses this algorithm only for sorting of arrays that are permutations of numbers from 0 to n - 1. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement.
It is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases.
Input
The first line contains a single integer n (2 β€ n β€ 5000) β the length of the permutation. The second line contains n different integers from 0 to n - 1, inclusive β the actual permutation.
Output
Print two integers: the minimum number of times the swap function is executed and the number of such pairs (i, j) that swapping the elements of the input permutation with indexes i and j leads to the minimum number of the executions.
Examples
Input
5
4 0 3 1 2
Output
3 2
Input
5
1 2 3 4 0
Output
3 4
Note
In the first sample the appropriate pairs are (0, 3) and (0, 4).
In the second sample the appropriate pairs are (0, 4), (1, 4), (2, 4) and (3, 4). | arr = [0 for i in range(5001)]
def insertion_sort(n, a):
def modify(t):
while t > 0:
arr[t] += 1
t -= t & (-t)
def query(t):
res = 0
while t < 5001:
res += arr[t]
t += t & (-t)
return res
s = 0
ans = 0
way = 0
for i in range(n):
a[i] += 1
for i in range(n):
global arr
arr = [0 for j in range(5001)]
for j in range(i + 1, n):
if a[i] < a[j]:
continue
s += 1
tmp = 1 + 2 * query(a[j])
if tmp > ans:
ans = tmp
way = 1
elif tmp == ans:
way += 1
modify(a[j])
return s - ans, way
if __name__ == "__main__":
n = int(input())
a = list(map(int, input().split()))
result = insertion_sort(n, a)
print(*result)
| {
"input": [
"5\n1 2 3 4 0\n",
"5\n4 0 3 1 2\n"
],
"output": [
"3 4",
"3 2"
]
} |
1,576 | 7 | In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction).
Write a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.
Input
The first line of the input contains n (2 β€ n β€ 1000) β number of bidders. The second line contains n distinct integer numbers p1, p2, ... pn, separated by single spaces (1 β€ pi β€ 10000), where pi stands for the price offered by the i-th bidder.
Output
The single output line should contain two integers: index of the winner and the price he will pay. Indices are 1-based.
Examples
Input
2
5 7
Output
2 5
Input
3
10 2 8
Output
1 8
Input
6
3 8 2 9 4 14
Output
6 9 | import sys
def main():
_, *l = map(int, sys.stdin.read().strip().split())
t = sorted(zip(l, range(1, len(l)+1)))[-2:]
return t[1][1], t[0][0]
print(*main())
| {
"input": [
"6\n3 8 2 9 4 14\n",
"2\n5 7\n",
"3\n10 2 8\n"
],
"output": [
"6 9\n",
"2 5\n",
"1 8\n"
]
} |
1,577 | 7 | Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory.
Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work.
Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>.
Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 β€ x, y β€ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place.
Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers.
Input
The first line of input contains two integers n and m (1 β€ n, m β€ 105).
The next line contains m integers separated by spaces: a1, a2, ..., am (1 β€ ai β€ n).
Output
Print a single integer β the minimum number of pages Ryouko needs to turn.
Examples
Input
4 6
1 2 3 4 3 2
Output
3
Input
10 5
9 4 3 8 8
Output
6
Note
In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3.
In the second sample, optimal solution is achieved by merging page 9 to 4. | n, m = map(int, input().split())
arr = list(map(int, input().split()))
price = sum(abs(a - b) for a, b in zip(arr, arr[1:]))
from collections import defaultdict
adj = defaultdict(list)
for a,b in zip(arr, arr[1:]):
if a != b:
adj[a].append(b)
adj[b].append(a)
def median(xs):
return sorted(xs)[len(xs)//2]
res = 0
for i, xs in adj.items():
m = median(xs)
a = sum(abs(i - x) for x in xs)
b = sum(abs(m - x) for x in xs)
res = max(res, a - b)
print(price - res)
| {
"input": [
"4 6\n1 2 3 4 3 2\n",
"10 5\n9 4 3 8 8\n"
],
"output": [
"3\n",
"6\n"
]
} |
1,578 | 9 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
Input
The first line contains integer n (1 β€ n β€ 105) that shows how many numbers are in Alex's sequence.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 105).
Output
Print a single integer β the maximum number of points that Alex can earn.
Examples
Input
2
1 2
Output
2
Input
3
1 2 3
Output
4
Input
9
1 2 1 3 2 2 2 2 3
Output
10
Note
Consider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | def main():
input()
d=[0]*100001
for x in map(int,input().split()):
d[x] += x
a=b=0
for i in d:
a, b = max(a, i+b), a
print(a)
if __name__ == '__main__':
main() | {
"input": [
"9\n1 2 1 3 2 2 2 2 3\n",
"3\n1 2 3\n",
"2\n1 2\n"
],
"output": [
"10\n",
"4\n",
"2\n"
]
} |
1,579 | 7 | Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting expression is as large as possible. Let's consider an example: assume that the teacher wrote numbers 1, 2 and 3 on the blackboard. Here are some ways of placing signs and brackets:
* 1+2*3=7
* 1*(2+3)=5
* 1*2*3=6
* (1+2)*3=9
Note that you can insert operation signs only between a and b, and between b and c, that is, you cannot swap integers. For instance, in the given sample you cannot get expression (1+3)*2.
It's easy to see that the maximum value that you can obtain is 9.
Your task is: given a, b and c print the maximum value that you can get.
Input
The input contains three integers a, b and c, each on a single line (1 β€ a, b, c β€ 10).
Output
Print the maximum value of the expression that you can obtain.
Examples
Input
1
2
3
Output
9
Input
2
10
3
Output
60 | def x(): return int(input())
a = x()
b = x()
c = x()
print(max([a + b + c, a * b * c, (a + b) * c, a * (b + c)])) | {
"input": [
"2\n10\n3\n",
"1\n2\n3\n"
],
"output": [
"60\n",
"9\n"
]
} |
1,580 | 7 | Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contest started and Vasya submitted the problem d minutes after the contest started. As you know, on Codeforces the cost of a problem reduces as a round continues. That is, if you submit a problem that costs p points t minutes after the contest started, you get <image> points.
Misha and Vasya are having an argument trying to find out who got more points. Help them to find out the truth.
Input
The first line contains four integers a, b, c, d (250 β€ a, b β€ 3500, 0 β€ c, d β€ 180).
It is guaranteed that numbers a and b are divisible by 250 (just like on any real Codeforces round).
Output
Output on a single line:
"Misha" (without the quotes), if Misha got more points than Vasya.
"Vasya" (without the quotes), if Vasya got more points than Misha.
"Tie" (without the quotes), if both of them got the same number of points.
Examples
Input
500 1000 20 30
Output
Vasya
Input
1000 1000 1 1
Output
Tie
Input
1500 1000 176 177
Output
Misha | def f(p, t): return p * max(0.3, 1 - 0.004 * t)
a, b, c, d = map(int, input().split())
x, y = f(a, c), f(b, d)
print(['Tie', 'Vasya', 'Misha'][(x < y) - (x > y)]) | {
"input": [
"1000 1000 1 1\n",
"1500 1000 176 177\n",
"500 1000 20 30\n"
],
"output": [
"Tie",
"Misha",
"Vasya"
]
} |
1,581 | 8 | Vanya got an important task β he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers.
Vanya wants to know how many digits he will have to write down as he labels the books.
Input
The first line contains integer n (1 β€ n β€ 109) β the number of books in the library.
Output
Print the number of digits needed to number all the books.
Examples
Input
13
Output
17
Input
4
Output
4
Note
Note to the first test. The books get numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, which totals to 17 digits.
Note to the second sample. The books get numbers 1, 2, 3, 4, which totals to 4 digits. | def no_of_digits(n):
l=len(n)
return int(n)*l+l-int('1'*l)
n=input()
print(no_of_digits(n)) | {
"input": [
"13\n",
"4\n"
],
"output": [
"17\n",
"4\n"
]
} |
1,582 | 8 | There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.
Every contestant hopes that he can find a teammate so that their teamβs strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one.
Can you determine who will be each personβs teammate?
Input
There are 2n lines in the input.
The first line contains an integer n (1 β€ n β€ 400) β the number of teams to be formed.
The i-th line (i > 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 β€ aij β€ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
Output
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
Examples
Input
2
6
1 2
3 4 5
Output
2 1 4 3
Input
3
487060
3831 161856
845957 794650 976977
83847 50566 691206 498447
698377 156232 59015 382455 626960
Output
6 5 4 3 2 1
Note
In the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively. | def main():
n = int(input()) * 2
res = [0] * n
for _, i, j in sorted(((int(x), j, i) for i in range(1, n) for j, x in enumerate(input().split())), reverse=True):
if res[i] or res[j]:
continue
res[i], res[j] = j + 1, i + 1
print(' '.join(map(str, res)))
if __name__ == '__main__':
main()
| {
"input": [
"2\n6\n1 2\n3 4 5\n",
"3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960\n"
],
"output": [
"2 1 4 3\n",
"6 5 4 3 2 1\n"
]
} |
1,583 | 7 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.
You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).
Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.
For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
Input
The only line of input contains the string s (1 β€ |s| β€ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
Output
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34).
If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
Examples
Input
aba,123;1a;0
Output
"123,0"
"aba,1a"
Input
1;;01,a0,
Output
"1"
",01,a0,"
Input
1
Output
"1"
-
Input
a
Output
-
"a"
Note
In the second example the string s contains five words: "1", "", "01", "a0", "". | def main():
nw = ([], [])
for s in input().replace(';', ',').split(','):
nw[s.isdigit() and (s[0] != '0' or s == "0")].append(s)
for l in nw[::-1]:
print('"%s"' % ','.join(l) if l else "-")
if __name__ == '__main__':
main()
| {
"input": [
"1;;01,a0,\n",
"a\n",
"aba,123;1a;0\n",
"1\n"
],
"output": [
"\"1\"\n\",01,a0,\"\n",
"-\n\"a\"\n",
"\"123,0\"\n\"aba,1a\"\n",
"\"1\"\n-\n"
]
} |
1,584 | 10 | You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.
Let number i be in positions xi, yi (xi < yi) in the permuted array a. Let's define the value di = yi - xi β the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum <image>.
Input
The only line contains integer n (1 β€ n β€ 5Β·105).
Output
Print 2n integers β the permuted array a that minimizes the value of the sum s.
Examples
Input
2
Output
1 1 2 2
Input
1
Output
1 1 | #!/usr/bin/env python3
def make_seq(n):
os = list(range(1, n, 2))
es = list(range(2, n, 2))
ls = os[:]
if n % 2 != 0:
ls += [n]
ls += os[::-1]
ls += [n]
ls += es
if n % 2 == 0:
ls += [n]
ls += es[::-1]
return ls
def main():
print(' '.join(str(n) for n in make_seq(int(input()))))
if __name__ == '__main__':
main()
| {
"input": [
"1\n",
"2\n"
],
"output": [
"1 1 ",
"1 1 2 2 "
]
} |
1,585 | 12 | Vasya decided to pass a very large integer n to Kate. First, he wrote that number as a string, then he appended to the right integer k β the number of digits in n.
Magically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty substring of n (a substring of n is a sequence of consecutive digits of the number n).
Vasya knows that there may be more than one way to restore the number n. Your task is to find the smallest possible initial integer n. Note that decimal representation of number n contained no leading zeroes, except the case the integer n was equal to zero itself (in this case a single digit 0 was used).
Input
The first line of the input contains the string received by Kate. The number of digits in this string does not exceed 1 000 000.
The second line contains the substring of n which Vasya remembers. This string can contain leading zeroes.
It is guaranteed that the input data is correct, and the answer always exists.
Output
Print the smalles integer n which Vasya could pass to Kate.
Examples
Input
003512
021
Output
30021
Input
199966633300
63
Output
3036366999 | def main():
s = input()
if s in ("01", "10"):
print(0)
return
cnt = [0] * 58
for j in map(ord, s):
cnt[j] += 1
n, s1 = sum(cnt), input()
for le in range(n - 1, 0, -1):
if len(str(le)) + le == n:
break
for s in s1, str(le):
for j in map(ord, s):
cnt[j] -= 1
res = [''.join([s1] + [chr(i) * a for i, a in enumerate(cnt) if a])] if s1[0] > '0' else []
for i in range(49, 58):
if cnt[i]:
cnt[i] -= 1
l = [chr(i) * a for i, a in enumerate(cnt) if a]
l.append(s1)
res.append(''.join([chr(i)] + sorted(l)))
break
print(min(res))
if __name__ == '__main__':
main()
| {
"input": [
"199966633300\n63\n",
"003512\n021\n"
],
"output": [
"3036366999",
"30021"
]
} |
1,586 | 9 | As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup.
<image>
Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start.
After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right.
Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that
<image>
in other words, n is multiplication of all elements of the given array.
Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7.
Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7.
Input
The first line of input contains a single integer k (1 β€ k β€ 105) β the number of elements in array Barney gave you.
The second line contains k integers a1, a2, ..., ak (1 β€ ai β€ 1018) β the elements of the array.
Output
In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7.
Examples
Input
1
2
Output
1/2
Input
3
1 1 1
Output
0/1 | n = int(input())
ls = [int(x) for x in input().split(' ')]
t = 1
mod = 1000000007
def qpow(n: int, m: int):
m %= mod - 1
ans = 1
while m:
if m & 1: ans = ans * n % mod
n = n * n % mod
m >>= 1
return ans
k = 0
r=mod*2-2
for x in ls:
t = t * x % (mod * 2 - 2)
if x % 2 == 0:
k = 1
t = (t - 1 + r) % r
fz = (qpow(4, t >> 1) - 1) * qpow(3, mod - 2) % mod
if k == 1: fz = (fz * 2 + 1) % mod
fm = qpow(2, t)
print('{}/{}'.format(fz, fm))
| {
"input": [
"1\n2\n",
"3\n1 1 1\n"
],
"output": [
"1/2\n",
"0/1\n"
]
} |
1,587 | 10 | Dexterina and Womandark have been arch-rivals since theyβve known each other. Since both are super-intelligent teenage girls, theyβve always been trying to solve their disputes in a peaceful and nonviolent way. After god knows how many different challenges theyβve given to one another, their score is equal and theyβre both desperately trying to best the other in various games of wits. This time, Dexterina challenged Womandark to a game of Nim.
Nim is a two-player game in which players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object, and may remove any number of objects from a single heap. The player who can't make a turn loses. By their agreement, the sizes of piles are selected randomly from the range [0, x]. Each pile's size is taken independently from the same probability distribution that is known before the start of the game.
Womandark is coming up with a brand new and evil idea on how to thwart Dexterinaβs plans, so she hasnβt got much spare time. She, however, offered you some tips on looking fabulous in exchange for helping her win in Nim. Your task is to tell her what is the probability that the first player to play wins, given the rules as above.
Input
The first line of the input contains two integers n (1 β€ n β€ 109) and x (1 β€ x β€ 100) β the number of heaps and the maximum number of objects in a heap, respectively. The second line contains x + 1 real numbers, given with up to 6 decimal places each: P(0), P(1), ... , P(X). Here, P(i) is the probability of a heap having exactly i objects in start of a game. It's guaranteed that the sum of all P(i) is equal to 1.
Output
Output a single real number, the probability that the first player wins. The answer will be judged as correct if it differs from the correct answer by at most 10 - 6.
Example
Input
2 2
0.500000 0.250000 0.250000
Output
0.62500000 | from sys import stdin,stdout
def mult(x,y):
z = [0]*128
for i in range(128):
for j in range(128):
z[i^j] += x[i]*y[j]
return z
n,x = map(int,stdin.readline().split())
a = list(map(float,stdin.readline().split()))
for _ in range(x,128):
a.append(0)
ans = [0]*128
ans[0] = 1
while n > 0:
if n % 2 == 1:
ans = mult(ans,a)
a = mult(a,a)
n //= 2
stdout.write(str(1-ans[0])) | {
"input": [
"2 2\n0.500000 0.250000 0.250000\n"
],
"output": [
"0.62500000\n"
]
} |
1,588 | 11 | Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity β origami, but remembered the puzzle that she could not solve.
<image>
The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices.
The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points.
Help Dasha to find any suitable way to position the tree vertices on the plane.
It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value.
Input
The first line contains single integer n (1 β€ n β€ 30) β the number of vertices in the tree.
Each of next n - 1 lines contains two integers ui, vi (1 β€ ui, vi β€ n) that mean that the i-th edge of the tree connects vertices ui and vi.
It is guaranteed that the described graph is a tree.
Output
If the puzzle doesn't have a solution then in the only line print "NO".
Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| β€ 1018) β the coordinates of the point which corresponds to the i-th vertex of the tree.
If there are several solutions, print any of them.
Examples
Input
7
1 2
1 3
2 4
2 5
3 6
3 7
Output
YES
0 0
1 0
0 1
2 0
1 -1
-1 1
0 2
Input
6
1 2
2 3
2 4
2 5
2 6
Output
NO
Input
4
1 2
2 3
3 4
Output
YES
3 3
4 3
5 3
6 3
Note
In the first sample one of the possible positions of tree is: <image> | def dfs(v, x, y, t, l, pr):
ans[v] = x, y
p = [(0, 1, 3), (0, 1, 2), (1, 2, 3), (0, 2, 3)][t]
g[v] = [u for u in g[v] if u != pr]
for i in range(min(len(p), len(g[v]))):
newx = x + nx[p[i]][0] * l
newy = y + nx[p[i]][1] * l
dfs(g[v][i], newx, newy, p[i], l // 4, v)
read = lambda: map(int, input().split())
n = int(input())
g = [list() for i in range(n + 1)]
for i in range(n - 1):
u, v = read()
g[u].append(v)
g[v].append(u)
root = 1
for i in range(n + 1):
if len(g[i]) > 4:
print('NO')
exit()
ans = [0] * (n + 1)
ans[root] = 0, 0
inf = 10 ** 18
l = inf // 4
nx = (1, 0), (0, -1), (-1, 0), (0, 1)
for i in range(len(g[root])):
dfs(g[root][i], nx[i][0] * l, nx[i][1] * l, i, l // 4, root)
print('YES')
[print(*i) for i in ans[1:]] | {
"input": [
"6\n1 2\n2 3\n2 4\n2 5\n2 6\n",
"4\n1 2\n2 3\n3 4",
"7\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"
],
"output": [
"NO\n",
"YES\n0 0\n1073741824 0\n1610612736 0\n1879048192 0\n",
"YES\n0 0\n0 1073741824\n1073741824 0\n0 1610612736\n536870912 1073741824\n1073741824 536870912\n1610612736 0\n"
]
} |
1,589 | 7 | Array of integers is unimodal, if:
* it is strictly increasing in the beginning;
* after that it is constant;
* after that it is strictly decreasing.
The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent.
For example, the following three arrays are unimodal: [5, 7, 11, 11, 2, 1], [4, 4, 2], [7], but the following three are not unimodal: [5, 5, 6, 6, 1], [1, 2, 1, 2], [4, 5, 5, 6].
Write a program that checks if an array is unimodal.
Input
The first line contains integer n (1 β€ n β€ 100) β the number of elements in the array.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1 000) β the elements of the array.
Output
Print "YES" if the given array is unimodal. Otherwise, print "NO".
You can output each letter in any case (upper or lower).
Examples
Input
6
1 5 5 5 4 2
Output
YES
Input
5
10 20 30 20 10
Output
YES
Input
4
1 2 1 2
Output
NO
Input
7
3 3 3 3 3 3 3
Output
YES
Note
In the first example the array is unimodal, because it is strictly increasing in the beginning (from position 1 to position 2, inclusively), that it is constant (from position 2 to position 4, inclusively) and then it is strictly decreasing (from position 4 to position 6, inclusively). | I = lambda: list(map(int, input().split()))
def sign(x):
if x==0:
return 0
return x//abs(x)
n = int(input())
a = I()
d = [sign(i-j) for i, j in zip(a[1:], a[:-1])]
md = 2
for i in d:
if i<=md:
md = i
else:
md = -2
print("NO" if md==-2 else "YES") | {
"input": [
"7\n3 3 3 3 3 3 3\n",
"6\n1 5 5 5 4 2\n",
"4\n1 2 1 2\n",
"5\n10 20 30 20 10\n"
],
"output": [
"YES\n",
"YES\n",
"NO\n",
"YES\n"
]
} |
1,590 | 8 | Due to the recent popularity of the Deep learning new countries are starting to look like Neural Networks. That is, the countries are being built deep with many layers, each layer possibly having many cities. They also have one entry, and one exit point.
There are exactly L layers, each having N cities. Let us look at the two adjacent layers L1 and L2. Each city from the layer L1 is connected to each city from the layer L2 with the traveling cost cij for <image>, and each pair of adjacent layers has the same cost in between their cities as any other pair (they just stacked the same layers, as usual). Also, the traveling costs to each city from the layer L2 are same for all cities in the L1, that is cij is the same for <image>, and fixed j.
Doctor G. needs to speed up his computations for this country so he asks you to find the number of paths he can take from entry to exit point such that his traveling cost is divisible by given number M.
Input
The first line of input contains N (1 β€ N β€ 106), L (2 β€ L β€ 105) and M (2 β€ M β€ 100), the number of cities in each layer, the number of layers and the number that travelling cost should be divisible by, respectively.
Second, third and fourth line contain N integers each denoting costs 0 β€ cost β€ M from entry point to the first layer, costs between adjacent layers as described above, and costs from the last layer to the exit point.
Output
Output a single integer, the number of paths Doctor G. can take which have total cost divisible by M, modulo 109 + 7.
Example
Input
2 3 13
4 6
2 1
3 4
Output
2
Note
<image>
This is a country with 3 layers, each layer having 2 cities. Paths <image>, and <image> are the only paths having total cost divisible by 13. Notice that input edges for layer cities have the same cost, and that they are same for all layers. | from sys import stdin
input = stdin.readline
def main():
mod = 10**9 + 7
n,l,m = map(int,input().split())
ar = [0 for i in range(m)]
ar3 = [0 for i in range(m)]
def f(num):
return int(num) % m
def f2(num):
return num % 1000000007
ai1 = list(map(f,input().split()))
ai2 = list(map(f,input().split()))
ai3 = list(map(f,input().split()))
mm = m**2
ar2 = [0 for i in range(mm)]
def mult(m1,m2):
ans = [0 for i in range(mm)]
m12 = [0 for i in range(m)]
for i in range(m):
for j in range(m):
m12[i] += m1[i+j*m]
for i in range(m):
for j in range(m):
temp = (i+j)%m
for j2 in range(m):
ans[temp+j2*m] += m12[i] * m2[j+j2*m]
ans = list(map(f2,ans))
return ans
def mult2(m1,m2):
ans = [0] * m
for i in range(m):
for j in range(m):
ans[(i+j)%m] += m1[i] * m2[j]
print(ans[0] % mod)
def mult3(m1,m2):
m12 = [0 for i in range(m)]
for i in range(m):
for j in range(m):
m12[i] += m1[i+j*m]
m12[i] %= mod
m22 = [0 for i in range(m)]
for i in range(m):
for j in range(m):
m22[i] += m2[i+j*m]
m22[i] %= mod
ans = [0 for i in range(mm)]
for i in range(m):
for j in range(m):
ans[(i+j)%m] += m12[i] * m22[j]
ans[(i+j)%m] %= mod
return ans
def power(number, n):
n -= 1
if n == -1:
return number
res = number
number2 = [number[i] for i in range(mm)]
while(n):
if n & 1:
res = mult3(res,number)
number = mult3(number,number)
n >>= 1
return mult(res,number2)
for i in range(n):
ar[ai1[i]] += 1
ar2[ai2[i] + ai3[i]* m] += 1
ar3[ai2[i]] += 1
if l == 1:
mult2(ar,ar3)
return
ans = power(ar2,l-2)
ar4 = [0] * m
for i in range(m):
for j in range(m):
ar4[(i+j)%m] += ans[i + j*m]
mult2(ar,ar4)
main()
| {
"input": [
"2 3 13\n4 6\n2 1\n3 4\n"
],
"output": [
"2\n"
]
} |
1,591 | 9 | Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer x was given. The task was to add x to the sum of the digits of the number x written in decimal numeral system.
Since the number n on the board was small, Vova quickly guessed which x could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number n for all suitable values of x or determine that such x does not exist. Write such a program for Vova.
Input
The first line contains integer n (1 β€ n β€ 109).
Output
In the first line print one integer k β number of different values of x satisfying the condition.
In next k lines print these values in ascending order.
Examples
Input
21
Output
1
15
Input
20
Output
0
Note
In the first test case x = 15 there is only one variant: 15 + 1 + 5 = 21.
In the second test case there are no such x. | n = int(input())
def s(x):
return x + sum(map(int, list(str(x))))
ans = [i for i in range(max(1, n-100), n) if s(i)==n]
print(len(ans))
for i in ans:
print(i) | {
"input": [
"20\n",
"21\n"
],
"output": [
"0\n",
"1\n15 "
]
} |
1,592 | 9 | Girl Lena likes it when everything is in order, and looks for order everywhere. Once she was getting ready for the University and noticed that the room was in a mess β all the objects from her handbag were thrown about the room. Of course, she wanted to put them back into her handbag. The problem is that the girl cannot carry more than two objects at a time, and cannot move the handbag. Also, if he has taken an object, she cannot put it anywhere except her handbag β her inherent sense of order does not let her do so.
You are given the coordinates of the handbag and the coordinates of the objects in some Π‘artesian coordinate system. It is known that the girl covers the distance between any two objects in the time equal to the squared length of the segment between the points of the objects. It is also known that initially the coordinates of the girl and the handbag are the same. You are asked to find such an order of actions, that the girl can put all the objects back into her handbag in a minimum time period.
Input
The first line of the input file contains the handbag's coordinates xs, ys. The second line contains number n (1 β€ n β€ 24) β the amount of objects the girl has. The following n lines contain the objects' coordinates. All the coordinates do not exceed 100 in absolute value. All the given positions are different. All the numbers are integer.
Output
In the first line output the only number β the minimum time the girl needs to put the objects into her handbag.
In the second line output the possible optimum way for Lena. Each object in the input is described by its index number (from 1 to n), the handbag's point is described by number 0. The path should start and end in the handbag's point. If there are several optimal paths, print any of them.
Examples
Input
0 0
2
1 1
-1 1
Output
8
0 1 2 0
Input
1 1
3
4 3
3 4
0 0
Output
32
0 1 2 0 3 0 | x0, y0 = map(int, input().split())
n = int(input())
arr = [[x0, y0]]
for i in range(0, n):
x, y = map(int, input().split())
arr.append([x, y])
dist = [[0 for j in range(0, n+1)] for i in range(0, n+1)]
for i in range(0, n+1):
for j in range(0, n+1):
dist[i][j] = (arr[i][0] - arr[j][0])**2 + (arr[i][1] - arr[j][1])**2
def dfs(status, memo, pp):
if memo[status] != None:
return memo[status]
if status < 0:
return 1e8
res = 1e8
prev = []
for i in range(1, n+1):
if (status & (1 << (i - 1))) == 0:
continue
t1 = status ^ (1 << (i - 1))
# print(memo, pp)
temp = dfs(t1, memo, pp) + dist[0][i]*2
if temp < res:
res = temp
prev = [i, 0]
for j in range(i+1, n+1):
if j == i:
continue
if (t1 & (1 << (j - 1))) == 0:
continue
next = t1 ^ (1 << (j - 1))
temp = dfs(next, memo, pp) + dist[0][j] + dist[j][i] + dist[i][0]
if temp < res:
res = temp
prev = [i, j, 0]
break
memo[status] = res
pp[status] = prev
return res
memo = [None for i in range(0, 1 << n)]
pp = [None for i in range(0, 1 << n)]
memo[0] = 0
pp[0] = []
start = 0
end = 0
for i in range(0, n):
end += (1 << i)
res = dfs(end, memo, pp)
path = [0]
cur = end
while cur > 0:
prev = pp[cur]
path.extend(prev)
for i in range(len(prev) - 1):
cur -= (1 << (prev[i] - 1))
print(res)
print(' '.join(map(str, path)))
| {
"input": [
"0 0\n2\n1 1\n-1 1\n",
"1 1\n3\n4 3\n3 4\n0 0\n"
],
"output": [
"8\n0 1 2 0\n",
"32\n0 1 2 0 3 0\n"
]
} |
1,593 | 8 | Imp is in a magic forest, where xorangles grow (wut?)
<image>
A xorangle of order n is such a non-degenerate triangle, that lengths of its sides are integers not exceeding n, and the xor-sum of the lengths is equal to zero. Imp has to count the number of distinct xorangles of order n to get out of the forest.
Formally, for a given integer n you have to find the number of such triples (a, b, c), that:
* 1 β€ a β€ b β€ c β€ n;
* <image>, where <image> denotes the [bitwise xor](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of integers x and y.
* (a, b, c) form a non-degenerate (with strictly positive area) triangle.
Input
The only line contains a single integer n (1 β€ n β€ 2500).
Output
Print the number of xorangles of order n.
Examples
Input
6
Output
1
Input
10
Output
2
Note
The only xorangle in the first sample is (3, 5, 6). | def a(n):
w=0
for i in range(1,n+1):
for j in range(i,n+1):
q=i^j
if q<=j and q+i>j:w+=1
print(w//2)
a(int(input())) | {
"input": [
"6\n",
"10\n"
],
"output": [
"1\n",
"2\n"
]
} |
1,594 | 9 | Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good.
Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window.
Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.
Input
The only line contains four integers n, m, a, b (1 β€ n, m β€ 109, 1 β€ a β€ b β€ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.
Output
Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b.
Examples
Input
11 4 3 9
Output
3
Input
20 5 2 20
Output
2
Note
The images below illustrate statement tests.
The first test:
<image>
In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.
The second test:
<image>
In this test we can first select all folders in the first row (2, 3, 4, 5), then β all other ones. | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, m, a, b = map(int, input().split())
a, b = a - 1, b - 1
if b + 1 == n:
b = (b // m + 1) * m - 1
if a // m == b // m:
print(1)
elif a % m == 0 and b % m == m - 1:
print(1)
elif b % m + 1 == a % m:
print(2)
elif a // m + 1 == b // m:
print(2)
else:
ans = 1 + (a % m != 0) + (b % m != m - 1)
print(ans)
| {
"input": [
"20 5 2 20\n",
"11 4 3 9\n"
],
"output": [
"2\n",
"3\n"
]
} |
1,595 | 7 | Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements.
Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.
Input
The first line contains a single integer n (1 β€ n β€ 50) β the number of elements in Petya's array.
The following line contains a sequence a_1, a_2, ..., a_n (1 β€ a_i β€ 1 000) β the Petya's array.
Output
In the first line print integer x β the number of elements which will be left in Petya's array after he removed the duplicates.
In the second line print x integers separated with a space β Petya's array after he removed the duplicates. For each unique element only the rightmost entry should be left.
Examples
Input
6
1 5 5 1 6 1
Output
3
5 6 1
Input
5
2 4 2 4 4
Output
2
2 4
Input
5
6 6 6 6 6
Output
1
6
Note
In the first example you should remove two integers 1, which are in the positions 1 and 4. Also you should remove the integer 5, which is in the position 2.
In the second example you should remove integer 2, which is in the position 1, and two integers 4, which are in the positions 2 and 4.
In the third example you should remove four integers 6, which are in the positions 1, 2, 3 and 4. | def solve():
input()
ls = list(map(int,input().split()))
ans = []
for x in ls[::-1]:
if x not in ans:
ans = [x] + ans
print(len(ans))
print(*ans)
solve() | {
"input": [
"5\n6 6 6 6 6\n",
"6\n1 5 5 1 6 1\n",
"5\n2 4 2 4 4\n"
],
"output": [
"1\n6\n",
"3\n5 6 1\n",
"2\n2 4\n"
]
} |
1,596 | 10 | Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 β€ x_1, x_2, x_3 β€ n, 0 β€ y_1, y_2, y_3 β€ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1β€ n, m β€ 10^9, 2 β€ k β€ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i β coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7. | def gcd(a, b):
while b:
a, b = b, a % b
return a
n, m, k = map(int, input().split())
if n*m*2 % k:
print("NO")
else:
print("YES")
g1 = gcd(n, k)
n //= g1
k //= g1
g2 = gcd(m, k)
m //= g2
k //= g2
if k == 1:
if g1 == 1:
m *= 2
else:
n *= 2
print('0 0')
print('0', m)
print(n, '0')
| {
"input": [
"4 4 7\n",
"4 3 3\n"
],
"output": [
"NO",
"YES\n0 0\n4 0\n0 2\n"
]
} |
1,597 | 8 | Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid. | from array import array
def popcount(x):
res = 0;
while(x > 0):
res += (x & 1)
x >>= 1
return res
def main():
n = int(input())
a = array('i',[popcount(int(x)) for x in input().split(' ')])
ans,s0,s1 = 0,0,0
for i in range(n):
if(a[i] & 1):
s0,s1 = s1,s0 + 1
else:
s0,s1 = s0 + 1, s1
ans += s0
for i in range(n):
mx,sum = a[i],0
for j in range(i, min(n, i + 70)):
mx = max(mx, a[j]<<1)
sum += a[j]
if( (sum & 1 is 0) and (mx > sum)):
ans-=1
print(ans)
main()
| {
"input": [
"3\n6 7 14\n",
"4\n1 2 1 16\n"
],
"output": [
"2",
"4"
]
} |
1,598 | 9 | On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. | #n=int(input())
n,m=map(int,input().split())
vert=[]
for i in range(n):
v=int(input())
vert.append(v)
horz=[]
for i in range(m):
x1,x2,y=map(int,input().split())
if x1==1:
horz.append(x2)
vert.sort()
horz.sort()
vert.append(1000000000)
def next(k,a,x):
while k<len(a) and a[k]<x:
k+=1
return k
num=next(0,horz,vert[0])
ans=len(horz)-num
for i in range(1,len(vert)):
num2=next(num,horz,vert[i])
t=i+len(horz)-num2
if t<ans: ans=t
num=num2
print(ans)
| {
"input": [
"1 3\n4\n1 5 3\n1 9 4\n4 6 6\n",
"0 0\n",
"0 2\n1 1000000000 4\n1 1000000000 2\n",
"2 3\n6\n8\n1 5 6\n1 9 4\n2 4 2\n",
"2 3\n4\n6\n1 4 3\n1 5 2\n1 6 5\n"
],
"output": [
"1\n",
"0\n",
"2\n",
"1\n",
"2\n"
]
} |
1,599 | 10 | Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length n consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaard can be considered hard statements, while har, hart and drah are easy statements.
Vasya doesn't want the statement to be hard. He may remove some characters from the statement in order to make it easy. But, of course, some parts of the statement can be crucial to understanding. Initially the ambiguity of the statement is 0, and removing i-th character increases the ambiguity by a_i (the index of each character is considered as it was in the original statement, so, for example, if you delete character r from hard, and then character d, the index of d is still 4 even though you delete it from the string had).
Vasya wants to calculate the minimum ambiguity of the statement, if he removes some characters (possibly zero) so that the statement is easy. Help him to do it!
Recall that subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the length of the statement.
The second line contains one string s of length n, consisting of lowercase Latin letters β the statement written by Vasya.
The third line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 998244353).
Output
Print minimum possible ambiguity of the statement after Vasya deletes some (possibly zero) characters so the resulting statement is easy.
Examples
Input
6
hhardh
3 2 9 11 7 1
Output
5
Input
8
hhzarwde
3 2 6 9 4 8 7 1
Output
4
Input
6
hhaarr
1 2 3 4 5 6
Output
0
Note
In the first example, first two characters are removed so the result is ardh.
In the second example, 5-th character is removed so the result is hhzawde.
In the third example there's no need to remove anything. | def f(a):
s="hard"
dp=[[float("inf")]*5 for i in range(len(a)+1)]
dp[0][0]=0
for i in range(len(a)):
for j in range(4):
dp[i+1][j+(s[j]==a[i][1])]=min(dp[i+1][j+(s[j]==a[i][1])],dp[i][j])
dp[i+1][j]=min(dp[i+1][j],dp[i][j]+a[i][0])
return min(dp[len(a)][:4])
n=int(input())
s=list(input())
cost=[*map(int,input().strip().split())]
a=[*zip(cost,s)]
print(f(a)) | {
"input": [
"6\nhhaarr\n1 2 3 4 5 6\n",
"6\nhhardh\n3 2 9 11 7 1\n",
"8\nhhzarwde\n3 2 6 9 4 8 7 1\n"
],
"output": [
"0\n",
"5\n",
"4\n"
]
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.