index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
4,100 | 11 | Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future.
<image>
Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A.
During the divination, Kaavi needs to perform a sequence of operations. There are two different operations:
* Delete the first character of S and add it at the front of A.
* Delete the first character of S and add it at the back of A.
Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353.
Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different.
A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S.
Input
The first line contains a string S of length n (1 β€ n β€ 3000).
The second line contains a string T of length m (1 β€ m β€ n).
Both strings contain only lowercase Latin letters.
Output
The output contains only one integer β the answer modulo 998 244 353.
Examples
Input
abab
ba
Output
12
Input
defineintlonglong
signedmain
Output
0
Input
rotator
rotator
Output
4
Input
cacdcdbbbb
bdcaccdbbb
Output
24
Note
The first test:
<image>
The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6Γ2=12. | from functools import lru_cache
MOD = 998244353
def solve():
S = input().strip()
T = input().strip()
N = len(S)
M = len(T)
dp = [[0] * N for _ in range(N)]
for j in range(N):
if j >= M or S[0] == T[j]:
dp[j][j] = 2
for i in range(2, N + 1):
for j in range(N - i + 1):
k = j + i - 1
if j >= M or S[i - 1] == T[j]:
dp[j][k] = (dp[j][k] + dp[j + 1][k]) % MOD
if j + i - 1 >= M or S[i - 1] == T[k]:
dp[j][k] = (dp[j][k] + dp[j][k - 1]) % MOD
ans = 0
for i in range(M - 1, N):
ans = (ans + dp[0][i]) % MOD
return ans
if __name__ == '__main__':
print(solve()) | {
"input": [
"cacdcdbbbb\nbdcaccdbbb\n",
"defineintlonglong\nsignedmain\n",
"abab\nba\n",
"rotator\nrotator\n"
],
"output": [
"24\n",
"0\n",
"12\n",
"4\n"
]
} |
4,101 | 9 | Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him.
Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01010101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 0100101.
The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it.
An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.
Input
The first line contains a sequence of characters each of which can either be a "0", a "1" or a "?". This sequence determines the initial arrangement of cards on the table from the left to the right. The characters "?" mean that the given card was spoiled before the game. The sequence's length ranges from 2 to 105, inclusive.
Output
Print the set of outcomes for all possible initial digits arrangements. Print each possible outcome on a single line. Each outcome should be represented by two characters: the digits written on the cards that were left by the end of the game. The outcomes should be sorted lexicographically in ascending order (see the first sample).
Examples
Input
????
Output
00
01
10
11
Input
1010
Output
10
Input
1?1
Output
01
11
Note
In the first sample all 16 variants of numbers arrangement are possible. For the variant 0000 the outcome is 00. For the variant 1111 the outcome is 11. For the variant 0011 the outcome is 01. For the variant 1100 the outcome is 10. Regardless of outcomes for all other variants the set which we are looking for will contain all 4 possible outcomes.
In the third sample only 2 variants of numbers arrangement are possible: 111 and 101. For the variant 111 the outcome is 11. For the variant 101 the outcome is 01, because on the first turn Masha can remove the first card from the left after which the game will end. | #!/usr/bin/env python3
import sys
def rint():
return map(int, sys.stdin.readline().split())
#lines = stdin.readlines()
s = list(input())
q = s.count('?')
o = s.count('1')
z = s.count('0')
ans =[]
#00
if z+q >= o+1:
ans.append("00")
#01
tmp = o+q-z - (z+o+q)%2
if tmp%2 == 0:
x = tmp//2
if x >= 0 and x <= q:
if s[-1] == '1' or s[-1] == '?' and q-x > 0:
ans.append("01")
#10
tmp = z+q-o + (z+o+q)%2
if tmp%2 == 0:
x = tmp//2
if x >= 0 and x <= q:
if s[-1] == '0' or s[-1] == '?' and q-x > 0:
ans.append("10")
#11
if o+q >= z+2:
ans.append("11")
for a in ans:
print(a)
| {
"input": [
"????\n",
"1?1\n",
"1010\n"
],
"output": [
"00\n01\n10\n11\n",
"01\n11\n",
"10\n"
]
} |
4,102 | 12 | We start with a permutation a_1, a_2, β¦, a_n and with an empty array b. We apply the following operation k times.
On the i-th iteration, we select an index t_i (1 β€ t_i β€ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, β¦, a_n to the left in order to fill in the empty space.
You are given the initial permutation a_1, a_2, β¦, a_n and the resulting array b_1, b_2, β¦, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, β¦, t_k modulo 998 244 353.
Input
Each test contains multiple test cases. The first line contains an integer t (1 β€ t β€ 100 000), denoting the number of test cases, followed by a description of the test cases.
The first line of each test case contains two integers n, k (1 β€ k < n β€ 200 000): sizes of arrays a and b.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n): elements of a. All elements of a are distinct.
The third line of each test case contains k integers b_1, b_2, β¦, b_k (1 β€ b_i β€ n): elements of b. All elements of b are distinct.
The sum of all n among all test cases is guaranteed to not exceed 200 000.
Output
For each test case print one integer: the number of possible sequences modulo 998 244 353.
Example
Input
3
5 3
1 2 3 4 5
3 2 5
4 3
4 3 2 1
4 3 1
7 4
1 4 7 3 6 2 5
3 2 4 5
Output
2
0
4
Note
\require{cancel}
Let's denote as a_1 a_2 β¦ \cancel{a_i} \underline{a_{i+1}} β¦ a_n β a_1 a_2 β¦ a_{i-1} a_{i+1} β¦ a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b.
In the first example test, the following two options can be used to produce the given array b:
* 1 2 \underline{3} \cancel{4} 5 β 1 \underline{2} \cancel{3} 5 β 1 \cancel{2} \underline{5} β 1 2; (t_1, t_2, t_3) = (4, 3, 2);
* 1 2 \underline{3} \cancel{4} 5 β \cancel{1} \underline{2} 3 5 β 2 \cancel{3} \underline{5} β 1 5; (t_1, t_2, t_3) = (4, 1, 2).
In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step.
In the third example test, there are four options to achieve the given array b:
* 1 4 \cancel{7} \underline{3} 6 2 5 β 1 4 3 \cancel{6} \underline{2} 5 β \cancel{1} \underline{4} 3 2 5 β 4 3 \cancel{2} \underline{5} β 4 3 5;
* 1 4 \cancel{7} \underline{3} 6 2 5 β 1 4 3 \cancel{6} \underline{2} 5 β 1 \underline{4} \cancel{3} 2 5 β 1 4 \cancel{2} \underline{5} β 1 4 5;
* 1 4 7 \underline{3} \cancel{6} 2 5 β 1 4 7 \cancel{3} \underline{2} 5 β \cancel{1} \underline{4} 7 2 5 β 4 7 \cancel{2} \underline{5} β 4 7 5;
* 1 4 7 \underline{3} \cancel{6} 2 5 β 1 4 7 \cancel{3} \underline{2} 5 β 1 \underline{4} \cancel{7} 2 5 β 1 4 \cancel{2} \underline{5} β 1 4 5; | import sys
import math
def II():
return int(sys.stdin.readline())
def LI():
return list(map(int, sys.stdin.readline().split()))
def MI():
return map(int, sys.stdin.readline().split())
def SI():
return sys.stdin.readline().strip()
t = II()
for q in range(t):
n,k = MI()
ans = 1
x = [0]*(n+1)
y = [0]*(n+1)
a = LI()
b = LI()
mod = 998244353
boo = True
for i in range(n):
x[a[i]] = i
for i in range(k):
y[b[i]] = i
for i in range(k):
count = 0
tot = 0
if x[b[i]]-1>=0:
if y[a[x[b[i]]-1]] > i:
count+=1
tot+=1
if x[b[i]]+1<n:
if y[a[x[b[i]]+1]] > i:
count+=1
tot+=1
if tot == count:
boo = False
break
elif count == 0 and tot == 2:
ans*=2
ans%=mod
print(0 if not boo else ans)
| {
"input": [
"3\n5 3\n1 2 3 4 5\n3 2 5\n4 3\n4 3 2 1\n4 3 1\n7 4\n1 4 7 3 6 2 5\n3 2 4 5\n"
],
"output": [
"2\n0\n4\n"
]
} |
4,103 | 7 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS".
You are given a sequence s of n characters (, ), and/or ?. There is exactly one character ( and exactly one character ) in this sequence.
You have to replace every character ? with either ) or ( (different characters ? can be replaced with different brackets). You cannot reorder the characters, remove them, insert other characters, and each ? must be replaced.
Determine if it is possible to obtain an RBS after these replacements.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of test cases.
Each test case consists of one line containing s (2 β€ |s| β€ 100) β a sequence of characters (, ), and/or ?. There is exactly one character ( and exactly one character ) in this sequence.
Output
For each test case, print YES if it is possible to obtain a regular bracket sequence, or NO otherwise}.
You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).
Example
Input
5
()
(?)
(??)
??()
)?(?
Output
YES
NO
YES
YES
NO
Note
In the first test case, the sequence is already an RBS.
In the third test case, you can obtain an RBS as follows: ()() or (()).
In the fourth test case, you can obtain an RBS as follows: ()(). | n = int(input())
def solve(x):
if len(x) % 2 == 1:
return "NO"
if x[0] == ')' or x[-1] == '(': return "NO"
return "YES"
for _ in range(n):
print(solve(input()))
| {
"input": [
"5\n()\n(?)\n(??)\n??()\n)?(?\n"
],
"output": [
"\nYES\nNO\nYES\nYES\nNO\n"
]
} |
4,104 | 9 | You are playing a game similar to Sokoban on an infinite number line. The game is discrete, so you only consider integer positions on the line.
You start on a position 0. There are n boxes, the i-th box is on a position a_i. All positions of the boxes are distinct. There are also m special positions, the j-th position is b_j. All the special positions are also distinct.
In one move you can go one position to the left or to the right. If there is a box in the direction of your move, then you push the box to the next position in that direction. If the next position is taken by another box, then that box is also pushed to the next position, and so on. You can't go through the boxes. You can't pull the boxes towards you.
You are allowed to perform any number of moves (possibly, zero). Your goal is to place as many boxes on special positions as possible. Note that some boxes can be initially placed on special positions.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then descriptions of t testcases follow.
The first line of each testcase contains two integers n and m (1 β€ n, m β€ 2 β
10^5) β the number of boxes and the number of special positions, respectively.
The second line of each testcase contains n distinct integers in the increasing order a_1, a_2, ..., a_n (-10^9 β€ a_1 < a_2 < ... < a_n β€ 10^9; a_i β 0) β the initial positions of the boxes.
The third line of each testcase contains m distinct integers in the increasing order b_1, b_2, ..., b_m (-10^9 β€ b_1 < b_2 < ... < b_m β€ 10^9; b_i β 0) β the special positions.
The sum of n over all testcases doesn't exceed 2 β
10^5. The sum of m over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print a single integer β the maximum number of boxes that can be placed on special positions.
Example
Input
5
5 6
-1 1 5 11 15
-4 -3 -2 6 7 15
2 2
-1 1
-1000000000 1000000000
2 2
-1000000000 1000000000
-1 1
3 5
-1 1 2
-2 -1 1 2 5
2 1
1 2
10
Output
4
2
0
3
1
Note
In the first testcase you can go 5 to the right: the box on position 1 gets pushed to position 6 and the box on position 5 gets pushed to position 7. Then you can go 6 to the left to end up on position -1 and push a box to -2. At the end, the boxes are on positions [-2, 6, 7, 11, 15], respectively. Among them positions [-2, 6, 7, 15] are special, thus, the answer is 4.
In the second testcase you can push the box from -1 to -10^9, then the box from 1 to 10^9 and obtain the answer 2.
The third testcase showcases that you are not allowed to pull the boxes, thus, you can't bring them closer to special positions.
In the fourth testcase all the boxes are already on special positions, so you can do nothing and still obtain the answer 3.
In the fifth testcase there are fewer special positions than boxes. You can move either 8 or 9 to the right to have some box on position 10. | from bisect import*
l=bisect_left;r=range
def s(a):
A,B=a;S=set(A);b=len(B);C=[0]*(b+1)
for i in r(b-1,-1,-1):
if B[i] in S:C[i]+=1
C[i]+=C[i+1]
a=C[0];X=0
for i in r(b):
while X<len(A) and A[X]<=B[i]:X+=1
if X>0:a=max(a,l(B,B[i])-l(B,B[i]-X+1)+1+C[i+1])
return a
def g():
A=[];B=[]
for v in p():
if v<0:A+=-v,
else:B+=v,
return A[::-1],B
p=lambda:map(int,input().split())
for t in r(*p()):p();print(sum(map(s,zip(g(),g())))) | {
"input": [
"5\n5 6\n-1 1 5 11 15\n-4 -3 -2 6 7 15\n2 2\n-1 1\n-1000000000 1000000000\n2 2\n-1000000000 1000000000\n-1 1\n3 5\n-1 1 2\n-2 -1 1 2 5\n2 1\n1 2\n10\n"
],
"output": [
"\n4\n2\n0\n3\n1\n"
]
} |
4,105 | 8 | The 2050 volunteers are organizing the "Run! Chase the Rising Sun" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town.
There are n+1 checkpoints on the trail. They are numbered by 0, 1, ..., n. A runner must start at checkpoint 0 and finish at checkpoint n. No checkpoint is skippable β he must run from checkpoint 0 to checkpoint 1, then from checkpoint 1 to checkpoint 2 and so on. Look at the picture in notes section for clarification.
Between any two adjacent checkpoints, there are m different paths to choose. For any 1β€ iβ€ n, to run from checkpoint i-1 to checkpoint i, a runner can choose exactly one from the m possible paths. The length of the j-th path between checkpoint i-1 and i is b_{i,j} for any 1β€ jβ€ m and 1β€ iβ€ n.
To test the trail, we have m runners. Each runner must run from the checkpoint 0 to the checkpoint n once, visiting all the checkpoints. Every path between every pair of adjacent checkpoints needs to be ran by exactly one runner. If a runner chooses the path of length l_i between checkpoint i-1 and i (1β€ iβ€ n), his tiredness is $$$min_{i=1}^n l_i,$$$ i. e. the minimum length of the paths he takes.
Please arrange the paths of the m runners to minimize the sum of tiredness of them.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 10 000). Description of the test cases follows.
The first line of each test case contains two integers n and m (1 β€ n,m β€ 100).
The i-th of the next n lines contains m integers b_{i,1}, b_{i,2}, ..., b_{i,m} (1 β€ b_{i,j} β€ 10^9).
It is guaranteed that the sum of nβ
m over all test cases does not exceed 10^4.
Output
For each test case, output n lines. The j-th number in the i-th line should contain the length of the path that runner j chooses to run from checkpoint i-1 to checkpoint i. There should be exactly m integers in the i-th line and these integers should form a permuatation of b_{i, 1}, ..., b_{i, m} for all 1β€ iβ€ n.
If there are multiple answers, print any.
Example
Input
2
2 3
2 3 4
1 3 5
3 2
2 3
4 1
3 5
Output
2 3 4
5 3 1
2 3
4 1
3 5
Note
In the first case, the sum of tiredness is min(2,5) + min(3,3) + min(4,1) = 6.
<image>
In the second case, the sum of tiredness is min(2,4,3) + min(3,1,5) = 3. | def ints():
return map(int, input().split())
for _ in range(int(input())):
n, m = ints()
s = []
for i in range(n):
for j in ints():
s.append([j, i])
s.sort()
res = [[0] * m for i in range(n)]
for i in range(m):
res[s[i][1]][i] = s[i][0]
for i in range(m, n*m):
for j in range(m):
if not res[s[i][1]][j]:
res[s[i][1]][j] = s[i][0]
break
for row in res:
print(*row)
| {
"input": [
"2\n2 3\n2 3 4\n1 3 5\n3 2\n2 3\n4 1\n3 5\n"
],
"output": [
"\n2 3 4\n5 3 1\n2 3\n4 1\n3 5\n"
]
} |
4,106 | 7 | AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right. | T = int(input())
from collections import defaultdict
def solve():
n = int(input())
nums = [int(x) for x in input().split()]
arr = sorted(nums)
d = defaultdict(int)
for symb, data in ((1, nums), (-1, arr)):
for i, x in enumerate(data):
d[x] += symb if i%2==0 else -symb
for k in d:
if d[k] != 0:
print("NO")
return
print("YES")
for _ in range(T):
solve()
| {
"input": [
"3\n4\n4 3 2 5\n4\n3 3 2 2\n5\n1 2 3 5 4\n"
],
"output": [
"YES\nYES\nNO\n"
]
} |
4,107 | 7 | As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as <image>, where k is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers.
A well-known hipster Andrew adores everything funky and cool but unfortunately, he isn't good at maths. Given number n, help him define whether this number can be represented by a sum of two triangular numbers (not necessarily different)!
Input
The first input line contains an integer n (1 β€ n β€ 109).
Output
Print "YES" (without the quotes), if n can be represented as a sum of two triangular numbers, otherwise print "NO" (without the quotes).
Examples
Input
256
Output
YES
Input
512
Output
NO
Note
In the first sample number <image>.
In the second sample number 512 can not be represented as a sum of two triangular numbers. | n=int(input())
a=set([k*(k+1)//2 for k in range(1,int(2*n**.5))])
def fn(a):
for i in a:
if n-i in a:return 'YES'
return 'NO'
print(fn(a))
| {
"input": [
"512\n",
"256\n"
],
"output": [
"NO\n",
"YES\n"
]
} |
4,108 | 7 | Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles.
The hall also turned out hexagonal in its shape. The King walked along the perimeter of the hall and concluded that each of the six sides has a, b, c, a, b and c adjacent tiles, correspondingly.
To better visualize the situation, look at the picture showing a similar hexagon for a = 2, b = 3 and c = 4.
<image>
According to the legend, as the King of Berland obtained the values a, b and c, he almost immediately calculated the total number of tiles on the hall floor. Can you do the same?
Input
The first line contains three integers: a, b and c (2 β€ a, b, c β€ 1000).
Output
Print a single number β the total number of tiles on the hall floor.
Examples
Input
2 3 4
Output
18 | # 216A
def do():
a, b, c = map(int, input().split(" "))
print((b + a - 1) * (c + a - 1) - a * (a - 1))
do()
| {
"input": [
"2 3 4\n"
],
"output": [
"18"
]
} |
4,109 | 7 | You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).
Input
The first input line contains the string. It's guaranteed, that the string is non-empty, consists of lower-case Latin letters, and its length doesn't exceed 100.
Output
Output one number β length of the longest substring that can be met in the string at least twice.
Examples
Input
abcd
Output
0
Input
ababa
Output
3
Input
zzz
Output
2 | def cnt(s,t):
i,c=0,0
while(s.count(t)):
s=s[s[i:].index(t)+1:]
c+=1
return c
s=(input())
n=len(s)
ln=0
for i in range(n):
for j in range(i,n):
if(j-i+1<=ln):
continue
if(cnt(s,s[i:j+1])>=2):
ln=max(ln,j-i+1)
print(ln)
| {
"input": [
"abcd\n",
"ababa\n",
"zzz\n"
],
"output": [
"0",
"3",
"2"
]
} |
4,110 | 10 | Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as n holes in a row. We will consider the holes numbered from 1 to n, from left to right.
Ilya is really keep on helping his city. So, he wants to fix at least k holes (perharps he can fix more) on a single ZooVille road.
The city has m building companies, the i-th company needs ci money units to fix a road segment containing holes with numbers of at least li and at most ri. The companies in ZooVille are very greedy, so, if they fix a segment containing some already fixed holes, they do not decrease the price for fixing the segment.
Determine the minimum money Ilya will need to fix at least k holes.
Input
The first line contains three integers n, m, k (1 β€ n β€ 300, 1 β€ m β€ 105, 1 β€ k β€ n). The next m lines contain the companies' description. The i-th line contains three integers li, ri, ci (1 β€ li β€ ri β€ n, 1 β€ ci β€ 109).
Output
Print a single integer β the minimum money Ilya needs to fix at least k holes.
If it is impossible to fix at least k holes, print -1.
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
10 4 6
7 9 11
6 9 13
7 7 7
3 5 6
Output
17
Input
10 7 1
3 4 15
8 9 8
5 6 8
9 10 6
1 4 2
1 4 10
8 10 13
Output
2
Input
10 1 9
5 10 14
Output
-1 | """
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.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")
from collections import defaultdict as dd, deque as dq
import math, string
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
MOD = 10**9+7
"""
min cost to fix 1 hole is the min cost of any segment
min cost to fix 2 holes is the min cost of all segments length >= 2, or the min cost of two distinct segments length 1
min cost to fix K holes is the min cost of all segments length >= K, or the min cost of fixing K-1 segments + the min cost of any other segment
What is the cost of filling interval [L,R]?
"""
from bisect import bisect_left
def solve():
N, M, K = getInts()
costs = []
cost = [[float('inf') for R in range(N+1)] for L in range(N+1)]
for m in range(M):
L, R, C = getInts()
L -= 1
costs.append((L,R,C))
cost[L][R] = min(cost[L][R], C)
for L in range(N+1):
for R in range(1,N+1):
cost[R][L] = min(cost[R][L], cost[R-1][L])
dp = [[10**18 for R in range(N+1)] for L in range(N+1)]
#print(cost)
for i in range(N):
dp[i][0] = 0
for j in range(i+1):
if dp[i][j] < 10**18:
dp[i+1][j] = min(dp[i+1][j], dp[i][j])
for k in range(i+1,N+1):
dp[k][j+k-i] = min(dp[k][j+k-i],dp[i][j]+cost[i][k])
ans = 10**18
#print(dp)
ans = dp[N][K]
return ans if ans < 10**18 else -1
#for _ in range(getInt()):
print(solve())
#solve() | {
"input": [
"10 4 6\n7 9 11\n6 9 13\n7 7 7\n3 5 6\n",
"10 7 1\n3 4 15\n8 9 8\n5 6 8\n9 10 6\n1 4 2\n1 4 10\n8 10 13\n",
"10 1 9\n5 10 14\n"
],
"output": [
"17\n",
"2\n",
"-1\n"
]
} |
4,111 | 7 | Vasily the bear has a favorite rectangle, it has one vertex at point (0, 0), and the opposite vertex at point (x, y). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes.
Vasya also loves triangles, if the triangles have one vertex at point B = (0, 0). That's why today he asks you to find two points A = (x1, y1) and C = (x2, y2), such that the following conditions hold:
* the coordinates of points: x1, x2, y1, y2 are integers. Besides, the following inequation holds: x1 < x2;
* the triangle formed by point A, B and C is rectangular and isosceles (<image> is right);
* all points of the favorite rectangle are located inside or on the border of triangle ABC;
* the area of triangle ABC is as small as possible.
Help the bear, find the required points. It is not so hard to proof that these points are unique.
Input
The first line contains two integers x, y ( - 109 β€ x, y β€ 109, x β 0, y β 0).
Output
Print in the single line four integers x1, y1, x2, y2 β the coordinates of the required points.
Examples
Input
10 5
Output
0 15 15 0
Input
-10 5
Output
-15 0 0 15
Note
<image>
Figure to the first sample | def f(l):
x,y = l
yy = y+x if y*x>0 else y-x
xx = x+y if y*x>0 else x-y
return [xx,0,0,yy] if xx<0 else [0,yy,xx,0]
l = list(map(int,input().split()))
print(*f(l))
| {
"input": [
"-10 5\n",
"10 5\n"
],
"output": [
"-15 0 0 15 ",
"0 15 15 0"
]
} |
4,112 | 8 | A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn.
Simon has a positive integer n and a non-negative integer k, such that 2k β€ n. Help him find permutation a of length 2n, such that it meets this equation: <image>.
Input
The first line contains two integers n and k (1 β€ n β€ 50000, 0 β€ 2k β€ n).
Output
Print 2n integers a1, a2, ..., a2n β the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them.
Examples
Input
1 0
Output
1 2
Input
2 1
Output
3 2 1 4
Input
4 0
Output
2 7 4 6 1 3 5 8
Note
Record |x| represents the absolute value of number x.
In the first sample |1 - 2| - |1 - 2| = 0.
In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2.
In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0. | def mi():
return map(int, input().split())
n,k = mi()
a = list(range(2*n+1))
for i in range(1, k+1):
a[2*i], a[2*i-1] = a[2*i-1], a[2*i]
print (*a[1:])
| {
"input": [
"1 0\n",
"2 1\n",
"4 0\n"
],
"output": [
"1 2 ",
"2 1 3 4 ",
"1 2 3 4 5 6 7 8 "
]
} |
4,113 | 7 | Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium.
The scales is in equilibrium if the total sum of weights on the left pan is equal to the total sum of weights on the right pan.
Input
The first line has a non-empty sequence of characters describing the scales. In this sequence, an uppercase English letter indicates a weight, and the symbol "|" indicates the delimiter (the character occurs in the sequence exactly once). All weights that are recorded in the sequence before the delimiter are initially on the left pan of the scale. All weights that are recorded in the sequence after the delimiter are initially on the right pan of the scale.
The second line contains a non-empty sequence containing uppercase English letters. Each letter indicates a weight which is not used yet.
It is guaranteed that all the English letters in the input data are different. It is guaranteed that the input does not contain any extra characters.
Output
If you cannot put all the weights on the scales so that the scales were in equilibrium, print string "Impossible". Otherwise, print the description of the resulting scales, copy the format of the input.
If there are multiple answers, print any of them.
Examples
Input
AC|T
L
Output
AC|TL
Input
|ABC
XYZ
Output
XYZ|ABC
Input
W|T
F
Output
Impossible
Input
ABC|
D
Output
Impossible | def inp():
return map(str, input().split('|'))
left, right = inp()
l, r = len(left), len(right)
rem, sum = input(), l + r
total = (sum + len(rem)) // 2
s1, s2 = left + rem[0:total - len(left)],right + rem[total - len(left):]
if (len(s1) == len(s2)):
exit(print(s1+ '|' +s2 ))
print('Impossible')
| {
"input": [
"W|T\nF\n",
"AC|T\nL\n",
"ABC|\nD\n",
"|ABC\nXYZ\n"
],
"output": [
"Impossible\n",
"AC|TL\n",
"Impossible\n",
"XYZ|ABC\n"
]
} |
4,114 | 10 | You have k pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has n1 washing machines, n2 drying machines and n3 folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before it is dried. Moreover, after a piece of laundry is washed, it needs to be immediately moved into a drying machine, and after it is dried, it needs to be immediately moved into a folding machine.
It takes t1 minutes to wash one piece of laundry in a washing machine, t2 minutes to dry it in a drying machine, and t3 minutes to fold it in a folding machine. Find the smallest number of minutes that is enough to wash, dry and fold all the laundry you have.
Input
The only line of the input contains seven integers: k, n1, n2, n3, t1, t2, t3 (1 β€ k β€ 104; 1 β€ n1, n2, n3, t1, t2, t3 β€ 1000).
Output
Print one integer β smallest number of minutes to do all your laundry.
Examples
Input
1 1 1 1 5 5 5
Output
15
Input
8 4 3 2 10 5 2
Output
32
Note
In the first example there's one instance of each machine, each taking 5 minutes to complete. You have only one piece of laundry, so it takes 15 minutes to process it.
In the second example you start washing first two pieces at moment 0. If you start the third piece of laundry immediately, then by the time it is dried, there will be no folding machine available, so you have to wait, and start washing third piece at moment 2. Similarly, you can't start washing next piece until moment 5, since otherwise there will be no dryer available, when it is washed. Start time for each of the eight pieces of laundry is 0, 0, 2, 5, 10, 10, 12 and 15 minutes respectively. The last piece of laundry will be ready after 15 + 10 + 5 + 2 = 32 minutes. | class step(object):
timer = []
def __init__(self, name, machin_num, step_time):
self.machin_num = machin_num
self.step_time = step_time
self.name = name
def step_input(self, cloth_num, t):
'''
if cloth_num + len(self.timer) > self.machin_num:
excloth = cloth_num + len(self.timer) - self.machin_num
print('%s error excloth is %d' %(self.name , excloth))
return 'error'
else:
for new_cloth in range(cloth_num):
self.timer.append(t)
#print(self.timer)
'''
for new_cloth in range(cloth_num):
self.timer.append(t)
def step_run(self, t):
tmptimer = [each_timer for each_timer in self.timer if t - each_timer < self.step_time]
#next_num = len(self.timer) - len(tmptimer)
self.timer = tmptimer
#if len(self.timer) == 0:
#print('%s in %d is empty' %(self.name, t))
#pass
#print('%d: %s timer:\n%s \n' %(t, self.name, self.timer))
#print('%d: %s timer: %d \n' %(t, self.name, next_num))
#return next_num
def checkstate(self, pre_t):
running_machine = len(self.timer)
#output = 0
for each_timer in range(running_machine):
if pre_t - self.timer[each_timer] >= self.step_time:
running_machine -= 1
#output += 1
return self.machin_num - running_machine
def main():
p, n1, n2, n3, t1, t2, t3 = map(int, input().split())
'''
p = 8
n1 = 4
n2 = 3
n3 = 2
t1 = 10
t2 = 5
t3 = 2
'''
step1 = step('step1', n1, t1)
step2 = step('step2', n2, t2)
step3 = step('step3', n3, t3)
t = 0
#cp = 0
while True:
pre_num1 = step1.checkstate(t)
pre_num2 = step2.checkstate(t + t1)
pre_num3 = step3.checkstate(t + t1 + t2)
step1_input = min(pre_num1, pre_num2, pre_num3)
p -= step1_input
step1.step_run(t)
step1.step_input(step1_input, t)
step2.step_run(t + t1)
step2.step_input(step1_input, t + t1)
step3.step_run(t + t1 + t2)
step3.step_input(step1_input, t + t1 + t2)
if p <= 0:
print(t + t1 + t2 + t3)
break
pre_t = []
if len(step1.timer) == step1.machin_num:
#print('step1 stun')
pre_t.append(t1 - (t - step1.timer[0]))
if len(step2.timer) == step2.machin_num:
#print('step2 stun')
pre_t.append(t2 - (t + t1 - step2.timer[0]))
if len(step3.timer) == step3.machin_num:
#print('step3 stun')
pre_t.append(t3 - (t + t1 + t2 - step3.timer[0]))
#print('pre_t: %s' %(pre_t))
if len(pre_t) == 0:
pre_t = 1
else:
pre_t = min(pre_t)
'''
print('%d minute input: %d' %(t, step1_input))
print('step1 timer:\n%s\npre_num1: %d'%(step1.timer, pre_num1))
print('step2 timer:\n%s\npre_num2: %d'%(step2.timer, pre_num2))
print('step3 timer:\n%s\npre_num3: %d'%(step3.timer, pre_num3))
print('pre_t: %d' %pre_t)
input()
'''
t += pre_t
if __name__ == '__main__':
main()
| {
"input": [
"8 4 3 2 10 5 2\n",
"1 1 1 1 5 5 5\n"
],
"output": [
"32",
"15"
]
} |
4,115 | 8 | Imagine a city with n horizontal streets crossing m vertical streets, forming an (n - 1) Γ (m - 1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traffic moves only from north to south or only from south to north in each vertical street. It is possible to enter a horizontal street from a vertical street, or vice versa, at their intersection.
<image>
The mayor has received some street direction patterns. Your task is to check whether it is possible to reach any junction from any other junction in the proposed street direction pattern.
Input
The first line of input contains two integers n and m, (2 β€ n, m β€ 20), denoting the number of horizontal streets and the number of vertical streets.
The second line contains a string of length n, made of characters '<' and '>', denoting direction of each horizontal street. If the i-th character is equal to '<', the street is directed from east to west otherwise, the street is directed from west to east. Streets are listed in order from north to south.
The third line contains a string of length m, made of characters '^' and 'v', denoting direction of each vertical street. If the i-th character is equal to '^', the street is directed from south to north, otherwise the street is directed from north to south. Streets are listed in order from west to east.
Output
If the given pattern meets the mayor's criteria, print a single line containing "YES", otherwise print a single line containing "NO".
Examples
Input
3 3
><>
v^v
Output
NO
Input
4 6
<><>
v^v^v^
Output
YES
Note
The figure above shows street directions in the second sample test case. | def main():
n, m = map(int, input().split())
a = input()
b = input()
valid = (a[0] == '>' and a[-1] == '<' and b[0] == '^' and b[-1] == 'v') \
or (a[0] == '<' and a[-1] == '>' and b[0] == 'v' and b[-1] == '^')
print("YES" if valid else "NO")
main()
| {
"input": [
"3 3\n><>\nv^v\n",
"4 6\n<><>\nv^v^v^\n"
],
"output": [
"NO\n",
"NO\n"
]
} |
4,116 | 8 | You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
Input
The first line contains two integers, n and m (1 β€ n β€ 3000, 1 β€ m β€ 3000) β the number of words in the professor's lecture and the number of words in each of these languages.
The following m lines contain the words. The i-th line contains two strings ai, bi meaning that the word ai belongs to the first language, the word bi belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once.
The next line contains n space-separated strings c1, c2, ..., cn β the text of the lecture. It is guaranteed that each of the strings ci belongs to the set of strings {a1, a2, ... am}.
All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.
Output
Output exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.
Examples
Input
4 3
codeforces codesecrof
contest round
letter message
codeforces contest letter contest
Output
codeforces round letter round
Input
5 3
joll wuqrd
euzf un
hbnyiyc rsoqqveh
hbnyiyc joll joll euzf joll
Output
hbnyiyc joll joll un joll | def func(n):
dictionary = dict(input().split() for i in range(n[1]))
text = input().split()
ans = []
for i in text:
ans.append(min(i,dictionary[i],key=len))
print(' '.join(ans))
n = list(map(int,input().split()))
func(n) | {
"input": [
"4 3\ncodeforces codesecrof\ncontest round\nletter message\ncodeforces contest letter contest\n",
"5 3\njoll wuqrd\neuzf un\nhbnyiyc rsoqqveh\nhbnyiyc joll joll euzf joll\n"
],
"output": [
"codeforces round letter round ",
"hbnyiyc joll joll un joll "
]
} |
4,117 | 9 | Polycarp is flying in the airplane. Finally, it is his favorite time β the lunchtime. The BerAvia company stewardess is giving food consecutively to all the passengers from the 1-th one to the last one. Polycarp is sitting on seat m, that means, he will be the m-th person to get food.
The flight menu has k dishes in total and when Polycarp boarded the flight, he had time to count the number of portions of each dish on board. Thus, he knows values a1, a2, ..., ak, where ai is the number of portions of the i-th dish.
The stewardess has already given food to m - 1 passengers, gave Polycarp a polite smile and asked him what he would prefer. That's when Polycarp realized that they might have run out of some dishes by that moment. For some of the m - 1 passengers ahead of him, he noticed what dishes they were given. Besides, he's heard some strange mumbling from some of the m - 1 passengers ahead of him, similar to phrase 'I'm disappointed'. That happened when a passenger asked for some dish but the stewardess gave him a polite smile and said that they had run out of that dish. In that case the passenger needed to choose some other dish that was available. If Polycarp heard no more sounds from a passenger, that meant that the passenger chose his dish at the first try.
Help Polycarp to find out for each dish: whether they could have run out of the dish by the moment Polyarp was served or that dish was definitely available.
Input
Each test in this problem consists of one or more input sets. First goes a string that contains a single integer t (1 β€ t β€ 100 000) β the number of input data sets in the test. Then the sets follow, each set is preceded by an empty line.
The first line of each set of the input contains integers m, k (2 β€ m β€ 100 000, 1 β€ k β€ 100 000) β the number of Polycarp's seat and the number of dishes, respectively.
The second line contains a sequence of k integers a1, a2, ..., ak (1 β€ ai β€ 100 000), where ai is the initial number of portions of the i-th dish.
Then m - 1 lines follow, each line contains the description of Polycarp's observations about giving food to a passenger sitting in front of him: the j-th line contains a pair of integers tj, rj (0 β€ tj β€ k, 0 β€ rj β€ 1), where tj is the number of the dish that was given to the j-th passenger (or 0, if Polycarp didn't notice what dish was given to the passenger), and rj β a 1 or a 0, depending on whether the j-th passenger was or wasn't disappointed, respectively.
We know that sum ai equals at least m, that is,Polycarp will definitely get some dish, even if it is the last thing he wanted. It is guaranteed that the data is consistent.
Sum m for all input sets doesn't exceed 100 000. Sum k for all input sets doesn't exceed 100 000.
Output
For each input set print the answer as a single line. Print a string of k letters "Y" or "N". Letter "Y" in position i should be printed if they could have run out of the i-th dish by the time the stewardess started serving Polycarp.
Examples
Input
2
3 4
2 3 2 1
1 0
0 0
5 5
1 2 1 3 1
3 0
0 0
2 1
4 0
Output
YNNY
YYYNY
Note
In the first input set depending on the choice of the second passenger the situation could develop in different ways:
* If he chose the first dish, then by the moment the stewardess reaches Polycarp, they will have run out of the first dish;
* If he chose the fourth dish, then by the moment the stewardess reaches Polycarp, they will have run out of the fourth dish;
* Otherwise, Polycarp will be able to choose from any of the four dishes.
Thus, the answer is "YNNY".
In the second input set there is, for example, the following possible scenario. First, the first passenger takes the only third dish, then the second passenger takes the second dish. Then, the third passenger asks for the third dish, but it is not available, so he makes disappointed muttering and ends up with the second dish. Then the fourth passenger takes the fourth dish, and Polycarp ends up with the choice between the first, fourth and fifth dish.
Likewise, another possible scenario is when by the time the stewardess comes to Polycarp, they will have run out of either the first or the fifth dish (this can happen if one of these dishes is taken by the second passenger). It is easy to see that there is more than enough of the fourth dish, so Polycarp can always count on it. Thus, the answer is "YYYNY". | def ris():
return map(int, input().split())
def testCase():
m, k = ris()
q = 0
a = list(ris())
some_is_out = False
tmp = set()
for i in range(m - 1):
t, r = ris()
t -= 1
if r == 1 and not some_is_out:
some_is_out = True
tmp = tmp.union(set(filter(lambda x: a[x] <= q, range(k))))
if t == -1:
q += 1
else:
if t in tmp:
tmp.remove(t)
a[t] -= 1
if a[t] < 0:
a[t] = 0
q += 1
if tmp:
q -= min(map(lambda x: a[x], tmp))
print("".join(list(map(lambda x: 'Y' if a[x] - q <= 0 or x in tmp else 'N', range(len(a))))))
for i in range(int(input())):
input()
testCase() | {
"input": [
"2\n\n3 4\n2 3 2 1\n1 0\n0 0\n\n5 5\n1 2 1 3 1\n3 0\n0 0\n2 1\n4 0\n"
],
"output": [
"YNNY\nYYYNY\n"
]
} |
4,118 | 8 | You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given.
One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.
For example, if the string s is abacaba and the query is l1 = 3, r1 = 6, k1 = 1 then the answer is abbacaa. If after that we would process the query l2 = 1, r2 = 4, k2 = 2 then we would get the string baabcaa.
Input
The first line of the input contains the string s (1 β€ |s| β€ 10 000) in its initial state, where |s| stands for the length of s. It contains only lowercase English letters.
Second line contains a single integer m (1 β€ m β€ 300) β the number of queries.
The i-th of the next m lines contains three integers li, ri and ki (1 β€ li β€ ri β€ |s|, 1 β€ ki β€ 1 000 000) β the description of the i-th query.
Output
Print the resulting string s after processing all m queries.
Examples
Input
abacaba
2
3 6 1
1 4 2
Output
baabcaa
Note
The sample is described in problem statement. | s=input()
def shift(x,k):
x=x[-k:]+x[:-k]
return x
for i in range(int(input())):
l,r,k=tuple(map(int,input().split()))
l-=1
k%=(r-l)
s=s[:l]+shift(s[l:r],k)+s[r:]
print(s)
| {
"input": [
"abacaba\n2\n3 6 1\n1 4 2\n"
],
"output": [
"baabcaa\n"
]
} |
4,119 | 8 | <image>
As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore.
A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive β convex polygon.
Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length li.
The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle <image>.
Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing.
Help sculptor!
Input
The first line contains an integer n (3 β€ n β€ 105) β a number of rod-blanks.
The second line contains n integers li (1 β€ li β€ 109) β lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.
Output
Print the only integer z β the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the rods.
Examples
Input
3
1 2 1
Output
1
Input
5
20 4 3 2 1
Output
11
Note
In the first example triangle with sides {1 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}.
In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}. | def main():
input()
l = list(map(int, input().split()))
print(max(l) * 2 - sum(l) + 1)
if __name__ == '__main__':
main()
| {
"input": [
"3\n1 2 1\n",
"5\n20 4 3 2 1\n"
],
"output": [
"1\n",
"11\n"
]
} |
4,120 | 8 | Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6.
Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task!
Each digit can be used no more than once, i.e. the composed integers should contain no more than k2 digits 2, k3 digits 3 and so on. Of course, unused digits are not counted in the sum.
Input
The only line of the input contains four integers k2, k3, k5 and k6 β the number of digits 2, 3, 5 and 6 respectively (0 β€ k2, k3, k5, k6 β€ 5Β·106).
Output
Print one integer β maximum possible sum of Anton's favorite integers that can be composed using digits from the box.
Examples
Input
5 1 3 4
Output
800
Input
1 1 1 1
Output
256
Note
In the first sample, there are five digits 2, one digit 3, three digits 5 and four digits 6. Anton can compose three integers 256 and one integer 32 to achieve the value 256 + 256 + 256 + 32 = 800. Note, that there is one unused integer 2 and one unused integer 6. They are not counted in the answer.
In the second sample, the optimal answer is to create on integer 256, thus the answer is 256. | def Anton(l):
t=min([l[0],l[2],l[3]])
print(t*256+min([l[1],l[0]-t])*32)
Anton([int(x) for x in input().split()]) | {
"input": [
"1 1 1 1\n",
"5 1 3 4\n"
],
"output": [
"256\n",
"800\n"
]
} |
4,121 | 8 | Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland.
Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is working.
It is known that the garland contains light bulbs of four colors: red, blue, yellow and green. The garland is made as follows: if you take any four consecutive light bulbs then there will not be light bulbs with the same color among them. For example, the garland can look like "RYBGRYBGRY", "YBGRYBGRYBG", "BGRYB", but can not look like "BGRYG", "YBGRYBYGR" or "BGYBGY". Letters denote colors: 'R' β red, 'B' β blue, 'Y' β yellow, 'G' β green.
Using the information that for each color at least one light bulb still works count the number of dead light bulbs of each four colors.
Input
The first and the only line contains the string s (4 β€ |s| β€ 100), which describes the garland, the i-th symbol of which describes the color of the i-th light bulb in the order from the beginning of garland:
* 'R' β the light bulb is red,
* 'B' β the light bulb is blue,
* 'Y' β the light bulb is yellow,
* 'G' β the light bulb is green,
* '!' β the light bulb is dead.
The string s can not contain other symbols except those five which were described.
It is guaranteed that in the given string at least once there is each of four letters 'R', 'B', 'Y' and 'G'.
It is guaranteed that the string s is correct garland with some blown light bulbs, it means that for example the line "GRBY!!!B" can not be in the input data.
Output
In the only line print four integers kr, kb, ky, kg β the number of dead light bulbs of red, blue, yellow and green colors accordingly.
Examples
Input
RYBGRYBGR
Output
0 0 0 0
Input
!RGYB
Output
0 1 0 0
Input
!!!!YGRB
Output
1 1 1 1
Input
!GB!RG!Y!
Output
2 1 1 0
Note
In the first example there are no dead light bulbs.
In the second example it is obvious that one blue bulb is blown, because it could not be light bulbs of other colors on its place according to the statements. | def main():
s = list(input())
ans = []
for c in "RBYG":
x = s.index(c)
x %= 4
cn = 0
while (x < len(s)):
if (s[x] == '!'):
cn += 1
x += 4
ans.append(cn)
print(*ans)
main() | {
"input": [
"!RGYB\n",
"!!!!YGRB\n",
"RYBGRYBGR\n",
"!GB!RG!Y!\n"
],
"output": [
"0 1 0 0\n",
"1 1 1 1\n",
"0 0 0 0\n",
"2 1 1 0\n"
]
} |
4,122 | 9 | From beginning till end, this message has been waiting to be conveyed.
For a given unordered multiset of n lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation n - 1 times:
* Remove any two elements s and t from the set, and add their concatenation s + t to the set.
The cost of such operation is defined to be <image>, where f(s, c) denotes the number of times character c appears in string s.
Given a non-negative integer k, construct any valid non-empty set of no more than 100 000 letters, such that the minimum accumulative cost of the whole process is exactly k. It can be shown that a solution always exists.
Input
The first and only line of input contains a non-negative integer k (0 β€ k β€ 100 000) β the required minimum cost.
Output
Output a non-empty string of no more than 100 000 lowercase English letters β any multiset satisfying the requirements, concatenated to be a string.
Note that the printed string doesn't need to be the final concatenated string. It only needs to represent an unordered multiset of letters.
Examples
Input
12
Output
abababab
Input
3
Output
codeforces
Note
For the multiset {'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'}, one of the ways to complete the process is as follows:
* {"ab", "a", "b", "a", "b", "a", "b"}, with a cost of 0;
* {"aba", "b", "a", "b", "a", "b"}, with a cost of 1;
* {"abab", "a", "b", "a", "b"}, with a cost of 1;
* {"abab", "ab", "a", "b"}, with a cost of 0;
* {"abab", "aba", "b"}, with a cost of 1;
* {"abab", "abab"}, with a cost of 1;
* {"abababab"}, with a cost of 8.
The total cost is 12, and it can be proved to be the minimum cost of the process. | n = int(input())
def locos(n):
cos = 0
i = 1
while cos + i <= n:
cos += i
i += 1
return i , cos
rtn = ''
for i in "abcdefghijklmnopqrstuvwxyz":
#print(locos(n))
num , cos = locos(n)
#print(num)
rtn += i * num
n -= cos
if(n == 0): break
print(rtn)
| {
"input": [
"3\n",
"12\n"
],
"output": [
"aaa",
"aaaaabbcc"
]
} |
4,123 | 7 | We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that a yuan for b kilos (You don't need to care about what "yuan" is), the same as a/b yuan for a kilo.
Now imagine you'd like to buy m kilos of apples. You've asked n supermarkets and got the prices. Find the minimum cost for those apples.
You can assume that there are enough apples in all supermarkets.
Input
The first line contains two positive integers n and m (1 β€ n β€ 5 000, 1 β€ m β€ 100), denoting that there are n supermarkets and you want to buy m kilos of apples.
The following n lines describe the information of the supermarkets. Each line contains two positive integers a, b (1 β€ a, b β€ 100), denoting that in this supermarket, you are supposed to pay a yuan for b kilos of apples.
Output
The only line, denoting the minimum cost for m kilos of apples. Please make sure that the absolute or relative error between your answer and the correct answer won't exceed 10^{-6}.
Formally, let your answer be x, and the jury's answer be y. Your answer is considered correct if \frac{|x - y|}{max{(1, |y|)}} β€ 10^{-6}.
Examples
Input
3 5
1 2
3 4
1 3
Output
1.66666667
Input
2 1
99 100
98 99
Output
0.98989899
Note
In the first sample, you are supposed to buy 5 kilos of apples in supermarket 3. The cost is 5/3 yuan.
In the second sample, you are supposed to buy 1 kilo of apples in supermarket 2. The cost is 98/99 yuan. |
def Solve():
n, m = map(int, input().split())
min_number = []
for index in range(n):
a, b = map(int, input().split())
min_number.append(a*m/b)
print("%.8f"% min(min_number))
Solve()
| {
"input": [
"2 1\n99 100\n98 99\n",
"3 5\n1 2\n3 4\n1 3\n"
],
"output": [
"0.989898989899\n",
"1.66666666667\n"
]
} |
4,124 | 9 | Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1, s2, ..., sn. All those strings consist of uppercase and lowercase Latin letters. String w has the length of |w|, its characters are numbered from 1 to |w|.
First Petya should find all the occurrences of forbidden substrings in the w string. During the search of substrings the case of letter shouldn't be taken into consideration. That is, strings "aBC" and "ABc" are considered equal.
After that Petya should perform the replacement of all letters covered by the occurrences. More formally: a letter in the position i should be replaced by any other one if for position i in string w there exist pair of indices l, r (1 β€ l β€ i β€ r β€ |w|) such that substring w[l ... r] is contained in the collection s1, s2, ..., sn, when using case insensitive comparison. During the replacement the letter's case should remain the same. Petya is not allowed to replace the letters that aren't covered by any forbidden substring.
Letter letter (uppercase or lowercase) is considered lucky for the hockey players. That's why Petya should perform the changes so that the letter occurred in the resulting string as many times as possible. Help Petya to find such resulting string. If there are several such strings, find the one that comes first lexicographically.
Note that the process of replacements is not repeated, it occurs only once. That is, if after Petya's replacements the string started to contain new occurrences of bad substrings, Petya pays no attention to them.
Input
The first line contains the only integer n (1 β€ n β€ 100) β the number of forbidden substrings in the collection. Next n lines contain these substrings. The next line contains string w. All those n + 1 lines are non-empty strings consisting of uppercase and lowercase Latin letters whose length does not exceed 100. The last line contains a lowercase letter letter.
Output
Output the only line β Petya's resulting string with the maximum number of letters letter. If there are several answers then output the one that comes first lexicographically.
The lexicographical comparison is performed by the standard < operator in modern programming languages. The line a is lexicographically smaller than the line b, if a is a prefix of b, or there exists such an i (1 β€ i β€ |a|), that ai < bi, and for any j (1 β€ j < i) aj = bj. |a| stands for the length of string a.
Examples
Input
3
bers
ucky
elu
PetrLoveLuckyNumbers
t
Output
PetrLovtTttttNumtttt
Input
4
hello
party
abefglghjdhfgj
IVan
petrsmatchwin
a
Output
petrsmatchwin
Input
2
aCa
cba
abAcaba
c
Output
abCacba | import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def same(a, b):
return a.lower() == b.lower()
n = mint()
w = []
for i in range(n):
w.append(minp().lower())
s = minp()
g = [False]*len(s)
c = minp()
for i in w:
for j in range(len(s)-len(i)+1):
if s[j:j+len(i)].lower() == i:
for k in range(len(i)):
g[j+k] = True
r = ''
for i in range(len(s)):
if g[i]:
x = s[i]
if x == c.lower():
if c.lower() == 'a':
r += 'b'
else:
r += 'a'
elif x == c.upper():
if c.lower() == 'a':
r += 'B'
else:
r += 'A'
elif x.islower():
r += c.lower()
else:
r += c.upper()
else:
r += s[i]
print(r) | {
"input": [
"3\nbers\nucky\nelu\nPetrLoveLuckyNumbers\nt\n",
"2\naCa\ncba\nabAcaba\nc\n",
"4\nhello\nparty\nabefglghjdhfgj\nIVan\npetrsmatchwin\na\n"
],
"output": [
"PetrLovtTttttNumtttt\n",
"abCacba\n",
"petrsmatchwin\n"
]
} |
4,125 | 9 | You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect.
The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the two squares only share one common point, they are also considered to intersect.
Input
The input data consists of two lines, one for each square, both containing 4 pairs of integers. Each pair represents coordinates of one vertex of the square. Coordinates within each line are either in clockwise or counterclockwise order.
The first line contains the coordinates of the square with sides parallel to the coordinate axes, the second line contains the coordinates of the square at 45 degrees.
All the values are integer and between -100 and 100.
Output
Print "Yes" if squares intersect, otherwise print "No".
You can print each letter in any case (upper or lower).
Examples
Input
0 0 6 0 6 6 0 6
1 3 3 5 5 3 3 1
Output
YES
Input
0 0 6 0 6 6 0 6
7 3 9 5 11 3 9 1
Output
NO
Input
6 0 6 6 0 6 0 0
7 4 4 7 7 10 10 7
Output
YES
Note
In the first example the second square lies entirely within the first square, so they do intersect.
In the second sample squares do not have any points in common.
Here are images corresponding to the samples:
<image> <image> <image> | I=lambda:list(map(int,input().split()))
q,w=I(),I()
def c(q,w):
l=0
w+=[(w[0]+w[4])/2,(w[1]+w[5])/2]
for j in range(0,10,2):
e,r=w[j],w[j+1]
o=0
for i in range(0,8,2):
a,b=q[(i+4)%8],q[(i+5)%8]
s=(b-q[i+1])*(q[(i+2)%8]-q[i])-(q[(i+3)%8]-q[i+1])*(a-q[i])
if s>0:
if (r-q[i+1])*(q[(i+2)%8]-q[i])-(q[(i+3)%8]-q[i+1])*(e-q[i])>=0:o+=1
else:
if (r-q[i+1])*(q[(i+2)%8]-q[i])-(q[(i+3)%8]-q[i+1])*(e-q[i])<=0:o+=1
if o==4:l=1
return l
print("YES" if c(q,w)+c(w,q)else"NO") | {
"input": [
"0 0 6 0 6 6 0 6\n7 3 9 5 11 3 9 1\n",
"0 0 6 0 6 6 0 6\n1 3 3 5 5 3 3 1\n",
"6 0 6 6 0 6 0 0\n7 4 4 7 7 10 10 7\n"
],
"output": [
"NO\n",
"YES\n",
"YES\n"
]
} |
4,126 | 8 | Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number n.
There are m buses running between the house and the school: the i-th bus goes from stop si to ti (si < ti), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the i-th bus on any stop numbered from si to ti - 1 inclusive, but he can get off the i-th bus only on the bus stop ti.
Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house.
Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (109 + 7).
Input
The first line contains two space-separated integers: n and m (1 β€ n β€ 109, 0 β€ m β€ 105). Then follow m lines each containing two integers si, ti. They are the numbers of starting stops and end stops of the buses (0 β€ si < ti β€ n).
Output
Print the only number β the number of ways to get to the school modulo 1000000007 (109 + 7).
Examples
Input
2 2
0 1
1 2
Output
1
Input
3 2
0 1
1 2
Output
0
Input
5 5
0 1
0 2
0 3
0 4
0 5
Output
16
Note
The first test has the only variant to get to school: first on bus number one to the bus stop number one; then on bus number two to the bus stop number two.
In the second test no bus goes to the third bus stop, where the school is positioned. Thus, the correct answer is 0.
In the third test Gerald can either get or not on any of the first four buses to get closer to the school. Thus, the correct answer is 24 = 16. | a,b=map(int,input().split())
z=[]
g=10**9+7
def f():
return map(int,input().split())
if b==0:
print (0)
else:
s=set()
for i in range(b):
x,y=f()
z.append((x,y))
s.add(x)
s.add(y)
s.add (0)
s.add (a)
s = sorted(list(s))
a=len(s)-1
s=dict([(s[j],j) for j in range(a+1)])
z=[(s[x],s[y]) for (x,y)in z]
z.sort(key=lambda x:x[1])
x=[0]*(a+1)
x[0]=1
y=[0]*(a+2)
i=0
j=0
for i in range (a+1):
while j<b and z[j][1]==i:
q,p=z[j]
x[p]+=y[p]-y[q]
j+=1
y[i+1]=y[i]+x[i]
y[i+1]%=g
print (x[a]%g) | {
"input": [
"3 2\n0 1\n1 2\n",
"5 5\n0 1\n0 2\n0 3\n0 4\n0 5\n",
"2 2\n0 1\n1 2\n"
],
"output": [
"0\n",
"16\n",
"1\n"
]
} |
4,127 | 11 | Consider some set of distinct characters A and some string S, consisting of exactly n characters, where each character is present in A.
You are given an array of m integers b (b_1 < b_2 < ... < b_m).
You are allowed to perform the following move on the string S:
1. Choose some valid i and set k = b_i;
2. Take the first k characters of S = Pr_k;
3. Take the last k characters of S = Su_k;
4. Substitute the first k characters of S with the reversed Su_k;
5. Substitute the last k characters of S with the reversed Pr_k.
For example, let's take a look at S = "abcdefghi" and k = 2. Pr_2 = "ab", Su_2 = "hi". Reversed Pr_2 = "ba", Su_2 = "ih". Thus, the resulting S is "ihcdefgba".
The move can be performed arbitrary number of times (possibly zero). Any i can be selected multiple times over these moves.
Let's call some strings S and T equal if and only if there exists such a sequence of moves to transmute string S to string T. For the above example strings "abcdefghi" and "ihcdefgba" are equal. Also note that this implies S = S.
The task is simple. Count the number of distinct strings.
The answer can be huge enough, so calculate it modulo 998244353.
Input
The first line contains three integers n, m and |A| (2 β€ n β€ 10^9, 1 β€ m β€ min(\frac n 2, 2 β
10^5), 1 β€ |A| β€ 10^9) β the length of the strings, the size of the array b and the size of the set A, respectively.
The second line contains m integers b_1, b_2, ..., b_m (1 β€ b_i β€ \frac n 2, b_1 < b_2 < ... < b_m).
Output
Print a single integer β the number of distinct strings of length n with characters from set A modulo 998244353.
Examples
Input
3 1 2
1
Output
6
Input
9 2 26
2 3
Output
150352234
Input
12 3 1
2 5 6
Output
1
Note
Here are all the distinct strings for the first example. The chosen letters 'a' and 'b' are there just to show that the characters in A are different.
1. "aaa"
2. "aab" = "baa"
3. "aba"
4. "abb" = "bba"
5. "bab"
6. "bbb" | n,m,a=map(int,input().split())
b=list(map(int,input().split()))
for i in range(m):
if i==0:
diffs=[b[0]]
else:
diffs.append(b[i]-b[i-1])
powers=[a%998244353]
for i in range(30):
powers.append(powers[-1]**2%998244353)
def power(x,y,binpowers):
prod=1
bits=bin(y)[2:]
bits=bits[::-1]
for i in range(len(bits)):
if bits[i]=="1":
prod*=binpowers[i]
prod%=998244353
return prod
maxi=b[-1]
prod1=power(a,n-2*maxi,powers)
for guy in diffs:
newprod=power(a,guy,powers)
newprod=(newprod*(newprod+1))//2
newprod%=998244353
prod1*=newprod
prod1%=998244353
print(prod1) | {
"input": [
"9 2 26\n2 3\n",
"12 3 1\n2 5 6\n",
"3 1 2\n1\n"
],
"output": [
"150352234\n",
"1\n",
"6\n"
]
} |
4,128 | 9 | You're given an array a of length n. You can perform the following operations on it:
* choose an index i (1 β€ i β€ n), an integer x (0 β€ x β€ 10^6), and replace a_j with a_j+x for all (1 β€ j β€ i), which means add x to all the elements in the prefix ending at i.
* choose an index i (1 β€ i β€ n), an integer x (1 β€ x β€ 10^6), and replace a_j with a_j \% x for all (1 β€ j β€ i), which means replace every element in the prefix ending at i with the remainder after dividing it by x.
Can you make the array strictly increasing in no more than n+1 operations?
Input
The first line contains an integer n (1 β€ n β€ 2000), the number of elements in the array a.
The second line contains n space-separated integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10^5), the elements of the array a.
Output
On the first line, print the number of operations you wish to perform. On the next lines, you should print the operations.
To print an adding operation, use the format "1 i x"; to print a modding operation, use the format "2 i x". If i or x don't satisfy the limitations above, or you use more than n+1 operations, you'll get wrong answer verdict.
Examples
Input
3
1 2 3
Output
0
Input
3
7 6 3
Output
2
1 1 1
2 2 4
Note
In the first sample, the array is already increasing so we don't need any operations.
In the second sample:
In the first step: the array becomes [8,6,3].
In the second step: the array becomes [0,2,3]. | def mi():
return map(int, input().split())
'''
3 5
1 2 3
'''
n = int(input())
a = list(mi())
i = n-1
res = 0
temp = []
print (n+1)
while i>=0:
temp= i-((res+a[i])%n)
if temp<0:
temp+=n
res += temp
print (1,i+1,temp)
i-=1
print (2,n,n)
| {
"input": [
"3\n7 6 3\n",
"3\n1 2 3\n"
],
"output": [
"4\n1 3 2\n1 2 2\n1 1 1\n2 3 3\n",
"4\n1 3 2\n1 2 0\n1 1 0\n2 3 3\n"
]
} |
4,129 | 9 | You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.
You are playing the game on the new generation console so your gamepad have 26 buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.
You are given a sequence of hits, the i-th hit deals a_i units of damage to the opponent's character. To perform the i-th hit you have to press the button s_i on your gamepad. Hits are numbered from 1 to n.
You know that if you press some button more than k times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.
To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of a_i over all i for the hits which weren't skipped.
Note that if you skip the hit then the counter of consecutive presses the button won't reset.
Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of hits and the maximum number of times you can push the same button in a row.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the damage of the i-th hit.
The third line of the input contains the string s consisting of exactly n lowercase Latin letters β the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).
Output
Print one integer dmg β the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.
Examples
Input
7 3
1 5 16 18 7 2 10
baaaaca
Output
54
Input
5 5
2 4 1 3 1000
aaaaa
Output
1010
Input
5 4
2 4 1 3 1000
aaaaa
Output
1009
Input
8 1
10 15 2 1 4 8 15 16
qqwweerr
Output
41
Input
6 3
14 18 9 19 2 15
cccccc
Output
52
Input
2 1
10 10
qq
Output
10
Note
In the first example you can choose hits with numbers [1, 3, 4, 5, 6, 7] with the total damage 1 + 16 + 18 + 7 + 2 + 10 = 54.
In the second example you can choose all hits so the total damage is 2 + 4 + 1 + 3 + 1000 = 1010.
In the third example you can choose all hits expect the third one so the total damage is 2 + 4 + 3 + 1000 = 1009.
In the fourth example you can choose hits with numbers [2, 3, 6, 8]. Only this way you can reach the maximum total damage 15 + 2 + 8 + 16 = 41.
In the fifth example you can choose only hits with numbers [2, 4, 6] with the total damage 18 + 19 + 15 = 52.
In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage 10. | def get():
return map(int,input().split())
n,k=get()
a=list(get())
s=input()
i=0
dmg=0
while i<n:
j=i+1
while j<n and s[i]==s[j]:
j+=1
j-=1
if j-i+1<=k:
dmg+=sum(a[i:j+1])
else:
g=a[i:j+1]
g.sort()
dmg+=sum(g[len(g)-k:])
i=j+1
print(dmg)
| {
"input": [
"2 1\n10 10\nqq\n",
"8 1\n10 15 2 1 4 8 15 16\nqqwweerr\n",
"7 3\n1 5 16 18 7 2 10\nbaaaaca\n",
"5 5\n2 4 1 3 1000\naaaaa\n",
"6 3\n14 18 9 19 2 15\ncccccc\n",
"5 4\n2 4 1 3 1000\naaaaa\n"
],
"output": [
"10\n",
"41\n",
"54\n",
"1010\n",
"52\n",
"1009\n"
]
} |
4,130 | 9 | Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.
Two matrices A and B are given, each of them has size n Γ m. Nastya can perform the following operation to matrix A unlimited number of times:
* take any square square submatrix of A and transpose it (i.e. the element of the submatrix which was in the i-th row and j-th column of the submatrix will be in the j-th row and i-th column after transposing, and the transposed submatrix itself will keep its place in the matrix A).
Nastya's task is to check whether it is possible to transform the matrix A to the matrix B.
<image> Example of the operation
As it may require a lot of operations, you are asked to answer this question for Nastya.
A square submatrix of matrix M is a matrix which consist of all elements which comes from one of the rows with indeces x, x+1, ..., x+k-1 of matrix M and comes from one of the columns with indeces y, y+1, ..., y+k-1 of matrix M. k is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).
Input
The first line contains two integers n and m separated by space (1 β€ n, m β€ 500) β the numbers of rows and columns in A and B respectively.
Each of the next n lines contains m integers, the j-th number in the i-th of these lines denotes the j-th element of the i-th row of the matrix A (1 β€ A_{ij} β€ 10^{9}).
Each of the next n lines contains m integers, the j-th number in the i-th of these lines denotes the j-th element of the i-th row of the matrix B (1 β€ B_{ij} β€ 10^{9}).
Output
Print "YES" (without quotes) if it is possible to transform A to B and "NO" (without quotes) otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2 2
1 1
6 1
1 6
1 1
Output
YES
Input
2 2
4 4
4 5
5 4
4 4
Output
NO
Input
3 3
1 2 3
4 5 6
7 8 9
1 4 7
2 5 6
3 8 9
Output
YES
Note
Consider the third example. The matrix A initially looks as follows.
$$$ \begin{bmatrix} 1 & 2 & 3\\\ 4 & 5 & 6\\\ 7 & 8 & 9 \end{bmatrix} $$$
Then we choose the whole matrix as transposed submatrix and it becomes
$$$ \begin{bmatrix} 1 & 4 & 7\\\ 2 & 5 & 8\\\ 3 & 6 & 9 \end{bmatrix} $$$
Then we transpose the submatrix with corners in cells (2, 2) and (3, 3).
$$$ \begin{bmatrix} 1 & 4 & 7\\\ 2 & 5 & 8\\\ 3 & 6 & 9 \end{bmatrix} $$$
So matrix becomes
$$$ \begin{bmatrix} 1 & 4 & 7\\\ 2 & 5 & 6\\\ 3 & 8 & 9 \end{bmatrix} $$$
and it is B. | R=lambda:map(int,input().split())
n,m=R()
def f():
a=[()]*(n+m)
for i in range(n):
for x in R():a[i]+=x,;i+=1
return[*map(sorted,a)]
print('YNEOS'[f()!=f()::2]) | {
"input": [
"3 3\n1 2 3\n4 5 6\n7 8 9\n1 4 7\n2 5 6\n3 8 9\n",
"2 2\n1 1\n6 1\n1 6\n1 1\n",
"2 2\n4 4\n4 5\n5 4\n4 4\n"
],
"output": [
"YES\n",
"YES\n",
"NO\n"
]
} |
4,131 | 11 | You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most βn/2β vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 β€ n β€ 2 β
10^5, n - 1 β€ m β€ min(2 β
10^5, (n(n-1))/(2))) β the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 β€ v_i, u_i β€ n, u_i β v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i β u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that β m β€ 2 β
10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 β€ βn/2β) β the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image> | class Item:
def __init__(self, k):
self.k = k
self.free = True
self.next = []
def bind(self, other):
self.next.append(other)
other.next.append(self)
n, m = map(int, input().split())
items = [Item(i) for i in range(1, n+1)]
for _ in range(m):
x, y = map(int, input().split())
items[x-1].bind(items[y-1])
s = max(items, key = lambda x: len(x.next))
s.free = False
q = [s]
while q:
cur = q.pop()
for nxt in cur.next:
if nxt.free:
print(cur.k, nxt.k)
nxt.free = False
q.append(nxt) | {
"input": [
"2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6\n"
],
"output": [
"1\n1 \n3\n3 4 6 \n"
]
} |
4,132 | 10 | This problem differs from the next one only in the presence of the constraint on the equal length of all numbers a_1, a_2, ..., a_n. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.
A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.
Let's denote a function that alternates digits of two numbers f(a_1 a_2 ... a_{p - 1} a_p, b_1 b_2 ... b_{q - 1} b_q), where a_1 ... a_p and b_1 ... b_q are digits of two integers written in the decimal notation without leading zeros.
In other words, the function f(x, y) alternately shuffles the digits of the numbers x and y by writing them from the lowest digits to the older ones, starting with the number y. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.
For example: $$$f(1111, 2222) = 12121212 f(7777, 888) = 7787878 f(33, 44444) = 4443434 f(555, 6) = 5556 f(111, 2222) = 2121212$$$
Formally,
* if p β₯ q then f(a_1 ... a_p, b_1 ... b_q) = a_1 a_2 ... a_{p - q + 1} b_1 a_{p - q + 2} b_2 ... a_{p - 1} b_{q - 1} a_p b_q;
* if p < q then f(a_1 ... a_p, b_1 ... b_q) = b_1 b_2 ... b_{q - p} a_1 b_{q - p + 1} a_2 ... a_{p - 1} b_{q - 1} a_p b_q.
Mishanya gives you an array consisting of n integers a_i. All numbers in this array are of equal length (that is, they consist of the same number of digits). Your task is to help students to calculate β_{i = 1}^{n}β_{j = 1}^{n} f(a_i, a_j) modulo 998 244 353.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of elements in the array. The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the elements of the array. All numbers a_1, a_2, ..., a_n are of equal length (that is, they consist of the same number of digits).
Output
Print the answer modulo 998 244 353.
Examples
Input
3
12 33 45
Output
26730
Input
2
123 456
Output
1115598
Input
1
1
Output
11
Input
5
1000000000 1000000000 1000000000 1000000000 1000000000
Output
265359409 | import itertools
def F(s):
a = ''
for i in s:
a += i * 2
return int(a)
n = int(input())
a = input().split()
print((sum(list(map(F, a))) * n) % 998244353)
| {
"input": [
"1\n1\n",
"2\n123 456\n",
"3\n12 33 45\n",
"5\n1000000000 1000000000 1000000000 1000000000 1000000000\n"
],
"output": [
"11\n",
"1115598\n",
"26730\n",
"265359409\n"
]
} |
4,133 | 11 | The mayor of the Central Town wants to modernize Central Street, represented in this problem by the (Ox) axis.
On this street, there are n antennas, numbered from 1 to n. The i-th antenna lies on the position x_i and has an initial scope of s_i: it covers all integer positions inside the interval [x_i - s_i; x_i + s_i].
It is possible to increment the scope of any antenna by 1, this operation costs 1 coin. We can do this operation as much as we want (multiple times on the same antenna if we want).
To modernize the street, we need to make all integer positions from 1 to m inclusive covered by at least one antenna. Note that it is authorized to cover positions outside [1; m], even if it's not required.
What is the minimum amount of coins needed to achieve this modernization?
Input
The first line contains two integers n and m (1 β€ n β€ 80 and n β€ m β€ 100\ 000).
The i-th of the next n lines contains two integers x_i and s_i (1 β€ x_i β€ m and 0 β€ s_i β€ m).
On each position, there is at most one antenna (values x_i are pairwise distinct).
Output
You have to output a single integer: the minimum amount of coins required to make all integer positions from 1 to m inclusive covered by at least one antenna.
Examples
Input
3 595
43 2
300 4
554 10
Output
281
Input
1 1
1 1
Output
0
Input
2 50
20 0
3 1
Output
30
Input
5 240
13 0
50 25
60 5
155 70
165 70
Output
26
Note
In the first example, here is a possible strategy:
* Increase the scope of the first antenna by 40, so that it becomes 2 + 40 = 42. This antenna will cover interval [43 - 42; 43 + 42] which is [1; 85]
* Increase the scope of the second antenna by 210, so that it becomes 4 + 210 = 214. This antenna will cover interval [300 - 214; 300 + 214], which is [86; 514]
* Increase the scope of the third antenna by 31, so that it becomes 10 + 31 = 41. This antenna will cover interval [554 - 41; 554 + 41], which is [513; 595]
Total cost is 40 + 210 + 31 = 281. We can prove that it's the minimum cost required to make all positions from 1 to 595 covered by at least one antenna.
Note that positions 513 and 514 are in this solution covered by two different antennas, but it's not important.
β
In the second example, the first antenna already covers an interval [0; 2] so we have nothing to do.
Note that the only position that we needed to cover was position 1; positions 0 and 2 are covered, but it's not important. | import sys
from array import array # noqa: F401
from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def main():
n, m = map(int, input().split())
a = sorted(tuple(map(int, input().split())) for _ in range(n))
dp = array('i', [10**9]) * (m + 1)
dp[0] = 0
for xi, si in a:
dp[min(xi + si, m)] = min(dp[min(xi + si, m)], dp[max(0, xi - si - 1)])
for i, delta in zip(range(xi - si - 2, xi - si - m - 1, -1), range(2, m + 1)):
dp[min(xi + si + delta - 1, m)] = min(
dp[min(xi + si + delta - 1, m)],
dp[i if i >= 0 else 0] + delta - 1
)
for i in range(m - 1, 0, -1):
if dp[i] > dp[i + 1]:
dp[i] = dp[i + 1]
print(dp[-1])
if __name__ == '__main__':
main()
| {
"input": [
"1 1\n1 1\n",
"3 595\n43 2\n300 4\n554 10\n",
"5 240\n13 0\n50 25\n60 5\n155 70\n165 70\n",
"2 50\n20 0\n3 1\n"
],
"output": [
"0",
"281",
"26",
"30"
]
} |
4,134 | 10 | Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 β€ n β€ 2β
10^5) β the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4β
10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2β
10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4β
10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 β€ k β€ n) β the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers β the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2 | def rev(l1, l2):
m = (len(l1) - len(l2))//2
if m==0:
return []
torev = []
for k in l1:
if k[::-1] not in l2:
torev.append(k)
if len(torev) < m:
return -1
else:
return torev[:m]
for _ in range(int(input())):
n = int(input())
oo = []
zz = []
zo = set()
oz = set()
ind = dict()
for i in range(n):
s = input()
ind[s] = i+1
if s[0] == '0':
if s[-1] == '0':
zz.append(s)
else:
zo.add(s)
else:
if s[-1] == '0':
oz.add(s)
else:
oo.append(s)
if len(oz) >= len(zo):
strings = rev(oz, zo)
else:
strings = rev(zo, oz)
if strings == -1:
print(-1)
elif len(oo) >= 1 and len(zz) >= 1 and len(oz) + len(zo) == 0 :
print(-1)
else:
print(len(strings))
print(' '.join([str(ind[x]) for x in strings])) | {
"input": [
"4\n4\n0001\n1000\n0011\n0111\n3\n010\n101\n0\n2\n00000\n00001\n4\n01\n001\n0001\n00001\n"
],
"output": [
"1\n3\n-1\n0\n\n2\n1 2\n"
]
} |
4,135 | 9 | INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | def f(x):
return int(format(256 + x, 'b')[:: -1][: -1], 2)
t, x = input(), 0
for i in t:
y = f(ord(i))
print((x - y) % 256)
x = y
# Made By Mostafa_Khaled | {
"input": [
"Hello, World!\n"
],
"output": [
"238\n108\n112\n0\n64\n194\n48\n26\n244\n168\n24\n16\n162\n"
]
} |
4,136 | 12 | You are given an array a of length 2^n. You should process q queries on it. Each query has one of the following 4 types:
1. Replace(x, k) β change a_x to k;
2. Reverse(k) β reverse each subarray [(i-1) β
2^k+1, i β
2^k] for all i (i β₯ 1);
3. Swap(k) β swap subarrays [(2i-2) β
2^k+1, (2i-1) β
2^k] and [(2i-1) β
2^k+1, 2i β
2^k] for all i (i β₯ 1);
4. Sum(l, r) β print the sum of the elements of subarray [l, r].
Write a program that can quickly process given queries.
Input
The first line contains two integers n, q (0 β€ n β€ 18; 1 β€ q β€ 10^5) β the length of array a and the number of queries.
The second line contains 2^n integers a_1, a_2, β¦, a_{2^n} (0 β€ a_i β€ 10^9).
Next q lines contains queries β one per line. Each query has one of 4 types:
* "1 x k" (1 β€ x β€ 2^n; 0 β€ k β€ 10^9) β Replace(x, k);
* "2 k" (0 β€ k β€ n) β Reverse(k);
* "3 k" (0 β€ k < n) β Swap(k);
* "4 l r" (1 β€ l β€ r β€ 2^n) β Sum(l, r).
It is guaranteed that there is at least one Sum query.
Output
Print the answer for each Sum query.
Examples
Input
2 3
7 4 9 9
1 2 8
3 1
4 2 4
Output
24
Input
3 8
7 0 8 8 7 1 5 2
4 3 7
2 1
3 2
4 1 6
2 3
1 5 16
4 8 8
3 0
Output
29
22
1
Note
In the first sample, initially, the array a is equal to \{7,4,9,9\}.
After processing the first query. the array a becomes \{7,8,9,9\}.
After processing the second query, the array a_i becomes \{9,9,7,8\}
Therefore, the answer to the third query is 9+7+8=24.
In the second sample, initially, the array a is equal to \{7,0,8,8,7,1,5,2\}. What happens next is:
1. Sum(3, 7) β 8 + 8 + 7 + 1 + 5 = 29;
2. Reverse(1) β \{0,7,8,8,1,7,2,5\};
3. Swap(2) β \{1,7,2,5,0,7,8,8\};
4. Sum(1, 6) β 1 + 7 + 2 + 5 + 0 + 7 = 22;
5. Reverse(3) β \{8,8,7,0,5,2,7,1\};
6. Replace(5, 16) β \{8,8,7,0,16,2,7,1\};
7. Sum(8, 8) β 1;
8. Swap(0) β \{8,8,0,7,2,16,1,7\}. | class BIT():
def __init__(self,n):
self.BIT=[0]*(n+1)
self.num=n
def query(self,idx):
res_sum = 0
while idx > 0:
res_sum += self.BIT[idx]
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
while idx <= self.num:
self.BIT[idx] += x
idx += idx&(-idx)
return
n,q=map(int,input().split())
a=list(map(int,input().split()))
bit=BIT(2**n)
for i in range(2**n):
bit.update(i+1,a[i])
b=0
def Sum(r,xor):
id=xor
res=0
if r==-1:
return res
for i in range(n,-1,-1):
if r>>i &1:
L=(id>>i)<<i
R=L+(1<<i)-1
res+=bit.query(R+1)-bit.query(L)
id^=(1<<i)
return res
for _ in range(q):
query=tuple(map(int,input().split()))
if query[0]==1:
g,x,k=query
x-=1
x^=b
bit.update(x+1,k-a[x])
a[x]=k
elif query[0]==2:
k=query[1]
b^=2**k-1
elif query[0]==3:
k=query[1]
if k!=n:
b^=2**k
else:
gl,l,r=query
l-=1
test=Sum(r,b)-Sum(l,b)
print(test) | {
"input": [
"3 8\n7 0 8 8 7 1 5 2\n4 3 7\n2 1\n3 2\n4 1 6\n2 3\n1 5 16\n4 8 8\n3 0\n",
"2 3\n7 4 9 9\n1 2 8\n3 1\n4 2 4\n"
],
"output": [
"29\n22\n1\n",
"24\n"
]
} |
4,137 | 10 | This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.
You are given an array [a_1, a_2, ..., a_n].
Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs f times in this subarray, then at least 2 different values should occur exactly f times.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
The first line contains a single integer n (1 β€ n β€ 200 000) β the length of the array.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ min(n, 100)) β elements of the array.
Output
You should output exactly one integer β the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output 0.
Examples
Input
7
1 1 2 2 3 3 3
Output
6
Input
10
1 1 1 5 4 1 3 1 2 2
Output
7
Input
1
1
Output
0
Note
In the first sample, the subarray [1, 1, 2, 2, 3, 3] is good, but [1, 1, 2, 2, 3, 3, 3] isn't: in the latter there are 3 occurrences of number 3, and no other element appears 3 times. | import sys
input = sys.stdin.buffer.readline
def prog():
n = int(input())
a = list(map(int,input().split()))
freq = [0]*101
for i in range(n):
freq[a[i]] += 1
mx = max(freq)
amt = freq.count(mx)
if amt >= 2:
print(n)
else:
must_appear = freq.index(mx)
ans = 0
for j in range(1,101):
if j == must_appear:
continue
first_idx = [10**6]*(n+1)
first_idx[0] = -1
curr = 0
for i in range(n):
if a[i] == must_appear:
curr += 1
elif a[i] == j:
curr -= 1
ans = max(ans, i - first_idx[curr])
first_idx[curr] = min(first_idx[curr],i)
print(ans)
prog()
| {
"input": [
"1\n1\n",
"7\n1 1 2 2 3 3 3\n",
"10\n1 1 1 5 4 1 3 1 2 2\n"
],
"output": [
"0\n",
"6\n",
"7\n"
]
} |
4,138 | 10 | Students of Winter Informatics School are going to live in a set of houses connected by underground passages. Teachers are also going to live in some of these houses, but they can not be accommodated randomly. For safety reasons, the following must hold:
* All passages between two houses will be closed, if there are no teachers in both of them. All other passages will stay open.
* It should be possible to travel between any two houses using the underground passages that are open.
* Teachers should not live in houses, directly connected by a passage.
Please help the organizers to choose the houses where teachers will live to satisfy the safety requirements or determine that it is impossible.
Input
The first input line contains a single integer t β the number of test cases (1 β€ t β€ 10^5).
Each test case starts with two integers n and m (2 β€ n β€ 3 β
10^5, 0 β€ m β€ 3 β
10^5) β the number of houses and the number of passages.
Then m lines follow, each of them contains two integers u and v (1 β€ u, v β€ n, u β v), describing a passage between the houses u and v. It is guaranteed that there are no two passages connecting the same pair of houses.
The sum of values n over all test cases does not exceed 3 β
10^5, and the sum of values m over all test cases does not exceed 3 β
10^5.
Output
For each test case, if there is no way to choose the desired set of houses, output "NO". Otherwise, output "YES", then the total number of houses chosen, and then the indices of the chosen houses in arbitrary order.
Examples
Input
2
3 2
3 2
2 1
4 2
1 4
2 3
Output
YES
2
1 3
NO
Input
1
17 27
1 8
2 9
3 10
4 11
5 12
6 13
7 14
8 9
8 14
8 15
9 10
9 15
10 11
10 15
10 17
11 12
11 17
12 13
12 16
12 17
13 14
13 16
14 16
14 15
15 16
15 17
16 17
Output
YES
8
1 3 4 5 6 9 14 17
Note
The picture below shows the second example test.
<image> | import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def ngsearch(x):
for to in E[x]:
if NG[to]==0:
NG[to]=1
Q.append(to)
t=int(input())
for tests in range(t):
n,m=map(int,input().split())
E=[[] for i in range(n+1)]
for i in range(m):
x,y=map(int,input().split())
E[x].append(y)
E[y].append(x)
OK=[0]*(n+1)
NG=[0]*(n+1)
Q=[]
ngsearch(1)
while Q:
x=Q.pop()
for to in E[x]:
if NG[to]==0:
OK[to]=1
ngsearch(to)
count=0
ANS=[]
for i in range(1,n+1):
if OK[i]==1 or NG[i]==1:
count+=1
if OK[i]==1:
ANS.append(i)
if count==n:
print("YES")
print(len(ANS))
print(*ANS)
else:
print("NO")
| {
"input": [
"2\n3 2\n3 2\n2 1\n4 2\n1 4\n2 3\n",
"1\n17 27\n1 8\n2 9\n3 10\n4 11\n5 12\n6 13\n7 14\n8 9\n8 14\n8 15\n9 10\n9 15\n10 11\n10 15\n10 17\n11 12\n11 17\n12 13\n12 16\n12 17\n13 14\n13 16\n14 16\n14 15\n15 16\n15 17\n16 17\n"
],
"output": [
"\nYES\n2\n1 3 \nNO\n",
"\nYES\n8\n1 3 4 5 6 9 14 17 \n"
]
} |
4,139 | 9 | It is the hard version of the problem. The only difference is that in this version 3 β€ k β€ n.
You are given a positive integer n. Find k positive integers a_1, a_2, β¦, a_k, such that:
* a_1 + a_2 + β¦ + a_k = n
* LCM(a_1, a_2, β¦, a_k) β€ n/2
Here LCM is the [least common multiple](https://en.wikipedia.org/wiki/Least_common_multiple) of numbers a_1, a_2, β¦, a_k.
We can show that for given constraints the answer always exists.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The only line of each test case contains two integers n, k (3 β€ n β€ 10^9, 3 β€ k β€ n).
It is guaranteed that the sum of k over all test cases does not exceed 10^5.
Output
For each test case print k positive integers a_1, a_2, β¦, a_k, for which all conditions are satisfied.
Example
Input
2
6 4
9 5
Output
1 2 2 1
1 3 3 1 1 | def answer():
if(n & 1):return [1]*(k-3) + [n//2,n//2,1]
else:
if(n//2 & 1==0):return [1]*(k-3) + [n//2,n//4,n//4]
else:return [1]*(k-3) + [2,n//2-1,n//2-1]
for T in range(int(input())):
n,k=map(int,input().split())
n-=(k-3)
print(*answer())
| {
"input": [
"2\n6 4\n9 5\n"
],
"output": [
"\n1 2 2 1 \n1 3 3 1 1 \n"
]
} |
4,140 | 8 | Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.
You are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type).
If the phone book of one person contains some number two times, you should count it twice. That is, each number should be taken into consideration the number of times it occurs in the phone book.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of friends.
Then follow n data blocks that describe each friend's phone books. Each block is presented in the following form: first goes the line that contains integer si and string namei (0 β€ si β€ 100) β the number of phone numbers in the phone book of the i-th friend and the name of the i-th friend. The name is a non-empty sequence of uppercase and lowercase Latin letters, containing no more than 20 characters. Next si lines contain numbers as "XX-XX-XX", where X is arbitrary digits from 0 to 9.
Output
In the first line print the phrase "If you want to call a taxi, you should call: ". Then print names of all friends whose phone books contain maximal number of taxi phone numbers.
In the second line print the phrase "If you want to order a pizza, you should call: ". Then print names of all friends who have maximal number of pizza phone numbers.
In the third line print the phrase "If you want to go to a cafe with a wonderful girl, you should call: ". Then print names of all friends who have maximal number of girls' phone numbers.
Print the names in the order in which they are given in the input data. Separate two consecutive names with a comma and a space. Each line should end with exactly one point. For clarifications concerning the output form, see sample tests. It is necessary that you follow the output form strictly. Extra spaces are not allowed.
Examples
Input
4
2 Fedorov
22-22-22
98-76-54
3 Melnikov
75-19-09
23-45-67
99-99-98
7 Rogulenko
22-22-22
11-11-11
33-33-33
44-44-44
55-55-55
66-66-66
95-43-21
3 Kaluzhin
11-11-11
99-99-99
98-65-32
Output
If you want to call a taxi, you should call: Rogulenko.
If you want to order a pizza, you should call: Fedorov, Rogulenko, Kaluzhin.
If you want to go to a cafe with a wonderful girl, you should call: Melnikov.
Input
3
5 Gleb
66-66-66
55-55-55
01-01-01
65-43-21
12-34-56
3 Serega
55-55-55
87-65-43
65-55-21
5 Melnik
12-42-12
87-73-01
36-04-12
88-12-22
82-11-43
Output
If you want to call a taxi, you should call: Gleb.
If you want to order a pizza, you should call: Gleb, Serega.
If you want to go to a cafe with a wonderful girl, you should call: Melnik.
Input
3
3 Kulczynski
22-22-22
65-43-21
98-12-00
4 Pachocki
11-11-11
11-11-11
11-11-11
98-76-54
0 Smietanka
Output
If you want to call a taxi, you should call: Pachocki.
If you want to order a pizza, you should call: Kulczynski, Pachocki.
If you want to go to a cafe with a wonderful girl, you should call: Kulczynski.
Note
In the first sample you are given four friends. Fedorov's phone book contains one taxi number and one pizza delivery number, Melnikov's phone book only has 3 numbers of girls, Rogulenko's one has 6 taxi numbers and one pizza delivery number, Kaluzhin's one contains 2 taxi numbers and one pizza delivery number.
Thus, if you need to order a taxi, you should obviously call Rogulenko, if you need to order a pizza you should call anybody of the following: Rogulenko, Fedorov, Kaluzhin (each of them has one number). Melnikov has maximal number of phone numbers of girls. | def g(t):
if len(set(t)) == 2: return 0
if t[0] > t[1] > t[3] > t[4] > t[6] > t[7]: return 1
return 2
q, f = [-1] * 3, [0] * 3
s = ['If you want to call a taxi, you should call: ', 'If you want to order a pizza, you should call: ', 'If you want to go to a cafe with a wonderful girl, you should call: ']
for i in range(int(input())):
n, t = input().split()
p = [0] * 3
for i in range(int(n)):
p[g(input())] += 1
for i in range(3):
if p[i] == q[i]: f[i].append(t)
elif p[i] > q[i]:
q[i] = p[i]
f[i] = [t]
for i in range(3):
print(s[i] + ', '.join(f[i]) + '.') | {
"input": [
"4\n2 Fedorov\n22-22-22\n98-76-54\n3 Melnikov\n75-19-09\n23-45-67\n99-99-98\n7 Rogulenko\n22-22-22\n11-11-11\n33-33-33\n44-44-44\n55-55-55\n66-66-66\n95-43-21\n3 Kaluzhin\n11-11-11\n99-99-99\n98-65-32\n",
"3\n3 Kulczynski\n22-22-22\n65-43-21\n98-12-00\n4 Pachocki\n11-11-11\n11-11-11\n11-11-11\n98-76-54\n0 Smietanka\n",
"3\n5 Gleb\n66-66-66\n55-55-55\n01-01-01\n65-43-21\n12-34-56\n3 Serega\n55-55-55\n87-65-43\n65-55-21\n5 Melnik\n12-42-12\n87-73-01\n36-04-12\n88-12-22\n82-11-43\n"
],
"output": [
"If you want to call a taxi, you should call: Rogulenko.\nIf you want to order a pizza, you should call: Fedorov, Rogulenko, Kaluzhin.\nIf you want to go to a cafe with a wonderful girl, you should call: Melnikov.\n",
"If you want to call a taxi, you should call: Pachocki.\nIf you want to order a pizza, you should call: Kulczynski, Pachocki.\nIf you want to go to a cafe with a wonderful girl, you should call: Kulczynski.\n",
"If you want to call a taxi, you should call: Gleb.\nIf you want to order a pizza, you should call: Gleb, Serega.\nIf you want to go to a cafe with a wonderful girl, you should call: Melnik.\n"
]
} |
4,141 | 8 | A string s of length n (1 β€ n β€ 26) is called alphabetical if it can be obtained using the following algorithm:
* first, write an empty string to s (i.e. perform the assignment s := "");
* then perform the next step n times;
* at the i-th step take i-th lowercase letter of the Latin alphabet and write it either to the left of the string s or to the right of the string s (i.e. perform the assignment s := c+s or s := s+c, where c is the i-th letter of the Latin alphabet).
In other words, iterate over the n first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string s or append a letter to the right of the string s. Strings that can be obtained in that way are alphabetical.
For example, the following strings are alphabetical: "a", "ba", "ab", "bac" and "ihfcbadeg". The following strings are not alphabetical: "z", "aa", "ca", "acb", "xyz" and "ddcba".
From the given string, determine if it is alphabetical.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is written on a separate line that contains one string s. String s consists of lowercase letters of the Latin alphabet and has a length between 1 and 26, inclusive.
Output
Output t lines, each of them must contain the answer to the corresponding test case. Output YES if the given string s is alphabetical and NO otherwise.
You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive answer).
Example
Input
11
a
ba
ab
bac
ihfcbadeg
z
aa
ca
acb
xyz
ddcba
Output
YES
YES
YES
YES
YES
NO
NO
NO
NO
NO
NO
Note
The example contains test cases from the main part of the condition. | def f(s):
l=len(s)
while(l!=0):
if(s[0]==chr(96+l)):
s.pop(0)
l-=1
return f(s)
elif(s[l-1]==chr(96+l)):
s.pop()
return f(s)
l-=1
else:
return "NO"
return "YES"
t=int(input())
for i in range(0,t):
s=list(input())
print(f(s))
| {
"input": [
"11\na\nba\nab\nbac\nihfcbadeg\nz\naa\nca\nacb\nxyz\nddcba\n"
],
"output": [
"YES\nYES\nYES\nYES\nYES\nNO\nNO\nNO\nNO\nNO\nNO\n"
]
} |
4,142 | 11 | Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 β€ i β€ |a|), such that ai β bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.
John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.
Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition <image>.
To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
Input
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4).
All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
Output
Print -1 if there's no suitable set of strings.
Otherwise print on the first line number len β the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
Examples
Input
4 4 4
4 4
4
Output
6
aaaabb
aabbaa
bbaaaa
bbbbbb | def get_input():
a, b, d = map(int, input().split())
c, e = map(int, input().split())
f = int(input())
return [a, b, c, d, e, f]
def check_condition(a, b, c, d, e, f):
condition1 = (a + b + c) % 2 == 0
condition2 = (d + e + a) % 2 == 0
condition3 = (e + f + c) % 2 == 0
condition4 = (d + f + b) % 2 == 0
condition = condition1 and condition2 and condition3 and condition4
return condition
def find_t(a, b, c, d, e, f):
t_min1 = round((d + f - a - c) / 2)
t_min2 = round((e + f - a - b) / 2)
t_min3 = round((d + e - b - c) / 2)
t_min4 = 0
t_min = max(t_min1, t_min2, t_min3, t_min4)
t_max1 = round((d + e - a) / 2)
t_max2 = round((e + f - c) / 2)
t_max3 = round((d + f - b) / 2)
t_max = min(t_max1, t_max2, t_max3)
if t_min <= t_max:
return t_min
else:
return -1
def find_all(a, b, c, d, e, f, t):
x1 = round((a + c - d - f) / 2 + t)
x2 = round((d + f - b) / 2 - t)
y1 = round((a + b - e - f) / 2 + t)
y2 = round((e + f - c) / 2 - t)
z1 = round((b + c - d - e) / 2 + t)
z2 = round((d + e - a) / 2 - t)
return [x1, x2, y1, y2, z1, z2]
def generate_string(x1, x2, y1, y2, z1, z2, t):
n = x1 + x2 + y1 + y2 + z1 + z2 + t
s1 = ''.join(['a'] * n)
s2 = ''.join(['a'] * (z1 + z2 + t)) + ''.join(['b'] * (x1 + x2 + y1 + y2))
s3 = ''.join(['a'] * t) + ''.join(['b'] * (y1 + y2 + z1 + z2)) + ''.join(['a'] * (x1 + x2))
s4 = ''.join(['b'] * (t + z2)) + ''.join(['a'] * (z1 + y2)) + ''.join(['b'] * (y1 + x2)) + ''.join(['a'] * x1)
return [s1, s2, s3, s4]
def __main__():
fail_output = "-1"
a, b, c, d, e, f = map(int, get_input())
if not(check_condition(a, b, c, d, e, f)):
print(fail_output)
return False
t = find_t(a, b, c, d, e, f)
if t < 0:
print(fail_output)
return False
x1, x2, y1, y2, z1, z2 = map(int, find_all(a, b, c, d, e, f, t))
s1, s2, s3, s4 = map(str, generate_string(x1, x2, y1, y2, z1, z2, t))
print(str(x1 + x2 + y1 + y2 + z1 + z2 + t) + '\n')
print(s1 + '\n')
print(s2 + '\n')
print(s3 + '\n')
print(s4 + '\n')
__main__()
| {
"input": [
"4 4 4\n4 4\n4\n"
],
"output": [
"6\naaaaaa\naabbbb\nbbaabb\nbbbbaa"
]
} |
4,143 | 8 | A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.
Formally we will assume that segment [a, b] covers segment [c, d], if they meet this condition a β€ c β€ d β€ b.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers li, ri (1 β€ li β€ ri β€ 109) β the borders of the i-th segment.
It is guaranteed that no two segments coincide.
Output
Print a single integer β the number of the segment that covers all other segments in the set. If there's no solution, print -1.
The segments are numbered starting from 1 in the order in which they appear in the input.
Examples
Input
3
1 1
2 2
3 3
Output
-1
Input
6
1 5
2 3
1 10
7 10
7 7
10 10
Output
3 | def main():
a = [list(map(int,input().split())) for _ in ' '*int(input())]
l = min([x[0] for x in a])
r = max([x[1] for x in a])
try: print(a.index([l,r])+1)
except ValueError: print(-1)
main() | {
"input": [
"6\n1 5\n2 3\n1 10\n7 10\n7 7\n10 10\n",
"3\n1 1\n2 2\n3 3\n"
],
"output": [
"3\n",
"-1\n"
]
} |
4,144 | 8 | In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input
The first line contains two integers n (1 β€ n β€ 103) and x (1 β€ x β€ n) β the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ n) β the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1):
* It is guaranteed that the number of zero elements ai doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2):
* The number of zero elements ai is arbitrary.
Output
Print all possible positions of the Smart Beaver in the line in the increasing order.
Examples
Input
6 1
2 0 4 0 6 0
Output
2
4
6
Input
6 2
2 3 0 5 6 0
Output
2
5
Input
4 1
0 0 0 0
Output
1
2
3
4
Input
6 2
0 0 1 0 4 5
Output
1
3
4
6
Note
<image> Picture for the fourth test. | def f(x, p):
q = []
while x:
q.append(x)
x = p[x]
return q
from collections import defaultdict
n, k = map(int, input().split())
t = list(map(int, input().split()))
p = [0] * (n + 1)
for i, j in enumerate(t, 1):
p[j] = i
p = [f(i, p) for i, j in enumerate(t, 1) if j == 0]
s = defaultdict(int)
for i in p:
if k in i: t = {i.index(k) + 1}
else: s[len(i)] += 1
s = [list(range(i, k * i + 1, i)) for i, k in s.items()]
for q in s:
t |= {x + y for x in q for y in t}
print('\n'.join(map(str, sorted(list(t))))) | {
"input": [
"6 2\n2 3 0 5 6 0\n",
"6 2\n0 0 1 0 4 5\n",
"4 1\n0 0 0 0\n",
"6 1\n2 0 4 0 6 0\n"
],
"output": [
"2\n5\n",
"1\n3\n4\n6\n",
"1\n2\n3\n4\n",
"2\n4\n6\n"
]
} |
4,145 | 8 | Levko loves permutations very much. A permutation of length n is a sequence of distinct positive integers, each is at most n.
Letβs assume that value gcd(a, b) shows the greatest common divisor of numbers a and b. Levko assumes that element pi of permutation p1, p2, ... , pn is good if gcd(i, pi) > 1. Levko considers a permutation beautiful, if it has exactly k good elements. Unfortunately, he doesnβt know any beautiful permutation. Your task is to help him to find at least one of them.
Input
The single line contains two integers n and k (1 β€ n β€ 105, 0 β€ k β€ n).
Output
In a single line print either any beautiful permutation or -1, if such permutation doesnβt exist.
If there are multiple suitable permutations, you are allowed to print any of them.
Examples
Input
4 2
Output
2 4 3 1
Input
1 1
Output
-1
Note
In the first sample elements 4 and 3 are good because gcd(2, 4) = 2 > 1 and gcd(3, 3) = 3 > 1. Elements 2 and 1 are not good because gcd(1, 2) = 1 and gcd(4, 1) = 1. As there are exactly 2 good elements, the permutation is beautiful.
The second sample has no beautiful permutations. | def f(l):
n,k = l
return [-1] if k>=n else [n-k]+list(range(1,n-k))+list(range(n-k+1,n+1))
l = list(map(int,input().split()))
print(*f(l))
| {
"input": [
"1 1\n",
"4 2\n"
],
"output": [
"-1\n",
"2 1 3 4\n"
]
} |
4,146 | 10 | Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris.
There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset Y from the remaining blocks, that the equality holds:
<image> "Are you kidding me?", asks Chris.
For example, consider a case where s = 8 and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: (1 - 1) + (4 - 1) + (5 - 1) = (8 - 3) + (8 - 6) = 7.
<image>
However, now Chris has exactly s = 106 blocks. Given the set X of blocks his teacher chooses, help Chris to find the required set Y!
Input
The first line of input contains a single integer n (1 β€ n β€ 5Β·105), the number of blocks in the set X. The next line contains n distinct space-separated integers x1, x2, ..., xn (1 β€ xi β€ 106), the numbers of the blocks in X.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
In the first line of output print a single integer m (1 β€ m β€ 106 - n), the number of blocks in the set Y. In the next line output m distinct space-separated integers y1, y2, ..., ym (1 β€ yi β€ 106), such that the required equality holds. The sets X and Y should not intersect, i.e. xi β yj for all i, j (1 β€ i β€ n; 1 β€ j β€ m). It is guaranteed that at least one solution always exists. If there are multiple solutions, output any of them.
Examples
Input
3
1 4 5
Output
2
999993 1000000
Input
1
1
Output
1
1000000 | import sys
from math import gcd,sqrt,ceil
from collections import defaultdict,Counter,deque
import math
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
# sys.stdout=open("CP1/output.txt",'w')
# sys.stdin=open("CP1/input.txt",'r')
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write 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")
# import sys
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def get_sum(bit,i):
s = 0
i+=1
while i>0:
s+=bit[i]
i-=i&(-i)
return s
def update(bit,n,i,v):
i+=1
while i<=n:
bit[i]+=v
i+=i&(-i)
def modInverse(b,m):
g = math.gcd(b, m)
if (g != 1):
return -1
else:
return pow(b, m - 2, m)
# print(lo,ha)
n = int(input())
l = list(map(int,input().split()))
s = 10**6
ans = set()
l = set(l)
w = 0
for i in range(1,s+1):
opp = s+1-i
if i in l and opp not in l:
ans.add(opp)
elif i in l and opp in l:
w+=1
w//=2
for i in range(1,s+1):
opp = s+1-i
if w == 0:
break
if opp not in ans and i not in ans and i not in l and opp not in l:
ans.add(opp)
ans.add(i)
w-=1
print(len(ans))
print(*ans) | {
"input": [
"1\n1\n",
"3\n1 4 5\n"
],
"output": [
"1\n1000000 ",
"3\n1000000 999997 999996 "
]
} |
4,147 | 8 | Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 β€ n β€ 105; 1 β€ k β€ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second | from sys import stdin, setrecursionlimit
setrecursionlimit(200000)
n,k = [int(x) for x in stdin.readline().split()]
tree = {}
for x in range(n):
s = stdin.readline().strip()
cur = tree
for x in s:
if not x in cur:
cur[x] = {}
cur = cur[x]
def forced(tree):
if not tree:
return (False,True)
else:
win = False
lose = False
for x in tree:
a,b = forced(tree[x])
if not a:
win = True
if not b:
lose = True
return (win,lose)
a,b = forced(tree)
if a == 0:
print('Second')
elif a == 1 and b == 1:
print('First')
else:
if k%2 == 0:
print('Second')
else:
print('First') | {
"input": [
"3 1\na\nb\nc\n",
"2 3\na\nb\n",
"1 2\nab\n"
],
"output": [
"First\n",
"First\n",
"Second\n"
]
} |
4,148 | 8 | User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.
Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 β€ k β€ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak < bk all holds.
As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n Γ n binary matrix A, user ainta can swap the values of pi and pj (1 β€ i, j β€ n, i β j) if and only if Ai, j = 1.
Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
Input
The first line contains an integer n (1 β€ n β€ 300) β the size of the permutation p.
The second line contains n space-separated integers p1, p2, ..., pn β the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation.
Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 β€ i < j β€ n, Ai, j = Aj, i holds. Also, for all integers i where 1 β€ i β€ n, Ai, i = 0 holds.
Output
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
Examples
Input
7
5 2 4 3 6 7 1
0001001
0000000
0000010
1000001
0000000
0010000
1001000
Output
1 2 4 3 6 7 5
Input
5
4 2 1 5 3
00100
00011
10010
01101
01010
Output
1 2 3 4 5
Note
In the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).
In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4).
<image>
A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n. | n=int(input())
p=list(map(int, input().split()))
a=[list(map(int, list(input()))) for _ in range(n)]
v=[0]*n
l=n+1
xx=[-1]*n
def dfs(x):
global l
v[x]=1
if xx[x]==-1:
l=min(x,l)
for i in range(n):
if a[x][i]==1 and v[i]==0:
dfs(i)
x = [0]*(n+1)
for i in range(n):
x[p[i]]=i
for i in range(1,n+1):
v=[0]*n
l=n+1
dfs(x[i])
xx[l]=i
print(' '.join(map(str,xx))) | {
"input": [
"5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010\n",
"7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000\n"
],
"output": [
"1 2 3 4 5 ",
"1 2 4 3 6 7 5 "
]
} |
4,149 | 7 | Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the rating of i-th student as ai. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings.
He thinks that each student will take place equal to <image>. In particular, if student A has rating strictly lower then student B, A will get the strictly better position than B, and if two students have equal ratings, they will share the same position.
GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.
Input
The first line contains integer n (1 β€ n β€ 2000), number of GukiZ's students.
The second line contains n numbers a1, a2, ... an (1 β€ ai β€ 2000) where ai is the rating of i-th student (1 β€ i β€ n).
Output
In a single line, print the position after the end of the contest for each of n students in the same order as they appear in the input.
Examples
Input
3
1 3 3
Output
3 1 1
Input
1
1
Output
1
Input
5
3 5 3 4 5
Output
4 1 4 3 1
Note
In the first sample, students 2 and 3 are positioned first (there is no other student with higher rating), and student 1 is positioned third since there are two students with higher rating.
In the second sample, first student is the only one on the contest.
In the third sample, students 2 and 5 share the first position with highest rating, student 4 is next with third position, and students 1 and 3 are the last sharing fourth position. | #!/usr/bin/python3
def getRating(r):
return 1+len(list(filter(lambda x:x>r,a)))
n=int(input())
a=list(map(int,input().split()))
res=list(map(getRating,a))
print(*res)
| {
"input": [
"1\n1\n",
"3\n1 3 3\n",
"5\n3 5 3 4 5\n"
],
"output": [
"1 ",
"3 1 1 ",
"4 1 4 3 1 "
]
} |
4,150 | 8 | You are given n numbers a1, a2, ..., an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make <image> as large as possible, where <image> denotes the bitwise OR.
Find the maximum possible value of <image> after performing at most k operations optimally.
Input
The first line contains three integers n, k and x (1 β€ n β€ 200 000, 1 β€ k β€ 10, 2 β€ x β€ 8).
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 109).
Output
Output the maximum value of a bitwise OR of sequence elements after performing operations.
Examples
Input
3 1 2
1 1 1
Output
3
Input
4 2 3
1 2 4 8
Output
79
Note
For the first sample, any possible choice of doing one operation will result the same three numbers 1, 1, 2 so the result is <image>.
For the second sample if we multiply 8 by 3 two times we'll get 72. In this case the numbers will become 1, 2, 4, 72 so the OR value will be 79 and is the largest possible result. | def main():
n, k, x = map(int, input().split())
aa = list(map(int, input().split()))
x, lo, u = x ** k, [0] * n, 0
for i, a in enumerate(aa):
lo[i] = u
u |= a
hi, u = [], 0
for a in reversed(aa):
hi.append(u)
u |= a
hi.reverse()
for i, u, a, v in zip(range(n), lo, aa, hi):
aa[i] = a * x | u | v
print(max(aa))
if __name__ == '__main__':
main()
| {
"input": [
"3 1 2\n1 1 1\n",
"4 2 3\n1 2 4 8\n"
],
"output": [
"3\n",
"79\n"
]
} |
4,151 | 11 | In Ancient Berland there were n cities and m two-way roads of equal length. The cities are numbered with integers from 1 to n inclusively. According to an ancient superstition, if a traveller visits three cities ai, bi, ci in row, without visiting other cities between them, a great disaster awaits him. Overall there are k such city triplets. Each triplet is ordered, which means that, for example, you are allowed to visit the cities in the following order: ai, ci, bi. Vasya wants to get from the city 1 to the city n and not fulfil the superstition. Find out which minimal number of roads he should take. Also you are required to find one of his possible path routes.
Input
The first line contains three integers n, m, k (2 β€ n β€ 3000, 1 β€ m β€ 20000, 0 β€ k β€ 105) which are the number of cities, the number of roads and the number of the forbidden triplets correspondingly.
Then follow m lines each containing two integers xi, yi (1 β€ xi, yi β€ n) which are the road descriptions. The road is described by the numbers of the cities it joins. No road joins a city with itself, there cannot be more than one road between a pair of cities.
Then follow k lines each containing three integers ai, bi, ci (1 β€ ai, bi, ci β€ n) which are the forbidden triplets. Each ordered triplet is listed mo more than one time. All three cities in each triplet are distinct.
City n can be unreachable from city 1 by roads.
Output
If there are no path from 1 to n print -1. Otherwise on the first line print the number of roads d along the shortest path from the city 1 to the city n. On the second line print d + 1 numbers β any of the possible shortest paths for Vasya. The path should start in the city 1 and end in the city n.
Examples
Input
4 4 1
1 2
2 3
3 4
1 3
1 4 3
Output
2
1 3 4
Input
3 1 0
1 2
Output
-1
Input
4 4 2
1 2
2 3
3 4
1 3
1 2 3
1 3 4
Output
4
1 3 2 3 4 | import sys
def srch(b,c):
if b:srch(pre[b][c],b)
print(c,end=' ')
I=lambda:[*map(int,input().split())]
n,m,k=I()
points=[[]for i in range(n+1)]
for i in range(m):
a,b=I()
points[a]+=[b]
points[b]+=[a]
curse=set()
for i in range(k):curse.add(tuple(I()))
pre=[[0]*(n+1) for i in range(n+1)]
dp=[[100000000]*(n+1)for i in range(n+1)]
q=[(0,1)]
dp[0][1]=0
while(q):
a,b=q.pop(0)
d=dp[a][b]+1
for c in points[b]:
if dp[b][c]>d and (a,b,c) not in curse:
q+=[(b,c)]
dp[b][c]=d
pre[b][c]=a
if c==n:
print(d)
srch(b,c)
sys.exit(0)
print(-1) | {
"input": [
"4 4 1\n1 2\n2 3\n3 4\n1 3\n1 4 3\n",
"3 1 0\n1 2\n",
"4 4 2\n1 2\n2 3\n3 4\n1 3\n1 2 3\n1 3 4\n"
],
"output": [
"2\n1 3 4\n",
"-1\n",
"4\n1 3 2 3 4\n"
]
} |
4,152 | 9 | There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too.
Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from li to ri. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product siΒ·sj is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.
At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.
Input
The first line of the input contains two space-separated integers n and p (3 β€ n β€ 100 000, 2 β€ p β€ 109) β the number of sharks and Wet Shark's favourite prime number. It is guaranteed that p is prime.
The i-th of the following n lines contains information about i-th shark β two space-separated integers li and ri (1 β€ li β€ ri β€ 109), the range of flowers shark i can produce. Remember that si is chosen equiprobably among all integers from li to ri, inclusive.
Output
Print a single real number β the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.
Examples
Input
3 2
1 2
420 421
420420 420421
Output
4500.0
Input
3 5
1 4
2 3
11 14
Output
0.0
Note
A prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.
Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (s0, s1, s2) each shark grows:
1. (1, 420, 420420): note that s0Β·s1 = 420, s1Β·s2 = 176576400, and s2Β·s0 = 420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars.
2. (1, 420, 420421): now, the product s2Β·s0 is not divisible by 2. Therefore, sharks s0 and s2 will receive 1000 dollars, while shark s1 will receive 2000. The total is 4000.
3. (1, 421, 420420): total is 4000
4. (1, 421, 420421): total is 0.
5. (2, 420, 420420): total is 6000.
6. (2, 420, 420421): total is 6000.
7. (2, 421, 420420): total is 6000.
8. (2, 421, 420421): total is 4000.
The expected value is <image>.
In the second sample, no combination of quantities will garner the sharks any money. | n,m=map(int,input().split())
def f():
a,b=map(int,input().split())
return(b//m-(a-1)//m)/(b-a+1)
a=[f() for _ in range(n)]
r=0
for i in range(n):
r+=1-(1-a[i])*(1-a[(i+1)%n])
print(r*2000) | {
"input": [
"3 2\n1 2\n420 421\n420420 420421\n",
"3 5\n1 4\n2 3\n11 14\n"
],
"output": [
"4500.0000000000",
"0.0000000000"
]
} |
4,153 | 7 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.
For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.
There are <image> non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant.
Input
The first line of the input contains a single integer n (1 β€ n β€ 5000) β the number of balls.
The second line contains n integers t1, t2, ..., tn (1 β€ ti β€ n) where ti is the color of the i-th ball.
Output
Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color.
Examples
Input
4
1 2 1 2
Output
7 3 0 0
Input
3
1 1 1
Output
6 0 0
Note
In the first sample, color 2 is dominant in three intervals:
* An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color.
* An interval [4, 4] contains one ball, with color 2 again.
* An interval [2, 4] contains two balls of color 2 and one ball of color 1.
There are 7 more intervals and color 1 is dominant in all of them. | def solve(n, t):
sol = [0 for _ in range(n)]
for i in range(n):
cts = [0 for _ in range(n+1)]
best_c = 0
for j in range(i, n):
cts[t[j]] += 1
if cts[t[j]] > cts[best_c] or (cts[t[j]] == cts[best_c] and t[j] < best_c):
best_c = t[j]
sol[best_c-1] += 1
return ' '.join(map(str, sol))
n = int(input())
t = [int(v) for v in input().split()]
print(solve(n, t)) | {
"input": [
"3\n1 1 1\n",
"4\n1 2 1 2\n"
],
"output": [
"6 0 0 ",
"7 3 0 0 "
]
} |
4,154 | 7 | On the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Martians have the same weeks as earthlings β 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars.
Input
The first line of the input contains a positive integer n (1 β€ n β€ 1 000 000) β the number of days in a year on Mars.
Output
Print two integers β the minimum possible and the maximum possible number of days off per year on Mars.
Examples
Input
14
Output
4 4
Input
2
Output
0 2
Note
In the first sample there are 14 days in a year on Mars, and therefore independently of the day a year starts with there will be exactly 4 days off .
In the second sample there are only 2 days in a year on Mars, and they can both be either work days or days off. | def main():
n=int(input())
min=(n//7)+(n+1)//7
max=(n+5)//7+(n+6)//7
print(min,max)
main() | {
"input": [
"2\n",
"14\n"
],
"output": [
"0 2",
"4 4"
]
} |
4,155 | 9 | You are given a positive decimal number x.
Your task is to convert it to the "simple exponential notation".
Let x = aΒ·10b, where 1 β€ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b.
Input
The only line contains the positive decimal number x. The length of the line will not exceed 106. Note that you are given too large number, so you can't use standard built-in data types "float", "double" and other.
Output
Print the only line β the "simple exponential notation" of the given number x.
Examples
Input
16
Output
1.6E1
Input
01.23400
Output
1.234
Input
.100
Output
1E-1
Input
100.
Output
1E2 | def f(q):
i = 0
while i < len(q) and q[i] == '0': i += 1
return q[i:]
def g(q):
i = len(q)
while i > 0 and q[i - 1] == '0': i -= 1
return q[:i]
a, b = (input() + '.').split('.')[:2]
a, b = f(a), g(b)
e = len(a) - 1
if not b: a = g(a)
if not a:
e = len(b) + 1
b = f(b)
e = len(b) - e
s = a + b
s = s[0] + '.' + s[1:] if len(s) > 1 else s
print(s + 'E' + str(e) if s and e else max(s, '0')) | {
"input": [
"01.23400\n",
".100\n",
"100.\n",
"16\n"
],
"output": [
"1.234\n",
"1E-1\n",
"1E2\n",
"1.6E1\n"
]
} |
4,156 | 9 | ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '<image>' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1.
When ZS the Coder is at level k, he can :
1. Press the ' + ' button. This increases the number on the screen by exactly k. So, if the number on the screen was x, it becomes x + k.
2. Press the '<image>' button. Let the number on the screen be x. After pressing this button, the number becomes <image>. After that, ZS the Coder levels up, so his current level becomes k + 1. This button can only be pressed when x is a perfect square, i.e. x = m2 for some positive integer m.
Additionally, after each move, if ZS the Coder is at level k, and the number on the screen is m, then m must be a multiple of k. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '<image>' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5.
ZS the Coder needs your help in beating the game β he wants to reach level n + 1. In other words, he needs to press the '<image>' button n times. Help him determine the number of times he should press the ' + ' button before pressing the '<image>' button at each level.
Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level n + 1, but not necessarily a sequence minimizing the number of presses.
Input
The first and only line of the input contains a single integer n (1 β€ n β€ 100 000), denoting that ZS the Coder wants to reach level n + 1.
Output
Print n non-negative integers, one per line. i-th of them should be equal to the number of times that ZS the Coder needs to press the ' + ' button before pressing the '<image>' button at level i.
Each number in the output should not exceed 1018. However, the number on the screen can be greater than 1018.
It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them.
Examples
Input
3
Output
14
16
46
Input
2
Output
999999999999999998
44500000000
Input
4
Output
2
17
46
97
Note
In the first sample case:
On the first level, ZS the Coder pressed the ' + ' button 14 times (and the number on screen is initially 2), so the number became 2 + 14Β·1 = 16. Then, ZS the Coder pressed the '<image>' button, and the number became <image>.
After that, on the second level, ZS pressed the ' + ' button 16 times, so the number becomes 4 + 16Β·2 = 36. Then, ZS pressed the '<image>' button, levelling up and changing the number into <image>.
After that, on the third level, ZS pressed the ' + ' button 46 times, so the number becomes 6 + 46Β·3 = 144. Then, ZS pressed the '<image>' button, levelling up and changing the number into <image>.
Note that 12 is indeed divisible by 4, so ZS the Coder can reach level 4.
Also, note that pressing the ' + ' button 10 times on the third level before levelling up does not work, because the number becomes 6 + 10Β·3 = 36, and when the '<image>' button is pressed, the number becomes <image> and ZS the Coder is at Level 4. However, 6 is not divisible by 4 now, so this is not a valid solution.
In the second sample case:
On the first level, ZS the Coder pressed the ' + ' button 999999999999999998 times (and the number on screen is initially 2), so the number became 2 + 999999999999999998Β·1 = 1018. Then, ZS the Coder pressed the '<image>' button, and the number became <image>.
After that, on the second level, ZS pressed the ' + ' button 44500000000 times, so the number becomes 109 + 44500000000Β·2 = 9Β·1010. Then, ZS pressed the '<image>' button, levelling up and changing the number into <image>.
Note that 300000 is a multiple of 3, so ZS the Coder can reach level 3. | def scarry(n):
a = [2]
for i in range(2, n + 1):
a.append(i * (i + 1) * (i + 1) - (i - 1))
return a
print(*scarry(int(input())), sep='\n')
| {
"input": [
"2\n",
"3\n",
"4\n"
],
"output": [
"2\n17\n",
"2\n17\n46\n",
"2\n17\n46\n97\n"
]
} |
4,157 | 7 |
Input
The input contains a single integer a (1 β€ a β€ 30).
Output
Output a single integer.
Example
Input
3
Output
27 | ans = [0, 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438, 454, 483, 517, 526, 535, 562, 576, 588, 627, 634, 636, 645, 648]
def main():
n = int(input())
print(ans[n])
main()
| {
"input": [
"3\n"
],
"output": [
"27\n"
]
} |
4,158 | 7 | Arpa is researching the Mexican wave.
There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0.
* At time 1, the first spectator stands.
* At time 2, the second spectator stands.
* ...
* At time k, the k-th spectator stands.
* At time k + 1, the (k + 1)-th spectator stands and the first spectator sits.
* At time k + 2, the (k + 2)-th spectator stands and the second spectator sits.
* ...
* At time n, the n-th spectator stands and the (n - k)-th spectator sits.
* At time n + 1, the (n + 1 - k)-th spectator sits.
* ...
* At time n + k, the n-th spectator sits.
Arpa wants to know how many spectators are standing at time t.
Input
The first line contains three integers n, k, t (1 β€ n β€ 109, 1 β€ k β€ n, 1 β€ t < n + k).
Output
Print single integer: how many spectators are standing at time t.
Examples
Input
10 5 3
Output
3
Input
10 5 7
Output
5
Input
10 5 12
Output
3
Note
In the following a sitting spectator is represented as -, a standing spectator is represented as ^.
* At t = 0 ---------- <image> number of standing spectators = 0.
* At t = 1 ^--------- <image> number of standing spectators = 1.
* At t = 2 ^^-------- <image> number of standing spectators = 2.
* At t = 3 ^^^------- <image> number of standing spectators = 3.
* At t = 4 ^^^^------ <image> number of standing spectators = 4.
* At t = 5 ^^^^^----- <image> number of standing spectators = 5.
* At t = 6 -^^^^^---- <image> number of standing spectators = 5.
* At t = 7 --^^^^^--- <image> number of standing spectators = 5.
* At t = 8 ---^^^^^-- <image> number of standing spectators = 5.
* At t = 9 ----^^^^^- <image> number of standing spectators = 5.
* At t = 10 -----^^^^^ <image> number of standing spectators = 5.
* At t = 11 ------^^^^ <image> number of standing spectators = 4.
* At t = 12 -------^^^ <image> number of standing spectators = 3.
* At t = 13 --------^^ <image> number of standing spectators = 2.
* At t = 14 ---------^ <image> number of standing spectators = 1.
* At t = 15 ---------- <image> number of standing spectators = 0. | def main():
N, K, T = map(int, input().split())
ans = min(K, T, K - (T - N))
print(ans)
main()
| {
"input": [
"10 5 3\n",
"10 5 7\n",
"10 5 12\n"
],
"output": [
"3\n",
"5\n",
"3\n"
]
} |
4,159 | 9 | You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | from collections import defaultdict, deque
def main():
n,m = map(int, input().split())
cap = [None]*(m+1)
same_cap = defaultdict(list)
q = deque()
def apply_cap(a, c):
if cap[a] is not None:
return cap[a] == c
q.append((a,c))
while q:
b = q.pop()
if b[1] == c:
if cap[b[0]] is None:
cap[b[0]] = c
q.extend(same_cap[b[0]])
same_cap[b[0]] = []
elif cap[b[0]]!=c:
return False
return True
def same(a,b):
same_cap[b].append((a,True))
same_cap[a].append((b,False))
if cap[a] == False:
return apply_cap(b, False)
if cap[b] == True:
return apply_cap(a, True)
return True
def process(p,c):
lp = p[0]
lc = c[0]
for i in range(1, min(lp,lc)+1):
if p[i]>c[i]:
return apply_cap(p[i], True) and apply_cap(c[i], False)
if p[i]<c[i]:
return same(p[i], c[i])
return lp<=lc
p = list(map(int, input().split()))
for i in range(n-1):
c = list(map(int, input().split()))
if not process(p, c):
print ('No')
break
p = c
else:
print ('Yes')
res = []
for i,b in enumerate(cap):
if b:
res.append(i)
print(len(res))
print(' '.join(map(str,res)))
main() | {
"input": [
"4 3\n1 2\n1 1\n3 1 3 2\n2 1 1\n",
"4 3\n4 3 2 2 1\n3 1 1 3\n3 2 3 3\n2 3 1\n",
"6 5\n2 1 2\n2 1 2\n3 1 2 3\n2 1 5\n2 4 4\n2 4 4\n"
],
"output": [
"Yes\n2\n2 3 \n",
"No\n",
"Yes\n0\n\n"
]
} |
4,160 | 8 | Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other.
A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type.
Types HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets β they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change.
We shall assume that the widget a is packed in the widget b if there exists a chain of widgets a = c1, c2, ..., ck = b, k β₯ 2, for which ci is packed directly to ci + 1 for any 1 β€ i < k. In Vasya's library the situation when the widget a is packed in the widget a (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error.
Also, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal 0.
<image>
The picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox β vertically. The parameter spacing sets the distance between adjacent widgets, and border β a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to 0 Γ 0, regardless of the options border and spacing.
The construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data.
For the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript.
Input
The first line contains an integer n β the number of instructions (1 β€ n β€ 100). Next n lines contain instructions in the language VasyaScript β one instruction per line. There is a list of possible instructions below.
* "Widget [name]([x],[y])" β create a new widget [name] of the type Widget possessing the width of [x] units and the height of [y] units.
* "HBox [name]" β create a new widget [name] of the type HBox.
* "VBox [name]" β create a new widget [name] of the type VBox.
* "[name1].pack([name2])" β pack the widget [name2] in the widget [name1]. At that, the widget [name1] must be of type HBox or VBox.
* "[name].set_border([x])" β set for a widget [name] the border parameter to [x] units. The widget [name] must be of type HBox or VBox.
* "[name].set_spacing([x])" β set for a widget [name] the spacing parameter to [x] units. The widget [name] must be of type HBox or VBox.
All instructions are written without spaces at the beginning and at the end of the string. The words inside the instruction are separated by exactly one space. There are no spaces directly before the numbers and directly after them.
The case matters, for example, "wiDget x" is not a correct instruction. The case of the letters is correct in the input data.
All names of the widgets consist of lowercase Latin letters and has the length from 1 to 10 characters inclusive. The names of all widgets are pairwise different. All numbers in the script are integers from 0 to 100 inclusive
It is guaranteed that the above-given script is correct, that is that all the operations with the widgets take place after the widgets are created and no widget is packed in itself. It is guaranteed that the script creates at least one widget.
Output
For each widget print on a single line its name, width and height, separated by spaces. The lines must be ordered lexicographically by a widget's name.
Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d specificator)
Examples
Input
12
Widget me(50,40)
VBox grandpa
HBox father
grandpa.pack(father)
father.pack(me)
grandpa.set_border(10)
grandpa.set_spacing(20)
Widget brother(30,60)
father.pack(brother)
Widget friend(20,60)
Widget uncle(100,20)
grandpa.pack(uncle)
Output
brother 30 60
father 80 60
friend 20 60
grandpa 120 120
me 50 40
uncle 100 20
Input
15
Widget pack(10,10)
HBox dummy
HBox x
VBox y
y.pack(dummy)
y.set_border(5)
y.set_spacing(55)
dummy.set_border(10)
dummy.set_spacing(20)
x.set_border(10)
x.set_spacing(10)
x.pack(pack)
x.pack(dummy)
x.pack(pack)
x.set_border(0)
Output
dummy 0 0
pack 10 10
x 40 10
y 10 10
Note
In the first sample the widgets are arranged as follows:
<image> | n = int(input())
widgets = {}
class Widget:
def __init__(self, w, h):
self.w = w
self.h = h
def calc_size(self):
return (self.w, self.h)
class Box:
def __init__(self, direction):
self.dir = direction
self.packed = []
self.border = 0
self.spacing = 0
self.size = None
def calc_size(self):
if self.size is not None: return self.size
if not len(self.packed):
self.size = (0, 0)
return self.size
child_sizes = []
for kid in self.packed:
child_sizes.append(kid.calc_size())
s = 0
for kid in child_sizes: s += kid[self.dir=='V']
s += self.spacing*max(0, len(self.packed)-1)
mx = 0
for kid in child_sizes: mx = max(mx, kid[self.dir=='H'])
self.size = (mx + 2*self.border, s + 2*self.border)
if self.dir == 'H':
self.size = (self.size[1], self.size[0])
return self.size
for _ in range(n):
s = input().strip()
spacespl = s.split(' ')
if len(spacespl) > 1:
cmd, rest = spacespl
if cmd == 'Widget':
name, rest = rest.split('(')
w, h = map(int, rest[:-1].split(','))
widgets[name] = Widget(w, h)
elif cmd == 'HBox':
widgets[rest] = Box('H')
elif cmd == 'VBox':
widgets[rest] = Box('V')
else:
name1, rest = s.split('.')
method, args = rest[:-1].split('(')
if method == 'pack':
widgets[name1].packed.append(widgets[args])
elif method == 'set_border':
widgets[name1].border = int(args)
elif method == 'set_spacing':
widgets[name1].spacing = int(args)
for name, thing in sorted(widgets.items()):
print(name, *thing.calc_size())
| {
"input": [
"12\nWidget me(50,40)\nVBox grandpa\nHBox father\ngrandpa.pack(father)\nfather.pack(me)\ngrandpa.set_border(10)\ngrandpa.set_spacing(20)\nWidget brother(30,60)\nfather.pack(brother)\nWidget friend(20,60)\nWidget uncle(100,20)\ngrandpa.pack(uncle)\n",
"15\nWidget pack(10,10)\nHBox dummy\nHBox x\nVBox y\ny.pack(dummy)\ny.set_border(5)\ny.set_spacing(55)\ndummy.set_border(10)\ndummy.set_spacing(20)\nx.set_border(10)\nx.set_spacing(10)\nx.pack(pack)\nx.pack(dummy)\nx.pack(pack)\nx.set_border(0)\n"
],
"output": [
"brother 30 60\nfather 80 60\nfriend 20 60\ngrandpa 120 120\nme 50 40\nuncle 100 20\n",
"dummy 0 0\npack 10 10\nx 40 10\ny 10 10\n"
]
} |
4,161 | 8 | Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm.
Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows:
<image>
You have to write a program that allows you to determine what number will be in the cell with index x (1 β€ x β€ n) after Dima's algorithm finishes.
Input
The first line contains two integers n and q (1 β€ n β€ 1018, 1 β€ q β€ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer.
Next q lines contain integers xi (1 β€ xi β€ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes.
Output
For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes.
Examples
Input
4 3
2
3
4
Output
3
2
4
Input
13 4
10
5
4
8
Output
13
3
8
9
Note
The first example is shown in the picture.
In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7]. | import sys
[n, q] = map(int, sys.stdin.readline().strip().split())
qis = [int(sys.stdin.readline().strip()) for _ in range(q)]
def query(n, q):
d = 2 * n - q
while d % 2 == 0:
d //= 2
return (n - d // 2)
for qi in qis:
print (query(n, qi)) | {
"input": [
"13 4\n10\n5\n4\n8\n",
"4 3\n2\n3\n4\n"
],
"output": [
"13\n3\n8\n9\n",
"3\n2\n4\n"
]
} |
4,162 | 7 | Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit).
You are given an integer number n. Tanya will subtract one from it k times. Your task is to print the result after all k subtractions.
It is guaranteed that the result will be positive integer number.
Input
The first line of the input contains two integer numbers n and k (2 β€ n β€ 10^9, 1 β€ k β€ 50) β the number from which Tanya will subtract and the number of subtractions correspondingly.
Output
Print one integer number β the result of the decreasing n by one k times.
It is guaranteed that the result will be positive integer number.
Examples
Input
512 4
Output
50
Input
1000000000 9
Output
1
Note
The first example corresponds to the following sequence: 512 β 511 β 510 β 51 β 50. | def f(n):
if n%10==0:
return n//10
else:
return n-1
n,k=map(int,input().split())
for i in range(k):
n=f(n)
print(n) | {
"input": [
"512 4\n",
"1000000000 9\n"
],
"output": [
"50\n",
"1\n"
]
} |
4,163 | 11 | For a vector \vec{v} = (x, y), define |v| = β{x^2 + y^2}.
Allen had a bit too much to drink at the bar, which is at the origin. There are n vectors \vec{v_1}, \vec{v_2}, β
β
β
, \vec{v_n}. Allen will make n moves. As Allen's sense of direction is impaired, during the i-th move he will either move in the direction \vec{v_i} or -\vec{v_i}. In other words, if his position is currently p = (x, y), he will either move to p + \vec{v_i} or p - \vec{v_i}.
Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position p satisfies |p| β€ 1.5 β
10^6 so that he can stay safe.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of moves.
Each of the following lines contains two space-separated integers x_i and y_i, meaning that \vec{v_i} = (x_i, y_i). We have that |v_i| β€ 10^6 for all i.
Output
Output a single line containing n integers c_1, c_2, β
β
β
, c_n, each of which is either 1 or -1. Your solution is correct if the value of p = β_{i = 1}^n c_i \vec{v_i}, satisfies |p| β€ 1.5 β
10^6.
It can be shown that a solution always exists under the given constraints.
Examples
Input
3
999999 0
0 999999
999999 0
Output
1 1 -1
Input
1
-824590 246031
Output
1
Input
8
-67761 603277
640586 -396671
46147 -122580
569609 -2112
400 914208
131792 309779
-850150 -486293
5272 721899
Output
1 1 1 1 1 1 1 -1 | n=int(input())
l=[]
def d(x,y):
return x**2 + y**2
lv=[0 for i in range(n)]
for i in range(n):
l1=list(map(int,input().strip().split()))
l.append(l1)
vx=l[0][0]
vy=l[0][1]
lv[0]=1
for i in range(1,n-1,2):
vx1,vy1,vx2,vy2=l[i][0],l[i][1],l[i+1][0],l[i+1][1]
_,c1,c2=min((d(vx+vx1+vx2,vy+vy1+vy2),1,1),(d(vx+vx1-vx2,vy+vy1-vy2),1,-1),(d(vx-vx1+vx2,vy-vy1+vy2),-1,1),(d(vx-vx1-vx2,vy-vy1-vy2),-1,-1))
vx=vx+c1*vx1+c2*vx2
vy=vy+vy1*c1+vy2*c2
lv[i]=c1
lv[i+1]=c2
if (lv[n-1]==0):
_,c1=min((d(vx+l[n-1][0],vy+l[n-1][1]),1),(d(vx-l[n-1][0],vy-l[n-1][1]),-1))
lv[n-1]=c1
print (" ".join(map(str,lv))) | {
"input": [
"3\n999999 0\n0 999999\n999999 0\n",
"1\n-824590 246031\n",
"8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n"
],
"output": [
"-1 -1 1 ",
"1 ",
"1 1 -1 -1 -1 -1 -1 1 \n"
]
} |
4,164 | 7 | You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of s can be replaced with anything. If it is possible to replace a wildcard character '*' in s to obtain a string t, then the string t matches the pattern s.
For example, if s="aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".
If the given string t matches the given string s, print "YES", otherwise print "NO".
Input
The first line contains two integers n and m (1 β€ n, m β€ 2 β
10^5) β the length of the string s and the length of the string t, respectively.
The second line contains string s of length n, which consists of lowercase Latin letters and at most one wildcard character '*'.
The third line contains string t of length m, which consists only of lowercase Latin letters.
Output
Print "YES" (without quotes), if you can obtain the string t from the string s. Otherwise print "NO" (without quotes).
Examples
Input
6 10
code*s
codeforces
Output
YES
Input
6 5
vk*cup
vkcup
Output
YES
Input
1 1
v
k
Output
NO
Input
9 6
gfgf*gfgf
gfgfgf
Output
NO
Note
In the first example a wildcard character '*' can be replaced with a string "force". So the string s after this replacement is "codeforces" and the answer is "YES".
In the second example a wildcard character '*' can be replaced with an empty string. So the string s after this replacement is "vkcup" and the answer is "YES".
There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".
In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string t so the answer is "NO". | i=input
i()
s=i()
t=i()
def go():
if '*' not in s: return s!=t
a,b=s.split('*')
return len(a+b)>len(t) or not (t.startswith(a) and t.endswith(b))
print('YNEOS'[go()::2]) | {
"input": [
"6 10\ncode*s\ncodeforces\n",
"9 6\ngfgf*gfgf\ngfgfgf\n",
"6 5\nvk*cup\nvkcup\n",
"1 1\nv\nk\n"
],
"output": [
"YES\n",
"NO\n",
"YES\n",
"NO\n"
]
} |
4,165 | 8 | You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree.
You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled x_1, x_2, β¦, x_{k_1} in your labeling, Li Chen's subtree consists of the vertices labeled y_1, y_2, β¦, y_{k_2} in his labeling. The values of x_1, x_2, β¦, x_{k_1} and y_1, y_2, β¦, y_{k_2} are known to both of you.
<image> The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes.
You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most 5 questions, each of which is in one of the following two forms:
* A x: Andrew will look at vertex x in your labeling and tell you the number of this vertex in Li Chen's labeling.
* B y: Andrew will look at vertex y in Li Chen's labeling and tell you the number of this vertex in your labeling.
Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.
Interaction
Each test consists of several test cases.
The first line of input contains a single integer t (1 β€ t β€ 100) β the number of test cases.
For each testcase, your program should interact in the following format.
The first line contains a single integer n (1 β€ n β€ 1 000) β 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) β the edges of the tree, indicating an edge between node a_i and b_i according to your labeling of the nodes.
The next line contains a single integer k_1 (1 β€ k_1 β€ n) β the number of nodes in your subtree.
The next line contains k_1 distinct integers x_1,x_2,β¦,x_{k_1} (1 β€ x_i β€ n) β the indices of the nodes in your subtree, according to your labeling. It is guaranteed that these vertices form a subtree.
The next line contains a single integer k_2 (1 β€ k_2 β€ n) β the number of nodes in Li Chen's subtree.
The next line contains k_2 distinct integers y_1, y_2, β¦, y_{k_2} (1 β€ y_i β€ n) β the indices (according to Li Chen's labeling) of the nodes in Li Chen's subtree. It is guaranteed that these vertices form a subtree according to Li Chen's labelling of the tree's nodes.
Test cases will be provided one by one, so you must complete interacting with the previous test (i.e. by printing out a common node or -1 if there is not such node) to start receiving the next one.
You can ask the Andrew two different types of questions.
* You can print "A x" (1 β€ x β€ n). Andrew will look at vertex x in your labeling and respond to you with the number of this vertex in Li Chen's labeling.
* You can print "B y" (1 β€ y β€ n). Andrew will look at vertex y in Li Chen's labeling and respond to you with the number of this vertex in your labeling.
You may only ask at most 5 questions per tree.
When you are ready to answer, print "C s", where s is your label of a vertex that is common to both subtrees, or -1, if no such vertex exists. Printing the answer does not count as a question. Remember to flush your answer to start receiving the next test case.
After printing a question do not forget to print end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If the judge responds with -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive Wrong Answer; it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
Hack Format
To hack, use the following format. Note that you can only hack with one test case.
The first line should contain a single integer t (t=1).
The second line should contain a single integer n (1 β€ n β€ 1 000).
The third line should contain n integers p_1, p_2, β¦, p_n (1β€ p_iβ€ n) β a permutation of 1 to n. This encodes the labels that Li Chen chose for his tree. In particular, Li Chen chose label p_i for the node you labeled i.
Each of the next n-1 lines should contain two integers a_i and b_i (1β€ a_i, b_iβ€ n). These edges should form a tree.
The next line should contain a single integer k_1 (1 β€ k_1 β€ n).
The next line should contain k_1 distinct integers x_1,x_2,β¦,x_{k_1} (1 β€ x_i β€ n). These vertices should form a subtree.
The next line should contain a single integer k_2 (1 β€ k_2 β€ n).
The next line should contain k_2 distinct integers y_1, y_2, β¦, y_{k_2} (1 β€ y_i β€ n). These vertices should form a subtree in Li Chen's tree according to the permutation above.
Examples
Input
1
3
1 2
2 3
1
1
1
2
2
1
Output
A 1
B 2
C 1
Input
2
6
1 2
1 3
1 4
4 5
4 6
4
1 3 4 5
3
3 5 2
3
6
1 2
1 3
1 4
4 5
4 6
3
1 2 3
3
4 1 6
5
Output
B 2
C 1
A 1
C -1
Note
For the first sample, Li Chen's hidden permutation is [2, 3, 1], and for the second, his hidden permutation is [5, 3, 2, 4, 1, 6] for both cases.
In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose:
<image>
In the first question, you ask Andrew to look at node 1 in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with 2. At this point, you know that both of your subtrees contain the same node (i.e. node 1 according to your labeling), so you can output "C 1" and finish. However, you can also ask Andrew to look at node 2 in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with 1 (this step was given with the only reason β to show you how to ask questions).
For the second sample, there are two test cases. The first looks is the one from the statement:
<image>
We first ask "B 2", and Andrew will tell us 3. In this case, we know 3 is a common vertex, and moreover, any subtree with size 3 that contains node 3 must contain node 1 as well, so we can output either "C 1" or "C 3" as our answer.
In the second case in the second sample, the situation looks as follows:
<image>
In this case, you know that the only subtree of size 3 that doesn't contain node 1 is subtree 4,5,6. You ask Andrew for the label of node 1 in Li Chen's labelling and Andrew says 5. In this case, you know that Li Chen's subtree doesn't contain node 1, so his subtree must be consist of the nodes 4,5,6 (in your labelling), thus the two subtrees have no common nodes. | import sys
from math import *
from random import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
e = [[] for i in range(n+1)]
p = [None]*(n+1)
my = [False]*(n+1)
for i in range(n-1):
a,b = mints()
e[a].append(b)
e[b].append(a)
def dfs(x):
for i in e[x]:
if p[i] == None:
p[i] = x
dfs(i)
k1 = mint()
x = list(mints())
for i in x:
my[i] = True
k2 = mint()
y = list(mints())
p[x[0]] = 0
dfs(x[0])
print('B',y[0])
sys.stdout.flush()
z = mint()
while my[z] != True:
z = p[z]
print('A',z)
sys.stdout.flush()
zz = mint()
if zz in y:
print('C',z)
else:
print('C',-1)
sys.stdout.flush()
t = mint()
for i in range(t):
solve()
| {
"input": [
"1\n3\n1 2\n2 3\n1\n1\n1\n2\n2\n1\n",
"2\n6\n1 2\n1 3\n1 4\n4 5\n4 6\n4\n1 3 4 5\n3\n3 5 2\n3\n6\n1 2\n1 3\n1 4\n4 5\n4 6\n3\n1 2 3\n3\n4 1 6\n5\n"
],
"output": [
"B 2\nA 1\nC -1\n",
"B 2\nC 3\nB 6\nA 1\nC -1\n"
]
} |
4,166 | 7 | Ivan unexpectedly saw a present from one of his previous birthdays. It is array of n numbers from 1 to 200. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally:
a_{1} β€ a_{2},
a_{n} β€ a_{n-1} and
a_{i} β€ max(a_{i-1}, a_{i+1}) for all i from 2 to n-1.
Ivan does not remember the array and asks to find the number of ways to restore it. Restored elements also should be integers from 1 to 200. Since the number of ways can be big, print it modulo 998244353.
Input
First line of input contains one integer n (2 β€ n β€ 10^{5}) β size of the array.
Second line of input contains n integers a_{i} β elements of array. Either a_{i} = -1 or 1 β€ a_{i} β€ 200. a_{i} = -1 means that i-th element can't be read.
Output
Print number of ways to restore the array modulo 998244353.
Examples
Input
3
1 -1 2
Output
1
Input
2
-1 -1
Output
200
Note
In the first example, only possible value of a_{2} is 2.
In the second example, a_{1} = a_{2} so there are 200 different values because all restored elements should be integers between 1 and 200. | import os
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
MOD = 998244353
MODF = 1.0*MOD
from math import trunc
def quickmod(a):
return a-MODF*trunc(a/MODF)
def main():
n = int(input())
a = [int(i) for i in input().split()]
f0, f1 = [1.0] * 201, [0.0] * 201
for i in range(n):
nf0, nf1 = [0.0] * 201, [0.0] * 201
if a[i] == -1:
for j in range(200):
nf0[j + 1] = quickmod(nf0[j] + f0[j] + f1[j])
nf1[j + 1] = quickmod(nf1[j] - f0[j] + f0[j + 1] - f1[j] + f1[200])
else:
for j in range(200):
nf0[j + 1], nf1[j + 1] = nf0[j], nf1[j]
if j + 1 == a[i]:
nf0[j + 1] = quickmod(nf0[j] + f0[j] + f1[j])
nf1[j + 1] = quickmod(nf1[j] - f0[j] + f0[j + 1] - f1[j] + f1[200])
f0, f1 = nf0, nf1
os.write(1, str(int(quickmod(f1[200]))%MOD).encode())
if __name__ == '__main__':
main() | {
"input": [
"2\n-1 -1\n",
"3\n1 -1 2\n"
],
"output": [
"200\n",
"1\n"
]
} |
4,167 | 11 | The only difference between easy and hard versions is a number of elements in the array.
You are given an array a consisting of n integers. The value of the i-th element of the array is a_i.
You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 β€ l_j β€ r_j β€ n.
You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0].
You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible.
Note that you can choose the empty set.
If there are multiple answers, you can print any.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains two integers n and m (1 β€ n β€ 300, 0 β€ m β€ 300) β the length of the array a and the number of segments, respectively.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 β€ a_i β€ 10^6), where a_i is the value of the i-th element of the array a.
The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 β€ l_j β€ r_j β€ n), where l_j and r_j are the ends of the j-th segment.
Output
In the first line of the output print one integer d β the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a.
In the second line of the output print one integer q (0 β€ q β€ m) β the number of segments you apply.
In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 β€ c_k β€ m) β indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible.
If there are multiple answers, you can print any.
Examples
Input
5 4
2 -2 3 1 2
1 3
4 5
2 5
1 3
Output
6
2
1 4
Input
5 4
2 -2 3 1 4
3 5
3 4
2 4
2 5
Output
7
2
3 2
Input
1 0
1000000
Output
0
0
Note
In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6.
In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7.
In the third example you cannot do anything so the answer is 0. | import sys
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n,m = inpl()
a = inpl()
mx = max(a)
a = [-(x-mx) for x in a]
s = [inpl() for _ in range(m)]
res = 0
Q = []
for i in range(n):
for j in range(n):
if i == j: continue
q = []
for k,(l,r) in enumerate(s):
if l-1 <= i <= r-1 and not l-1 <= j <= r-1:
q.append(k+1)
ans = a[i] - a[j] + len(q)
if ans > res:
res = ans
Q = q[::]
print(res)
print(len(Q))
print(*Q) | {
"input": [
"5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3\n",
"5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5\n",
"1 0\n1000000\n"
],
"output": [
"6\n2\n1 4 \n",
"7\n2\n2 3 \n",
"0\n0\n\n"
]
} |
4,168 | 7 | Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.
The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from the left sushi as t_i, where t_i = 1 means it is with tuna, and t_i = 2 means it is with eel.
Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment [2, 2, 2, 1, 1, 1] is valid, but subsegment [1, 2, 1, 2, 1, 2] is not, because both halves contain both types of sushi.
Find the length of the longest continuous subsegment of sushi Arkady can buy.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of pieces of sushi.
The second line contains n integers t_1, t_2, ..., t_n (t_i = 1, denoting a sushi with tuna or t_i = 2, denoting a sushi with eel), representing the types of sushi from left to right.
It is guaranteed that there is at least one piece of sushi of each type. Note that it means that there is at least one valid continuous segment.
Output
Print a single integer β the maximum length of a valid continuous segment.
Examples
Input
7
2 2 2 1 1 2 2
Output
4
Input
6
1 2 1 2 1 2
Output
2
Input
9
2 2 1 1 1 2 2 2 2
Output
6
Note
In the first example Arkady can choose the subsegment [2, 2, 1, 1] or the subsegment [1, 1, 2, 2] with length 4.
In the second example there is no way but to choose one of the subsegments [2, 1] or [1, 2] with length 2.
In the third example Arkady's best choice is the subsegment [1, 1, 1, 2, 2, 2]. |
from itertools import groupby
def sushi(arr1):
a= [len([*g]) for k , g in groupby(arr1.split())]
return 2*max(list(map(min,zip(a,a[1:]))))
n=int(input())
arr1=input()
print(sushi(arr1))
| {
"input": [
"6\n1 2 1 2 1 2\n",
"9\n2 2 1 1 1 2 2 2 2\n",
"7\n2 2 2 1 1 2 2\n"
],
"output": [
"2\n",
"6\n",
"4\n"
]
} |
4,169 | 9 | You are given a set of points x_1, x_2, ..., x_n on the number line.
Two points i and j can be matched with each other if the following conditions hold:
* neither i nor j is matched with any other point;
* |x_i - x_j| β₯ z.
What is the maximum number of pairs of points you can match with each other?
Input
The first line contains two integers n and z (2 β€ n β€ 2 β
10^5, 1 β€ z β€ 10^9) β the number of points and the constraint on the distance between matched points, respectively.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ 10^9).
Output
Print one integer β the maximum number of pairs of points you can match with each other.
Examples
Input
4 2
1 3 3 7
Output
2
Input
5 5
10 9 5 8 7
Output
1
Note
In the first example, you may match point 1 with point 2 (|3 - 1| β₯ 2), and point 3 with point 4 (|7 - 3| β₯ 2).
In the second example, you may match point 1 with point 3 (|5 - 10| β₯ 5). | n, z = map(int, input().split())
arrs = [int(x) for x in input().split()]
arrs.sort()
def fi(k):
l = arrs[:k]
r = arrs[-k:]
return all([r[i] - l[i] >= z for i in range(len(r))])
l = 0; r = len(arrs) // 2 + 1
while r - l > 1:
m = (l + r) // 2
if fi(m):
l = m
else:
r = m
print(l)
| {
"input": [
"4 2\n1 3 3 7\n",
"5 5\n10 9 5 8 7\n"
],
"output": [
"2\n",
"1\n"
]
} |
4,170 | 12 | This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.
There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0.
Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 β€ a_i < b_i β€ m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i β 0). Every colour other than 0 is visible on the strip.
Count the number of different pairs of sequences \\{a_i\}_{i=1}^n, \\{b_i\}_{i=1}^n that result in this configuration.
Since this number may be large, output it modulo 998244353.
Input
The first line contains a two integers n, m (1 β€ n β€ 500, n = m) β the number of colours excluding the colour 0 and the length of the paper, respectively.
The second line contains m space separated integers c_1, c_2, β¦, c_m (1 β€ c_i β€ n) β the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.
Note that since in this subtask n = m, this means that c is a permutation of integers 1 through n.
Output
Output a single integer β the number of ways Alice can perform the painting, modulo 998244353.
Examples
Input
3 3
1 2 3
Output
5
Input
7 7
4 5 1 6 2 3 7
Output
165
Note
In the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.
<image>
Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.
<image> | def main():
line = input().split()
n = int(line[0])
line = input().split()
v = [int(x) for x in line]
mod = 998244353
dp = [[1] * (n + 5) for i in range(n + 5)]
for sz in range(2, n + 1):
for lo in range(1, n - sz + 2):
hi = lo + sz - 1
pos, num = -1, n + 5
for k in range(lo, hi + 1):
if v[k - 1] < num:
num = v[k - 1]
pos = k
s1, s2 = 0, 0
for k in range(lo, pos + 1):
cnt = dp[lo][k - 1] * dp[k][pos - 1] % mod
s1 = (s1 + cnt) % mod
for k in range(pos, hi + 1):
cnt = dp[pos + 1][k] * dp[k + 1][hi] % mod
s2 = (s2 + cnt) % mod
dp[lo][hi] = s1 * s2 % mod
print(dp[1][n])
main() | {
"input": [
"3 3\n1 2 3\n",
"7 7\n4 5 1 6 2 3 7\n"
],
"output": [
"5\n",
"165\n"
]
} |
4,171 | 11 | You are given two integers b and w. You have a chessboard of size 10^9 Γ 10^9 with the top left cell at (1; 1), the cell (1; 1) is painted white.
Your task is to find a connected component on this chessboard that contains exactly b black cells and exactly w white cells. Two cells are called connected if they share a side (i.e. for the cell (x, y) there are at most four connected cells: (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)). A set of cells is called a connected component if for every pair of cells C_1 and C_2 from this set, there exists a sequence of cells c_1, c_2, ..., c_k such that c_1 = C_1, c_k = C_2, all c_i from 1 to k are belong to this set of cells and for every i β [1, k - 1], cells c_i and c_{i + 1} are connected.
Obviously, it can be impossible to find such component. In this case print "NO". Otherwise, print "YES" and any suitable connected component.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Then q queries follow.
The only line of the query contains two integers b and w (1 β€ b, w β€ 10^5) β the number of black cells required and the number of white cells required.
It is guaranteed that the sum of numbers of cells does not exceed 2 β
10^5 (β w + β b β€ 2 β
10^5).
Output
For each query, print the answer to it.
If it is impossible to find the required component, print "NO" on the first line.
Otherwise, print "YES" on the first line. In the next b + w lines print coordinates of cells of your component in any order. There should be exactly b black cells and w white cells in your answer. The printed component should be connected.
If there are several answers, you can print any. All coordinates in the answer should be in the range [1; 10^9].
Example
Input
3
1 1
1 4
2 5
Output
YES
2 2
1 2
YES
2 3
1 3
3 3
2 2
2 4
YES
2 3
2 4
2 5
1 3
1 5
3 3
3 5 | def one_case():
b, w = map(int, input().split())
sx, sy = 2, 2
if b < w: sx, sy = 2, 3
mi, ma = min(b, w), max(b, w)
if ma > mi * 3 + 1:
print('NO')
return
print('YES')
l1 = min(ma, mi + 1)
l2 = min(ma - l1, mi)
l3 = ma - l1 - l2
for i in range(mi):
print(sx, sy + 2 * i)
for i in range(l1):
print(sx, sy - 1 + 2 * i)
for i in range(l2):
print(sx - 1, sy + 2 * i)
for i in range(l3):
print(sx + 1, sy + 2 * i)
t = int(input())
for i in range(t):
one_case()
| {
"input": [
"3\n1 1\n1 4\n2 5\n"
],
"output": [
"YES\n2 1\n2 2\nYES\n3 1\n3 2\n3 3\n2 2\n4 2\nYES\n3 1\n3 2\n3 3\n3 4\n3 5\n2 2\n4 2\n"
]
} |
4,172 | 9 | This is an easier version of the problem. In this version, n β€ 2000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) β€ x_c β€ max(x_a, x_b), min(y_a, y_b) β€ y_c β€ max(y_a, y_b), and min(z_a, z_b) β€ z_c β€ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 β€ n β€ 2000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 β€ x_i, y_i, z_i β€ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 β€ a_i, b_i β€ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image> | def dist(p1, p2):
return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (
p1[1] - p2[1]) + (p1[2] - p2[2]) * (p1[2] - p2[2])
n = int(input())
seq = set([tuple([int(c) for c in input().split()] + [i]) for i in range(n)])
while seq:
p1 = seq.pop()
mn = float('infinity')
p2 = -1
for e in seq:
d = dist(p1, e)
if d < mn:
mn = d
p2 = e
print(p1[3] + 1, p2[3] + 1)
seq.remove(p2)
| {
"input": [
"8\n0 1 1\n1 0 1\n1 1 0\n1 1 1\n2 2 2\n3 2 2\n2 3 2\n2 2 3\n",
"6\n3 1 0\n0 3 0\n2 2 0\n1 0 0\n1 3 0\n0 1 0\n"
],
"output": [
"3 4\n5 8\n1 2\n7 6\n",
"6 2\n4 5\n3 1\n"
]
} |
4,173 | 8 | Hanh lives in a shared apartment. There are n people (including Hanh) living there, each has a private fridge.
n fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridge can be open only if all chains connected to it are unlocked. For example, if a fridge has no chains connected to it at all, then any of n people can open it.
<image> For exampe, in the picture there are n=4 people and 5 chains. The first person knows passcodes of two chains: 1-4 and 1-2. The fridge 1 can be open by its owner (the person 1), also two people 2 and 4 (acting together) can open it.
The weights of these fridges are a_1, a_2, β¦, a_n. To make a steel chain connecting fridges u and v, you have to pay a_u + a_v dollars. Note that the landlord allows you to create multiple chains connecting the same pair of fridges.
Hanh's apartment landlord asks you to create exactly m steel chains so that all fridges are private. A fridge is private if and only if, among n people living in the apartment, only the owner can open it (i.e. no other person acting alone can do it). In other words, the fridge i is not private if there exists the person j (i β j) that the person j can open the fridge i.
For example, in the picture all the fridges are private. On the other hand, if there are n=2 fridges and only one chain (which connects them) then both fridges are not private (both fridges can be open not only by its owner but also by another person).
Of course, the landlord wants to minimize the total cost of all steel chains to fulfill his request. Determine whether there exists any way to make exactly m chains, and if yes, output any solution that minimizes the total cost.
Input
Each test contains multiple test cases. The first line contains the number of test cases T (1 β€ T β€ 10). Then the descriptions of the test cases follow.
The first line of each test case contains two integers n, m (2 β€ n β€ 1000, 1 β€ m β€ n) β the number of people living in Hanh's apartment and the number of steel chains that the landlord requires, respectively.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^4) β weights of all fridges.
Output
For each test case:
* If there is no solution, print a single integer -1.
* Otherwise, print a single integer c β the minimum total cost. The i-th of the next m lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i), meaning that the i-th steel chain connects fridges u_i and v_i. An arbitrary number of chains can be between a pair of fridges.
If there are multiple answers, print any.
Example
Input
3
4 4
1 1 1 1
3 1
1 2 3
3 3
1 2 3
Output
8
1 2
4 3
3 2
4 1
-1
12
3 2
1 2
3 1 | def solve():
n, m = map(int, input().split())
a = list(map(int, input().split()))
d = []
if m != n or n == 2:
return print(-1)
print(sum(a)*2)
for i in range(n):
print(i + 1, (i + 1) % n + 1)
for _ in range(int(input())):
solve()
| {
"input": [
"3\n4 4\n1 1 1 1\n3 1\n1 2 3\n3 3\n1 2 3\n"
],
"output": [
"8\n1 2\n2 3\n3 4\n4 1\n-1\n12\n1 2\n2 3\n3 1\n"
]
} |
4,174 | 7 | Polycarp is sad β New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 β€ r, g, b β€ 10^9) β the number of red, green and blue lamps in the set, respectively.
Output
Print t lines β for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example. | def sol():
a, b, c = sorted(map(int, input().split()))
print("Yes" if a + b + 1 >= c else "No")
for i in range(int(input())):
sol()
| {
"input": [
"3\n3 3 3\n1 10 2\n2 1 1\n"
],
"output": [
"Yes\nNo\nYes\n"
]
} |
4,175 | 8 | Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one β xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute
$$$ (a_1 + a_2) β (a_1 + a_3) β β¦ β (a_1 + a_n) \\\ β (a_2 + a_3) β β¦ β (a_2 + a_n) \\\ β¦ \\\ β (a_{n-1} + a_n) \\\ $$$
Here x β y is a bitwise XOR operation (i.e. x ^ y in many modern programming languages). You can read about it in Wikipedia: <https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation>.
Input
The first line contains a single integer n (2 β€ n β€ 400 000) β the number of integers in the array.
The second line contains integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^7).
Output
Print a single integer β xor of all pairwise sums of integers in the given array.
Examples
Input
2
1 2
Output
3
Input
3
1 2 3
Output
2
Note
In the first sample case there is only one sum 1 + 2 = 3.
In the second sample case there are three sums: 1 + 2 = 3, 1 + 3 = 4, 2 + 3 = 5. In binary they are represented as 011_2 β 100_2 β 101_2 = 010_2, thus the answer is 2.
β is the bitwise xor operation. To define x β y, consider binary representations of integers x and y. We put the i-th bit of the result to be 1 when exactly one of the i-th bits of x and y is 1. Otherwise, the i-th bit of the result is put to be 0. For example, 0101_2 β 0011_2 = 0110_2. | from collections import defaultdict
from queue import deque
def arrinp():
return [*map(int, input().split(' '))]
def mulinp():
return map(int, input().split(' '))
def intinp():
return int(input())
def solution():
co=0
n=int(input())
l=list(map(int, input().split()))
for e in range(1,25):
po=2**e
re=sorted([k%po for k in l])
b=n
r=0
for a in range(n):
b-=1
while re[a]+re[b]>=po and b>=0:
b-=1
b+=1
r+=n-b-(a>=b)
r//=2
if r%2:
co+=2**e
if n%2==0:
for k in l:
co=co^k
print(co)
testcases = 1
# testcases = int(input())
for _ in range(testcases):
solution()
| {
"input": [
"2\n1 2\n",
"3\n1 2 3\n"
],
"output": [
"3\n",
"2\n"
]
} |
4,176 | 7 | Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.
In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the whole package of n grains weighs from c - d to c + d grams, inclusive (numbers c and d are known). The weight of the package is the sum of the weights of all n grains in it.
Help Nastya understand if this information can be correct. In other words, check whether each grain can have such a mass that the i-th grain weighs some integer number x_i (a - b β€ x_i β€ a + b), and in total they weigh from c - d to c + d, inclusive (c - d β€ β_{i=1}^{n}{x_i} β€ c + d).
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines contain descriptions of the test cases, each line contains 5 integers: n (1 β€ n β€ 1000) β the number of grains that Nastya counted and a, b, c, d (0 β€ b < a β€ 1000, 0 β€ d < c β€ 1000) β numbers that determine the possible weight of one grain of rice (from a - b to a + b) and the possible total weight of the package (from c - d to c + d).
Output
For each test case given in the input print "Yes", if the information about the weights is not inconsistent, and print "No" if n grains with masses from a - b to a + b cannot make a package with a total mass from c - d to c + d.
Example
Input
5
7 20 3 101 18
11 11 10 234 2
8 9 7 250 122
19 41 21 321 10
3 10 8 6 1
Output
Yes
No
Yes
No
Yes
Note
In the first test case of the example, we can assume that each grain weighs 17 grams, and a pack 119 grams, then really Nastya could collect the whole pack.
In the third test case of the example, we can assume that each grain weighs 16 grams, and a pack 128 grams, then really Nastya could collect the whole pack.
In the fifth test case of the example, we can be assumed that 3 grains of rice weigh 2, 2, and 3 grams, and a pack is 7 grams, then really Nastya could collect the whole pack.
In the second and fourth test cases of the example, we can prove that it is impossible to determine the correct weight of all grains of rice and the weight of the pack so that the weight of the pack is equal to the total weight of all collected grains. | def f(l):
n,a,b,c,d = l
return (n*(a-b))<=(c+d) and (n*(a+b))>=(c-d)
t = int(input())
for _ in range(t):
l = list(map(int,input().split()))
print('Yes' if f(l) else 'No')
| {
"input": [
"5\n7 20 3 101 18\n11 11 10 234 2\n8 9 7 250 122\n19 41 21 321 10\n3 10 8 6 1\n"
],
"output": [
"Yes\nNo\nYes\nNo\nYes\n"
]
} |
4,177 | 7 | Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.
Tell him whether he can do so.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n and x (1 β€ x β€ n β€ 1000) β the length of the array and the number of elements you need to choose.
The next line of each test case contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 1000) β elements of the array.
Output
For each test case, print "Yes" or "No" depending on whether it is possible to choose x elements such that their sum is odd.
You may print every letter in any case you want.
Example
Input
5
1 1
999
1 1
1000
2 1
51 50
2 2
51 50
3 3
101 102 103
Output
Yes
No
Yes
Yes
No
Note
For 1st case: We must select element 999, and the sum is odd.
For 2nd case: We must select element 1000, so overall sum is not odd.
For 3rd case: We can select element 51.
For 4th case: We must select both elements 50 and 51 β so overall sum is odd.
For 5th case: We must select all elements β but overall sum is not odd. | def main():
for _ in range(int(input())):
n, x = map(int, input().split())
s = sum(ord(s[-1]) & 1 for s in input().split())
print(('Yes', 'No')[s == n and not (x & 1) or not s or not (s & 1) and x == n])
if __name__ == '__main__':
main()
| {
"input": [
"5\n1 1\n999\n1 1\n1000\n2 1\n51 50\n2 2\n51 50\n3 3\n101 102 103\n"
],
"output": [
"YES\nNO\nYES\nYES\nNO\n"
]
} |
4,178 | 9 | Let a_1, β¦, a_n be an array of n positive integers. In one operation, you can choose an index i such that a_i = i, and remove a_i from the array (after the removal, the remaining parts are concatenated).
The weight of a is defined as the maximum number of elements you can remove.
You must answer q independent queries (x, y): after replacing the x first elements of a and the y last elements of a by n+1 (making them impossible to remove), what would be the weight of a?
Input
The first line contains two integers n and q (1 β€ n, q β€ 3 β
10^5) β the length of the array and the number of queries.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ n) β elements of the array.
The i-th of the next q lines contains two integers x and y (x, y β₯ 0 and x+y < n).
Output
Print q lines, i-th line should contain a single integer β the answer to the i-th query.
Examples
Input
13 5
2 2 3 9 5 4 6 5 7 8 3 11 13
3 1
0 0
2 4
5 0
0 12
Output
5
11
6
1
0
Input
5 2
1 4 1 2 4
0 0
1 0
Output
2
0
Note
Explanation of the first query:
After making first x = 3 and last y = 1 elements impossible to remove, a becomes [Γ, Γ, Γ, 9, 5, 4, 6, 5, 7, 8, 3, 11, Γ] (we represent 14 as Γ for clarity).
Here is a strategy that removes 5 elements (the element removed is colored in red):
* [Γ, Γ, Γ, 9, \color{red}{5}, 4, 6, 5, 7, 8, 3, 11, Γ]
* [Γ, Γ, Γ, 9, 4, 6, 5, 7, 8, 3, \color{red}{11}, Γ]
* [Γ, Γ, Γ, 9, 4, \color{red}{6}, 5, 7, 8, 3, Γ]
* [Γ, Γ, Γ, 9, 4, 5, 7, \color{red}{8}, 3, Γ]
* [Γ, Γ, Γ, 9, 4, 5, \color{red}{7}, 3, Γ]
* [Γ, Γ, Γ, 9, 4, 5, 3, Γ] (final state)
It is impossible to remove more than 5 elements, hence the weight is 5. | n,q = map(int,input().split())
a = list(map(int,input().split()))
a = [i-a[i]+1 for i in range(n)]
Q = [[] for _ in range(n)]
ans = [-1]*q
for _ in range(q):
L,R = map(int,input().split())
R = n-1-R
Q[R].append((L,_))
bit = [0]*(n+1)
def update(idx,val):
idx = n-1-idx
idx += 1
while idx < n+1:
bit[idx] += val
idx += idx&-idx
def getSum(idx):
idx = n-1-idx
idx += 1
ans = 0
while idx:
ans += bit[idx]
idx -= idx&-idx
return ans
for R in range(n):
if a[R] < 0 or getSum(0) < a[R]:
for L,i in Q[R]:
ans[i] = getSum(L)
continue
lo,hi = 0,R
while lo+1 < hi:
mid = (lo+hi)//2
if getSum(mid) < a[R]:
hi = mid
else:
lo = mid
if getSum(hi) >= a[R]:
update(hi,1)
else:
update(lo,1)
for L,i in Q[R]:
ans[i] = getSum(L)
print(*ans)
| {
"input": [
"5 2\n1 4 1 2 4\n0 0\n1 0\n",
"13 5\n2 2 3 9 5 4 6 5 7 8 3 11 13\n3 1\n0 0\n2 4\n5 0\n0 12\n"
],
"output": [
"2\n0\n",
"5\n11\n6\n1\n0\n"
]
} |
4,179 | 12 | This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.
You are given an array [a_1, a_2, ..., a_n].
Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs f times in this subarray, then at least 2 different values should occur exactly f times.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
The first line contains a single integer n (1 β€ n β€ 200 000) β the length of the array.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ min(n, 100)) β elements of the array.
Output
You should output exactly one integer β the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output 0.
Examples
Input
7
1 1 2 2 3 3 3
Output
6
Input
10
1 1 1 5 4 1 3 1 2 2
Output
7
Input
1
1
Output
0
Note
In the first sample, the subarray [1, 1, 2, 2, 3, 3] is good, but [1, 1, 2, 2, 3, 3, 3] isn't: in the latter there are 3 occurrences of number 3, and no other element appears 3 times. | import sys
input = sys.stdin.buffer.readline
def prog():
n = int(input())
a = list(map(int,input().split()))
freq = [0]*101
for i in range(n):
freq[a[i]] += 1
mx = max(freq)
amt = freq.count(mx)
if amt >= 2:
print(n)
else:
must_appear = freq.index(mx)
ans = 0
for j in range(1,101):
if j == must_appear:
continue
first_idx = [10**6]*(n+1)
first_idx[0] = -1
curr = 0
for i in range(n):
if a[i] == must_appear:
curr += 1
elif a[i] == j:
curr -= 1
ans = max(ans, i - first_idx[curr])
first_idx[curr] = min(first_idx[curr],i)
print(ans)
prog()
| {
"input": [
"7\n1 1 2 2 3 3 3\n",
"1\n1\n",
"10\n1 1 1 5 4 1 3 1 2 2\n"
],
"output": [
"6\n",
"0\n",
"7\n"
]
} |
4,180 | 12 | Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 Γ n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 Γ 1 and 1 Γ 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 β€ n β€ 10^9, 1 β€ m β€ 2 β
10^5) β the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 β€ r_i β€ 2, 1 β€ c_i β€ n) β numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) β (r_j, c_j), i β j.
It is guaranteed that the sum of m over all test cases does not exceed 2 β
10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 Γ 1 and 1 Γ 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled. | def gint():
return list(map(int, input().split()))
for _ in range(int(input())):
input()
n, m = gint()
inp = []
for i in range(m):
inp.append(gint())
inp.sort(key=lambda e: e[0] + 2*e[1])
def check(pos):
if pos % 2 == 0:
return sum(inp[pos])%2 != sum(inp[pos+1])%2
else:
return inp[pos][1] != inp[pos+1][1]
if m % 2 != 0 or False in list(map(check, range(m-1))):
print("NO")
else:
print("YES")
| {
"input": [
"3\n\n5 2\n2 2\n1 4\n\n3 2\n2 1\n2 3\n\n6 4\n2 1\n2 3\n2 4\n2 6\n"
],
"output": [
"\nYES\nNO\nNO\n"
]
} |
4,181 | 7 | You have a board represented as a grid with 2 Γ n cells.
The first k_1 cells on the first row and first k_2 cells on the second row are colored in white. All other cells are colored in black.
You have w white dominoes (2 Γ 1 tiles, both cells are colored in white) and b black dominoes (2 Γ 1 tiles, both cells are colored in black).
You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.
Can you place all w + b dominoes on the board if you can place dominoes both horizontally and vertically?
Input
The first line contains a single integer t (1 β€ t β€ 3000) β the number of test cases.
The first line of each test case contains three integers n, k_1 and k_2 (1 β€ n β€ 1000; 0 β€ k_1, k_2 β€ n).
The second line of each test case contains two integers w and b (0 β€ w, b β€ n).
Output
For each test case, print YES if it's possible to place all w + b dominoes on the board and NO, otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
1 0 1
1 0
1 1 1
0 0
3 0 0
1 3
4 3 1
2 2
5 4 3
3 1
Output
NO
YES
NO
YES
YES
Note
In the first test case, n = 1, k_1 = 0 and k_2 = 1. It means that 2 Γ 1 board has black cell (1, 1) and white cell (2, 1). So, you can't place any white domino, since there is only one white cell.
In the second test case, the board of the same size 2 Γ 1, but both cell are white. Since w = 0 and b = 0, so you can place 0 + 0 = 0 dominoes on the board.
In the third test case, board 2 Γ 3, but fully colored in black (since k_1 = k_2 = 0), so you can't place any white domino.
In the fourth test case, cells (1, 1), (1, 2), (1, 3), and (2, 1) are white and other cells are black. You can place 2 white dominoes at positions ((1, 1), (2, 1)) and ((1, 2), (1, 3)) and 2 black dominoes at positions ((1, 4), (2, 4)) ((2, 2), (2, 3)). | import sys
input = sys.stdin.readline
def solve():
if w + b > n:
return "NO"
if k1 + k2 < w*2:
return "NO"
if 2*n-(k1+k2) < b*2:
return "NO"
return "YES"
t = int(input())
for i in range(t):
n, k1, k2= map(int, input().split())
w, b = map(int, input().split())
print(solve())
| {
"input": [
"5\n1 0 1\n1 0\n1 1 1\n0 0\n3 0 0\n1 3\n4 3 1\n2 2\n5 4 3\n3 1\n"
],
"output": [
"\nNO\nYES\nNO\nYES\nYES\n"
]
} |
4,182 | 12 | This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 β€ t β€ min(n, 10^4) and the total number of queries is limited to 6 β
10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 β
10^4 requests totally of the following type:
* ? l r β find out the sum of all elements in positions from l to r (1 β€ l β€ r β€ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 β€ n β€ 2 β
10^5, 1 β€ t β€ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 β€ k β€ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 β
10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 β
10^4):
* ! x β position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 β€ |s| β€ 2 β
10^5), consisting of zeros and ones, and an integer t (1 β€ t β€ min(|s|, 10^4)) β hidden array and number of requests, respectively. In the next t lines output the number k (1 β€ k β€ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1]. | import sys
def ask_query(l, r):
print ("?", l+1, r+1)
sys.stdout.flush()
return int(input())
def check(low, mid):
return mid - low + 1 - ask_query(low, mid)
d = {}
n, t = map(int,input().split())
for nt in range(t):
k = int(input())
low = 0
high = n-1
while low<high:
mid = (low+high)//2
if (low, mid) not in d:
count = check(low, mid)
d[(low, mid)] = count
count = d[(low, mid)]
if count>=k:
high = mid
else:
k -= count
low = mid + 1
if (low, high) in d:
d[(low, high)] -= 1
print ("!", high+1)
| {
"input": [
"6 2\n\n2\n\n2\n\n1\n\n1\n\n0\n\n1\n\n0"
],
"output": [
"\n? 4 6\n\n? 1 1\n\n? 1 2\n\n? 5 5\n\n! 5\n\n? 2 2\n\n! 2\n\n"
]
} |
4,183 | 8 | Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab | def WordCut():
start = input()
end = input()
k = int(input())
n=len(start)
dpA,dpB = (start==end),(start!=end)
end+=end
A=sum(start==end[i:i+n] for i in range(n))
B = n- A
M = 10**9+7
for _ in range(k):
dpA,dpB=(dpA*(A-1)+dpB*A)%M,(dpA*B+dpB*(B-1))%M
return int(dpA)
print(WordCut()) | {
"input": [
"ab\nba\n2\n",
"ab\nab\n2\n",
"ababab\nababab\n1\n"
],
"output": [
"0\n",
"1\n",
"2\n"
]
} |
4,184 | 10 | You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself).
Input
The first line of the input contains two integers n and m (1 β€ n β€ 15, 0 β€ m β€ 2000), n is the amount of vertices, and m is the amount of edges. Following m lines contain edges as a triples x, y, w (1 β€ x, y β€ n, 1 β€ w β€ 10000), x, y are edge endpoints, and w is the edge length.
Output
Output minimal cycle length or -1 if it doesn't exists.
Examples
Input
3 3
1 2 1
2 3 1
3 1 1
Output
3
Input
3 2
1 2 3
2 3 4
Output
14 | import math
N = 15
mat = 0
inf = 1000000000
answer = inf
def Get_Cycle_Length(v,graph):
global mat
global answer
if len(v) == 0: #por lo de conf 3
answer = min(answer,mat)
return
end = v.pop()
i = 0
while i<len(v):
se = v.pop(i)
mat += graph[se][end]
Get_Cycle_Length(v,graph)
mat -= graph[se][end]
v.insert(i,se)
i+=1
v.append(end)
def main():
n,m = map(int,input().split())
graph = [[inf] * n for i in range(n)]
deg = [0] * n
sum = 0
for i in range(n):
graph[i][i] = 0
for i in range(m):
x,y,w = map(int,input().split())
x -= 1
y -= 1
deg[x]+=1
deg[y]+=1
graph[x][y] = min(graph[x][y],w)
graph[y][x] = min(graph[y][x],w)
sum += w
for i in range(n):
for j in range(n): # aqui veo si hay algun camino de menos peso
for k in range(n):
graph[j][k] = min(graph[j][k],graph[j][i] + graph[i][k])
for i in range(n):
if graph[0][i] == inf and deg[i] > 0:
print('-1')
return
v = []
for i in range(n):
if deg[i] % 2 != 0:
v.append(i)
Get_Cycle_Length(v,graph)
print(sum + answer)
main()
| {
"input": [
"3 3\n1 2 1\n2 3 1\n3 1 1\n",
"3 2\n1 2 3\n2 3 4\n"
],
"output": [
"3\n",
"14\n"
]
} |
4,185 | 7 | One day Ms Swan bought an orange in a shop. The orange consisted of nΒ·k segments, numbered with integers from 1 to nΒ·k.
There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 β€ i β€ k) child wrote the number ai (1 β€ ai β€ nΒ·k). All numbers ai accidentally turned out to be different.
Now the children wonder, how to divide the orange so as to meet these conditions:
* each child gets exactly n orange segments;
* the i-th child gets the segment with number ai for sure;
* no segment goes to two children simultaneously.
Help the children, divide the orange and fulfill the requirements, described above.
Input
The first line contains two integers n, k (1 β€ n, k β€ 30). The second line contains k space-separated integers a1, a2, ..., ak (1 β€ ai β€ nΒ·k), where ai is the number of the orange segment that the i-th child would like to get.
It is guaranteed that all numbers ai are distinct.
Output
Print exactly nΒ·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces.
You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.
Examples
Input
2 2
4 1
Output
2 4
1 3
Input
3 1
2
Output
3 2 1 | def main():
n,k= [int(i) for i in input().split()]
s= list(range(1,n*k+1))
arr=[int(i) for i in input().split()]
plist=[]
for i in arr:
s.remove(i)
for i in arr:
plist.append([i]+s[:n-1])
s[:]=s[n-1:]
for i in plist:
print(*i)
return 0
if __name__ == '__main__':
main()
| {
"input": [
"2 2\n4 1\n",
"3 1\n2\n"
],
"output": [
"4 2 \n1 3 \n",
"2 1 3 \n"
]
} |
4,186 | 7 | Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci β the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 β€ n β€ 103) β the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 β€ ti, ci β€ 106) β the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 β€ i < n).
Output
In a single line print two space-separated integers β the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3. | import re
import itertools
from collections import Counter, deque
class Task:
tasks = []
answer = ""
def getData(self):
numberOfTasks = int(input())
for i in range(0, numberOfTasks):
self.tasks += [[int(x) for x in input().split(' ')]]
#inFile = open('input.txt', 'r')
#inFile.readline().rstrip()
#self.childs = inFile.readline().rstrip()
def solve(self):
queueSize, maxQueueSize = 0, 0
time, timeOfLastMessage = 1, 1
currentTask = 0
while currentTask < len(self.tasks) or queueSize > 0:
maxQueueSize = max(maxQueueSize, queueSize)
if currentTask < len(self.tasks):
timeDelta = self.tasks[currentTask][0] - time
queueSize -= min(queueSize, timeDelta)
time += timeDelta
else:
timeOfLastMessage = time + queueSize
break
if currentTask < len(self.tasks) and \
self.tasks[currentTask][0] == time:
queueSize += self.tasks[currentTask][1]
currentTask += 1
self.answer = str(timeOfLastMessage) + " " + str(maxQueueSize)
def printAnswer(self):
print(self.answer)
#outFile = open('output.txt', 'w')
#outFile.write(self.answer)
task = Task()
task.getData()
task.solve()
task.printAnswer()
| {
"input": [
"1\n1000000 10\n",
"2\n1 1\n2 1\n",
"3\n3 3\n4 3\n5 3\n"
],
"output": [
"1000010 10",
"3 1",
"12 7"
]
} |
4,187 | 7 | You know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban β an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about them. Let's have a look at the Soroban's construction.
<image>
Soroban consists of some number of rods, each rod contains five beads. We will assume that the rods are horizontal lines. One bead on each rod (the leftmost one) is divided from the others by a bar (the reckoning bar). This single bead is called go-dama and four others are ichi-damas. Each rod is responsible for representing a single digit from 0 to 9. We can obtain the value of a digit by following simple algorithm:
* Set the value of a digit equal to 0.
* If the go-dama is shifted to the right, add 5.
* Add the number of ichi-damas shifted to the left.
Thus, the upper rod on the picture shows digit 0, the middle one shows digit 2 and the lower one shows 7. We will consider the top rod to represent the last decimal digit of a number, so the picture shows number 720.
Write the program that prints the way Soroban shows the given number n.
Input
The first line contains a single integer n (0 β€ n < 109).
Output
Print the description of the decimal digits of number n from the last one to the first one (as mentioned on the picture in the statement), one per line. Print the beads as large English letters 'O', rod pieces as character '-' and the reckoning bar as '|'. Print as many rods, as many digits are in the decimal representation of number n without leading zeroes. We can assume that number 0 has no leading zeroes.
Examples
Input
2
Output
O-|OO-OO
Input
13
Output
O-|OOO-O
O-|O-OOO
Input
720
Output
O-|-OOOO
O-|OO-OO
-O|OO-OO | def print_digit(n):
if n < 5:
print('O-|'+'O'*n+'-'+'O'*(4-n))
else:
n -= 5
print('-O|'+'O'*n+'-'+'O'*(4-n))
for i in input()[::-1]:
print_digit(int(i))
| {
"input": [
"2\n",
"720\n",
"13\n"
],
"output": [
"O-|OO-OO\n",
"O-|-OOOO\nO-|OO-OO\n-O|OO-OO\n",
"O-|OOO-O\nO-|O-OOO\n"
]
} |
4,188 | 10 | You are playing the following game. There are n points on a plane. They are the vertices of a regular n-polygon. Points are labeled with integer numbers from 1 to n. Each pair of distinct points is connected by a diagonal, which is colored in one of 26 colors. Points are denoted by lowercase English letters. There are three stones positioned on three distinct vertices. All stones are the same. With one move you can move the stone to another free vertex along some diagonal. The color of this diagonal must be the same as the color of the diagonal, connecting another two stones.
Your goal is to move stones in such way that the only vertices occupied by stones are 1, 2 and 3. You must achieve such position using minimal number of moves. Write a program which plays this game in an optimal way.
Input
In the first line there is one integer n (3 β€ n β€ 70) β the number of points. In the second line there are three space-separated integer from 1 to n β numbers of vertices, where stones are initially located.
Each of the following n lines contains n symbols β the matrix denoting the colors of the diagonals. Colors are denoted by lowercase English letters. The symbol j of line i denotes the color of diagonal between points i and j. Matrix is symmetric, so j-th symbol of i-th line is equal to i-th symbol of j-th line. Main diagonal is filled with '*' symbols because there is no diagonal, connecting point to itself.
Output
If there is no way to put stones on vertices 1, 2 and 3, print -1 on a single line. Otherwise, on the first line print minimal required number of moves and in the next lines print the description of each move, one move per line. To describe a move print two integers. The point from which to remove the stone, and the point to which move the stone. If there are several optimal solutions, print any of them.
Examples
Input
4
2 3 4
*aba
a*ab
ba*b
abb*
Output
1
4 1
Input
4
2 3 4
*abc
a*ab
ba*b
cbb*
Output
-1
Note
In the first example we can move stone from point 4 to point 1 because this points are connected by the diagonal of color 'a' and the diagonal connection point 2 and 3, where the other stones are located, are connected by the diagonal of the same color. After that stones will be on the points 1, 2 and 3. | from collections import deque
__author__ = 'asmn'
n = int(input())
end = tuple(sorted(map(lambda x: int(x) - 1, input().split())))
st = (0, 1, 2)
mat = [input() for i in range(n)]
v = set([st])
path = {}
dist = {st: 0}
queue = deque([st])
while end not in v and len(queue) > 0:
p = queue.popleft()
for x in range(-2, 1):
p1, p2, p3 = p[x], p[x + 1], p[x + 2]
for i in range(n):
if i not in (p1, p2, p3) and mat[i][p3] == mat[p1][p2]:
np = tuple(sorted((p1, p2, i)))
if np not in v:
v.add(np)
queue.append(np)
path[np] = p
dist[np] = dist[p] + 1
def pathinfo(fr, to):
return str((set(fr) - set(to)).pop() + 1) + ' ' + str((set(to) - set(fr)).pop() + 1)
if end not in dist:
print(-1)
exit()
print(dist[end])
while end in path:
print(pathinfo(end, path[end]))
end = path[end]
| {
"input": [
"4\n2 3 4\n*abc\na*ab\nba*b\ncbb*\n",
"4\n2 3 4\n*aba\na*ab\nba*b\nabb*\n"
],
"output": [
"-1\n",
"1\n4 1\n"
]
} |
4,189 | 7 | Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number <image>, in particular that q2 = q + 1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression a0a1...an equals to <image>.
Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.
Given two numbers written in golden system notation, determine which of them has larger decimal value.
Input
Input consists of two lines β one for each number. Each line contains non-empty string consisting of '0' and '1' characters. The length of each string does not exceed 100000.
Output
Print ">" if the first number is larger, "<" if it is smaller and "=" if they are equal.
Examples
Input
1000
111
Output
<
Input
00100
11
Output
=
Input
110
101
Output
>
Note
In the first example first number equals to <image>, while second number is approximately 1.6180339882 + 1.618033988 + 1 β 5.236, which is clearly a bigger number.
In the second example numbers are equal. Each of them is β 2.618. | def clean(d):
ans = ['0']
for c in list(d):
ans.append(c)
i = len(ans) - 1 #find last index
while i > 1 and ans[i-2]== '0' and ans[i - 1] == '1' and ans[i] == '1':
ans[i - 2] = '1'
ans[i - 1] = '0'
ans[i] = '0'
i -= 2
return ''.join(ans).lstrip('0')
a = clean(input())
b = clean(input())
#print(a)
#print(b)
if a == b:
print('=')
elif len(a) > len(b):
print('>')
elif len(a) < len(b):
print('<')
elif a > b: # now the length are equal
print('>')
else:
print('<')
| {
"input": [
"110\n101\n",
"00100\n11\n",
"1000\n111\n"
],
"output": [
">",
"=",
"<"
]
} |
4,190 | 10 | Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler!
However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measurements. We assume that the marks are numbered from 1 to n in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance l from the origin. This ruler can be repesented by an increasing sequence a1, a2, ..., an, where ai denotes the distance of the i-th mark from the origin (a1 = 0, an = l).
Valery believes that with a ruler he can measure the distance of d centimeters, if there is a pair of integers i and j (1 β€ i β€ j β€ n), such that the distance between the i-th and the j-th mark is exactly equal to d (in other words, aj - ai = d).
Under the rules, the girls should be able to jump at least x centimeters, and the boys should be able to jump at least y (x < y) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances x and y.
Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances x and y. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler.
Input
The first line contains four positive space-separated integers n, l, x, y (2 β€ n β€ 105, 2 β€ l β€ 109, 1 β€ x < y β€ l) β the number of marks, the length of the ruler and the jump norms for girls and boys, correspondingly.
The second line contains a sequence of n integers a1, a2, ..., an (0 = a1 < a2 < ... < an = l), where ai shows the distance from the i-th mark to the origin.
Output
In the first line print a single non-negative integer v β the minimum number of marks that you need to add on the ruler.
In the second line print v space-separated integers p1, p2, ..., pv (0 β€ pi β€ l). Number pi means that the i-th mark should be at the distance of pi centimeters from the origin. Print the marks in any order. If there are multiple solutions, print any of them.
Examples
Input
3 250 185 230
0 185 250
Output
1
230
Input
4 250 185 230
0 20 185 250
Output
0
Input
2 300 185 230
0 300
Output
2
185 230
Note
In the first sample it is impossible to initially measure the distance of 230 centimeters. For that it is enough to add a 20 centimeter mark or a 230 centimeter mark.
In the second sample you already can use the ruler to measure the distances of 185 and 230 centimeters, so you don't have to add new marks.
In the third sample the ruler only contains the initial and the final marks. We will need to add two marks to be able to test the children's skills. | n, l, x, y = map(int, input().split())
s = set(map(int, input().split()))
def f(d): return any(i + d in s for i in s)
def g():
for i in s:
if i + x + y in s: return i + x
return 0
def h():
for i in s:
if i + y - x in s:
if i - x >= 0: return i - x
if i + y <= l: return i + y
return 0
def e(d):
print(1)
print(d)
if f(x):
if f(y):
print(0)
else:
e(y)
elif f(y):
e(x)
else:
z = g()
if z:
e(z)
else:
z = h()
if z:
e(z)
else:
print(2)
print(x, y) | {
"input": [
"2 300 185 230\n0 300\n",
"3 250 185 230\n0 185 250\n",
"4 250 185 230\n0 20 185 250\n"
],
"output": [
"2\n185 230\n",
"1\n230\n",
"0\n"
]
} |
4,191 | 10 | Let's define the sum of two permutations p and q of numbers 0, 1, ..., (n - 1) as permutation <image>, where Perm(x) is the x-th lexicographically permutation of numbers 0, 1, ..., (n - 1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.
For example, Perm(0) = (0, 1, ..., n - 2, n - 1), Perm(n! - 1) = (n - 1, n - 2, ..., 1, 0)
Misha has two permutations, p and q. Your task is to find their sum.
Permutation a = (a0, a1, ..., an - 1) is called to be lexicographically smaller than permutation b = (b0, b1, ..., bn - 1), if for some k following conditions hold: a0 = b0, a1 = b1, ..., ak - 1 = bk - 1, ak < bk.
Input
The first line contains an integer n (1 β€ n β€ 200 000).
The second line contains n distinct integers from 0 to n - 1, separated by a space, forming permutation p.
The third line contains n distinct integers from 0 to n - 1, separated by spaces, forming permutation q.
Output
Print n distinct integers from 0 to n - 1, forming the sum of the given permutations. Separate the numbers by spaces.
Examples
Input
2
0 1
0 1
Output
0 1
Input
2
0 1
1 0
Output
1 0
Input
3
1 2 0
2 1 0
Output
1 0 2
Note
Permutations of numbers from 0 to 1 in the lexicographical order: (0, 1), (1, 0).
In the first sample Ord(p) = 0 and Ord(q) = 0, so the answer is <image>.
In the second sample Ord(p) = 0 and Ord(q) = 1, so the answer is <image>.
Permutations of numbers from 0 to 2 in the lexicographical order: (0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0).
In the third sample Ord(p) = 3 and Ord(q) = 5, so the answer is <image>. | def sum(BIT, i):
s = 0
while i > 0:
s += BIT[i]
i -= i & (-i)
return s
def update(BIT, i, v):
while i < len(BIT):
BIT[i] += v
i += i & (-i)
def find(fen, k):
curr = 0
ans = 0
prevsum = 0
for i in range(19, -1, -1):
if ((curr + (1 << i) < n) and fen[curr + (1 << i)] + prevsum < k):
ans = curr + (1 << i)
curr = ans
prevsum += fen[curr]
return ans + 1
def Rank(x,BIT) :
return sum(BIT,x)
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
factp = []
factq = []
BIT = [0] * (n + 1)
for j in range(n):
update(BIT,j+1,1)
for val in p:
factp.append(Rank(val+1,BIT)-1)
update(BIT,val+1,-1)
BIT = [0] * (n + 1)
for j in range(n):
update(BIT,j+1,1)
for val in q:
factq.append(Rank(val+1,BIT)-1)
update(BIT,val+1,-1)
carry = 0
for i in range(n - 1, -1, -1):
radix = n - i
factp[i] = factp[i] + factq[i] + carry
if factp[i] < radix:
carry = 0
else:
carry = 1
factp[i] -= radix
BIT = [0] * (n + 1)
for j in range(n):
update(BIT,j+1,1)
res=[]
for i in range(n):
k = factp[i]+1
res.append(find(BIT,k)-1)
update(BIT,res[-1]+1,-1)
print(*res) | {
"input": [
"3\n1 2 0\n2 1 0\n",
"2\n0 1\n0 1\n",
"2\n0 1\n1 0\n"
],
"output": [
"1 0 2 ",
"0 1 ",
"1 0 "
]
} |
4,192 | 8 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 β€ n β€ 200 000) β the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x β the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 β€ i, j β€ n, i β j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3. | def gao():
n = int(input())
a = input()
b = input()
mp = {}
cnt = 0
for i in range(n):
if a[i] != b[i]:
cnt += 1
mp[(a[i], b[i])] = i + 1
l = [chr(ord('a') + i) for i in range(26)]
for i in l:
for j in l:
if (i, j) in mp and (j, i) in mp:
print(cnt - 2)
print(mp[(i, j)], mp[(j, i)])
return
for i in l:
for j in l:
for k in l:
if (i, j) in mp and (j, k) in mp:
print(cnt - 1)
print(mp[(i, j)], mp[(j, k)])
return
print(cnt)
print(-1, -1)
gao()
| {
"input": [
"6\ndouble\nbundle\n",
"4\npetr\negor\n",
"6\nwookie\ncookie\n",
"9\npergament\npermanent\n"
],
"output": [
"2\n1 4\n",
"2\n1 2\n",
"1\n-1 -1\n",
"1\n4 6\n"
]
} |
4,193 | 11 | Vanya is doing his maths homework. He has an expression of form <image>, where x1, x2, ..., xn are digits from 1 to 9, and sign <image> represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.
Input
The first line contains expression s (1 β€ |s| β€ 5001, |s| is odd), its odd positions only contain digits from 1 to 9, and even positions only contain signs + and * .
The number of signs * doesn't exceed 15.
Output
In the first line print the maximum possible value of an expression.
Examples
Input
3+5*7+8*4
Output
303
Input
2+3*5
Output
25
Input
3*4*5
Output
60
Note
Note to the first sample test. 3 + 5 * (7 + 8) * 4 = 303.
Note to the second sample test. (2 + 3) * 5 = 25.
Note to the third sample test. (3 * 4) * 5 = 60 (also many other variants are valid, for instance, (3) * 4 * 5 = 60). | def main():
s = input()
n = len(s)
ans = -(10**18)
for i in range(1, n + 1, 2):
for j in range(0, i, 2):
if (j == 0 or s[j - 1] == '*') and (i == n or s[i] == '*'):
ans = max(ans, eval(s[:j] + '(' + s[j : i] + ')' + s[i:]))
print(ans)
if __name__ == '__main__':
main() | {
"input": [
"3+5*7+8*4\n",
"2+3*5\n",
"3*4*5\n"
],
"output": [
"303\n",
"25\n",
"60\n"
]
} |
4,194 | 11 | You are given a sequence of n integers a1, a2, ..., an.
Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible.
The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.
The poorness of a segment is defined as the absolute value of sum of the elements of segment.
Input
The first line contains one integer n (1 β€ n β€ 200 000), the length of a sequence.
The second line contains n integers a1, a2, ..., an (|ai| β€ 10 000).
Output
Output a real number denoting the minimum possible weakness of a1 - x, a2 - x, ..., an - x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.
Examples
Input
3
1 2 3
Output
1.000000000000000
Input
4
1 2 3 4
Output
2.000000000000000
Input
10
1 10 2 9 3 8 4 7 5 6
Output
4.500000000000000
Note
For the first case, the optimal value of x is 2 so the sequence becomes - 1, 0, 1 and the max poorness occurs at the segment "-1" or segment "1". The poorness value (answer) equals to 1 in this case.
For the second sample the optimal value of x is 2.5 so the sequence becomes - 1.5, - 0.5, 0.5, 1.5 and the max poorness occurs on segment "-1.5 -0.5" or "0.5 1.5". The poorness value (answer) equals to 2 in this case. | def main():
input()
a = list(map(int, input().split()))
def f(a):
maxend = maxnow = 0
for x in a:
maxend = max(0, maxend + x)
maxnow = max(maxnow, maxend)
return maxnow
f1 = lambda x: f(i - x for i in a)
f2 = lambda x: f(x - i for i in a)
Max = max(abs(i) for i in a)
L, R = -Max, Max
eps = 10 ** -8
for i in range(100):
m = (L + R) / 2
v1, v2 = f1(m), f2(m)
if abs(v1 - v2) < eps:
break
if v1 > v2:
L = m
else:
R = m
print(v1)
main() | {
"input": [
"3\n1 2 3\n",
"4\n1 2 3 4\n",
"10\n1 10 2 9 3 8 4 7 5 6\n"
],
"output": [
"1.0000000037252903\n",
"2.0\n",
"4.499999997206032\n"
]
} |
4,195 | 10 | You are given two circles. Find the area of their intersection.
Input
The first line contains three integers x1, y1, r1 ( - 109 β€ x1, y1 β€ 109, 1 β€ r1 β€ 109) β the position of the center and the radius of the first circle.
The second line contains three integers x2, y2, r2 ( - 109 β€ x2, y2 β€ 109, 1 β€ r2 β€ 109) β the position of the center and the radius of the second circle.
Output
Print the area of the intersection of the circles. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
0 0 4
6 0 4
Output
7.25298806364175601379
Input
0 0 5
11 0 5
Output
0.00000000000000000000 | import math
import decimal
def dec(n):
return decimal.Decimal(n)
def acos(x):
return dec(math.atan2((1-x**2).sqrt(),x))
def x_minus_sin_cos(x):
if x<0.01:
return 2*x**3/3-2*x**5/15+4*x**7/315
return x-dec(math.sin(x)*math.cos(x))
x_1,y_1,r_1=map(int,input().split())
x_2,y_2,r_2=map(int,input().split())
pi=dec(31415926535897932384626433832795)/10**31
d_square=(x_1-x_2)**2+(y_1-y_2)**2
d=dec(d_square).sqrt()
r_min=min(r_1,r_2)
r_max=max(r_1,r_2)
if d+r_min<=r_max:
print(pi*r_min**2)
elif d>=r_1+r_2:
print(0)
else:
cos_1=(r_1**2+d_square-r_2**2)/(2*r_1*d)
acos_1=acos(cos_1)
s_1=(r_1**2)*x_minus_sin_cos(acos_1)
cos_2=(r_2**2+d_square-r_1**2)/(2*r_2*d)
acos_2=acos(cos_2)
s_2=(r_2**2)*x_minus_sin_cos(acos_2)
print(s_1+s_2) | {
"input": [
"0 0 4\n6 0 4\n",
"0 0 5\n11 0 5\n"
],
"output": [
"7.25298806364175601379",
"0\n"
]
} |
4,196 | 7 | One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. | from queue import Queue
from sys import stdin
def YES():
print("Yes"), print("".join(ans)), exit(0)
def NO():
print("No"), exit(0)
n, m = [int(t) for t in input().split()]
tru = [[False for f in range(n)] for t in range(n)]
for _ in range(m):
l, r = [int(t) for t in stdin.readline().split()]
tru[l-1][r-1] = True
tru[r-1][l-1] = True
ans = ['-' for t in range(n)]
for i in range(n):
if tru[i].count(True) == n-1:
ans[i] = 'b'
if '-' in ans:
idx = ans.index('-')
ans[idx] = 'a'
for i in range(n):
if i != idx and ans[i] != 'b':
ans[i] = 'a' if tru[i][idx] else 'c'
else:
YES()
for p1 in range(n):
for p2 in range(p1+1, n):
if (abs(ord(ans[p1]) - ord(ans[p2])) < 2) != (tru[p1][p2]):
NO()
YES()
| {
"input": [
"4 3\n1 2\n1 3\n1 4\n",
"2 1\n1 2\n"
],
"output": [
"No\n",
"Yes\nbb\n"
]
} |
4,197 | 9 | There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.
You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where:
* <hostname> β server name (consists of words and maybe some dots separating them),
* /<path> β optional part, where <path> consists of words separated by slashes.
We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa β for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications.
Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.
Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where:
* <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20.
* <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20.
Addresses are not guaranteed to be distinct.
Output
First print k β the number of groups of server names that correspond to one website. You should count only groups of size greater than one.
Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
Examples
Input
10
http://abacaba.ru/test
http://abacaba.ru/
http://abacaba.com
http://abacaba.com/test
http://abacaba.de/
http://abacaba.ru/test
http://abacaba.de/test
http://abacaba.com/
http://abacaba.com/t
http://abacaba.com/test
Output
1
http://abacaba.de http://abacaba.ru
Input
14
http://c
http://ccc.bbbb/aba..b
http://cba.com
http://a.c/aba..b/a
http://abc/
http://a.c/
http://ccc.bbbb
http://ab.ac.bc.aa/
http://a.a.a/
http://ccc.bbbb/
http://cba.com/
http://cba.com/aba..b
http://a.a.a/aba..b/a
http://abc/aba..b/a
Output
2
http://cba.com http://ccc.bbbb
http://a.a.a http://a.c http://abc | n=int(input())
d={}
D={}
for i in range(n):
h,*p=(input()[7:]+'/').split('/')
d.setdefault(h,set()).add('/'.join(p))
for x in d: D.setdefault(frozenset(d[x]),[]).append(x)
def ans():
for x in D:
if len(D[x])>1:
yield 'http://'+' http://'.join(D[x])
print(sum(1 for x in D if len(D[x])>1))
print('\n'.join(ans())) | {
"input": [
"10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test\n",
"14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a\n"
],
"output": [
"1\nhttp://abacaba.de http://abacaba.ru \n\n",
"2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc \n\n"
]
} |
4,198 | 8 | Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!
The computers bought for the room were different. Some of them had only USB ports, some β only PS/2 ports, and some had both options.
You have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.
You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.
Input
The first line contains three integers a, b and c (0 β€ a, b, c β€ 105) β the number of computers that only have USB ports, the number of computers, that only have PS/2 ports, and the number of computers, that have both options, respectively.
The next line contains one integer m (0 β€ m β€ 3Β·105) β the number of mouses in the price list.
The next m lines each describe another mouse. The i-th line contains first integer vali (1 β€ vali β€ 109) β the cost of the i-th mouse, then the type of port (USB or PS/2) that is required to plug the mouse in.
Output
Output two integers separated by space β the number of equipped computers and the total cost of the mouses you will buy.
Example
Input
2 1 1
4
5 USB
6 PS/2
3 PS/2
7 PS/2
Output
3 14
Note
In the first example you can buy the first three mouses. This way you will equip one of the computers that has only a USB port with a USB mouse, and the two PS/2 mouses you will plug into the computer with PS/2 port and the computer with both ports. | def r():
return list(map(int, input().split()))
n, ans = 0, 0
a, b, c = r()
m = int(input())
tt = []
for i in range(m):
val, port = input().split()
val = int(val)
if port[0] is 'U':
tt.append([val, 1])
else:
tt.append([val, 0])
tt.sort(key = lambda x: x[0])
tt2 = []
for x, y in tt:
if y == 0 and b > 0:
b -= 1
ans += x
n += 1
elif y == 1 and a > 0:
a -= 1
ans += x
n += 1
else:
tt2.append(x)
mn = min(c, len(tt2))
ans += sum(tt2[:mn])
n += mn
print(n, ans) | {
"input": [
"2 1 1\n4\n5 USB\n6 PS/2\n3 PS/2\n7 PS/2\n"
],
"output": [
"3 14\n"
]
} |
4,199 | 9 | Anton likes to listen to fairy tales, especially when Danik, Anton's best friend, tells them. Right now Danik tells Anton a fairy tale:
"Once upon a time, there lived an emperor. He was very rich and had much grain. One day he ordered to build a huge barn to put there all his grain. Best builders were building that barn for three days and three nights. But they overlooked and there remained a little hole in the barn, from which every day sparrows came through. Here flew a sparrow, took a grain and flew away..."
More formally, the following takes place in the fairy tale. At the beginning of the first day the barn with the capacity of n grains was full. Then, every day (starting with the first day) the following happens:
* m grains are brought to the barn. If m grains doesn't fit to the barn, the barn becomes full and the grains that doesn't fit are brought back (in this problem we can assume that the grains that doesn't fit to the barn are not taken into account).
* Sparrows come and eat grain. In the i-th day i sparrows come, that is on the first day one sparrow come, on the second day two sparrows come and so on. Every sparrow eats one grain. If the barn is empty, a sparrow eats nothing.
Anton is tired of listening how Danik describes every sparrow that eats grain from the barn. Anton doesn't know when the fairy tale ends, so he asked you to determine, by the end of which day the barn will become empty for the first time. Help Anton and write a program that will determine the number of that day!
Input
The only line of the input contains two integers n and m (1 β€ n, m β€ 1018) β the capacity of the barn and the number of grains that are brought every day.
Output
Output one integer β the number of the day when the barn will become empty for the first time. Days are numbered starting with one.
Examples
Input
5 2
Output
4
Input
8 1
Output
5
Note
In the first sample the capacity of the barn is five grains and two grains are brought every day. The following happens:
* At the beginning of the first day grain is brought to the barn. It's full, so nothing happens.
* At the end of the first day one sparrow comes and eats one grain, so 5 - 1 = 4 grains remain.
* At the beginning of the second day two grains are brought. The barn becomes full and one grain doesn't fit to it.
* At the end of the second day two sparrows come. 5 - 2 = 3 grains remain.
* At the beginning of the third day two grains are brought. The barn becomes full again.
* At the end of the third day three sparrows come and eat grain. 5 - 3 = 2 grains remain.
* At the beginning of the fourth day grain is brought again. 2 + 2 = 4 grains remain.
* At the end of the fourth day four sparrows come and eat grain. 4 - 4 = 0 grains remain. The barn is empty.
So the answer is 4, because by the end of the fourth day the barn becomes empty. | n,m=map(int,input().split())
def bs(f,l):
mid=(f+l)//2
t=mid-m
if(f==l-1):
return l
if(n-m-t*(t+1)//2>0):
return bs(mid,l)
return bs(f,mid)
if(m<n):
print(bs(m-1,n+1))
else:
print(n)
| {
"input": [
"8 1\n",
"5 2\n"
],
"output": [
"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.