index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
3,000 | 10 | You have a bag of size n. Also you have m boxes. The size of i-th box is a_i, where each a_i is an integer non-negative power of two.
You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.
For example, if n = 10 and a = [1, 1, 32] then you have to divide the box of size 32 into two parts of size 16, and then divide the box of size 16. So you can fill the bag with boxes of size 1, 1 and 8.
Calculate the minimum number of divisions required to fill the bag of size n.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains two integers n and m (1 β€ n β€ 10^{18}, 1 β€ m β€ 10^5) β the size of bag and the number of boxes, respectively.
The second line of each test case contains m integers a_1, a_2, ... , a_m (1 β€ a_i β€ 10^9) β the sizes of boxes. It is guaranteed that each a_i is a power of two.
It is also guaranteed that sum of all m over all test cases does not exceed 10^5.
Output
For each test case print one integer β the minimum number of divisions required to fill the bag of size n (or -1, if it is impossible).
Example
Input
3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
Output
2
-1
0 | def problem(n, a):
if sum(a) < n:
return -1
bit = [0] * 61
for i in a:
bit[i.bit_length() - 1] += 1
i, r, l = 0, 0, n.bit_length()
while i < l:
if n >> i & 1:
if bit[i]:
bit[i] -= 1
else:
while bit[i] == 0:
i, r = i + 1, r + 1
bit[i] -= 1
continue
bit[i+1] += bit[i] >> 1
i += 1
return r
for i in range(int(input())):
n = int(input().split()[0])
a = list(map(int,input().split()))
print(problem(n, a))
| {
"input": [
"3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8\n"
],
"output": [
"2\n-1\n0\n"
]
} |
3,001 | 11 | You wrote down all integers from 0 to 10^n - 1, padding them with leading zeroes so their lengths are exactly n. For example, if n = 3 then you wrote out 000, 001, ..., 998, 999.
A block in an integer x is a consecutive segment of equal digits that cannot be extended to the left or to the right.
For example, in the integer 00027734000 there are three blocks of length 1, one block of length 2 and two blocks of length 3.
For all integers i from 1 to n count the number of blocks of length i among the written down integers.
Since these integers may be too large, print them modulo 998244353.
Input
The only line contains one integer n (1 β€ n β€ 2 β
10^5).
Output
In the only line print n integers. The i-th integer is equal to the number of blocks of length i.
Since these integers may be too large, print them modulo 998244353.
Examples
Input
1
Output
10
Input
2
Output
180 10 | def main():
md=998244353
n=int(input())
for w in range(1,n):
ans=((n-w-1)*81+180)*pow(10,n-w-1,md)%md
print(ans)
print(10)
main() | {
"input": [
"1\n",
"2\n"
],
"output": [
"10\n",
"180 10\n"
]
} |
3,002 | 11 | Arthur owns a ski resort on a mountain. There are n landing spots on the mountain numbered from 1 to n from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are no directed cycles formed by the tracks. There are at most two tracks leaving each spot, but many tracks may enter the same spot.
A skier can start skiing from one spot and stop in another spot if there is a sequence of tracks that lead from the starting spot and end in the ending spot. Unfortunately, recently there were many accidents, because the structure of the resort allows a skier to go through dangerous paths, by reaching high speed and endangering himself and the other customers. Here, a path is called dangerous, if it consists of at least two tracks.
Arthur wants to secure his customers by closing some of the spots in a way that there are no dangerous paths in the resort. When a spot is closed, all tracks entering and leaving that spot become unusable.
Formally, after closing some of the spots, there should not be a path that consists of two or more tracks.
Arthur doesn't want to close too many spots. He will be happy to find any way to close at most 4/7n spots so that the remaining part is safe. Help him find any suitable way to do so.
Input
The first line contains a single positive integer T β the number of test cases. T test case description follows.
The first line of each description contains two integers n and m (1 β€ n β€ 2 β
10^5) β the number of landing spots and tracks respectively.
The following m lines describe the tracks. Each of these lines contains two integers x and y (1 β€ x < y β€ n) β indices of the starting and finishing spots for the respective track. It is guaranteed that at most two tracks start at each spot. There may be tracks in which starting and finishing spots both coincide.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case, print a single integer k (0 β€ k β€ 4/7n) β the number of spots to be closed. In the next line, print k distinct integers β indices of all spots to be closed, in any order.
If there are several answers, you may output any of them. Note that you don't have to minimize k. It can be shown that a suitable answer always exists.
Example
Input
2
4 6
1 2
1 3
2 3
2 4
3 4
3 4
7 6
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
3 4
4
4 5 6 7
Note
In the first sample case, closing any two spots is suitable.
In the second sample case, closing only the spot 1 is also suitable. | import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
def solve(n, m, g):
dp = [0] * n
ans = []
for i in range(n):
for w in g[i]:
dp[i] = max(dp[i], dp[w] + 1)
if dp[i] >= 2:
dp[i] = -1
ans.append(i+1)
wi(len(ans))
wia(ans)
def main():
for _ in range(ri()):
n, m = ria()
g = [[] for i in range(n)]
for __ in range(m):
u, v = ria()
g[v-1].append(u-1)
solve(n, m, g)
if __name__ == '__main__':
main()
| {
"input": [
"2\n4 6\n1 2\n1 3\n2 3\n2 4\n3 4\n3 4\n7 6\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n"
],
"output": [
"2\n3 4 \n4\n4 5 6 7 \n"
]
} |
3,003 | 10 | As Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest.
The New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are n problems for the contest. The penalty time for each solved problem is set as the distance from the moment of solution submission to the New Year in minutes. For example, the problem submitted at 21:00 (9.00 P.M.) gets penalty time 180, as well as the problem submitted at 3:00 (3.00 A.M.). The total penalty time is calculated as the sum of penalty time for all solved problems. It is allowed to submit a problem exactly at the end of the contest, at 6:00 (6.00 A.M.).
Gennady opened the problems exactly at 18:00 (6.00 P.M.) and managed to estimate their complexity during the first 10 minutes of the contest. He believes that writing a solution for the i-th problem will take ai minutes. Gennady can submit a solution for evaluation at any time after he completes writing it. Probably he will have to distract from writing some solution to send the solutions of other problems for evaluation. The time needed to send the solutions can be neglected, i.e. this time can be considered to equal zero. Gennady can simultaneously submit multiple solutions. Besides, he can move at any time from writing one problem to another, and then return to the first problem from the very same place, where he has left it. Thus the total solution writing time of the i-th problem always equals ai minutes. Of course, Gennady does not commit wrong attempts, and his solutions are always correct and are accepted from the first attempt. He can begin to write the solutions starting from 18:10 (6.10 P.M.).
Help Gennady choose from the strategies that help him solve the maximum possible number of problems, the one with which his total penalty time will be minimum.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of the problems. The next line contains n space-separated integers ai (1 β€ ai β€ 720) β each number shows how much time in minutes Gennady will spend writing a solution to the problem.
Output
Print two integers β the number of problems Gennady will solve and the total penalty time considering that he chooses the optimal strategy.
Examples
Input
3
30 330 720
Output
2 10
Note
In the sample, one of Gennady's possible optimal strategies is as follows. At 18:10 (6:10 PM) he begins to write the first problem and solves it in 30 minutes (18:40 or 6.40 P.M.). At 18:40 (6.40 P.M.) he begins to write the second problem. There are 320 minutes left before the New Year, so Gennady does not have the time to finish writing the second problem before the New Year. At 0:00 (12.00 A.M.) he distracts from the second problem, submits the first one, and returns immediately to writing the second problem. At 0:10 (0.10 A.M.), he completes the solution for the second problem, submits it and gets 10 minute penalty time. Note that as the total duration of the contest is 720 minutes and Gennady has already spent 10 minutes on reading the problems, he will not have time to solve the third problem during the contest. Yes, such problems happen to exist.
Competitions by the given rules are held annually on the site http://b23.ru/3wvc | import sys
from itertools import *
from math import *
def solve():
n = int(input())
a = list(map(int, input().split()))
a.sort()
time = -6*60 + 10
maxtime = 6 * 60
completed = 0
penalty = 0
for i, val in enumerate(a):
timefinish = time + val
if timefinish <= maxtime:
penalty += max(0, timefinish)
completed+=1
time = timefinish
print(completed, penalty)
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve() | {
"input": [
"3\n30 330 720\n"
],
"output": [
"2 10\n"
]
} |
3,004 | 10 | You are given an integer n (n > 1).
Your task is to find a sequence of integers a_1, a_2, β¦, a_k such that:
* each a_i is strictly greater than 1;
* a_1 β
a_2 β
β¦ β
a_k = n (i. e. the product of this sequence is n);
* a_{i + 1} is divisible by a_i for each i from 1 to k-1;
* k is the maximum possible (i. e. the length of this sequence is the maximum possible).
If there are several such sequences, any of them is acceptable. It can be proven that at least one valid sequence always exists for any integer n > 1.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 5000) β the number of test cases. Then t test cases follow.
The only line of the test case contains one integer n (2 β€ n β€ 10^{10}).
It is guaranteed that the sum of n does not exceed 10^{10} (β n β€ 10^{10}).
Output
For each test case, print the answer: in the first line, print one positive integer k β the maximum possible length of a. In the second line, print k integers a_1, a_2, β¦, a_k β the sequence of length k satisfying the conditions from the problem statement.
If there are several answers, you can print any. It can be proven that at least one valid sequence always exists for any integer n > 1.
Example
Input
4
2
360
4999999937
4998207083
Output
1
2
3
2 2 90
1
4999999937
1
4998207083 |
def prime_factorize(n):
pf = {}
orig_n = n
p = 2
while n > 1 and p*p <= orig_n:
if n%p==0:
pf[p] = 0
while n%p==0:
pf[p] += 1
n //= p
p += 1
if n > 1:
pf[n] = 1
return pf
for _ in range(int(input())):
n = int(input())
pf = prime_factorize(n)
ans = [1 for i in range(max(pf.values()))]
for p,e in pf.items():
for i in range(e):
ans[i] *= p
ans.reverse()
print(len(ans))
print(*ans) | {
"input": [
"4\n2\n360\n4999999937\n4998207083\n"
],
"output": [
"\n1\n2 \n3\n2 2 90 \n1\n4999999937 \n1\n4998207083 \n"
]
} |
3,005 | 8 | Nezzar's favorite digit among 1,β¦,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation.
Given q integers a_1,a_2,β¦,a_q, for each 1 β€ i β€ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers.
Input
The first line contains a single integer t (1 β€ t β€ 9) β the number of test cases.
The first line of each test case contains two integers q and d (1 β€ q β€ 10^4, 1 β€ d β€ 9).
The second line of each test case contains q integers a_1,a_2,β¦,a_q (1 β€ a_i β€ 10^9).
Output
For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO".
You can print letters in any case (upper or lower).
Example
Input
2
3 7
24 25 27
10 7
51 52 53 54 55 56 57 58 59 60
Output
YES
NO
YES
YES
YES
NO
YES
YES
YES
YES
YES
YES
NO
Note
In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers. | def solve(x, y):
while x > 0:
for i in str(x):
if int(i) == y:
return "Yes"
x = x - y
return "No"
for _ in range(int(input())):
a = input().split()
a = int(a[1])
b = input().split()
for i in b:
print(solve(int(i), a))
| {
"input": [
"2\n3 7\n24 25 27\n10 7\n51 52 53 54 55 56 57 58 59 60\n"
],
"output": [
"\nYES\nNO\nYES\nYES\nYES\nNO\nYES\nYES\nYES\nYES\nYES\nYES\nNO\n"
]
} |
3,006 | 11 | A mouse encountered a nice big cake and decided to take a walk across it, eating the berries on top of the cake on its way. The cake is rectangular, neatly divided into squares; some of the squares have a berry in them, and some don't.
The mouse is in a bit of a hurry, though, so once she enters the cake from its northwest corner (the top left cell in the input data), she will only go east (right) or south (down), until she reaches the southeast corner (the bottom right cell). She will eat every berry in the squares she passes through, but not in the other squares.
The mouse tries to choose her path so as to maximize the number of berries consumed. However, her haste and hunger might be clouding her judgement, leading her to suboptimal decisions...
Input
The first line of input contains two integers H and W (1 β€ H, W β€ 5), separated by a space, β the height and the width of the cake.
The next H lines contain a string of W characters each, representing the squares of the cake in that row: '.' represents an empty square, and '*' represents a square with a berry.
Output
Output the number of berries the mouse will eat following her strategy.
Examples
Input
4 3
*..
.*.
..*
...
Output
3
Input
4 4
.*..
*...
...*
..*.
Output
2
Input
3 4
..**
*...
....
Output
1
Input
5 5
..*..
.....
**...
**...
**...
Output
1 | n,m = map(int,input().split())
g = [input() for i in range(n)]
def rec(i,j,ans):
if i == n - 1 and j == m - 1:
print(ans + (g[i][j] == '*'))
exit()
add = g[i][j] == '*'
if j == m - 1:
return rec(i+1,j,ans+add)
if i == n - 1:
return rec(i,j+1,ans+add)
if g[i][j+1] == '*':
return rec(i,j+1,ans+add)
if g[i+1][j] == '*':
return rec(i+1,j,ans+add)
return rec(i,j+1,ans+add)
rec(0,0,0) | {
"input": [
"4 3\n*..\n.*.\n..*\n...\n",
"5 5\n..*..\n.....\n**...\n**...\n**...\n",
"4 4\n.*..\n*...\n...*\n..*.\n",
"3 4\n..**\n*...\n....\n"
],
"output": [
"\n3\n",
"\n1\n",
"\n2\n",
"\n1\n"
]
} |
3,007 | 7 | Nick is interested in prime numbers. Once he read about Goldbach problem. It states that every even integer greater than 2 can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it Noldbach problem. Since Nick is interested only in prime numbers, Noldbach problem states that at least k prime numbers from 2 to n inclusively can be expressed as the sum of three integer numbers: two neighboring prime numbers and 1. For example, 19 = 7 + 11 + 1, or 13 = 5 + 7 + 1.
Two prime numbers are called neighboring if there are no other prime numbers between them.
You are to help Nick, and find out if he is right or wrong.
Input
The first line of the input contains two integers n (2 β€ n β€ 1000) and k (0 β€ k β€ 1000).
Output
Output YES if at least k prime numbers from 2 to n inclusively can be expressed as it was described above. Otherwise output NO.
Examples
Input
27 2
Output
YES
Input
45 7
Output
NO
Note
In the first sample the answer is YES since at least two numbers can be expressed as it was described (for example, 13 and 19). In the second sample the answer is NO since it is impossible to express 7 prime numbers from 2 to 45 in the desired form. | def is_prime(a):
i = 2
while i * i <= a:
if a % i == 0:
return False
i += 1
return True
n, k = [int(x) for x in input().split()]
a = []
for i in range(3, n + 1):
if is_prime(i):
a.append(i)
for i in range(1, len(a)):
if a[i - 1] + a[i] + 1 in a:
k -= 1
print('YES' if k <= 0 else 'NO') | {
"input": [
"27 2\n",
"45 7\n"
],
"output": [
"YES\n",
"NO\n"
]
} |
3,008 | 8 | A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem β a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.
You are invited to act as a fair judge and determine whether the problem is indeed brand new, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.
You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.
The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as <image>, where n is the number of words in Lesha's problem and x is the number of inversions in the chosen permutation. Note that the "similarity" p is always a positive integer.
The problem is called brand new if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.
Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.
Input
The first line contains a single integer n (1 β€ n β€ 4) β the number of words in Lesha's problem. The second line contains n space-separated words β the short description of the problem.
The third line contains a single integer m (1 β€ m β€ 10) β the number of problems in the Torcoder.com archive. Next m lines contain the descriptions of the problems as "k s1 s2 ... sk", where k (1 β€ k β€ 20) is the number of words in the problem and si is a word of the problem description.
All words from all problem descriptions contain no more than 10 lowercase English letters.
Output
If Lesha's problem is brand new, print string "Brand new problem!" (without quotes).
Otherwise, on the first line print the index of the archive problem which resembles Lesha's problem most. If there are multiple such problems, print the one with the smallest index. On the second line print a string consisting of characters [:, character | repeated p times, and characters :], where p is the "similarity" between this problem and Lesha's one. The archive problems are numbered starting from one in the order in which they are given in the input.
Examples
Input
4
find the next palindrome
1
10 find the previous palindrome or print better luck next time
Output
1
[:||||||:]
Input
3
add two numbers
3
1 add
2 two two
3 numbers numbers numbers
Output
Brand new problem!
Input
4
these papers are formulas
3
6 what are these formulas and papers
5 papers are driving me crazy
4 crazy into the night
Output
1
[:||||:]
Input
3
add two decimals
5
4 please two decimals add
5 decimals want to be added
4 two add decimals add
4 add one two three
7 one plus two plus three equals six
Output
3
[:|||:]
Note
Let us remind you that the number of inversions is the number of pairs of words that follow in the permutation not in their original order. Thus, for example, if the original problem is "add two numbers", then permutation "numbers add two" contains two inversions β pairs of words "numbers" and "add", "numbers" and "two".
Sequence b1, b2, ..., bk is a subsequence of sequence a1, a2, ..., an if there exists such a set of indices 1 β€ i1 < i2 < ... < ik β€ n that aij = bj (in other words, if sequence b can be obtained from a by deleting some of its elements).
In the first test case the first problem contains the "find the palindrome next" permutation as a subsequence, in which the number of inversions equals 1 (words "palindrome" and "next").
In the second test case there is no problem that contains a permutation of words from Lesha's problem as a subsequence. | import itertools
def check(curr_words, line):
if curr_words == []:
return True
for i in range(len(line)):
if line[i] == curr_words[0]:
return check(curr_words[1:], line[i+1:])
return False
n = int(input())
words = input().split()
m = int(input())
res, idx = 0, 0
for i in range(m):
line = input().split()[1:]
for p in itertools.permutations(range(n)):
curr_words = [words[j] for j in p]
cnt = 0
for j in range(n):
cnt += len([k for k in range(j+1, n) if p[k] < p[j]])
v = n * (n-1) // 2 - cnt + 1
if check(curr_words, line[:]) and v > res:
res, idx = v, i+1
if res > 0:
print(idx)
print('[:'+str('|'*res)+':]')
else:
print('Brand new problem!') | {
"input": [
"3\nadd two numbers\n3\n1 add\n2 two two\n3 numbers numbers numbers\n",
"3\nadd two decimals\n5\n4 please two decimals add\n5 decimals want to be added\n4 two add decimals add\n4 add one two three\n7 one plus two plus three equals six\n",
"4\nthese papers are formulas\n3\n6 what are these formulas and papers\n5 papers are driving me crazy\n4 crazy into the night\n",
"4\nfind the next palindrome\n1\n10 find the previous palindrome or print better luck next time\n"
],
"output": [
"Brand new problem!\n",
"3\n[:|||:]\n",
"1\n[:||||:]\n",
"1\n[:||||||:]\n"
]
} |
3,009 | 7 | Trouble came from the overseas lands: a three-headed dragon Gorynych arrived. The dragon settled at point C and began to terrorize the residents of the surrounding villages.
A brave hero decided to put an end to the dragon. He moved from point A to fight with Gorynych. The hero rode from point A along a straight road and met point B on his way. The hero knows that in this land for every pair of roads it is true that they are either parallel to each other, or lie on a straight line, or are perpendicular to each other. He also knows well that points B and C are connected by a road. So the hero must either turn 90 degrees to the left or continue riding straight ahead or turn 90 degrees to the right. But he forgot where the point C is located.
Fortunately, a Brave Falcon flew right by. It can see all three points from the sky. The hero asked him what way to go to get to the dragon's lair.
If you have not got it, you are the falcon. Help the hero and tell him how to get him to point C: turn left, go straight or turn right.
At this moment the hero is believed to stand at point B, turning his back to point A.
Input
The first input line contains two space-separated integers xa, ya (|xa|, |ya| β€ 109) β the coordinates of point A. The second line contains the coordinates of point B in the same form, the third line contains the coordinates of point C.
It is guaranteed that all points are pairwise different. It is also guaranteed that either point B lies on segment AC, or angle ABC is right.
Output
Print a single line. If a hero must turn left, print "LEFT" (without the quotes); If he must go straight ahead, print "TOWARDS" (without the quotes); if he should turn right, print "RIGHT" (without the quotes).
Examples
Input
0 0
0 1
1 1
Output
RIGHT
Input
-1 -1
-3 -3
-4 -4
Output
TOWARDS
Input
-4 -6
-3 -7
-2 -6
Output
LEFT
Note
The picture to the first sample:
<image>
The red color shows points A, B and C. The blue arrow shows the hero's direction. The green color shows the hero's trajectory.
The picture to the second sample:
<image> | def readln(): return tuple(map(int, input().split()))
x, y = list(zip(*[readln() for _ in range(3)]))
val = (x[1] - x[0]) * (y[2] - y[1]) - (x[2] - x[1]) * (y[1] - y[0])
if val > 0:
print('LEFT')
elif val < 0:
print('RIGHT')
else:
print('TOWARDS')
| {
"input": [
"0 0\n0 1\n1 1\n",
"-1 -1\n-3 -3\n-4 -4\n",
"-4 -6\n-3 -7\n-2 -6\n"
],
"output": [
"RIGHT\n",
"TOWARDS\n",
"LEFT\n"
]
} |
3,010 | 10 | Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages.
The river banks can be assumed to be vertical straight lines x = a and x = b (0 < a < b).
The west village lies in a steppe at point O = (0, 0). There are n pathways leading from the village to the river, they end at points Ai = (a, yi). The villagers there are plain and simple, so their pathways are straight segments as well.
The east village has reserved and cunning people. Their village is in the forest on the east bank of the river, but its exact position is not clear. There are m twisted paths leading from this village to the river and ending at points Bi = (b, y'i). The lengths of all these paths are known, the length of the path that leads from the eastern village to point Bi, equals li.
The villagers want to choose exactly one point on the left bank of river Ai, exactly one point on the right bank Bj and connect them by a straight-line bridge so as to make the total distance between the villages (the sum of |OAi| + |AiBj| + lj, where |XY| is the Euclidean distance between points X and Y) were minimum. The Euclidean distance between points (x1, y1) and (x2, y2) equals <image>.
Help them and find the required pair of points.
Input
The first line contains integers n, m, a, b (1 β€ n, m β€ 105, 0 < a < b < 106).
The second line contains n integers in the ascending order: the i-th integer determines the coordinate of point Ai and equals yi (|yi| β€ 106).
The third line contains m integers in the ascending order: the i-th integer determines the coordinate of point Bi and equals y'i (|y'i| β€ 106).
The fourth line contains m more integers: the i-th of them determines the length of the path that connects the eastern village and point Bi, and equals li (1 β€ li β€ 106).
It is guaranteed, that there is such a point C with abscissa at least b, that |BiC| β€ li for all i (1 β€ i β€ m). It is guaranteed that no two points Ai coincide. It is guaranteed that no two points Bi coincide.
Output
Print two integers β the numbers of points on the left (west) and right (east) banks, respectively, between which you need to build a bridge. You can assume that the points on the west bank are numbered from 1 to n, in the order in which they are given in the input. Similarly, the points on the east bank are numbered from 1 to m in the order in which they are given in the input.
If there are multiple solutions, print any of them. The solution will be accepted if the final length of the path will differ from the answer of the jury by no more than 10 - 6 in absolute or relative value.
Examples
Input
3 2 3 5
-2 -1 4
-1 2
7 3
Output
2 2 | import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n, m, a, b = mints()
A = list(mints())
B = list(mints())
l = list(mints())
j = -1
r = (1e100,-1,-1)
for i in range(m):
while not((j == -1 or a*B[i]-b*A[j] >= 0) \
and (j+1 == n or a*B[i]-b*A[j+1] < 0)):
j += 1
#print(j)#,a*B[i]-b*A[j],a*B[i]-b*A[j+1])
if j != -1:
r = min(r,(l[i]+sqrt(a*a+A[j]*A[j])+sqrt((b-a)**2+(B[i]-A[j])**2),j,i))
if j+1 != n:
r = min(r,(l[i]+sqrt(a*a+A[j+1]*A[j+1])+sqrt((b-a)**2+(B[i]-A[j+1])**2),j+1,i))
print(r[1]+1,r[2]+1) | {
"input": [
"3 2 3 5\n-2 -1 4\n-1 2\n7 3\n"
],
"output": [
"2 2\n"
]
} |
3,011 | 8 | Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1.
Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks.
Ksusha the squirrel keeps fit. She can jump from sector i to any of the sectors i + 1, i + 2, ..., i + k.
Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?
Input
The first line contains two integers n and k (2 β€ n β€ 3Β·105, 1 β€ k β€ 3Β·105). The next line contains n characters β the description of the road: the i-th character equals ".", if the i-th sector contains no rocks. Otherwise, it equals "#".
It is guaranteed that the first and the last characters equal ".".
Output
Print "YES" (without the quotes) if Ksusha can reach the end of the road, otherwise print "NO" (without the quotes).
Examples
Input
2 1
..
Output
YES
Input
5 2
.#.#.
Output
YES
Input
7 3
.#.###.
Output
NO | from sys import stdin
def read(): return map(int, stdin.readline().split())
n, k = read()
print ( "NO" if '#'*k in stdin.readline() else "YES" )
| {
"input": [
"2 1\n..\n",
"5 2\n.#.#.\n",
"7 3\n.#.###.\n"
],
"output": [
"YES\n",
"YES\n",
"NO\n"
]
} |
3,012 | 8 | Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.
A sequence of l integers b1, b2, ..., bl (1 β€ b1 β€ b2 β€ ... β€ bl β€ n) is called good if each number divides (without a remainder) by the next number in the sequence. More formally <image> for all i (1 β€ i β€ l - 1).
Given n and k find the number of good sequences of length k. As the answer can be rather large print it modulo 1000000007 (109 + 7).
Input
The first line of input contains two space-separated integers n, k (1 β€ n, k β€ 2000).
Output
Output a single integer β the number of good sequences of length k modulo 1000000007 (109 + 7).
Examples
Input
3 2
Output
5
Input
6 4
Output
39
Input
2 1
Output
2
Note
In the first sample the good sequences are: [1, 1], [2, 2], [3, 3], [1, 2], [1, 3]. | def C(n,m):
a=1
for i in range(n-m+1,n+1):a*=i
for i in range(1,m+1):a//=i
return a
n,k=[int(x) for x in input().split()]
a=0
for i in range (1,n+1):
t=1
I=i
for j in range(2,i+1):
s=0
while I%j==0:
s+=1
I//=j
if s:
t*=C(s+k-1,s)
a+=t
print(a%(10**9+7)) | {
"input": [
"3 2\n",
"6 4\n",
"2 1\n"
],
"output": [
"5",
"39",
"2"
]
} |
3,013 | 7 | Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.
Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed 99, because each seller maximizes the number of dollars in the change (100 cents can be replaced with a dollar).
Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change.
Input
The first line contains two space-separated integers n, s (1 β€ n, s β€ 100).
The i-th of the next n lines contains two integers xi, yi (1 β€ xi β€ 100; 0 β€ yi < 100), where xi represents the number of dollars and yi the number of cents needed in order to buy the i-th type of sugar.
Output
Print a single integer representing the maximum number of sweets he can buy, or -1 if he can't buy any type of sugar.
Examples
Input
5 10
3 90
12 0
9 70
5 50
7 0
Output
50
Input
5 5
10 10
20 20
30 30
40 40
50 50
Output
-1
Note
In the first test sample Caisa can buy the fourth type of sugar, in such a case he will take 50 sweets as a change. | def readln(): return tuple(map(int, input().split()))
n, s = readln()
ans = 0
ok = False
for _ in range(n):
d, c = readln()
if d + (c > 0) <= s:
ok = True
if c > 0:
ans = max(ans, 100 - c)
print(ans if ok else -1)
| {
"input": [
"5 10\n3 90\n12 0\n9 70\n5 50\n7 0\n",
"5 5\n10 10\n20 20\n30 30\n40 40\n50 50\n"
],
"output": [
"50\n",
"-1\n"
]
} |
3,014 | 11 | The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.
Nam created a sequence a consisting of n (1 β€ n β€ 105) elements a1, a2, ..., an (1 β€ ai β€ 105). A subsequence ai1, ai2, ..., aik where 1 β€ i1 < i2 < ... < ik β€ n is called increasing if ai1 < ai2 < ai3 < ... < aik. An increasing subsequence is called longest if it has maximum length among all increasing subsequences.
Nam realizes that a sequence may have several longest increasing subsequences. Hence, he divides all indexes i (1 β€ i β€ n), into three groups:
1. group of all i such that ai belongs to no longest increasing subsequences.
2. group of all i such that ai belongs to at least one but not every longest increasing subsequence.
3. group of all i such that ai belongs to every longest increasing subsequence.
Since the number of longest increasing subsequences of a may be very large, categorizing process is very difficult. Your task is to help him finish this job.
Input
The first line contains the single integer n (1 β€ n β€ 105) denoting the number of elements of sequence a.
The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 105).
Output
Print a string consisting of n characters. i-th character should be '1', '2' or '3' depending on which group among listed above index i belongs to.
Examples
Input
1
4
Output
3
Input
4
1 3 2 5
Output
3223
Input
4
1 5 2 3
Output
3133
Note
In the second sample, sequence a consists of 4 elements: {a1, a2, a3, a4} = {1, 3, 2, 5}. Sequence a has exactly 2 longest increasing subsequences of length 3, they are {a1, a2, a4} = {1, 3, 5} and {a1, a3, a4} = {1, 2, 5}.
In the third sample, sequence a consists of 4 elements: {a1, a2, a3, a4} = {1, 5, 2, 3}. Sequence a have exactly 1 longest increasing subsequence of length 3, that is {a1, a3, a4} = {1, 2, 3}. | import bisect
import sys
MAX_N = 1000000
from bisect import*
def LIS(arr):
d = [0]*n
last = []
for i in range(n):
if not last or last[-1] < arr[i]:
last.append(arr[i])
idx = bisect_left(last,arr[i])
last[idx] = arr[i]
d[i] = idx +1
return d
n = int(input())
a = list(map(int,input().split()))
Order_d = LIS(a)
b = [-v for v in a]
b.reverse()
Reverse_d = LIS(b)
Reverse_d.reverse()
Lis = max(Order_d)
ans = [1]*n
for i in range(n):
if Order_d[i] + Reverse_d[i] == Lis+1:
ans[i] = 3
Lmax = -1e10
Rmin = 1e10
for i in range(n):
if ans[i]==1:continue
if a[i]<=Lmax:
ans[i]=2
Lmax = max(Lmax,a[i])
for i in range(n-1,-1,-1):
if ans[i]==1:continue
if a[i]>=Rmin:
ans[i] = 2
Rmin = min(Rmin,a[i])
first_Lis_idx = 0
second_Lis_idx = 0
for i in range(n):
if ans[i]==3:
first_Lis_idx = i
break
for i in range(n-1,-1,-1):
if ans[i]==3:
second_Lis_idx = i
break
for v in ans:
print(v,end='')
| {
"input": [
"4\n1 3 2 5\n",
"1\n4\n",
"4\n1 5 2 3\n"
],
"output": [
"3223",
"3",
"3133"
]
} |
3,015 | 7 | A flea is sitting at one of the n hassocks, arranged in a circle, at the moment. After minute number k the flea jumps through k - 1 hassoΡks (clockwise). For example, after the first minute the flea jumps to the neighboring hassock. You should answer: will the flea visit all the hassocks or not. We assume that flea has infinitely much time for this jumping.
Input
The only line contains single integer: 1 β€ n β€ 1000 β number of hassocks.
Output
Output "YES" if all the hassocks will be visited and "NO" otherwise.
Examples
Input
1
Output
YES
Input
3
Output
NO | def f(n):
rl = [True]*n #True = nonvisited
nn = (n*(n-1))//2
for k in range(n):
kk = (k*(k+1))//2
rl[kk%n] = False
if n%2==0:
rl[(kk+nn)%n] = False
return sum(rl)==0
n = int(input())
print('YES' if f(n) else 'NO')
| {
"input": [
"1\n",
"3\n"
],
"output": [
"YES\n",
"NO\n"
]
} |
3,016 | 10 | In the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has n mandatory quests. To perform each of them, you need to take exactly two companions.
The attitude of each of the companions to the hero is an integer. Initially, the attitude of each of them to the hero of neutral and equal to 0. As the hero completes quests, he makes actions that change the attitude of the companions, whom he took to perform this task, in positive or negative direction.
Tell us what companions the hero needs to choose to make their attitude equal after completing all the quests. If this can be done in several ways, choose the one in which the value of resulting attitude is greatest possible.
Input
The first line contains positive integer n (1 β€ n β€ 25) β the number of important tasks.
Next n lines contain the descriptions of the tasks β the i-th line contains three integers li, mi, wi β the values by which the attitude of Lynn, Meliana and Worrigan respectively will change towards the hero if the hero takes them on the i-th task. All the numbers in the input are integers and do not exceed 107 in absolute value.
Output
If there is no solution, print in the first line "Impossible".
Otherwise, print n lines, two characters is each line β in the i-th line print the first letters of the companions' names that hero should take to complete the i-th task ('L' for Lynn, 'M' for Meliana, 'W' for Worrigan). Print the letters in any order, if there are multiple solutions, print any of them.
Examples
Input
3
1 0 0
0 1 0
0 0 1
Output
LM
MW
MW
Input
7
0 8 9
5 9 -2
6 -8 -7
9 4 5
-4 -9 9
-4 5 2
-6 8 -7
Output
LM
MW
LM
LW
MW
LM
LW
Input
2
1 0 0
1 1 0
Output
Impossible | n=int(input())
ans=(-10**8,["Impossible"])
s=[];d={};fl=True;
a=[list(map(int,input().split())) for i in range(n)]
def job(nom,l,m,w):
global s,ans
if nom==n//2 and fl:
su,ss=d.get((m-l,w-l),(-10**10,[]))
if l>su: d[(m-l,w-l)]=(l,s[:])
return
if nom==n:
su,ss=d.get((l-m,l-w),(-10**9,[]))
if su+l>ans[0]: ans=(su+l,ss[:]+s[:])
return
s+=["MW"] ;job(nom+1,l,m+a[nom][1],w+a[nom][2])
s[-1]="LW";job(nom+1,l+a[nom][0],m,w+a[nom][2])
s[-1]="LM";job(nom+1,l+a[nom][0],m+a[nom][1],w)
s.pop()
job(0,0,0,0);fl=False;
if n==1: d[(0,0)]=(0,[])
job(n//2,0,0,0)
print('\n'.join(ans[1])) | {
"input": [
"3\n1 0 0\n0 1 0\n0 0 1\n",
"2\n1 0 0\n1 1 0\n",
"7\n0 8 9\n5 9 -2\n6 -8 -7\n9 4 5\n-4 -9 9\n-4 5 2\n-6 8 -7\n"
],
"output": [
"LM\nLM\nLW\n",
"Impossible",
"LM\nMW\nLM\nLW\nMW\nLM\nLW\n"
]
} |
3,017 | 9 | As Famil Doorβs birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings!
The sequence of round brackets is called valid if and only if:
1. the total number of opening brackets is equal to the total number of closing brackets;
2. for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets.
Gabi bought a string s of length m (m β€ n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p + s + q, that is add the string p at the beginning of the string s and string q at the end of the string s.
Now he wonders, how many pairs of strings p and q exists, such that the string p + s + q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 109 + 7.
Input
First line contains n and m (1 β€ m β€ n β€ 100 000, n - m β€ 2000) β the desired length of the string and the length of the string bought by Gabi, respectively.
The second line contains string s of length m consisting of characters '(' and ')' only.
Output
Print the number of pairs of string p and q such that p + s + q is a valid sequence of round brackets modulo 109 + 7.
Examples
Input
4 1
(
Output
4
Input
4 4
(())
Output
1
Input
4 3
(((
Output
0
Note
In the first sample there are four different valid pairs:
1. p = "(", q = "))"
2. p = "()", q = ")"
3. p = "", q = "())"
4. p = "", q = ")()"
In the second sample the only way to obtain a desired string is choose empty p and q.
In the third sample there is no way to get a valid sequence of brackets. | def ij(s):
i = 0
j = 0
for c in s:
if c == ')':
if j > 0:
j -= 1
else:
i += 1
else:
j += 1
return i, j
K = 10**9 + 7
def ways(n, s):
I, J = ij(s)
f = n - len(s) - I - J
if f < 0 or f%2:
return 0
E = f//2
if E == 0:
return 1
C = [1]
for n in range(E+max(I,J)+1):
C.append(C[n] * 2 * (2*n + 1) // (n+2))
W = [[c % K for c in C]]
W.append(W[0][1:])
for i in range(2, E+max(I,J)+1):
W.append([(W[i-1][e+1]-W[i-2][e+1]) % K
for e in range(E+max(I,J)+1-i+1)])
result = sum((W[I+k][e-k] * W[J+k][E-e]) % K
for k in range(E+1)
for e in range(k, E+1))
return result
if __name__ == '__main__':
n, m = map(int, input().split())
s = input()
print(ways(n, s) % K)
| {
"input": [
"4 4\n(())\n",
"4 1\n(\n",
"4 3\n(((\n"
],
"output": [
"1\n",
"4\n",
"0\n"
]
} |
3,018 | 10 | Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.
In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.
Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.
Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
Input
The first line contains three integers n, m and x (2 β€ n β€ 50, 1 β€ m β€ 500, 1 β€ x β€ 100 000) β the number of nodes, the number of directed edges and the number of bears, respectively.
Each of the following m lines contains three integers ai, bi and ci (1 β€ ai, bi β€ n, ai β bi, 1 β€ ci β€ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i β j it's guaranteed that ai β aj or bi β bj. It is also guaranteed that there is at least one path from node 1 to node n.
Output
Print one real value on a single line β the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your 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
4 4 3
1 2 2
2 4 1
1 3 1
3 4 2
Output
1.5000000000
Input
5 11 23
1 2 3
2 3 4
3 4 5
4 5 6
1 3 4
2 4 5
3 5 6
1 4 2
2 5 3
1 5 2
3 2 30
Output
10.2222222222
Note
In the first sample, Niwel has three bears. Two bears can choose the path <image>, while one bear can choose the path <image>. Even though the bear that goes on the path <image> can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day. | from collections import defaultdict, deque
adj = defaultdict(lambda: defaultdict(lambda: 0))
def bfs(graph, inicio, destino, parent):
parent.clear()
queue = deque()
queue.append([inicio, float("Inf")])
parent[inicio] = -2
while (len(queue)):
current, flow = queue.popleft()
for i in adj[current]:
if parent[i] == -1 and graph[current][i] > 0:
parent[i] = current
flow = min(flow, graph[current][i])
if i == destino:
return flow
queue.append((i, flow))
return 0
def maxflow(graph, inicio, destino):
flow = 0
parent = defaultdict(lambda: -1)
while True:
t = bfs(graph, inicio, destino, parent)
if t:
flow += t
current = destino
while current != inicio:
prev = parent[current]
graph[prev][current] -= t
graph[current][prev] += t
current = prev
else:
break
return flow
n, m, x = [int(i) for i in input().split()]
for _ in range(m):
t = [int(i) for i in input().split()]
adj[t[0]][t[1]] = t[2]
def check(k):
meh = defaultdict(lambda: defaultdict(lambda: 0))
for i in adj:
for j in adj[i]:
ww = adj[i][j] // k
meh[i][j] = ww
flow = maxflow(meh, 1, n)
return flow
lo = 1 / x
hi = check(1)
for _ in range(70):
mid = (hi + lo) / 2
if check(mid)>=x:
lo = mid
else:
hi = mid
print(format(lo * x, '.9f')) | {
"input": [
"4 4 3\n1 2 2\n2 4 1\n1 3 1\n3 4 2\n",
"5 11 23\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 3 4\n2 4 5\n3 5 6\n1 4 2\n2 5 3\n1 5 2\n3 2 30\n"
],
"output": [
"1.50000000000000000\n",
"10.22222222222222143\n"
]
} |
3,019 | 8 | Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X β the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X β€ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 β€ m β€ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers β the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7Β·13 = 27 + 8 + 7 = 42. | def g(m, n, s):
if not m: return n, s
k = int(m ** (1 / 3))
x, y = k ** 3, (k - 1) ** 3
return max(g(m - x, n + 1, s + x), g(x - y - 1, n + 1, s + y))
print(*g(int(input()), 0, 0)) | {
"input": [
"6\n",
"48\n"
],
"output": [
"6 6\n",
"9 42\n"
]
} |
3,020 | 9 | Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 β€ n β€ 100 000) β the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6. | from collections import defaultdict
di = defaultdict(int)
n = int(input())
s = input()
cn = len(set(s))
co = 0
def ad(a):
global co,di
if(di[s[a]] == 0):
co += 1
di[s[a]] += 1
return
def re(a):
global co,di
di[s[a]] -= 1
if(di[s[a]] == 0):
co -= 1
return
ad(0)
po = 0
ma = n
for i in range(n):
while(co < cn):
if(po == n-1):
break
po += 1
ad(po)
if(co == cn):
ma = min(ma,po - i + 1)
re(i)
print(ma) | {
"input": [
"6\naaBCCe\n",
"7\nbcAAcbc\n",
"3\nAaA\n"
],
"output": [
"5",
"3",
"2"
]
} |
3,021 | 10 | The map of Berland is a rectangle of the size n Γ m, which consists of cells of size 1 Γ 1. Each cell is either land or water. The map is surrounded by the ocean.
Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.
You task is to fill up with the earth the minimum number of water cells so that there will be exactly k lakes in Berland. Note that the initial number of lakes on the map is not less than k.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 50, 0 β€ k β€ 50) β the sizes of the map and the number of lakes which should be left on the map.
The next n lines contain m characters each β the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land).
It is guaranteed that the map contain at least k lakes.
Output
In the first line print the minimum number of cells which should be transformed from water to land.
In the next n lines print m symbols β the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them.
It is guaranteed that the answer exists on the given data.
Examples
Input
5 4 1
****
*..*
****
**.*
..**
Output
1
****
*..*
****
****
..**
Input
3 3 0
***
*.*
***
Output
1
***
***
***
Note
In the first example there are only two lakes β the first consists of the cells (2, 2) and (2, 3), the second consists of the cell (4, 3). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean. | x,y,k=list(map(int,input().split()))
a=[input().strip() for i in range(x)]
m=[[0 if j=='*' else 1 for j in i] for i in a]
m1=[[0 if j=='*' else 1 for j in i] for i in a]
lk=[]
def bfs(m,i,j):
q=set()
s=0
f=1
q.add((i,j))
while q:
ax,ay=q.pop()
m[ax][ay]=0
s+=1
if ax==0 or ay==0 or ax==x-1 or ay==y-1:f=0
if ax<x-1 and m[ax+1][ay]:
q.add((ax+1,ay))
if ax>0 and m[ax-1][ay]:
q.add((ax-1,ay))
if ay<y-1 and m[ax][ay+1]:
q.add((ax,ay+1))
if ay>0 and m[ax][ay-1]:
q.add((ax,ay-1))
return f,s
for i in range(x):
for j in range(y):
if m1[i][j]:
f,s=bfs(m1,i,j)
if f:
lk.append((s,i,j))
lk.sort()
k1=len(lk)
sal=0
for e in range(k1-k):
s,i,j=lk[e]
sal+=s
bfs(m,i,j)
print(sal)
for i in range(x):
print(''.join(['.' if j else '*' for j in m[i]]))
| {
"input": [
"5 4 1\n****\n*..*\n****\n**.*\n..**\n",
"3 3 0\n***\n*.*\n***\n"
],
"output": [
"1\n****\n*..*\n****\n****\n..**\n",
"1\n***\n***\n***\n"
]
} |
3,022 | 9 | Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 β€ n β€ 1 000, 0 β€ m β€ 100 000, 1 β€ k β€ n) β the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 β€ ci β€ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 β€ ui, vi β€ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple. | def cin():
return list(map(int, input().split()))
def dfs(n):
if not C[n]:
C[n]=True
s[0]+=1
for i in B[n]:
if not C[i]:dfs(i)
n,m,k=cin()
A=cin()
A=[i-1 for i in A]
B=[list([]) for i in range(n)]
C=[False for i in range(n)]
ans=mx=0
for i in range(m):
a,b=[i-1 for i in cin()]
B[a].append(b)
B[b].append(a)
for i in range(k):
s=[0]
dfs(A[i])
ans+=s[0]*(s[0]-1)//2
mx=max(mx,s[0])
ans-=mx*(mx-1)//2
for i in range(n):
if not C[i]:
s=[0]
dfs(i)
mx+=s[0]
print(ans-m+mx*(mx-1)//2)
# Made By Mostafa_Khaled | {
"input": [
"4 1 2\n1 3\n1 2\n",
"3 3 1\n2\n1 2\n1 3\n2 3\n"
],
"output": [
"2",
"0"
]
} |
3,023 | 11 | Sam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple:
* The game starts with n piles of stones indexed from 1 to n. The i-th pile contains si stones.
* The players make their moves alternatively. A move is considered as removal of some number of stones from a pile. Removal of 0 stones does not count as a move.
* The player who is unable to make a move loses.
Now Jon believes that he is ready for battle, but Sam does not think so. To prove his argument, Sam suggested that they play a modified version of the game.
In this modified version, no move can be made more than once on a pile. For example, if 4 stones are removed from a pile, 4 stones cannot be removed from that pile again.
Sam sets up the game and makes the first move. Jon believes that Sam is just trying to prevent him from going to battle. Jon wants to know if he can win if both play optimally.
Input
First line consists of a single integer n (1 β€ n β€ 106) β the number of piles.
Each of next n lines contains an integer si (1 β€ si β€ 60) β the number of stones in i-th pile.
Output
Print a single line containing "YES" (without quotes) if Jon wins, otherwise print "NO" (without quotes)
Examples
Input
1
5
Output
NO
Input
2
1
2
Output
YES
Note
In the first case, Sam removes all the stones and Jon loses.
In second case, the following moves are possible by Sam: <image>
In each of these cases, last move can be made by Jon to win the game as follows: <image> | from math import ceil
from sys import stdin, stdout
def f(v):
return ceil(((9 + 8 * v) ** 0.5 - 3) / 2)
n, x = int(stdin.readline()), 0
for i in range(n):
x ^= f(int(stdin.readline()))
stdout.write("NO" if x else "YES")
| {
"input": [
"1\n5\n",
"2\n1\n2\n"
],
"output": [
"NO\n",
"YES\n"
]
} |
3,024 | 10 | T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.
In the picture you can see a complete binary tree with n = 15.
<image>
Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.
You have to write a program that for given n answers q queries to the tree.
Each query consists of an integer number ui (1 β€ ui β€ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.
For example, if ui = 4 and si = Β«UURLΒ», then the answer is 10.
Input
The first line contains two integer numbers n and q (1 β€ n β€ 1018, q β₯ 1). n is such that n + 1 is a power of 2.
The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 β€ ui β€ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'.
It is guaranteed that the sum of lengths of si (for each i such that 1 β€ i β€ q) doesn't exceed 105.
Output
Print q numbers, i-th number must be the answer to the i-th query.
Example
Input
15 2
4
UURL
8
LRLLLLLLLL
Output
10
5 | def maxx(n):
return n&-n
n,q=map(int,input().split())
root=n//2+1
while q>0:
x=int(input())
s=input()
for i in s:
if i=='U' and x!=root:
p=x+maxx(x)
if x==p-maxx(p)//2:
x=p
else:
x=x-maxx(x)
elif i=='L':
x=x-maxx(x)//2
elif i=='R':
x=x+maxx(x)//2
q=q-1
print(x) | {
"input": [
"15 2\n4\nUURL\n8\nLRLLLLLLLL\n"
],
"output": [
"10\n5\n"
]
} |
3,025 | 7 | Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!
This contest consists of n problems, and Pasha solves ith problem in ai time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. Pasha can send any number of solutions at the same moment.
Unfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during m time periods, jth period is represented by its starting moment lj and ending moment rj. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment T iff there exists a period x such that lx β€ T β€ rx.
Pasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have solutions to all problems submitted, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems.
Input
The first line contains one integer n (1 β€ n β€ 1000) β the number of problems. The second line contains n integers ai (1 β€ ai β€ 105) β the time Pasha needs to solve ith problem.
The third line contains one integer m (0 β€ m β€ 1000) β the number of periods of time when the website is working. Next m lines represent these periods. jth line contains two numbers lj and rj (1 β€ lj < rj β€ 105) β the starting and the ending moment of jth period.
It is guaranteed that the periods are not intersecting and are given in chronological order, so for every j > 1 the condition lj > rj - 1 is met.
Output
If Pasha can solve and submit all the problems before the end of the contest, print the minimal moment of time by which he can have all the solutions submitted.
Otherwise print "-1" (without brackets).
Examples
Input
2
3 4
2
1 4
7 9
Output
7
Input
1
5
1
1 4
Output
-1
Input
1
5
1
1 5
Output
5
Note
In the first example Pasha can act like this: he solves the second problem in 4 units of time and sends it immediately. Then he spends 3 time units to solve the first problem and sends it 7 time units after the contest starts, because at this moment the website starts working again.
In the second example Pasha invents the solution only after the website stops working for the last time.
In the third example Pasha sends the solution exactly at the end of the first period. | def solve():
n = int(input())
a = [int(s) for s in input().split(' ')]
x = sum(a)
m = int(input())
u = [tuple([int(x) for x in input().split(' ')]) for i in range(m)]
for l, r in u:
if r >= x:
return max(l, x)
return - 1
print(solve())
| {
"input": [
"2\n3 4\n2\n1 4\n7 9\n",
"1\n5\n1\n1 5\n",
"1\n5\n1\n1 4\n"
],
"output": [
"7",
"5",
"-1\n"
]
} |
3,026 | 9 | You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be eaten by just one person.
The way Alice and Bob decide who eats each slice is as follows. First, the order in which the pies are to be handed out is decided. There is a special token called the "decider" token, initially held by Bob. Until all the pie is handed out, whoever has the decider token will give the next slice of pie to one of the participants, and the decider token to the other participant. They continue until no slices of pie are left.
All of the slices are of excellent quality, so each participant obviously wants to maximize the total amount of pie they get to eat. Assuming both players make their decisions optimally, how much pie will each participant receive?
Input
Input will begin with an integer N (1 β€ N β€ 50), the number of slices of pie.
Following this is a line with N integers indicating the sizes of the slices (each between 1 and 100000, inclusive), in the order in which they must be handed out.
Output
Print two integers. First, the sum of the sizes of slices eaten by Alice, then the sum of the sizes of the slices eaten by Bob, assuming both players make their decisions optimally.
Examples
Input
3
141 592 653
Output
653 733
Input
5
10 21 10 21 10
Output
31 41
Note
In the first example, Bob takes the size 141 slice for himself and gives the decider token to Alice. Then Alice gives the size 592 slice to Bob and keeps the decider token for herself, so that she can then give the size 653 slice to herself. | def do(n,l):
if n==1:
return [l[0],0]
a=do(n-1,l[1:n])
if a[1]+l[0]>a[0]:
return [a[1]+l[0],a[0]]
return [a[0],a[1]+l[0]]
n=int(input())
l=list(map(int,input().split()))
lsp=do(n,l)
lsp.sort()
print(lsp[0],lsp[1])
| {
"input": [
"5\n10 21 10 21 10\n",
"3\n141 592 653\n"
],
"output": [
"31 41\n",
"653 733\n"
]
} |
3,027 | 8 | A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect.
For example:
* If x = 6 and the crossword is 111011, then its encoding is an array {3, 2};
* If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1};
* If x = 5 and the crossword is 11111, then its encoding is an array {5};
* If x = 5 and the crossword is 00000, then its encoding is an empty array.
Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!
Input
The first line contains two integer numbers n and x (1 β€ n β€ 100000, 1 β€ x β€ 109) β the number of elements in the encoding and the length of the crossword Mishka picked.
The second line contains n integer numbers a1, a2, ..., an (1 β€ ai β€ 10000) β the encoding.
Output
Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO.
Examples
Input
2 4
1 3
Output
NO
Input
3 10
3 3 2
Output
YES
Input
2 10
1 3
Output
NO | def main():
n, x = map(int, input().split())
a = list(map(int, input().split()))
s = sum(a)
print('YES' if s + (n - 1) == x else 'NO')
main()
| {
"input": [
"2 4\n1 3\n",
"3 10\n3 3 2\n",
"2 10\n1 3\n"
],
"output": [
"NO\n",
"YES\n",
"NO\n"
]
} |
3,028 | 10 | You are given three integers k, pa and pb.
You will construct a sequence with the following algorithm: Initially, start with the empty sequence. Each second, you do the following. With probability pa / (pa + pb), add 'a' to the end of the sequence. Otherwise (with probability pb / (pa + pb)), add 'b' to the end of the sequence.
You stop once there are at least k subsequences that form 'ab'. Determine the expected number of times 'ab' is a subsequence in the resulting sequence. It can be shown that this can be represented by P / Q, where P and Q are coprime integers, and <image>. Print the value of <image>.
Input
The first line will contain three integers integer k, pa, pb (1 β€ k β€ 1 000, 1 β€ pa, pb β€ 1 000 000).
Output
Print a single integer, the answer to the problem.
Examples
Input
1 1 1
Output
2
Input
3 1 4
Output
370000006
Note
The first sample, we will keep appending to our sequence until we get the subsequence 'ab' at least once. For instance, we get the sequence 'ab' with probability 1/4, 'bbab' with probability 1/16, and 'aab' with probability 1/8. Note, it's impossible for us to end with a sequence like 'aabab', since we would have stopped our algorithm once we had the prefix 'aab'.
The expected amount of times that 'ab' will occur across all valid sequences is 2.
For the second sample, the answer is equal to <image>. | mod = 1000000007
N = 1005
#input start
k,pa,pb = map(int,input().split())
dp = [[0 for x in range(N)] for y in range(N)]
#end of input
def fast_expo(a,b):
ret = 1
while b:
if b%2==1:
ret = ret*a%mod
b //= 2
a = a*a%mod
return ret
def inv(x):
return fast_expo(x,mod-2)%mod
def dp_val(a,b):
if b>=k:
return b
return dp[a][b]
for i in range(k):
dp[k][i] = (i+k+pa*inv(pb))%mod
den = inv(pa+pb)
for i in range(k-1,0,-1):
for j in range(k-1,-1,-1):
dp[i][j] = pa*dp_val(i+1,j)*den%mod+pb*dp_val(i,i+j)*den%mod
dp[i][j]%=mod
print(dp[1][0])
| {
"input": [
"1 1 1\n",
"3 1 4\n"
],
"output": [
"2\n",
"370000006\n"
]
} |
3,029 | 9 | A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.
For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".
Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?
Input
The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1 β€ |s1| β€ 104, 1 β€ |s2| β€ 106).
Output
If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.
Examples
Input
abc
xyz
Output
-1
Input
abcd
dabc
Output
2 | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
s = [ord(c) - 97 for c in input().rstrip()]
t = [ord(c) - 97 for c in input().rstrip()]
n, m = len(s), len(t)
next_c = [[-1] * 26 for _ in range(n)]
for _ in range(2):
for i in range(n - 1, -1, -1):
for cc in range(26):
next_c[i][cc] = next_c[(i + 1) % n][cc]
next_c[i][s[(i + 1) % n]] = (i + 1) % n
j = n - 1
ans = 0
for i, cc in enumerate(t):
k = next_c[j][cc]
if k == -1:
print(-1)
exit()
if j >= k:
ans += 1
j = k
print(ans)
| {
"input": [
"abcd\ndabc\n",
"abc\nxyz\n"
],
"output": [
"2\n",
"-1\n"
]
} |
3,030 | 8 | The Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect some of them.
The Resistance already has measures in place that will, when the time is right, enable them to control every planet that is not remote. A planet is considered to be remote if it is connected to the rest of the planets only via a single hyperspace tunnel.
How much work is there left to be done: that is, how many remote planets are there?
Input
The first line of the input contains an integer N (2 β€ N β€ 1000) β the number of planets in the galaxy.
The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 β€ u, v β€ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
Output
A single integer denoting the number of remote planets.
Examples
Input
5
4 1
4 2
1 3
1 5
Output
3
Input
4
1 2
4 3
1 4
Output
2
Note
In the first example, only planets 2, 3 and 5 are connected by a single tunnel.
In the second example, the remote planets are 2 and 3.
Note that this problem has only two versions β easy and medium. | occur = set()
remove = set()
def cek(x):
global occur, remove
if x in occur:
remove.add(x)
else:
occur.add(x)
for _ in range(int(input()) - 1):
a, b = map(int, input().split())
cek(a)
cek(b)
print(len(occur - remove))
| {
"input": [
"4\n1 2\n4 3\n1 4\n",
"5\n4 1\n4 2\n1 3\n1 5\n"
],
"output": [
"2\n",
"3\n"
]
} |
3,031 | 9 | You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.
Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.
According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.
The elevator has two commands:
* Go up or down one floor. The movement takes 1 second.
* Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator.
Initially the elevator is empty and is located on the floor 1.
You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
Input
The first line contains an integer n (1 β€ n β€ 2000) β the number of employees.
The i-th of the next n lines contains two integers ai and bi (1 β€ ai, bi β€ 9, ai β bi) β the floor on which an employee initially is, and the floor he wants to reach.
The employees are given in the order they came to the elevator.
Output
Print a single integer β the minimal possible time in seconds.
Examples
Input
2
3 5
5 3
Output
10
Input
2
5 3
3 5
Output
12
Note
Explaination for the first sample <image> t = 0
<image> t = 2
<image> t = 3
<image> t = 5
<image> t = 6
<image> t = 7
<image> t = 9
<image> t = 10 | # python3
import sys
from collections import namedtuple
def readline(): return map(int, input().split())
def readlines():
for line in sys.stdin.readlines():
yield map(int, line.split())
class State(namedtuple('State', 'payload time floor')):
def hook(self, pivot, a, b):
lo, up = min(pivot, a, self.floor), max(pivot, a, self.floor)
return tuple(x for x in self.payload if x < lo or up < x) + (b,), \
self.time + abs(self.floor - pivot) + abs(pivot - a)
def choices_to_take_next(self, a, b):
floor = self.floor
payload, time = self.hook(floor, a, b)
if len(payload) < 5:
yield payload, time
if floor > a:
pivots = (x for x in self.payload if x > floor)
elif floor == a:
pivots = ()
else:
pivots = (x for x in self.payload if x < floor)
else:
pivots = self.payload
for pivot in pivots:
yield self.hook(pivot, a, b)
def time_to_get_free(payload, floor):
if payload:
lo, up = min(payload), max(payload)
return abs(lo-up) + min(abs(floor-lo), abs(floor-up))
else:
return 0
def main():
n, = readline()
floor = 1
positions = {(): 0} # empty elevator, time = 0
for (a, b) in readlines():
max_acceptable_time = min(positions.values()) + 16 - abs(floor - a)
new_positions = dict()
for payload, time in positions.items():
state = State(payload, time, floor)
for npayload, ntime in state.choices_to_take_next(a, b):
if ntime <= max_acceptable_time:
npayload = tuple(sorted(npayload))
if new_positions.setdefault(npayload, ntime) > ntime:
new_positions[npayload] = ntime
positions = new_positions
floor = a
return min(t + time_to_get_free(p, floor) for p, t in positions.items()) \
+ 2 * n
print(main())
| {
"input": [
"2\n5 3\n3 5\n",
"2\n3 5\n5 3\n"
],
"output": [
"12\n",
"10\n"
]
} |
3,032 | 7 | Panic is rising in the committee for doggo standardization β the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.
The committee rules strictly prohibit even the smallest diversity between doggos and hence all the puppies should be of the same color. Thus Slava, the committee employee, has been assigned the task to recolor some puppies into other colors in order to eliminate the difference and make all the puppies have one common color.
Unfortunately, due to bureaucratic reasons and restricted budget, there's only one operation Slava can perform: he can choose a color x such that there are currently at least two puppies of color x and recolor all puppies of the color x into some arbitrary color y. Luckily, this operation can be applied multiple times (including zero).
For example, if the number of puppies is 7 and their colors are represented as the string "abababc", then in one operation Slava can get the results "zbzbzbc", "bbbbbbc", "aaaaaac", "acacacc" and others. However, if the current color sequence is "abababc", then he can't choose x='c' right now, because currently only one puppy has the color 'c'.
Help Slava and the committee determine whether it is possible to standardize all the puppies, i.e. after Slava's operations all the puppies should have the same color.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of puppies.
The second line contains a string s of length n consisting of lowercase Latin letters, where the i-th symbol denotes the i-th puppy's color.
Output
If it's possible to recolor all puppies into one color, print "Yes".
Otherwise print "No".
Output the answer without quotation signs.
Examples
Input
6
aabddc
Output
Yes
Input
3
abc
Output
No
Input
3
jjj
Output
Yes
Note
In the first example Slava can perform the following steps:
1. take all puppies of color 'a' (a total of two) and recolor them into 'b';
2. take all puppies of color 'd' (a total of two) and recolor them into 'c';
3. take all puppies of color 'b' (three puppies for now) and recolor them into 'c'.
In the second example it's impossible to recolor any of the puppies.
In the third example all the puppies' colors are the same; thus there's no need to recolor anything. | def main():
n = int(input())
puppies = dict.fromkeys(input())
print('NO' if 1 < n == len(puppies) else 'YES')
if __name__ == '__main__':
main()
| {
"input": [
"6\naabddc\n",
"3\nabc\n",
"3\njjj\n"
],
"output": [
"Yes\n",
"No\n",
"Yes\n"
]
} |
3,033 | 9 | Ivan is a novice painter. He has n dyes of different colors. He also knows exactly m pairs of colors which harmonize with each other.
Ivan also enjoy playing chess. He has 5000 rooks. He wants to take k rooks, paint each of them in one of n colors and then place this k rooks on a chessboard of size 10^{9} Γ 10^{9}.
Let's call the set of rooks on the board connected if from any rook we can get to any other rook in this set moving only through cells with rooks from this set. Assume that rooks can jump over other rooks, in other words a rook can go to any cell which shares vertical and to any cell which shares horizontal.
Ivan wants his arrangement of rooks to have following properties:
* For any color there is a rook of this color on a board;
* For any color the set of rooks of this color is connected;
* For any two different colors a b union of set of rooks of color a and set of rooks of color b is connected if and only if this two colors harmonize with each other.
Please help Ivan find such an arrangement.
Input
The first line of input contains 2 integers n, m (1 β€ n β€ 100, 0 β€ m β€ min(1000, (n(n-1))/(2))) β number of colors and number of pairs of colors which harmonize with each other.
In next m lines pairs of colors which harmonize with each other are listed. Colors are numbered from 1 to n. It is guaranteed that no pair occurs twice in this list.
Output
Print n blocks, i-th of them describes rooks of i-th color.
In the first line of block print one number a_{i} (1 β€ a_{i} β€ 5000) β number of rooks of color i. In each of next a_{i} lines print two integers x and y (1 β€ x, y β€ 10^{9}) β coordinates of the next rook.
All rooks must be on different cells.
Total number of rooks must not exceed 5000.
It is guaranteed that the solution exists.
Examples
Input
3 2
1 2
2 3
Output
2
3 4
1 4
4
1 2
2 2
2 4
5 4
1
5 1
Input
3 3
1 2
2 3
3 1
Output
1
1 1
1
1 2
1
1 3
Input
3 1
1 3
Output
1
1 1
1
2 2
1
3 1
Note
Rooks arrangements for all three examples (red is color 1, green is color 2 and blue is color 3).
<image>
<image>
<image> | import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n, m = mints()
a = []
p = [None]*n
for i in range(n):
p[i] = []
for i in range(m):
x, y = mints()
p[x-1].append((i+1,x))
p[y-1].append((i+1,y))
for i in range(n):
p[i].append((m+1+i,i+1))
for i in range(n):
print(len(p[i]))
for j in p[i]:
print(*j) | {
"input": [
"3 1\n1 3\n",
"3 3\n1 2\n2 3\n3 1\n",
"3 2\n1 2\n2 3\n"
],
"output": [
"2\n1 1\n1 4\n1\n2 2\n2\n3 3\n3 4\n",
"2\n1 1\n1 3\n2\n2 1\n2 2\n2\n3 2\n3 3\n",
"1\n1 1\n2\n2 1\n2 2\n1\n3 2\n"
]
} |
3,034 | 7 | A conglomerate consists of n companies. To make managing easier, their owners have decided to merge all companies into one. By law, it is only possible to merge two companies, so the owners plan to select two companies, merge them into one, and continue doing so until there is only one company left.
But anti-monopoly service forbids to merge companies if they suspect unfriendly absorption. The criterion they use is the difference in maximum salaries between two companies. Merging is allowed only if the maximum salaries are equal.
To fulfill the anti-monopoly requirements, the owners can change salaries in their companies before merging. But the labor union insists on two conditions: it is only allowed to increase salaries, moreover all the employees in one company must get the same increase.
Sure enough, the owners want to minimize the total increase of all salaries in all companies. Help them find the minimal possible increase that will allow them to merge companies into one.
Input
The first line contains a single integer n β the number of companies in the conglomerate (1 β€ n β€ 2 β
10^5). Each of the next n lines describes a company.
A company description start with an integer m_i β the number of its employees (1 β€ m_i β€ 2 β
10^5). Then m_i integers follow: the salaries of the employees. All salaries are positive and do not exceed 10^9.
The total number of employees in all companies does not exceed 2 β
10^5.
Output
Output a single integer β the minimal total increase of all employees that allows to merge all companies.
Example
Input
3
2 4 3
2 2 1
3 1 1 1
Output
13
Note
One of the optimal merging strategies is the following. First increase all salaries in the second company by 2, and merge the first and the second companies. Now the conglomerate consists of two companies with salaries [4, 3, 4, 3] and [1, 1, 1]. To merge them, increase the salaries in the second of those by 3. The total increase is 2 + 2 + 3 + 3 + 3 = 13. | def f():
v = list(map(int, input().split()))
return v[0], max(v[1:])
n = int(input())
a = [f() for _ in range(n)]
x = 0
for v in a:
x = max(x, v[1])
s = 0
for v in a:
s += (x - v[1]) * v[0]
print(s)
| {
"input": [
"3\n2 4 3\n2 2 1\n3 1 1 1\n"
],
"output": [
"13"
]
} |
3,035 | 8 | You went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock.
You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 β€ x_i β€ a_i), then for all 1 β€ j < i at least one of the following must hold:
* x_j = 0 (you bought zero chocolates of type j)
* x_j < x_i (you bought less chocolates of type j than of type i)
For example, the array x = [0, 0, 1, 2, 10] satisfies the requirement above (assuming that all a_i β₯ x_i), while arrays x = [0, 1, 0], x = [5, 5] and x = [3, 2] don't.
Calculate the maximum number of chocolates you can buy.
Input
The first line contains an integer n (1 β€ n β€ 2 β
10^5), denoting the number of types of chocolate.
The next line contains n integers a_i (1 β€ a_i β€ 10^9), denoting the number of chocolates of each type.
Output
Print the maximum number of chocolates you can buy.
Examples
Input
5
1 2 1 3 6
Output
10
Input
5
3 2 5 4 10
Output
20
Input
4
1 1 1 1
Output
1
Note
In the first example, it is optimal to buy: 0 + 0 + 1 + 3 + 6 chocolates.
In the second example, it is optimal to buy: 1 + 2 + 3 + 4 + 10 chocolates.
In the third example, it is optimal to buy: 0 + 0 + 0 + 1 chocolates. | def solve(xs):
last = xs[-1]
count = xs[-1]
for x in xs[-2::-1]:
last = max(0, min(x, last - 1))
count += last
return count
n = int(input())
xs = list(map(int, input().split()))[:n]
print(solve(xs)) | {
"input": [
"4\n1 1 1 1\n",
"5\n3 2 5 4 10\n",
"5\n1 2 1 3 6\n"
],
"output": [
"1",
"20",
"10"
]
} |
3,036 | 9 | The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).
You are given a sequence a consisting of n integers. All these integers are distinct, each value from 1 to n appears in the sequence exactly once.
You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).
For example, for the sequence [2, 1, 5, 4, 3] the answer is 4 (you take 2 and the sequence becomes [1, 5, 4, 3], then you take the rightmost element 3 and the sequence becomes [1, 5, 4], then you take 4 and the sequence becomes [1, 5] and then you take 5 and the sequence becomes [1], the obtained increasing sequence is [2, 3, 4, 5]).
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ n), where a_i is the i-th element of a. All these integers are pairwise distinct.
Output
In the first line of the output print k β the maximum number of elements in a strictly increasing sequence you can obtain.
In the second line print a string s of length k, where the j-th character of this string s_j should be 'L' if you take the leftmost element during the j-th move and 'R' otherwise. If there are multiple answers, you can print any.
Examples
Input
5
2 1 5 4 3
Output
4
LRRR
Input
7
1 3 5 6 7 4 2
Output
7
LRLRLLL
Input
3
1 2 3
Output
3
LLL
Input
4
1 2 4 3
Output
4
LLRL
Note
The first example is described in the problem statement. | def fun(a,n):
ans=''
last=-1
l,r=0,n-1
while l<=r:
if a[l]<a[r] and a[l]>last:
ans+='L'
last=a[l]
l+=1
elif a[r]<a[l] and a[r]>last:
ans+='R'
last=a[r]
r-=1
elif a[r]>last:
ans+='R'
last=a[r]
r-=1
elif a[l]>last:
ans+='L'
last=a[l]
l+=1
else:
break
print(len(ans))
print(ans)
n=int(input())
a=list(map(int,input().split( )))
fun(a,n) | {
"input": [
"7\n1 3 5 6 7 4 2\n",
"5\n2 1 5 4 3\n",
"4\n1 2 4 3\n",
"3\n1 2 3\n"
],
"output": [
"7\nLRLRLLL\n\n",
"4\nLRRR\n\n",
"4\nLLRL\n\n",
"3\nLLL\n\n"
]
} |
3,037 | 7 | You are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y?
Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime numbers starts with 2, 3, 5, 7, 11.
Your program should solve t independent test cases.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of test cases.
Then t lines follow, each describing a test case. Each line contains two integers x and y (1 β€ y < x β€ 10^{18}).
Output
For each test case, print YES if it is possible to choose a prime number p and subtract it any number of times from x so that x becomes equal to y. Otherwise, print NO.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answer).
Example
Input
4
100 98
42 32
1000000000000000000 1
41 40
Output
YES
YES
YES
NO
Note
In the first test of the example you may choose p = 2 and subtract it once.
In the second test of the example you may choose p = 5 and subtract it twice. Note that you cannot choose p = 7, subtract it, then choose p = 3 and subtract it again.
In the third test of the example you may choose p = 3 and subtract it 333333333333333333 times. | def f():
n = int(input())
for _ in range(n):
a,b = map(int, input().split())
print("YES" if a-b > 1 else "NO")
f() | {
"input": [
"4\n100 98\n42 32\n1000000000000000000 1\n41 40\n"
],
"output": [
"YES\nYES\nYES\nNO\n"
]
} |
3,038 | 8 | You are given a permutation of length n. Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (n=3 but there is 4 in the array).
You can perform at most n-1 operations with the given permutation (it is possible that you don't perform any operations at all). The i-th operation allows you to swap elements of the given permutation on positions i and i+1. Each operation can be performed at most once. The operations can be performed in arbitrary order.
Your task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order.
You can see the definition of the lexicographical order in the notes section.
You have to answer q independent test cases.
For example, let's consider the permutation [5, 4, 1, 3, 2]. The minimum possible permutation we can obtain is [1, 5, 2, 4, 3] and we can do it in the following way:
1. perform the second operation (swap the second and the third elements) and obtain the permutation [5, 1, 4, 3, 2];
2. perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation [5, 1, 4, 2, 3];
3. perform the third operation (swap the third and the fourth elements) and obtain the permutation [5, 1, 2, 4, 3].
4. perform the first operation (swap the first and the second elements) and obtain the permutation [1, 5, 2, 4, 3];
Another example is [1, 2, 4, 3]. The minimum possible permutation we can obtain is [1, 2, 3, 4] by performing the third operation (swap the third and the fourth elements).
Input
The first line of the input contains one integer q (1 β€ q β€ 100) β the number of test cases. Then q test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 100) β the number of elements in the permutation.
The second line of the test case contains n distinct integers from 1 to n β the given permutation.
Output
For each test case, print the answer on it β the lexicograhically minimum possible permutation obtained by performing some of the given operations in some order.
Example
Input
4
5
5 4 1 3 2
4
1 2 4 3
1
1
4
4 3 2 1
Output
1 5 2 4 3
1 2 3 4
1
1 4 3 2
Note
Recall that the permutation p of length n is lexicographically less than the permutation q of length n if there is such index i β€ n that for all j from 1 to i - 1 the condition p_j = q_j is satisfied, and p_i < q_i. For example:
* p = [1, 3, 5, 2, 4] is less than q = [1, 3, 5, 4, 2] (such i=4 exists, that p_i < q_i and for each j < i holds p_j = q_j),
* p = [1, 2] is less than q = [2, 1] (such i=1 exists, that p_i < q_i and for each j < i holds p_j = q_j). | def dequy(a):
if (len(a) == 1):
return a
x = min(a)
k = a.index(x)
if (k == 0):
return [a[0]]+dequy(a[1:])
return [x]+a[:k-1]+dequy([a[k-1]]+a[k+1:])
for tc in range(int(input())):
n = int(input())
a = dequy(list(map(int,input().split())))
for i in a:
print(i,end = ' ')
print() | {
"input": [
"4\n5\n5 4 1 3 2\n4\n1 2 4 3\n1\n1\n4\n4 3 2 1\n"
],
"output": [
"1 5 2 4 3 \n1 2 3 4 \n1 \n1 4 3 2 \n"
]
} |
3,039 | 8 | Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with.
Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h Γ w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.
Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 β€ ai β€ 100).
Output
Print the single number β the maximum number of frames Nicholas can make for his future canvases.
Examples
Input
5
2 4 3 2 3
Output
1
Input
13
2 2 4 4 4 4 6 6 6 7 7 9 9
Output
3
Input
4
3 3 3 5
Output
0 | def arr_inp():
return [int(x) for x in input().split()]
from collections import *
n, a = int(input()), arr_inp()
c = Counter(a)
# print(c)
print(int(sum(list(map(lambda x:x//2, c.values())))//2))
| {
"input": [
"5\n2 4 3 2 3\n",
"13\n2 2 4 4 4 4 6 6 6 7 7 9 9\n",
"4\n3 3 3 5\n"
],
"output": [
"1",
"3",
"0"
]
} |
3,040 | 7 | There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage, he penetrated into the Potatoland territory and reached the secret base.
Now he is standing at the entrance, but to get inside he need to pass combination lock. Minute ago one of the workers entered the password on the terminal and opened the door. The terminal is a square digital keyboard 3 Γ 3 with digits from 1 to 9.
Pearlo knows that the password consists from distinct digits and is probably symmetric with respect to the central button of the terminal. He has heat sensor which allowed him to detect the digits which the worker pressed. Now he wants to check whether the password entered by the worker is symmetric with respect to the central button of the terminal. This fact can Help Pearlo to reduce the number of different possible password combinations.
Input
Input contains the matrix of three rows of three symbols each. Symbol Β«XΒ» means that the corresponding button was pressed, and Β«.Β» means that is was not pressed. The matrix may contain no Β«XΒ», also it may contain no Β«.Β».
Output
Print YES if the password is symmetric with respect to the central button of the terminal and NO otherwise.
Examples
Input
XX.
...
.XX
Output
YES
Input
X.X
X..
...
Output
NO
Note
If you are not familiar with the term Β«central symmetryΒ», you may look into http://en.wikipedia.org/wiki/Central_symmetry | import sys
def main():
s = sys.stdin.read().strip()
return ('NO', 'YES')[s == s[::-1]]
print(main())
| {
"input": [
"X.X\nX..\n...\n",
"XX.\n...\n.XX\n"
],
"output": [
"NO\n",
"YES\n"
]
} |
3,041 | 9 | A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.
Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.
The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes l nanoseconds, where l is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 2 nanoseconds).
Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
Input
The first line contains a single integer n (1 β€ n β€ 10^6) β the length of Dima's sequence.
The second line contains string of length n, consisting of characters "(" and ")" only.
Output
Print a single integer β the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.
Examples
Input
8
))((())(
Output
6
Input
3
(()
Output
-1
Note
In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is 4 + 2 = 6 nanoseconds. | def solve(S):
res = s = 0
last_non_neg = -2
for i, c in enumerate(S):
s += 1 if c == '(' else -1
if s < 0:
if last_non_neg == -2:
last_non_neg = i-1
elif s == 0:
if last_non_neg != -2:
res += i-last_non_neg
last_non_neg = -2
return res if s == 0 else -1
input()
s = input().strip()
print(solve(s)) | {
"input": [
"8\n))((())(\n",
"3\n(()\n"
],
"output": [
"6\n",
"-1\n"
]
} |
3,042 | 8 | Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property.
Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=4.
You are given string t consisting only of 0's and 1's and you need to find such string s that:
1. String s consists only of 0's and 1's;
2. The length of s doesn't exceed 2 β
|t|;
3. String t is a subsequence of string s;
4. String s has smallest possible period among all strings that meet conditions 1β3.
Let us recall that t is a subsequence of s if t can be derived from s by deleting zero or more elements (any) without changing the order of the remaining elements. For example, t="011" is a subsequence of s="10101".
Input
The first line contains single integer T (1 β€ T β€ 100) β the number of test cases.
Next T lines contain test cases β one per line. Each line contains string t (1 β€ |t| β€ 100) consisting only of 0's and 1's.
Output
Print one string for each test case β string s you needed to find. If there are multiple solutions print any one of them.
Example
Input
4
00
01
111
110
Output
00
01
11111
1010
Note
In the first and second test cases, s = t since it's already one of the optimal solutions. Answers have periods equal to 1 and 2, respectively.
In the third test case, there are shorter optimal solutions, but it's okay since we don't need to minimize the string s. String s has period equal to 1. | I = input
pr = print
def main():
for _ in range(int(I())):
s=I()
if {*s}>{'0'}:
pr('01'*len(s))
else:pr(s)
main() | {
"input": [
"4\n00\n01\n111\n110\n"
],
"output": [
"00\n01\n111\n1010\n"
]
} |
3,043 | 8 | Given a permutation p of length n, find its subsequence s_1, s_2, β¦, s_k of length at least 2 such that:
* |s_1-s_2|+|s_2-s_3|+β¦+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2.
* Among all such subsequences, choose the one whose length, k, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence a is a subsequence of an array b if a can be obtained from b by deleting some (possibly, zero or all) elements.
A permutation of length n is an array of length n in which every element from 1 to n occurs exactly once.
Input
The first line contains an integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer n (2 β€ n β€ 10^5) β the length of the permutation p.
The second line of each test case contains n integers p_1, p_2, β¦, p_{n} (1 β€ p_i β€ n, p_i are distinct) β the elements of the permutation p.
The sum of n across the test cases doesn't exceed 10^5.
Output
For each test case, the first line should contain the length of the found subsequence, k. The second line should contain s_1, s_2, β¦, s_k β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
Example
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
Note
In the first test case, there are 4 subsequences of length at least 2:
* [3,2] which gives us |3-2|=1.
* [3,1] which gives us |3-1|=2.
* [2,1] which gives us |2-1|=1.
* [3,2,1] which gives us |3-2|+|2-1|=2.
So the answer is either [3,1] or [3,2,1]. Since we want the subsequence to be as short as possible, the answer is [3,1]. | from sys import stdin
import math
def inp():
return stdin.readline().strip()
t = int(inp())
for _ in range(t):
n = int(inp())
ar = [int(x) for x in inp().split()]
ans = [ar[0]]
for i in range(n-1):
if i > 0:
if ar[i-1] < ar[i] > ar[i+1] or ar[i-1] > ar[i] < ar[i+1]:
ans.append(ar[i])
ans.append(ar[n-1])
print(len(ans))
print(*ans) | {
"input": [
"2\n3\n3 2 1\n4\n1 3 4 2\n"
],
"output": [
"2\n3 1 \n3\n1 4 2 \n"
]
} |
3,044 | 9 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).
In one move Koa:
1. selects some subset of positions p_1, p_2, β¦, p_k (k β₯ 1; 1 β€ p_i β€ n; p_i β p_j if i β j) of A such that A_{p_1} = A_{p_2} = β¦ = A_{p_k} = x (ie. all letters on this positions are equal to some letter x).
2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x).
3. sets each letter in positions p_1, p_2, β¦, p_k to letter y. More formally: for each i (1 β€ i β€ k) Koa sets A_{p_i} = y.
Note that you can only modify letters in string A.
Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!
Input
Each test contains multiple test cases. The first line contains t (1 β€ t β€ 10) β the number of test cases. Description of the test cases follows.
The first line of each test case contains one integer n (1 β€ n β€ 10^5) β the length of strings A and B.
The second line of each test case contains string A (|A|=n).
The third line of each test case contains string B (|B|=n).
Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case:
Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.
Example
Input
5
3
aab
bcc
4
cabc
abcb
3
abc
tsr
4
aabd
cccd
5
abcbd
bcdda
Output
2
-1
3
2
-1
Note
* In the 1-st test case Koa:
1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β \color{blue}{bb}b).
2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β b\color{blue}{cc}).
* In the 2-nd test case Koa has no way to make string A equal B.
* In the 3-rd test case Koa:
1. selects position 1 and sets A_1 = t (\color{red}{a}bc β \color{blue}{t}bc).
2. selects position 2 and sets A_2 = s (t\color{red}{b}c β t\color{blue}{s}c).
3. selects position 3 and sets A_3 = r (ts\color{red}{c} β ts\color{blue}{r}). | def dfs(u):V[u]=0;return sum(dfs(v)for v in g[u]if V[v])+1
I=input
for _ in[0]*int(I()):
I();V=[1]*117;g=[[]for _ in V];f=0
for x,y in zip(map(ord,I()),map(ord,I())):f|=x>y;g[x]+=y,;g[y]+=x,
print((sum(dfs(i)-1for i in range(117)if V[i]),-1)[f]) | {
"input": [
"5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda\n"
],
"output": [
"2\n-1\n3\n2\n-1\n"
]
} |
3,045 | 11 | 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. | from sys import stdin
def bitadd(a,w,bit):
x = a
while x <= (len(bit)-1):bit[x] += w;x += x & (-1 * x)
def bitsum(a,bit):
ret = 0;x = a
while x > 0:ret += bit[x];x -= x & (-1 * x)
return ret
class RangeBIT:
def __init__(self,N,indexed):self.bit1 = [0] * (N+2);self.bit2 = [0] * (N+2);self.mode = indexed
def bitadd(self,a,w,bit):
x = a
while x <= (len(bit)-1):bit[x] += w;x += x & (-1 * x)
def bitsum(self,a,bit):
ret = 0;x = a
while x > 0:ret += bit[x];x -= x & (-1 * x)
return ret
def add(self,l,r,w):l = l + (1-self.mode);r = r + (1-self.mode);self.bitadd(l,-1*w*l,self.bit1);self.bitadd(r,w*r,self.bit1);self.bitadd(l,w,self.bit2);self.bitadd(r,-1*w,self.bit2)
def sum(self,l,r):l = l + (1-self.mode);r = r + (1-self.mode);ret = self.bitsum(r,self.bit1) + r * self.bitsum(r,self.bit2);ret -= self.bitsum(l,self.bit1) + l * self.bitsum(l,self.bit2);return ret
n,q = map(int,stdin.readline().split());a = list(map(int,stdin.readline().split()));qs = [ [] for i in range(n+1) ];ans = [None] * q;BIT = [0] * (n+1)
for loop in range(q):x,y = map(int,stdin.readline().split());l = x+1;r = n-y;qs[r].append((l,loop))
for r in range(1,n+1):
b = r-a[r-1]
if b >= 0:
L = 1;R = r+1
while R-L != 1:
M = (L+R)//2
if bitsum(M,BIT) >= b:L = M
else:R = M
if bitsum(L,BIT) >= b:bitadd(1,1,BIT);bitadd(L+1,-1,BIT)
for ql,qind in qs[r]:ans[qind] = bitsum(ql,BIT)
for i in ans:print (i) | {
"input": [
"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",
"5 2\n1 4 1 2 4\n0 0\n1 0\n"
],
"output": [
"5\n11\n6\n1\n0\n",
"2\n0\n"
]
} |
3,046 | 7 | You are given an array of n integers a_1,a_2,...,a_n.
You have to create an array of n integers b_1,b_2,...,b_n such that:
* The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_2,...,a_n\} and \\{b_1,b_2,...,b_n\} are equal.
For example, if a=[1,-1,0,1], then b=[-1,1,1,0] and b=[0,1,-1,1] are rearrangements of a, but b=[1,-1,-1,0] and b=[1,0,2,-3] are not rearrangements of a.
* For all k=1,2,...,n the sum of the first k elements of b is nonzero. Formally, for all k=1,2,...,n, it must hold $$$b_1+b_2+β
β
β
+b_knot=0 .$$$
If an array b_1,b_2,..., b_n with the required properties does not exist, you have to print NO.
Input
Each test contains multiple test cases. The first line contains an integer t (1β€ t β€ 1000) β the number of test cases. The description of the test cases follows.
The first line of each testcase contains one integer n (1β€ nβ€ 50) β the length of the array a.
The second line of each testcase contains n integers a_1,a_2,..., a_n (-50β€ a_iβ€ 50) β the elements of a.
Output
For each testcase, if there is not an array b_1,b_2,...,b_n with the required properties, print a single line with the word NO.
Otherwise print a line with the word YES, followed by a line with the n integers b_1,b_2,...,b_n.
If there is more than one array b_1,b_2,...,b_n satisfying the required properties, you can print any of them.
Example
Input
4
4
1 -2 3 -4
3
0 0 0
5
1 -1 1 -1 1
6
40 -31 -9 0 13 -40
Output
YES
1 -2 3 -4
NO
YES
1 1 -1 1 -1
YES
-40 13 40 0 -9 -31
Note
Explanation of the first testcase: An array with the desired properties is b=[1,-2,3,-4]. For this array, it holds:
* The first element of b is 1.
* The sum of the first two elements of b is -1.
* The sum of the first three elements of b is 2.
* The sum of the first four elements of b is -2.
Explanation of the second testcase: Since all values in a are 0, any rearrangement b of a will have all elements equal to 0 and therefore it clearly cannot satisfy the second property described in the statement (for example because b_1=0). Hence in this case the answer is NO.
Explanation of the third testcase: An array with the desired properties is b=[1, 1, -1, 1, -1]. For this array, it holds:
* The first element of b is 1.
* The sum of the first two elements of b is 2.
* The sum of the first three elements of b is 1.
* The sum of the first four elements of b is 2.
* The sum of the first five elements of b is 1.
Explanation of the fourth testcase: An array with the desired properties is b=[-40,13,40,0,-9,-31]. For this array, it holds:
* The first element of b is -40.
* The sum of the first two elements of b is -27.
* The sum of the first three elements of b is 13.
* The sum of the first four elements of b is 13.
* The sum of the first five elements of b is 4.
* The sum of the first six elements of b is -27. |
def sol(a):
fa=sorted(a)
s=sum(a)
if s>0:
print('YES')
print(' '.join(map(str,fa[::-1])))
if s<0:
print('YES')
print(' '.join(map(str,fa)))
if s==0:
print('NO')
t=int(input())
while t:
n=int(input())
a=list(map(int,input().split()))
sol(a)
t=t-1
| {
"input": [
"4\n4\n1 -2 3 -4\n3\n0 0 0\n5\n1 -1 1 -1 1\n6\n40 -31 -9 0 13 -40\n"
],
"output": [
"YES\n-4 -2 1 3\nNO\nYES\n1 1 1 -1 -1\nYES\n-40 -31 -9 0 13 40\n"
]
} |
3,047 | 7 | A string b is a subsequence of a string a if b can be obtained from a by deletion of several (possibly, zero or all) characters. For example, "xy" is a subsequence of "xzyw" and "xy", but not "yx".
You are given a string a. Your task is to reorder the characters of a so that "trygub" is not a subsequence of the resulting string.
In other words, you should find a string b which is a permutation of symbols of the string a and "trygub" is not a subsequence of b.
We have a truly marvelous proof that any string can be arranged not to contain "trygub" as a subsequence, but this problem statement is too short to contain it.
Input
The first line contains a single integer t (1β€ tβ€ 100) β the number of test cases.
The first line of each test case contains a single integer n (1β€ nβ€ 200) β the length of a.
The next line contains the string a of length n, consisting of lowercase English letters.
Output
For each test case, output a string b of length n which is a permutation of characters of the string a, and such that "trygub" is not a subsequence of it.
If there exist multiple possible strings b, you can print any.
Example
Input
3
11
antontrygub
15
bestcoordinator
19
trywatchinggurabruh
Output
bugyrtnotna
bestcoordinator
bruhtrywatchinggura
Note
In the first test case, "bugyrtnotna" does not contain "trygub" as a subsequence. It does contain the letters of "trygub", but not in the correct order, so it is not a subsequence.
In the second test case, we did not change the order of characters because it is not needed.
In the third test case, "bruhtrywatchinggura" does contain "trygu" as a subsequence, but not "trygub". | def solve(n):
s=input()
b=s.count('b')
return 'b'*b+s.replace('b','')
for _ in range(int(input())):
print(solve(int(input()))) | {
"input": [
"3\n11\nantontrygub\n15\nbestcoordinator\n19\ntrywatchinggurabruh\n"
],
"output": [
"\nbugyrtnotna\nbestcoordinator\nbruhtrywatchinggura\n"
]
} |
3,048 | 12 | Note that the memory limit is unusual.
You are given an integer n and two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n.
Let's call a set of integers S such that S β \{1, 2, 3, ..., n\} strange, if, for every element i of S, the following condition is met: for every j β [1, i - 1], if a_j divides a_i, then j is also included in S. An empty set is always strange.
The cost of the set S is β_{i β S} b_i. You have to calculate the maximum possible cost of a strange set.
Input
The first line contains one integer n (1 β€ n β€ 3000).
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 100).
The third line contains n integers b_1, b_2, ..., b_n (-10^5 β€ b_i β€ 10^5).
Output
Print one integer β the maximum cost of a strange set.
Examples
Input
9
4 7 3 4 5 6 7 8 13
-2 3 -19 5 -6 7 -8 9 1
Output
16
Input
2
42 42
-37 13
Output
0
Input
2
42 42
13 -37
Output
13
Note
The strange set with the maximum cost in the first example is \{1, 2, 4, 8, 9\}.
The strange set with the maximum cost in the second example is empty. | # Author: yumtam
# Created at: 2021-03-02 20:19
def main():
n = int(input())
A = [int(t) for t in input().split()]
cost = [int(t) for t in input().split()]
g = Flow(n+2)
s, t = n, n+1
last = [-1] * 101
for i, x in enumerate(A):
for d in range(1, 101):
if x % d == 0 and last[d] >= 0:
g.add_edge(i, last[d], float('inf'))
last[x] = i
if cost[i] >= 0:
g.add_edge(s, i, cost[i])
else:
g.add_edge(i, t, -cost[i])
min_cut = g.calc(s, t)
ans = sum(max(c, 0) for c in cost) - min_cut
print(ans)
class Flow:
def __init__(self, n):
self.n = n
self.g = [dict() for _ in range(n)]
def add_edge(self, u, v, w):
self.g[u][v] = w
self.g[v][u] = 0
def bfs(self, s, t):
q = [s]
vis = [0] * self.n
vis[s] = 1
prev = [-1] * self.n
found = False
for ver in q:
for nei, w in self.g[ver].items():
if not vis[nei] and w > 0:
vis[nei] = 1
prev[nei] = ver
q.append(nei)
if nei == t:
found = True
break
if found:
break
if not vis[t]:
return 0
flow = float('inf')
ver = t
while ver != s:
p = prev[ver]
flow = min(flow, self.g[p][ver])
ver = p
ver = t
while ver != s:
p = prev[ver]
self.g[p][ver] -= flow
self.g[ver][p] += flow
ver = p
return flow
def calc(self, s, t):
res = 0
while True:
flow = self.bfs(s, t)
res += flow
if not flow:
return res
main()
| {
"input": [
"2\n42 42\n-37 13\n",
"9\n4 7 3 4 5 6 7 8 13\n-2 3 -19 5 -6 7 -8 9 1\n",
"2\n42 42\n13 -37\n"
],
"output": [
"\n0\n",
"\n16\n",
"\n13\n"
]
} |
3,049 | 7 | What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until...
Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" β thought Petya. He know for a fact that if he fulfills the parents' task in the i-th (1 β€ i β€ 12) month of the year, then the flower will grow by ai centimeters, and if he doesn't water the flower in the i-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by k centimeters.
Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by k centimeters.
Input
The first line contains exactly one integer k (0 β€ k β€ 100). The next line contains twelve space-separated integers: the i-th (1 β€ i β€ 12) number in the line represents ai (0 β€ ai β€ 100).
Output
Print the only integer β the minimum number of months when Petya has to water the flower so that the flower grows no less than by k centimeters. If the flower can't grow by k centimeters in a year, print -1.
Examples
Input
5
1 1 1 1 2 2 3 2 2 1 1 1
Output
2
Input
0
0 0 0 0 0 0 0 1 1 2 3 0
Output
0
Input
11
1 1 4 1 1 5 1 1 4 1 1 1
Output
3
Note
Let's consider the first sample test. There it is enough to water the flower during the seventh and the ninth month. Then the flower grows by exactly five centimeters.
In the second sample Petya's parents will believe him even if the flower doesn't grow at all (k = 0). So, it is possible for Petya not to water the flower at all. | def fun(k,l):
if k==0:
return 0
for i in range(12):
if sum(l[:i+1])>=k:
return i+1
return -1
k=int(input())
l=list(map(int,input().split()))
l.sort(reverse=True)
print(fun(k,l)) | {
"input": [
"0\n0 0 0 0 0 0 0 1 1 2 3 0\n",
"5\n1 1 1 1 2 2 3 2 2 1 1 1\n",
"11\n1 1 4 1 1 5 1 1 4 1 1 1\n"
],
"output": [
"0\n",
"2\n",
"3\n"
]
} |
3,050 | 7 | <image>
William really likes the cellular automaton called "Game of Life" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing n cells, with each cell either being alive or dead.
Evolution of the array in William's cellular automaton occurs iteratively in the following way:
* If the element is dead and it has exactly 1 alive neighbor in the current state of the array, then on the next iteration it will become alive. For an element at index i the neighbors would be elements with indices i - 1 and i + 1. If there is no element at that index, it is considered to be a dead neighbor.
* William is a humane person so all alive elements stay alive.
Check the note section for examples of the evolution.
You are given some initial state of all elements and you need to help William find the state of the array after m iterations of evolution.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 10^3). Description of the test cases follows.
The first line of each test case contains two integers n and m (2 β€ n β€ 10^3, 1 β€ m β€ 10^9), which are the total number of cells in the array and the number of iterations.
The second line of each test case contains a string of length n made up of characters "0" and "1" and defines the initial state of the array. "1" means a cell is alive and "0" means it is dead.
It is guaranteed that the sum of n over all test cases does not exceed 10^4.
Output
In each test case output a string of length n, made up of characters "0" and "1" β the state of the array after m iterations of evolution.
Example
Input
4
11 3
01000000001
10 2
0110100101
5 2
10101
3 100
000
Output
11111001111
1110111101
10101
000
Note
Sequence of iterations of evolution for the first test case
* 01000000001 β initial state
* 11100000011 β first iteration of evolution
* 11110000111 β second iteration of evolution
* 11111001111 β third iteration of evolution
Sequence of iterations of evolution for the second test case
* 0110100101 β initial state
* 1110111101 β first iteration of evolution
* 1110111101 β second iteration of evolution | import bisect
def solve():
n,m = map(int,input().split())
s = input()
inf = float('inf')
I = [-inf] + [i for i in range(n) if s[i] == "1"] + [inf]
ans = ["0"]*n
for i in range(n):
k = bisect.bisect_left(I, i)
d = min(I[k] - i, i - I[k-1])
if I[k] - i == i - I[k-1]:
continue
if d <= m:
ans[i] = "1"
print("".join(ans))
for nt in range(int(input())):
solve()
| {
"input": [
"4\n11 3\n01000000001\n10 2\n0110100101\n5 2\n10101\n3 100\n000\n"
],
"output": [
"\n11111001111\n1110111101\n10101\n000\n"
]
} |
3,051 | 8 | The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = aΒ·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 β€ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n β the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 β€ n β€ 50
The input limitations for getting 100 points are:
* 2 β€ n β€ 109
Output
Print a single number β the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) β 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 β the maximum possible result. | def sieve(x):
i=2
while(i*i<=x):
if(x%i==0):
return x//i
i+=1
else:
return 1
n=int(input())
c=n
ans=c
while(c!=1):
c= sieve(c)
ans+=c
print(ans)
| {
"input": [
"10\n",
"8\n"
],
"output": [
"16\n",
"15\n"
]
} |
3,052 | 7 | Qwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high.
At the beginning of the first experiment there is a single bacterium in the test tube. Every second each bacterium in the test tube divides itself into k bacteria. After that some abnormal effects create b more bacteria in the test tube. Thus, if at the beginning of some second the test tube had x bacteria, then at the end of the second it will have kx + b bacteria.
The experiment showed that after n seconds there were exactly z bacteria and the experiment ended at this point.
For the second experiment Qwerty is going to sterilize the test tube and put there t bacteria. He hasn't started the experiment yet but he already wonders, how many seconds he will need to grow at least z bacteria. The ranger thinks that the bacteria will divide by the same rule as in the first experiment.
Help Qwerty and find the minimum number of seconds needed to get a tube with at least z bacteria in the second experiment.
Input
The first line contains four space-separated integers k, b, n and t (1 β€ k, b, n, t β€ 106) β the parameters of bacterial growth, the time Qwerty needed to grow z bacteria in the first experiment and the initial number of bacteria in the second experiment, correspondingly.
Output
Print a single number β the minimum number of seconds Qwerty needs to grow at least z bacteria in the tube.
Examples
Input
3 1 3 5
Output
2
Input
1 4 4 7
Output
3
Input
2 2 4 100
Output
0 | def mikroby(k, b, n, t):
z = 1
while z <= t:
z = k * z + b
n -= 1
return max(n + 1, 0)
K, B, N, T = [int(i) for i in input().split()]
print(mikroby(K, B, N, T))
| {
"input": [
"2 2 4 100\n",
"3 1 3 5\n",
"1 4 4 7\n"
],
"output": [
"0\n",
"2\n",
"3\n"
]
} |
3,053 | 8 | The Little Elephant loves numbers.
He has a positive integer x. The Little Elephant wants to find the number of positive integers d, such that d is the divisor of x, and x and d have at least one common (the same) digit in their decimal representations.
Help the Little Elephant to find the described number.
Input
A single line contains a single integer x (1 β€ x β€ 109).
Output
In a single line print an integer β the answer to the problem.
Examples
Input
1
Output
1
Input
10
Output
2 | x, val, i = int(input()), 0, 1
xs = set(str(x))
def dc(n):
return bool(xs & set(str(n)))
while i * i < x:
if x % i == 0:
val += dc(i) + dc(x // i)
i += 1
print(val + (i * i == x and dc(i))) | {
"input": [
"10\n",
"1\n"
],
"output": [
"2\n",
"1\n"
]
} |
3,054 | 9 | Two pirates Polycarpus and Vasily play a very interesting game. They have n chests with coins, the chests are numbered with integers from 1 to n. Chest number i has ai coins.
Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer x (2Β·x + 1 β€ n) and take a coin from each chest with numbers x, 2Β·x, 2Β·x + 1. It may turn out that some chest has no coins, in this case the player doesn't take a coin from this chest. The game finishes when all chests get emptied.
Polycarpus isn't a greedy scrooge. Polycarpys is a lazy slob. So he wonders in what minimum number of moves the game can finish. Help Polycarpus, determine the minimum number of moves in which the game can finish. Note that Polycarpus counts not only his moves, he also counts Vasily's moves.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of chests with coins. The second line contains a sequence of space-separated integers: a1, a2, ..., an (1 β€ ai β€ 1000), where ai is the number of coins in the chest number i at the beginning of the game.
Output
Print a single integer β the minimum number of moves needed to finish the game. If no sequence of turns leads to finishing the game, print -1.
Examples
Input
1
1
Output
-1
Input
3
1 2 3
Output
3
Note
In the first test case there isn't a single move that can be made. That's why the players won't be able to empty the chests.
In the second sample there is only one possible move x = 1. This move should be repeated at least 3 times to empty the third chest. | '''
Auther: ghoshashis545 Ashis Ghosh
College: Jalpaiguri Govt Enggineering College
'''
from os import path
from io import BytesIO, IOBase
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,Counter,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().rstrip()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def bo(i):
return ord(i)-ord('0')
file = 1
def ceil(a,b):
return (a+b-1)//b
def solve():
# for _ in range(1,ii()+1):
n = ii()
a = li()
if n == 1 or n%2==0:
print('-1')
return
cnt = 0
for i in range(n//2-1,-1,-1):
x = max(a[2*i+1],a[2*i+2])
cnt += x
a[i] = max(0,a[i]-x)
print(cnt + a[0])
if __name__ =="__main__":
if(file):
if path.exists('input.txt'):
sys.stdin=open('input.txt', 'r')
sys.stdout=open('output.txt','w')
else:
input=sys.stdin.readline
solve()
| {
"input": [
"1\n1\n",
"3\n1 2 3\n"
],
"output": [
"-1\n",
"3\n"
]
} |
3,055 | 7 | Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.
Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a?
Input
The first line of input contains an integer t (0 < t < 180) β the number of tests. Each of the following t lines contains a single integer a (0 < a < 180) β the angle the robot can make corners at measured in degrees.
Output
For each test, output on a single line "YES" (without quotes), if the robot can build a fence Emuskald wants, and "NO" (without quotes), if it is impossible.
Examples
Input
3
30
60
90
Output
NO
YES
YES
Note
In the first test case, it is impossible to build the fence, since there is no regular polygon with angle <image>.
In the second test case, the fence is a regular triangle, and in the last test case β a square. | def main():
for i in range(int(input())):
angle = int(input())
if (360 % (180 - angle)) == 0:
print('YES')
else:
print('NO')
main() | {
"input": [
"3\n30\n60\n90\n"
],
"output": [
"NO\nYES\nYES\n"
]
} |
3,056 | 7 | Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.
Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the numbers, (x + y).
What is the minimum number of such operations one has to perform in order to make the given pair of integers m-perfect?
Input
Single line of the input contains three integers x, y and m ( - 1018 β€ x, y, m β€ 1018).
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preffered to use the cin, cout streams or the %I64d specifier.
Output
Print the minimum number of operations or "-1" (without quotes), if it is impossible to transform the given pair to the m-perfect one.
Examples
Input
1 2 5
Output
2
Input
-1 4 15
Output
4
Input
0 -1 5
Output
-1
Note
In the first sample the following sequence of operations is suitable: (1, 2) <image> (3, 2) <image> (5, 2).
In the second sample: (-1, 4) <image> (3, 4) <image> (7, 4) <image> (11, 4) <image> (15, 4).
Finally, in the third sample x, y cannot be made positive, hence there is no proper sequence of operations. | def main():
a, b, m = map(int, input().split())
if a > b:
a, b = b, a
if m <= b:
print(0)
return
if b <= 0:
print(-1)
return
i = max((b - a) // b, 0)
a += b * i
while b < m:
a, b, i = b, a + b, i + 1
print(i)
if __name__ == '__main__':
main()
| {
"input": [
"0 -1 5\n",
"-1 4 15\n",
"1 2 5\n"
],
"output": [
"-1\n",
"4\n",
"2\n"
]
} |
3,057 | 7 | Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place.
Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination.
The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once.
Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.
Input
The first line contains integer n (2 β€ n β€ 105). Next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ 107).
Output
Output two integers β the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible.
Examples
Input
3
2 3 5
Output
22 3
Note
Consider 6 possible routes:
* [2, 3, 5]: total distance traveled: |2 β 0| + |3 β 2| + |5 β 3| = 5;
* [2, 5, 3]: |2 β 0| + |5 β 2| + |3 β 5| = 7;
* [3, 2, 5]: |3 β 0| + |2 β 3| + |5 β 2| = 7;
* [3, 5, 2]: |3 β 0| + |5 β 3| + |2 β 5| = 8;
* [5, 2, 3]: |5 β 0| + |2 β 5| + |3 β 2| = 9;
* [5, 3, 2]: |5 β 0| + |3 β 5| + |2 β 3| = 8.
The average travel distance is <image> = <image> = <image>. | def gcd(a,b) : return a if b==0 else gcd(b,a%b)
n = int(input())
l = sorted(map(int, input().split()))
t = sum((i+i-n+1)*l[i] for i in range(n))
t = t+t+sum(l)
d = gcd(t,n)
print(t//d,n//d)
| {
"input": [
"3\n2 3 5\n"
],
"output": [
"22 3\n"
]
} |
3,058 | 8 | Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 β€ k β€ 109).
Output
You should output a graph G with n vertexes (2 β€ n β€ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | n, m, cnt = int(input()), 148, 0
ans = [['N'] * m for i in range(m)]
def edge(i, j):
ans[i][j] = ans[j][i] = 'Y'
def node(*adj):
global cnt
i = cnt
cnt += 1
for j in adj:
edge(i, j)
return i
start, end, choice = node(), node(), node()
if n&1:
edge(choice, end)
for i in range(1, 30):
end, choice = node(node(end), node(end)), node(node(choice))
if n&(1<<i):
edge(choice, end)
edge(start, choice)
print(m)
for line in ans:
print(''.join(line))
# Made By Mostafa_Khaled | {
"input": [
"1",
"2",
"9"
],
"output": [
"2\nNY\nYN\n",
"4\nNNYY\nNNYY\nYYNN\nYYNN\n",
"11\nNNYYNNNNYNN\nNNNNNNYYNNY\nYNNNYYNNNNN\nYNNNYYNNNNN\nNNYYNNYYNNN\nNNYYNNYYNNN\nNYNNYYNNNNN\nNYNNYYNNNNN\nYNNNNNNNNYN\nNNNNNNNNYNY\nNYNNNNNNNYN\n"
]
} |
3,059 | 7 | The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem.
<image>
One day, Om Nom visited his friend Evan. Evan has n candies of two types (fruit drops and caramel drops), the i-th candy hangs at the height of hi centimeters above the floor of the house, its mass is mi. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most x centimeter high jumps. When Om Nom eats a candy of mass y, he gets stronger and the height of his jump increases by y centimeters.
What maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?
Input
The first line contains two integers, n and x (1 β€ n, x β€ 2000) β the number of sweets Evan has and the initial height of Om Nom's jump.
Each of the following n lines contains three integers ti, hi, mi (0 β€ ti β€ 1; 1 β€ hi, mi β€ 2000) β the type, height and the mass of the i-th candy. If number ti equals 0, then the current candy is a caramel drop, otherwise it is a fruit drop.
Output
Print a single integer β the maximum number of candies Om Nom can eat.
Examples
Input
5 3
0 2 4
1 3 1
0 8 3
0 20 10
1 5 5
Output
4
Note
One of the possible ways to eat 4 candies is to eat them in the order: 1, 5, 3, 2. Let's assume the following scenario:
1. Initially, the height of Om Nom's jump equals 3. He can reach candies 1 and 2. Let's assume that he eats candy 1. As the mass of this candy equals 4, the height of his jump will rise to 3 + 4 = 7.
2. Now Om Nom can reach candies 2 and 5. Let's assume that he eats candy 5. Then the height of his jump will be 7 + 5 = 12.
3. At this moment, Om Nom can reach two candies, 2 and 3. He won't eat candy 2 as its type matches the type of the previously eaten candy. Om Nom eats candy 3, the height of his jump is 12 + 3 = 15.
4. Om Nom eats candy 2, the height of his jump is 15 + 1 = 16. He cannot reach candy 4. |
n, x = (int(x) for x in input().split())
cs = []
for i in range(n):
cs.append([int(x) for x in input().split()])
if cs[-1][0] > 0:
cs[-1][0] = 1
def try_eat(t0):
h0 = x
used = set()
while True:
m0 = 0
i0 = -1
for i, (t, h, m) in enumerate(cs):
if t != t0 and h <= h0 and m > m0 and i not in used:
m0 = m
i0 = i
if i0 == -1:
break
used.add(i0)
h0 += cs[i0][2]
t0 = 1 - t0
return len(used)
print(max(try_eat(0), try_eat(1))) | {
"input": [
"5 3\n0 2 4\n1 3 1\n0 8 3\n0 20 10\n1 5 5\n"
],
"output": [
"4"
]
} |
3,060 | 8 | Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!
Your task is to write a program which calculates two things:
1. The maximum beauty difference of flowers that Pashmak can give to Parmida.
2. The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.
Input
The first line of the input contains n (2 β€ n β€ 2Β·105). In the next line there are n space-separated integers b1, b2, ..., bn (1 β€ bi β€ 109).
Output
The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.
Examples
Input
2
1 2
Output
1 1
Input
3
1 4 5
Output
4 1
Input
5
3 1 2 3 1
Output
2 4
Note
In the third sample the maximum beauty difference is 2 and there are 4 ways to do this:
1. choosing the first and the second flowers;
2. choosing the first and the fifth flowers;
3. choosing the fourth and the second flowers;
4. choosing the fourth and the fifth flowers. |
def flower():
k = int(input())
c = list(map(int,input().split(" ")))
i,j = max(c),min(c)
p = i-j
print (p,[(k*(k-1))//2,c.count(i)*c.count(j)][i!=j])
flower()
| {
"input": [
"3\n1 4 5\n",
"2\n1 2\n",
"5\n3 1 2 3 1\n"
],
"output": [
"4 1\n",
"1 1\n",
"2 4\n"
]
} |
3,061 | 7 | Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a student can take the exam for the i-th subject on the day number ai. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day bi (bi < ai). Thus, Valera can take an exam for the i-th subject either on day ai, or on day bi. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number ai.
Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.
Input
The first line contains a single positive integer n (1 β€ n β€ 5000) β the number of exams Valera will take.
Each of the next n lines contains two positive space-separated integers ai and bi (1 β€ bi < ai β€ 109) β the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly.
Output
Print a single integer β the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date.
Examples
Input
3
5 2
3 1
4 2
Output
2
Input
3
6 1
5 2
4 3
Output
6
Note
In the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5.
In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject. | C = 0
def main():
n = int(input())
a = 0
for b, c in sorted(tuple(map(int, input().split())) for _ in range(n)):
a = b if a > c else c
print(a)
if __name__ == '__main__':
main() | {
"input": [
"3\n6 1\n5 2\n4 3\n",
"3\n5 2\n3 1\n4 2\n"
],
"output": [
"6",
"2"
]
} |
3,062 | 7 | Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into s to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" and "kitayuta" are not.
You can choose any lowercase English letter, and insert it to any position of s, possibly to the beginning or the end of s. You have to insert a letter even if the given string is already a palindrome.
If it is possible to insert one lowercase English letter into s so that the resulting string will be a palindrome, print the string after the insertion. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one palindrome that can be obtained, you are allowed to print any of them.
Input
The only line of the input contains a string s (1 β€ |s| β€ 10). Each character in s is a lowercase English letter.
Output
If it is possible to turn s into a palindrome by inserting one lowercase English letter, print the resulting string in a single line. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one solution, any of them will be accepted.
Examples
Input
revive
Output
reviver
Input
ee
Output
eye
Input
kitayuta
Output
NA
Note
For the first sample, insert 'r' to the end of "revive" to obtain a palindrome "reviver".
For the second sample, there is more than one solution. For example, "eve" will also be accepted.
For the third sample, it is not possible to turn "kitayuta" into a palindrome by just inserting one letter. | def func(s):
for i in range(len(s)+1):
for j in range(97,123):
q = s[:i]+chr(j)+s[i:]
rev = q[::-1]
if q == rev:
return q
return "NA"
s=input()
print(func(s)) | {
"input": [
"ee\n",
"revive\n",
"kitayuta\n"
],
"output": [
"eee",
"reviver\n",
"NA\n"
]
} |
3,063 | 8 | Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.
Return the maximum number of rows that she can make completely clean.
Input
The first line of input will be a single integer n (1 β€ n β€ 100).
The next n lines will describe the state of the room. The i-th line will contain a binary string with n characters denoting the state of the i-th row of the room. The j-th character on this line is '1' if the j-th square in the i-th row is clean, and '0' if it is dirty.
Output
The output should be a single line containing an integer equal to a maximum possible number of rows that are completely clean.
Examples
Input
4
0101
1000
1111
0101
Output
2
Input
3
111
111
111
Output
3
Note
In the first sample, Ohana can sweep the 1st and 3rd columns. This will make the 1st and 4th row be completely clean.
In the second sample, everything is already clean, so Ohana doesn't need to do anything. | def most_common(a):
return max(set(a), key=a.count)
n=int(input())
import sys
a=sys.stdin.readlines()
print(a.count(most_common(a))) | {
"input": [
"4\n0101\n1000\n1111\n0101\n",
"3\n111\n111\n111\n"
],
"output": [
"2",
"3"
]
} |
3,064 | 7 | Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one. | def solve(Arr,n):
dp=[1 for _ in range(n)]
for i in range(1,n):
if Arr[i]>=Arr[i-1]:
dp[i]=dp[i-1]+1
return max(dp)
n=int(input())
Arr=list(map(int,input().split()))
print(solve(Arr,n))
| {
"input": [
"6\n2 2 1 3 4 1\n",
"3\n2 2 9\n"
],
"output": [
"3\n",
"3\n"
]
} |
3,065 | 9 | 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 collections import defaultdict,deque,Counter,OrderedDict
import sys
sys.setrecursionlimit(20000)
def main():
n,m = map(int,input().split())
adj = [[] for i in range(n+1)]
for i in range(m):
a,b = map(int,input().split())
a,b = a-1,b-1
adj[a].append(b)
adj[b].append(a)
ans = ["c"]*(n)
visited = [0]*(n)
for i in range(n):
if len(adj[i]) == n - 1:
visited[i] = 1
ans[i] = "b"
def dfs(s,c):
if visited[s]: return
visited[s],ans[s] = 1,c
for j in adj[s]:
dfs(j,c)
if "c" in ans:
st = ans.index("c")
dfs(st,"a")
if "c" in ans:
st = ans.index("c")
dfs(st,"c")
check,cnta,cntc,cntb = True,ans.count("a"),ans.count("c"),ans.count("b")
for i in range(n):
if ans[i] == "a":
check &= (len(adj[i])==cnta+cntb-1)
elif ans[i] == "c":
check &= (len(adj[i])==cntc+cntb-1)
if check:
print("Yes\n"+"".join(ans))
else:
print("No")
if __name__ == "__main__":
main() | {
"input": [
"2 1\n1 2\n",
"4 3\n1 2\n1 3\n1 4\n"
],
"output": [
"Yes\nbb\n",
"No\n"
]
} |
3,066 | 7 | Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. | n = int(input())
a = list(map(int, input().split()))
mem = {}
def solve(i, previous):
if i == n:
return 0
if a[i] == 0 or a[i] == previous:
return solve(i+1, 0) + 1
elif a[i] == 3:
if previous == 0:
return solve(i+1, 0)
return solve(i+1, 2 if previous == 1 else 1)
return solve(i+1, a[i])
print(solve(0, 0)) | {
"input": [
"4\n1 3 2 0\n",
"2\n2 2\n",
"7\n1 3 3 2 1 2 3\n"
],
"output": [
"2\n",
"1\n",
"0\n"
]
} |
3,067 | 7 | Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1. | def main():
n = int(input(""))
a = list(map(int, input().split()))
if a[n-1] == 15:
print("DOWN\n")
elif a[n-1] == 0:
print("UP\n")
elif n == 1:
print("-1\n")
elif a[n-1] > a[n-2]:
print("UP\n")
elif a[n-1] < a[n-2]:
print("DOWN\n")
main() | {
"input": [
"7\n12 13 14 15 14 13 12\n",
"5\n3 4 5 6 7\n",
"1\n8\n"
],
"output": [
"DOWN",
"UP",
"-1"
]
} |
3,068 | 9 | Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.
Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m.
Input
The first line contains two integers m and n (2 β€ m β€ 109 + 7, 1 β€ n β€ 105, m is prime) β Timofey's favorite prime module and the length of the sequence.
The second line contains n distinct integers a1, a2, ..., an (0 β€ ai < m) β the elements of the sequence.
Output
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.
Otherwise, print two integers β the first element of the obtained progression x (0 β€ x < m) and its difference d (0 β€ d < m).
If there are multiple answers, print any of them.
Examples
Input
17 5
0 2 4 13 15
Output
13 2
Input
17 5
0 2 4 13 14
Output
-1
Input
5 3
1 2 3
Output
3 4 | def solve(n, m, a):
if n == 0:
return 0, 1
if n == 1:
return a[0], 1
d = (a[1]-a[0]) % m
if d < 0: d += m
st = set(a)
cnt = 0
for v in a:
cnt += ((v + d) % m) in st
cnt = n-cnt
d = (d * pow(cnt, m-2, m)) % m
now = a[0]
while (now + m - d) % m in st:
now = (now + m - d) % m
for i in range(n):
if (now + i*d) % m not in st:
return -1, -1
return now, d
m, n = map(int, input().split())
a = list(map(int, input().split()))
if n * 2 > m:
st = set(a)
b = [i for i in range(m) if i not in st]
f, d = solve(len(b), m, b)
f = (f + d * (m-n)) % m
else:
f, d = solve(n, m, a)
if f < 0 or d < 0:
print(-1)
else:
print(f, d) | {
"input": [
"17 5\n0 2 4 13 15\n",
"17 5\n0 2 4 13 14\n",
"5 3\n1 2 3\n"
],
"output": [
"13 2\n",
"-1\n",
"1 1\n"
]
} |
3,069 | 10 | Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left. | a = int(input())
nums = [int(i) for i in input().split()]
tot = sum(nums)
def runner(lpr):
total = 0
used = {}
for i in range(*lpr):
used[nums[i]] = 1
total += nums[i]
distance = 2 * total - tot
if distance % 2 == 0 and used.get(distance // 2, -1) != -1:
print("YES")
exit(0)
runner((0, a))
runner((a - 1, -1, -1))
print("NO")
| {
"input": [
"5\n1 2 3 4 5\n",
"3\n1 3 2\n",
"5\n2 2 3 4 5\n"
],
"output": [
"NO",
"YES",
"YES"
]
} |
3,070 | 7 | Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.
Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.
Input
The first line contains an integer n (1 β€ n β€ 5Β·105) β the number of lines.
Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 β€ xi β€ 1023.
Output
Output an integer k (0 β€ k β€ 5) β the length of your program.
Next k lines must contain commands in the same format as in the input.
Examples
Input
3
| 3
^ 2
| 1
Output
2
| 3
^ 2
Input
3
& 1
& 3
& 5
Output
1
& 1
Input
3
^ 1
^ 2
^ 3
Output
0
Note
You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>.
Second sample:
Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. | def fun (n1,o,n2):
if o=="|":
return n1|n2
elif o=="&":
return n1&n2
else:
return n1^n2
def fun2(n):
l=[0 for i in range(10)]
for i in range(9,-1,-1):
if 1<<i <=n:
l[i]=1
n-=1<<i
return l
n=int(input())
a=0
b=1023
for i in range(n):
o,n2=input().split()
n2=int(n2)
a=fun(a,o,n2)
b=fun(b,o,n2)
l1=fun2(a)
l2=fun2(b)
a=0
b=0
for i in range(10):
if l1[i]==1 and l2[i]==1:
a+=1<<i
elif l1[i]==0 and l2[i]==0:
a+=1<<i
b+=1<<i
elif l1[i]==1 and l2[i]==0:
b+=1<<i
print(2)
print("|",a)
print("^",b)
| {
"input": [
"3\n& 1\n& 3\n& 5\n",
"3\n| 3\n^ 2\n| 1\n",
"3\n^ 1\n^ 2\n^ 3\n"
],
"output": [
"3\n& 0\n| 0\n^ 0\n",
"3\n& 1021\n| 1\n^ 0\n",
"3\n& 1023\n| 0\n^ 0\n"
]
} |
3,071 | 9 | You are given an undirected graph with n vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to n.
You have to answer q queries. Each query is described by a segment of vertices [l; r], and you have to count the number of its subsegments [x; y] (l β€ x β€ y β€ r), such that if we delete all vertices except the segment of vertices [x; y] (including x and y) and edges between them, the resulting graph is bipartite.
Input
The first line contains two integers n and m (1 β€ n β€ 3Β·105, 1 β€ m β€ 3Β·105) β the number of vertices and the number of edges in the graph.
The next m lines describe edges in the graph. The i-th of these lines contains two integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting an edge between vertices ai and bi. It is guaranteed that this graph does not contain edge-simple cycles of even length.
The next line contains a single integer q (1 β€ q β€ 3Β·105) β the number of queries.
The next q lines contain queries. The i-th of these lines contains two integers li and ri (1 β€ li β€ ri β€ n) β the query parameters.
Output
Print q numbers, each in new line: the i-th of them should be the number of subsegments [x; y] (li β€ x β€ y β€ ri), such that the graph that only includes vertices from segment [x; y] and edges between them is bipartite.
Examples
Input
6 6
1 2
2 3
3 1
4 5
5 6
6 4
3
1 3
4 6
1 6
Output
5
5
14
Input
8 9
1 2
2 3
3 1
4 5
5 6
6 7
7 8
8 4
7 2
3
1 8
1 4
3 8
Output
27
8
19
Note
The first example is shown on the picture below:
<image>
For the first query, all subsegments of [1; 3], except this segment itself, are suitable.
For the first query, all subsegments of [4; 6], except this segment itself, are suitable.
For the third query, all subsegments of [1; 6] are suitable, except [1; 3], [1; 4], [1; 5], [1; 6], [2; 6], [3; 6], [4; 6].
The second example is shown on the picture below:
<image> |
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n,mod=0):
self.BIT = [0]*(n+1)
self.num = n
self.mod = mod
def query(self,idx):
res_sum = 0
mod = self.mod
while idx > 0:
res_sum += self.BIT[idx]
if mod:
res_sum %= mod
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
mod = self.mod
while idx <= self.num:
self.BIT[idx] += x
if mod:
self.BIT[idx] %= mod
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
self.size = n
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
if r==self.size:
r = self.num
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] <= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] <=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return -1
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log
import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
mi = lambda :map(int,input().split())
li = lambda :list(mi())
n,m = mi()
edge = [[] for i in range(n)]
for _ in range(m):
u,v = mi()
edge[u-1].append(v-1)
edge[v-1].append(u-1)
parent = [-1 for i in range(n)]
depth = [0 for i in range(n)]
cnt = [0 for i in range(n)]
res = [n for i in range(n)]
for root in range(n):
if parent[root]==-1:
stack = [root]
while stack:
v = stack[-1]
if len(edge[v])==cnt[v]:
stack.pop()
else:
nv = edge[v][cnt[v]]
cnt[v] += 1
if nv==root or parent[nv]!=-1:
if depth[nv] < depth[v]-1:
m,M = nv,nv
pos = v
while pos!=nv:
m = min(pos,m)
M = max(pos,M)
pos = parent[pos]
res[m] = min(res[m],M)
else:
depth[nv] = depth[v] + 1
parent[nv] = v
stack.append(nv)
cnt = [0 for i in range(n)]
cnt[n-1] = res[n-1] - (n-1)
for i in range(n-2,-1,-1):
res[i] = min(res[i],res[i+1])
cnt[i] = res[i] - i
for i in range(1,n):
cnt[i] += cnt[i-1]
query = [[] for i in range(n+1)]
q = int(input())
for i in range(q):
l,r = mi()
query[r].append((i,l-1))
pos = -1
ans = [0 for i in range(q)]
for r in range(1,n+1):
while pos+1<n and res[pos+1]<=r:
pos += 1
for idx,l in query[r]:
if r<=pos:
tmp = cnt[r-1]
if l:
tmp -= cnt[l-1]
elif l<=pos:
tmp = cnt[pos]
if l:
tmp -= cnt[l-1]
tmp += (r-pos-1) * r - ((r+pos)*(r-pos-1)//2)
else:
tmp = (r-l) * r - ((r-1+l)*(r-l)//2)
ans[idx] = tmp
print(*ans,sep="\n")
| {
"input": [
"8 9\n1 2\n2 3\n3 1\n4 5\n5 6\n6 7\n7 8\n8 4\n7 2\n3\n1 8\n1 4\n3 8\n",
"6 6\n1 2\n2 3\n3 1\n4 5\n5 6\n6 4\n3\n1 3\n4 6\n1 6\n"
],
"output": [
"27\n8\n19\n",
"5\n5\n14\n"
]
} |
3,072 | 8 | If you have ever interacted with a cat, you have probably noticed that they are quite particular about how to pet them. Here is an approximate map of a normal cat.
<image>
However, some cats won't tolerate this nonsense from the humans. Here is a map of a grumpy cat.
<image>
You have met a cat. Can you figure out whether it's normal or grumpy?
Interaction
This is an interactive problem. Initially you're not given any information about the cat. Instead, the cat is divided into ten areas, indexed from 0 to 9.
In one query you can choose which area you'll pet and print the corresponding index to standard out. You will get the cat's response, as depicted on the corresponding map, via standard in. For simplicity all responses are written in lowercase.
Once you're certain what type of cat you're dealing with, output "normal" or "grumpy" to standard out.
Note
Please make sure to use the stream flushing operation after each query in order not to leave part of your output in some buffer. | def main():
grumpy = ["don't even", "are you serious?", "worse", "terrible", "no way", "go die in a hole"]
print(9)
res = input()
if res in grumpy:
print("grumpy")
return
else:
print("normal")
return
if __name__ == "__main__":
main()
| {
"input": [],
"output": []
} |
3,073 | 11 | There are n cities and m roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.
What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?
New roads will also be one-way.
Input
The first line of input consists of three integers n, m and s (1 β€ n β€ 5000, 0 β€ m β€ 5000, 1 β€ s β€ n) β the number of cities, the number of roads and the index of the capital. Cities are indexed from 1 to n.
The following m lines contain roads: road i is given as a pair of cities u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i). For each pair of cities (u, v), there can be at most one road from u to v. Roads in opposite directions between a pair of cities are allowed (i.e. from u to v and from v to u).
Output
Print one integer β the minimum number of extra roads needed to make all the cities reachable from city s. If all the cities are already reachable from s, print 0.
Examples
Input
9 9 1
1 2
1 3
2 3
1 5
5 6
6 1
1 8
9 8
7 1
Output
3
Input
5 4 5
1 2
2 3
3 4
4 1
Output
1
Note
The first example is illustrated by the following:
<image>
For example, you can add roads (6, 4), (7, 9), (1, 7) to make all the cities reachable from s = 1.
The second example is illustrated by the following:
<image>
In this example, you can add any one of the roads (5, 1), (5, 2), (5, 3), (5, 4) to make all the cities reachable from s = 5. | import sys
def d(u):
rt[u] = False
for v in q[u]:
if rt[v]:
d(v)
topo.append(u)
sys.setrecursionlimit(6000)
n, m, s = map(int, input().split())
q = [[] for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
q[u - 1].append(v - 1)
rt, topo = [True] * n, []
for i,a in enumerate(rt):
if a:
d(i)
rt, res = [True] * n, 0
d(s - 1)
for i in reversed(topo):
if rt[i]:
res += 1
d(i)
print(res) | {
"input": [
"5 4 5\n1 2\n2 3\n3 4\n4 1\n",
"9 9 1\n1 2\n1 3\n2 3\n1 5\n5 6\n6 1\n1 8\n9 8\n7 1\n"
],
"output": [
"1\n",
"3\n"
]
} |
3,074 | 8 | Little C loves number Β«3Β» very much. He loves all things about it.
Now he is playing a game on a chessboard of size n Γ m. The cell in the x-th row and in the y-th column is called (x,y). Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between which is exactly 3. The Manhattan distance between two cells (x_i,y_i) and (x_j,y_j) is defined as |x_i-x_j|+|y_i-y_j|.
He want to place as many chessmen as possible on the chessboard. Please help him find the maximum number of chessmen he can place.
Input
A single line contains two integers n and m (1 β€ n,m β€ 10^9) β the number of rows and the number of columns of the chessboard.
Output
Print one integer β the maximum number of chessmen Little C can place.
Examples
Input
2 2
Output
0
Input
3 3
Output
8
Note
In the first example, the Manhattan distance between any two cells is smaller than 3, so the answer is 0.
In the second example, a possible solution is (1,1)(3,2), (1,2)(3,3), (2,1)(1,3), (3,1)(2,3). | class Solution(object):
def run(self):
n, m = [int(x) for x in input().split()]
if n > m:
n, m = m, n
res = (n * m) // 2
if n == 1 and (m + 1) % 6 // 3:
res -= 1
elif n == 2:
if m == 2:
res = 0
elif m == 3:
res = 2
elif m == 7:
res = 6
print(res * 2)
if __name__ == '__main__':
Solution().run() | {
"input": [
"3 3\n",
"2 2\n"
],
"output": [
"8\n",
"0\n"
]
} |
3,075 | 8 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the interval [pl, pr] and Vasya chooses an integer v from the interval [vl, vr] (also randomly). Both players choose their integers equiprobably. Find the probability that the interval [min(v, p), max(v, p)] contains exactly k lucky numbers.
Input
The single line contains five integers pl, pr, vl, vr and k (1 β€ pl β€ pr β€ 109, 1 β€ vl β€ vr β€ 109, 1 β€ k β€ 1000).
Output
On the single line print the result with an absolute error of no more than 10 - 9.
Examples
Input
1 10 1 10 2
Output
0.320000000000
Input
5 6 8 10 1
Output
1.000000000000
Note
Consider that [a, b] denotes an interval of integers; this interval includes the boundaries. That is, <image>
In first case there are 32 suitable pairs: (1, 7), (1, 8), (1, 9), (1, 10), (2, 7), (2, 8), (2, 9), (2, 10), (3, 7), (3, 8), (3, 9), (3, 10), (4, 7), (4, 8), (4, 9), (4, 10), (7, 1), (7, 2), (7, 3), (7, 4), (8, 1), (8, 2), (8, 3), (8, 4), (9, 1), (9, 2), (9, 3), (9, 4), (10, 1), (10, 2), (10, 3), (10, 4). Total number of possible pairs is 10Β·10 = 100, so answer is 32 / 100.
In second case Petya always get number less than Vasya and the only lucky 7 is between this numbers, so there will be always 1 lucky number. | s = list()
def rec(x):
if x > 100000000000:
return
s.append(x)
rec(x * 10 + 4)
rec(x * 10 + 7)
def f(l1, r1, l2, r2):
l1 = max(l1, l2)
r1 = min(r1, r2)
return max(r1 - l1 + 1, 0)
def main():
rec(0)
s.sort()
args = input().split()
pl, pr, vl, vr, k = int(args[0]), int(args[1]), int(args[2]), int(args[3]), int(args[4])
ans = 0
i = 1
while i + k < len(s):
l1 = s[i - 1] + 1
r1 = s[i]
l2 = s[i + k - 1]
r2 = s[i + k] - 1
a = f(l1, r1, vl, vr) * f(l2, r2, pl, pr)
b = f(l1, r1, pl, pr) * f(l2, r2, vl, vr)
ans += a + b
if k == 1 and a > 0 and b > 0:
ans -= 1
i += 1
all = (pr - pl + 1) * (vr - vl + 1)
print(1.0 * ans / all)
if __name__ == '__main__':
main()
| {
"input": [
"1 10 1 10 2\n",
"5 6 8 10 1\n"
],
"output": [
"0.32000000000000000666",
"1"
]
} |
3,076 | 8 | One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.
A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add 1 to 9, to subtract 1 from 0 and to subtract 1 from the leading 1. Once the number on the screen becomes equal to b, the player wins the jackpot. a and b have the same number of digits.
Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.
Input
The first line contains a single integer n (2 β€ n β€ 10^5) standing for the length of numbers a and b.
The next two lines contain numbers a and b, each one on a separate line (10^{n-1} β€ a, b < 10^n).
Output
If it is impossible to win the jackpot, print a single integer -1.
Otherwise, the first line must contain the minimal possible number c of coins the player has to spend.
min(c, 10^5) lines should follow, i-th of them containing two integers d_i and s_i (1β€ d_iβ€ n - 1, s_i = Β± 1) denoting that on the i-th step the player should add s_i to the d_i-th and (d_i + 1)-st digits from the left (e. g. d_i = 1 means that two leading digits change while d_i = n - 1 means that there are two trailing digits which change).
Please notice that the answer may be very big and in case c > 10^5 you should print only the first 10^5 moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them.
Examples
Input
3
223
322
Output
2
1 1
2 -1
Input
2
20
42
Output
2
1 1
1 1
Input
2
35
44
Output
-1
Note
In the first example, we can make a +1 operation on the two first digits, transforming number 223 into 333, and then make a -1 operation on the last two digits, transforming 333 into 322.
It's also possible to do these operations in reverse order, which makes another correct answer.
In the last example, one can show that it's impossible to transform 35 into 44. | def main():
n = int(input())
a = list(map(int, (x for x in input())))
b = list(map(int, (x for x in input())))
x = [0] * (n - 1)
x[0] = b[0] - a[0]
for i in range(1, n - 1):
x[i] = b[i] - a[i] - x[i - 1]
if a[n - 1] + x[n - 2] != b[n - 1]:
print(-1)
return
cnt = sum(map(abs, x)) # prevbug: ftl
print(cnt)
cnt = min(cnt, 10 ** 5)
index = 0
def handle_zero_nine(cur_zero):
nonlocal cnt
nxt = index + 1
# cur_zero = True prevbug: preserved this line
while True:
if cur_zero and a[nxt + 1] != 9:
break
if not cur_zero and a[nxt + 1] != 0:
break
nxt += 1
cur_zero = not cur_zero
while nxt > index:
if cnt == 0:
break
if cur_zero:
print(nxt + 1, 1)
a[nxt] += 1
a[nxt + 1] += 1
else:
print(nxt + 1, -1)
a[nxt] -= 1
a[nxt + 1] -= 1
nxt -= 1
cnt -= 1
# print(a)
cur_zero = not cur_zero
while cnt > 0:
if a[index] == b[index]:
index += 1
continue
elif a[index] > b[index] and a[index + 1] == 0:
handle_zero_nine(True)
elif a[index] < b[index] and a[index + 1] == 9:
handle_zero_nine(False)
elif a[index] > b[index]:
print(index + 1, -1)
a[index] -= 1
a[index + 1] -= 1
cnt -= 1
# print(a)
elif a[index] < b[index]:
print(index + 1, 1)
a[index] += 1
a[index + 1] += 1
cnt -= 1
# print(a)
if __name__ == '__main__':
main()
| {
"input": [
"2\n35\n44\n",
"3\n223\n322\n",
"2\n20\n42\n"
],
"output": [
"-1\n",
" 2\n1 1\n2 -1\n",
" 2\n1 1\n1 1\n"
]
} |
3,077 | 8 | The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 β€ m β€ 5 β
10^4) β the number of friends.
The i-th of the next m lines contains t_i (1 β€ |t_i| β€ 2 β
10^5) β the name of the i-th friend.
It is guaranteed that β _{i=1}^m |t_i| β€ 2 β
10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9 | def ri():
return int(input())
n = ri()
s = input()
cnt = [[0] for i in range(200) ]
for i in range(n):
cnt[ord(s[i] )].append(i+1)
t = ri()
for _ in range(t):
s2 = input()
ans = 0
for i in range(26) :
ans = max(ans,cnt[i+97][s2.count(chr(97+i)) ] )
print(ans ) | {
"input": [
"9\narrayhead\n5\narya\nharry\nray\nr\nareahydra\n"
],
"output": [
"5\n6\n5\n2\n9\n"
]
} |
3,078 | 7 | You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m.
Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B.
For example, if A = [2, 1, 7] and B = [1, 3, 4], we can choose 1 from A and 4 from B, as number 5 = 1 + 4 doesn't belong to A and doesn't belong to B. However, we can't choose 2 from A and 1 from B, as 3 = 2 + 1 belongs to B.
It can be shown that such a pair exists. If there are multiple answers, print any.
Choose and print any such two numbers.
Input
The first line contains one integer n (1β€ n β€ 100) β the number of elements of A.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 200) β the elements of A.
The third line contains one integer m (1β€ m β€ 100) β the number of elements of B.
The fourth line contains m different integers b_1, b_2, ..., b_m (1 β€ b_i β€ 200) β the elements of B.
It can be shown that the answer always exists.
Output
Output two numbers a and b such that a belongs to A, b belongs to B, but a+b doesn't belong to nor A neither B.
If there are multiple answers, print any.
Examples
Input
1
20
2
10 20
Output
20 20
Input
3
3 2 2
5
1 5 7 7 9
Output
3 1
Input
4
1 3 5 7
4
7 5 3 1
Output
1 1
Note
In the first example, we can choose 20 from array [20] and 20 from array [10, 20]. Number 40 = 20 + 20 doesn't belong to any of those arrays. However, it is possible to choose 10 from the second array too.
In the second example, we can choose 3 from array [3, 2, 2] and 1 from array [1, 5, 7, 7, 9]. Number 4 = 3 + 1 doesn't belong to any of those arrays.
In the third example, we can choose 1 from array [1, 3, 5, 7] and 1 from array [7, 5, 3, 1]. Number 2 = 1 + 1 doesn't belong to any of those arrays. | def solve():
input()
return max(map(int, input().split()))
print(solve(), solve())
| {
"input": [
"4\n1 3 5 7\n4\n7 5 3 1\n",
"3\n3 2 2\n5\n1 5 7 7 9\n",
"1\n20\n2\n10 20\n"
],
"output": [
"7 7\n",
"3 9\n",
"20 20\n"
]
} |
3,079 | 10 | You are given a sequence a_1, a_2, ..., a_n, consisting of integers.
You can apply the following operation to this sequence: choose some integer x and move all elements equal to x either to the beginning, or to the end of a. Note that you have to move all these elements in one direction in one operation.
For example, if a = [2, 1, 3, 1, 1, 3, 2], you can get the following sequences in one operation (for convenience, denote elements equal to x as x-elements):
* [1, 1, 1, 2, 3, 3, 2] if you move all 1-elements to the beginning;
* [2, 3, 3, 2, 1, 1, 1] if you move all 1-elements to the end;
* [2, 2, 1, 3, 1, 1, 3] if you move all 2-elements to the beginning;
* [1, 3, 1, 1, 3, 2, 2] if you move all 2-elements to the end;
* [3, 3, 2, 1, 1, 1, 2] if you move all 3-elements to the beginning;
* [2, 1, 1, 1, 2, 3, 3] if you move all 3-elements to the end;
You have to determine the minimum number of such operations so that the sequence a becomes sorted in non-descending order. Non-descending order means that for all i from 2 to n, the condition a_{i-1} β€ a_i is satisfied.
Note that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 3 β
10^5) β the number of the queries. Each query is represented by two consecutive lines.
The first line of each query contains one integer n (1 β€ n β€ 3 β
10^5) β the number of elements.
The second line of each query contains n integers a_1, a_2, ... , a_n (1 β€ a_i β€ n) β the elements.
It is guaranteed that the sum of all n does not exceed 3 β
10^5.
Output
For each query print one integer β the minimum number of operation for sorting sequence a in non-descending order.
Example
Input
3
7
3 1 6 6 3 1 1
8
1 1 4 4 4 7 8 8
7
4 2 5 2 6 2 7
Output
2
0
1
Note
In the first query, you can move all 1-elements to the beginning (after that sequence turn into [1, 1, 1, 3, 6, 6, 3]) and then move all 6-elements to the end.
In the second query, the sequence is sorted initially, so the answer is zero.
In the third query, you have to move all 2-elements to the beginning. | import sys
input = sys.stdin.readline
def solve():
n = int(input())
a = list(map(int,input().split()))
s = set(a)
s = sorted(list(s))
ref = {x:i for i,x in enumerate(list(s))}
sz = len(s)
L = [1<<32]*sz
R = [-1<<32]*sz
for i in range(n):
k = ref[a[i]]
L[k] = min(L[k], i)
R[k] = max(R[k], i)
dp = [0]*sz
for k in range(sz):
if k == 0 or L[k] < R[k-1]:
dp[k] = 1
else:
dp[k] = 1 + dp[k-1]
ans = 1<<32
for k in range(sz):
ans = min(ans, sz - dp[k])
print(ans)
return 0
for nt in range(int(input())):
solve()
| {
"input": [
"3\n7\n3 1 6 6 3 1 1\n8\n1 1 4 4 4 7 8 8\n7\n4 2 5 2 6 2 7\n"
],
"output": [
"2\n0\n1\n"
]
} |
3,080 | 7 | You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that:
* No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than 1);
* the number of teams is the minimum possible.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 100) β the number of queries. Then q queries follow.
The first line of the query contains one integer n (1 β€ n β€ 100) β the number of students in the query. The second line of the query contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 100, all a_i are distinct), where a_i is the programming skill of the i-th student.
Output
For each query, print the answer on it β the minimum number of teams you can form if no two students i and j such that |a_i - a_j| = 1 may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than 1)
Example
Input
4
4
2 10 1 20
2
3 6
5
2 3 4 99 100
1
42
Output
2
1
2
1
Note
In the first query of the example, there are n=4 students with the skills a=[2, 10, 1, 20]. There is only one restriction here: the 1-st and the 3-th students can't be in the same team (because of |a_1 - a_3|=|2-1|=1). It is possible to divide them into 2 teams: for example, students 1, 2 and 4 are in the first team and the student 3 in the second team.
In the second query of the example, there are n=2 students with the skills a=[3, 6]. It is possible to compose just a single team containing both students. | def R(): return map(int, input().split())
q, = R()
for _ in[0]*q:
R()
a = set(R())
print(bool(a & {x+1 for x in a})+1)
| {
"input": [
"4\n4\n2 10 1 20\n2\n3 6\n5\n2 3 4 99 100\n1\n42\n"
],
"output": [
"2\n1\n2\n1\n"
]
} |
3,081 | 7 | In this task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8 Γ 8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains a statue cannot have anything or anyone β neither any other statues, nor Anna, nor Maria.
Anna is present on the board as a figurant (she stands still and never moves), and Maria has been actively involved in the game. Her goal is β to come to Anna's square. Maria and statues move in turn, Maria moves first. During one move Maria can go to any adjacent on the side or diagonal cell in which there is no statue, or she can stay in the cell where she is. The statues during their move must go one square down simultaneously, and those statues that were in the bottom row fall from the board and are no longer appeared.
At that moment, when one of the statues is in the cell in which the Maria is, the statues are declared winners. At the moment when Maria comes into the cell where Anna has been waiting, Maria is declared the winner.
Obviously, nothing depends on the statues, so it all depends on Maria. Determine who will win, if Maria does not make a strategic error.
Input
You are given the 8 strings whose length equals 8, describing the initial position on the board. The first line represents the top row of the board, the next one β for the second from the top, and so on, the last line represents the bottom row. Each character string matches a single cell board in the appropriate row, and the characters are in the same manner as that of the corresponding cell. If the cell is empty, the corresponding character is ".". If a cell has Maria, then it is represented by character "M". If a cell has Anna, it is represented by the character "A". If a cell has a statue, then the cell is represented by character "S".
It is guaranteed that the last character of the first row is always "A", the first character of the last line is always "M". The remaining characters are "." or "S".
Output
If Maria wins, print string "WIN". If the statues win, print string "LOSE".
Examples
Input
.......A
........
........
........
........
........
........
M.......
Output
WIN
Input
.......A
........
........
........
........
........
SS......
M.......
Output
LOSE
Input
.......A
........
........
........
........
.S......
S.......
MS......
Output
LOSE | start=[]
for i in range(8): start.append(input())
a=[start]
#start=[".......A","........","........","........","........",".SSSSSSS","S.......","M......."]
#a=[start]
for i in range(10):
tmp=a[-1]
tmp=[".......A"]+tmp
tmp[1]=tmp[1][:-1]+"."
a.append(tmp[:-1])
dx=[-1,1,0,0,0,1,1,-1,-1]
dy=[0,0,-1,1,0,-1,1,-1,1]
def chk(x,y,step):
if a[step][y][x]=="S": return False
if step==9:return True
for i in range(8):
x_,y_=x+dx[i],y+dy[i]
if min(x_,y_)<0 or max(x_,y_)>7:continue
if a[step][y_][x_]!='S' and chk(x_,y_,step+1): return True
return False
if chk(0,7,0):
print("WIN")
else:
print("LOSE")
| {
"input": [
".......A\n........\n........\n........\n........\n........\n........\nM.......\n",
".......A\n........\n........\n........\n........\n.S......\nS.......\nMS......\n",
".......A\n........\n........\n........\n........\n........\nSS......\nM.......\n"
],
"output": [
"WIN\n",
"LOSE",
"LOSE"
]
} |
3,082 | 8 | A positive integer is called composite if it can be represented as a product of two positive integers, both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. The following numbers aren't: 1, 2, 3, 17, 97.
Alice is given a sequence of n composite numbers a_1,a_2,β¦,a_n.
She wants to choose an integer m β€ 11 and color each element one of m colors from 1 to m so that:
* for each color from 1 to m there is at least one element of this color;
* each element is colored and colored exactly one color;
* the greatest common divisor of any two elements that are colored the same color is greater than 1, i.e. \gcd(a_i, a_j)>1 for each pair i, j if these elements are colored the same color.
Note that equal elements can be colored different colors β you just have to choose one of m colors for each of the indices from 1 to n.
Alice showed already that if all a_i β€ 1000 then she can always solve the task by choosing some m β€ 11.
Help Alice to find the required coloring. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some m from 1 to 11.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases. Then the descriptions of the test cases follow.
The first line of the test case contains a single integer n (1 β€ n β€ 1000) β the amount of numbers in a sequence a.
The second line of the test case contains n composite integers a_1,a_2,β¦,a_n (4 β€ a_i β€ 1000).
It is guaranteed that the sum of n over all test cases doesn't exceed 10^4.
Output
For each test case print 2 lines. The first line should contain a single integer m (1 β€ m β€ 11) β the number of used colors. Consider colors to be numbered from 1 to m. The second line should contain any coloring that satisfies the above conditions. Print n integers c_1, c_2, ..., c_n (1 β€ c_i β€ m), where c_i is the color of the i-th element. If there are multiple solutions then you can print any of them. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some m from 1 to 11.
Remember that each color from 1 to m should be used at least once. Any two elements of the same color should not be coprime (i.e. their GCD should be greater than 1).
Example
Input
3
3
6 10 15
2
4 9
23
437 519 865 808 909 391 194 291 237 395 323 365 511 497 781 737 871 559 731 697 779 841 961
Output
1
1 1 1
2
2 1
11
4 7 8 10 7 3 10 7 7 8 3 1 1 5 5 9 2 2 3 3 4 11 6
Note
In the first test case, \gcd(6,10)=2, \gcd(6,15)=3 and \gcd(10,15)=5. Therefore, it's valid to color all elements the same color. Note that there are other colorings which satisfy Alice's requirement in this test case.
In the second test case there is only one element of each color, so the coloring definitely satisfies Alice's requirement. | def get(x):
for i in range(2,x):
if x%i==0:
return i
return -1
pr=[2,3,5,7,11,13,17,19,23,29,31]
for _ in range(int(input())):
n=int(input());a=list(map(lambda x:pr.index(get(int(x))),input().split()))
used=[0]*11
for i in a:
used[i]=1
cnt=0;num=[]
for i in range(11):
num.append(cnt)
if used[i]:
cnt+=1
print(cnt)
print(*[num[i]+1 for i in a]) | {
"input": [
"3\n3\n6 10 15\n2\n4 9\n23\n437 519 865 808 909 391 194 291 237 395 323 365 511 497 781 737 871 559 731 697 779 841 961\n"
],
"output": [
"2\n1 1 2\n2\n1 2\n10\n8 2 3 1 2 7 1 2 2 3 7 3 4 4 5 5 6 6 7 7 8 9 10\n"
]
} |
3,083 | 11 | Pay attention to the non-standard memory limit in this problem.
In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.
The array a=[a_1, a_2, β¦, a_n] (1 β€ a_i β€ n) is given. Its element a_i is called special if there exists a pair of indices l and r (1 β€ l < r β€ n) such that a_i = a_l + a_{l+1} + β¦ + a_r. In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).
Print the number of special elements of the given array a.
For example, if n=9 and a=[3,1,4,1,5,9,2,6,5], then the answer is 5:
* a_3=4 is a special element, since a_3=4=a_1+a_2=3+1;
* a_5=5 is a special element, since a_5=5=a_2+a_3=1+4;
* a_6=9 is a special element, since a_6=9=a_1+a_2+a_3+a_4=3+1+4+1;
* a_8=6 is a special element, since a_8=6=a_2+a_3+a_4=1+4+1;
* a_9=5 is a special element, since a_9=5=a_2+a_3=1+4.
Please note that some of the elements of the array a may be equal β if several elements are equal and special, then all of them should be counted in the answer.
Input
The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases in the input. Then t test cases follow.
Each test case is given in two lines. The first line contains an integer n (1 β€ n β€ 8000) β the length of the array a. The second line contains integers a_1, a_2, ..., a_n (1 β€ a_i β€ n).
It is guaranteed that the sum of the values of n for all test cases in the input does not exceed 8000.
Output
Print t numbers β the number of special elements for each of the given arrays.
Example
Input
5
9
3 1 4 1 5 9 2 6 5
3
1 1 2
5
1 1 1 1 1
8
8 7 6 5 4 3 2 1
1
1
Output
5
1
0
4
0 | def main():
for s in[*open(0)][2::2]:
a=*map(int,s.split()),;n=len(a);b=2*n*[0];r=0
for x in a:b[x]+=1
for i in range(n):
t=a[i]
while i+1<n>=t+a[i+1]:i+=1;t+=a[i];r+=b[t];b[t]=0
print(r)
main() | {
"input": [
"5\n9\n3 1 4 1 5 9 2 6 5\n3\n1 1 2\n5\n1 1 1 1 1\n8\n8 7 6 5 4 3 2 1\n1\n1\n"
],
"output": [
"5\n1\n0\n4\n0\n"
]
} |
3,084 | 9 | Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across n sessions follow the identity permutation (ie. in the first game he scores 1 point, in the second game he scores 2 points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up!
Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on [1,2,3] can yield [3,1,2] but it cannot yield [3,2,1] since the 2 is in the same position.
Given a permutation of n integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed 10^{18}.
An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first line of each test case contains integer n (1 β€ n β€ 2 β
10^5) β the length of the given permutation.
The second line of each test case contains n integers a_{1},a_{2},...,a_{n} (1 β€ a_{i} β€ n) β the initial permutation.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.
Example
Input
2
5
1 2 3 4 5
7
3 2 4 5 1 6 7
Output
0
2
Note
In the first permutation, it is already sorted so no exchanges are needed.
It can be shown that you need at least 2 exchanges to sort the second permutation.
[3, 2, 4, 5, 1, 6, 7]
Perform special exchange on range (1, 5)
[4, 1, 2, 3, 5, 6, 7]
Perform special exchange on range (1, 4)
[1, 2, 3, 4, 5, 6, 7] | def solve(n, a):
last = -1
for i in range(n):
if a[i] != i + 1:
if last != -1 and last + 1 != i:
return 2
last = i
return 0 if last == -1 else 1
tests = int(input())
for test in range(tests):
n = int(input())
a = list(map(int, input().split()))
print(solve(n, a)) | {
"input": [
"2\n5\n1 2 3 4 5\n7\n3 2 4 5 1 6 7\n"
],
"output": [
"0\n2\n"
]
} |
3,085 | 8 | Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.
You are a new applicant for his company. Boboniu will test you with the following chess question:
Consider a nΓ m grid (rows are numbered from 1 to n, and columns are numbered from 1 to m). You have a chess piece, and it stands at some cell (S_x,S_y) which is not on the border (i.e. 2 β€ S_x β€ n-1 and 2 β€ S_y β€ m-1).
From the cell (x,y), you can move your chess piece to (x,y') (1β€ y'β€ m, y' β y) or (x',y) (1β€ x'β€ n, x'β x). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.
Your goal is to visit each cell exactly once. Can you find a solution?
Note that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.
Input
The only line of the input contains four integers n, m, S_x and S_y (3β€ n,mβ€ 100, 2 β€ S_x β€ n-1, 2 β€ S_y β€ m-1) β the number of rows, the number of columns, and the initial position of your chess piece, respectively.
Output
You should print nβ
m lines.
The i-th line should contain two integers x_i and y_i (1 β€ x_i β€ n, 1 β€ y_i β€ m), denoting the i-th cell that you visited. You should print exactly nm pairs (x_i, y_i), they should cover all possible pairs (x_i, y_i), such that 1 β€ x_i β€ n, 1 β€ y_i β€ m.
We can show that under these constraints there always exists a solution. If there are multiple answers, print any.
Examples
Input
3 3 2 2
Output
2 2
1 2
1 3
2 3
3 3
3 2
3 1
2 1
1 1
Input
3 4 2 2
Output
2 2
2 1
2 3
2 4
1 4
3 4
3 3
3 2
3 1
1 1
1 2
1 3
Note
Possible routes for two examples:
<image> | n,m,x,y = map(int,input().split())
print(x,y)
def lin(x,y):
for i in range(1,m+1):
if not(i==y):
print(x,i)
t = i
return t
y = lin(x,y)
for j in range(1,n+1):
if not(j == x):
print(j,y)
y = lin(j,y)
| {
"input": [
"3 3 2 2\n",
"3 4 2 2\n"
],
"output": [
"2 2\n1 2\n1 1\n1 3\n2 3\n2 1\n3 1\n3 2\n3 3\n",
"2 2\n1 2\n1 1\n1 3\n1 4\n2 4\n2 3\n2 1\n3 1\n3 2\n3 3\n3 4\n"
]
} |
3,086 | 10 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.
Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row and they are numbered from 1 to n from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.
An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.
You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of ice spheres in the shop.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the prices of ice spheres.
Output
In the first line print the maximum number of ice spheres that Sage can buy.
In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
Example
Input
7
1 3 2 2 4 5 4
Output
3
3 1 4 2 4 2 5
Note
In the sample it's not possible to place the ice spheres in any order so that Sage would buy 4 of them. If the spheres are placed in the order (3, 1, 4, 2, 4, 2, 5), then Sage will buy one sphere for 1 and two spheres for 2 each. | def check(arr):
n = len(arr)
ans = 0
for i in range(1,n-1):
if arr[i]<arr[i-1] and arr[i]<arr[i+1]:
ans+=1
return ans
n = int(input())
a = list(map(int,input().split()))
arr = [None]*n
a.sort()
start = 0
for i in range(1,n,2):
arr[i] = a[start]
start+=1
for i in range(n):
if arr[i]==None:
arr[i] = a[start]
start+=1
print(check(arr))
print(*arr) | {
"input": [
"7\n1 3 2 2 4 5 4\n"
],
"output": [
"3\n3 1 4 2 4 2 5 "
]
} |
3,087 | 11 | You are given an array of n integers a_1, a_2, ..., a_n, and a set b of k distinct integers from 1 to n.
In one operation, you may choose two integers i and x (1 β€ i β€ n, x can be any integer) and assign a_i := x. This operation can be done only if i does not belong to the set b.
Calculate the minimum number of operations you should perform so the array a is increasing (that is, a_1 < a_2 < a_3 < ... < a_n), or report that it is impossible.
Input
The first line contains two integers n and k (1 β€ n β€ 5 β
10^5, 0 β€ k β€ n) β the size of the array a and the set b, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
Then, if k β 0, the third line follows, containing k integers b_1, b_2, ..., b_k (1 β€ b_1 < b_2 < ... < b_k β€ n). If k = 0, this line is skipped.
Output
If it is impossible to make the array a increasing using the given operations, print -1.
Otherwise, print one integer β the minimum number of operations you have to perform.
Examples
Input
7 2
1 2 1 1 3 5 1
3 5
Output
4
Input
3 3
1 3 2
1 2 3
Output
-1
Input
5 0
4 3 1 2 3
Output
2
Input
10 3
1 3 5 6 12 9 8 10 13 15
2 4 9
Output
3 | import bisect
INF = 0x3f3f3f3f3f3f3f3f
n, k = map(int, input().split())
a = [-INF] + [ ai - i for i, ai in enumerate(map(int, input().split())) ] + [INF]
b = [0] + (list(map(int, input().split())) if k else list()) + [n+1]
def dsfa():
m=0
def gsdfa():
c=0
ans = 0
for j in range(k+1):
l = b[j]
r = b[j+1]
if a[r] < a[l]:
print("-1")
exit()
lis = list()
for ai in a[l+1:r]:
if a[l] <= ai <= a[r]:
pos = bisect.bisect(lis, ai)
if pos == len(lis):
lis.append(ai)
else:
lis[pos] = ai
ans += r - l - 1 - len(lis)
print(ans)
| {
"input": [
"7 2\n1 2 1 1 3 5 1\n3 5\n",
"5 0\n4 3 1 2 3\n",
"3 3\n1 3 2\n1 2 3\n",
"10 3\n1 3 5 6 12 9 8 10 13 15\n2 4 9\n"
],
"output": [
"4\n",
"2\n",
"-1\n",
"3\n"
]
} |
3,088 | 9 | You are given a positive number x. Find the smallest positive integer number that has the sum of digits equal to x and all digits are distinct (unique).
Input
The first line contains a single positive integer t (1 β€ t β€ 50) β the number of test cases in the test. Then t test cases follow.
Each test case consists of a single integer number x (1 β€ x β€ 50).
Output
Output t answers to the test cases:
* if a positive integer number with the sum of digits equal to x and all digits are different exists, print the smallest such number;
* otherwise print -1.
Example
Input
4
1
5
15
50
Output
1
5
69
-1 | def solution(n):
ans=[]
last=9
sm=0
while(sm<n and last>0):
ans.append(str(min(last,n-sm)))
sm+=last
last-=1
if(sm<n):
return -1
return "".join(ans[::-1])
for i in range(int(input())):
n=int(input())
print(solution(n)) | {
"input": [
"4\n1\n5\n15\n50\n"
],
"output": [
"\n1\n5\n69\n-1\n"
]
} |
3,089 | 10 | A Pythagorean triple is a triple of integer numbers (a, b, c) such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to a, b and c, respectively. An example of the Pythagorean triple is (3, 4, 5).
Vasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: c = a^2 - b.
Obviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple (3, 4, 5): 5 = 3^2 - 4, so, according to Vasya's formula, it is a Pythagorean triple.
When Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers (a, b, c) with 1 β€ a β€ b β€ c β€ n such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases.
Each test case consists of one line containing one integer n (1 β€ n β€ 10^9).
Output
For each test case, print one integer β the number of triples of integers (a, b, c) with 1 β€ a β€ b β€ c β€ n such that they are Pythagorean according both to the real definition and to the formula Vasya came up with.
Example
Input
3
3
6
9
Output
0
1
1
Note
The only Pythagorean triple satisfying c = a^2 - b with 1 β€ a β€ b β€ c β€ 9 is (3, 4, 5); that's why the answer for n = 3 is 0, and the answer for n = 6 (and for n = 9) is 1. | def pytho(n):
i=3
cnt=0
while i**2<=2*n-1:
cnt+=1
i+=2
return cnt
for i in range(int(input())):
print(pytho(int(input()))) | {
"input": [
"3\n3\n6\n9\n"
],
"output": [
"\n0\n1\n1\n"
]
} |
3,090 | 7 | You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press β upvote and downvote.
However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes.
n reviewers enter the site one by one. Each reviewer is one of the following types:
* type 1: a reviewer has watched the movie, and they like it β they press the upvote button;
* type 2: a reviewer has watched the movie, and they dislike it β they press the downvote button;
* type 3: a reviewer hasn't watched the movie β they look at the current number of upvotes and downvotes of the movie on the server they are in and decide what button to press. If there are more downvotes than upvotes, then a reviewer downvotes the movie. Otherwise, they upvote the movie.
Each reviewer votes on the movie exactly once.
Since you have two servers, you can actually manipulate the votes so that your movie gets as many upvotes as possible. When a reviewer enters a site, you know their type, and you can send them either to the first server or to the second one.
What is the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to?
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of testcases.
Then the descriptions of t testcases follow.
The first line of each testcase contains a single integer n (1 β€ n β€ 50) β the number of reviewers.
The second line of each testcase contains n integers r_1, r_2, ..., r_n (1 β€ r_i β€ 3) β the types of the reviewers in the same order they enter the site.
Output
For each testcase print a single integer β the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to.
Example
Input
4
1
2
3
1 2 3
5
1 1 1 1 1
3
3 3 2
Output
0
2
5
2
Note
In the first testcase of the example you can send the only reviewer to either of the servers β they'll downvote anyway. The movie won't receive any upvotes.
In the second testcase of the example you can send all reviewers to the first server:
* the first reviewer upvotes;
* the second reviewer downvotes;
* the last reviewer sees that the number of downvotes is not greater than the number of upvotes β upvote themselves.
There are two upvotes in total. Alternatevely, you can send the first and the second reviewers to the first server and the last reviewer β to the second server:
* the first reviewer upvotes on the first server;
* the second reviewer downvotes on the first server;
* the last reviewer sees no upvotes or downvotes on the second server β upvote themselves. | def ints():
return list(map(int, input().split()))
def case():
n, = ints()
r = ints()
return n - r.count(2)
t, = ints()
for i in range(t):
print(case())
| {
"input": [
"4\n1\n2\n3\n1 2 3\n5\n1 1 1 1 1\n3\n3 3 2\n"
],
"output": [
"\n0\n2\n5\n2\n"
]
} |
3,091 | 12 | You are given two integers l and r, where l < r. We will add 1 to l until the result is equal to r. Thus, there will be exactly r-l additions performed. For each such addition, let's look at the number of digits that will be changed after it.
For example:
* if l=909, then adding one will result in 910 and 2 digits will be changed;
* if you add one to l=9, the result will be 10 and 2 digits will also be changed;
* if you add one to l=489999, the result will be 490000 and 5 digits will be changed.
Changed digits always form a suffix of the result written in the decimal system.
Output the total number of changed digits, if you want to get r from l, adding 1 each time.
Input
The first line contains an integer t (1 β€ t β€ 10^4). Then t test cases follow.
Each test case is characterized by two integers l and r (1 β€ l < r β€ 10^9).
Output
For each test case, calculate the total number of changed digits if you want to get r from l, adding one each time.
Example
Input
4
1 9
9 10
10 20
1 1000000000
Output
8
2
11
1111111110 | def f(x):return sum([x//pow(10,i) for i in range(11)])
for _ in range(int(input())):
l,r=map(int,input().split())
print(f(r)-f(l))
| {
"input": [
"4\n1 9\n9 10\n10 20\n1 1000000000\n"
],
"output": [
"\n8\n2\n11\n1111111110\n"
]
} |
3,092 | 7 | One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y):
* point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y
* point (x', y') is (x, y)'s left neighbor, if x' < x and y' = y
* point (x', y') is (x, y)'s lower neighbor, if x' = x and y' < y
* point (x', y') is (x, y)'s upper neighbor, if x' = x and y' > y
We'll consider point (x, y) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.
Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.
Input
The first input line contains the only integer n (1 β€ n β€ 200) β the number of points in the given set. Next n lines contain the coordinates of the points written as "x y" (without the quotes) (|x|, |y| β€ 1000), all coordinates are integers. The numbers in the line are separated by exactly one space. It is guaranteed that all points are different.
Output
Print the only number β the number of supercentral points of the given set.
Examples
Input
8
1 1
4 2
3 1
1 2
0 2
0 1
1 0
1 3
Output
2
Input
5
0 0
0 1
1 0
0 -1
-1 0
Output
1
Note
In the first sample the supercentral points are only points (1, 1) and (1, 2).
In the second sample there is one supercental point β point (0, 0). | #!/usr/bin/python3
def readln(): return tuple(map(int, input().split()))
n, = readln()
xx = {}
yy = {}
points = []
for _ in range(n):
x, y = readln()
if x not in xx:
xx[x] = []
xx[x].append(y)
if y not in yy:
yy[y] = []
yy[y].append(x)
points.append((x, y))
ans = 0
for x, y in points:
ans += min(xx[x]) < y < max(xx[x]) and min(yy[y]) < x < max(yy[y])
print(ans)
| {
"input": [
"8\n1 1\n4 2\n3 1\n1 2\n0 2\n0 1\n1 0\n1 3\n",
"5\n0 0\n0 1\n1 0\n0 -1\n-1 0\n"
],
"output": [
"2\n",
"1\n"
]
} |
3,093 | 8 | Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3. | def main():
n,t1,t2,p=map(int,input().split())
p=1-(p/100)
a=[0]*n
for i in range(n):
x,y=map(int,input().split())
z=max(((x*t1*p)+(y*t2)),((y*t1*p)+(x*t2)))
a[i]=[i+1,z]
a.sort(key=lambda x:x[1],reverse=True)
for i in a:
print(i[0],'%.2f'%i[1])
main() | {
"input": [
"4 1 1 1\n544 397\n280 101\n280 101\n693 970\n",
"2 3 3 50\n2 4\n4 2\n"
],
"output": [
"4 1656.07\n1 937.03\n2 379.99\n3 379.99\n",
"1 15.00\n2 15.00\n"
]
} |
3,094 | 8 | You are given three positive integers x, y, n. Your task is to find the nearest fraction to fraction <image> whose denominator is no more than n.
Formally, you should find such pair of integers a, b (1 β€ b β€ n; 0 β€ a) that the value <image> is as minimal as possible.
If there are multiple "nearest" fractions, choose the one with the minimum denominator. If there are multiple "nearest" fractions with the minimum denominator, choose the one with the minimum numerator.
Input
A single line contains three integers x, y, n (1 β€ x, y, n β€ 105).
Output
Print the required fraction in the format "a/b" (without quotes).
Examples
Input
3 7 6
Output
2/5
Input
7 2 4
Output
7/2 | def s():
[x,y,n] = list(map(int,input().split()))
res = (0,1)
for b in range(1,n+1):
a = int(round(b*x/y,0)+0.1)
if abs(x*res[1]-y*res[0])*b > abs(x*b-y*(a-1))*res[1]:
res = (a-1,b)
if abs(x*res[1]-y*res[0])*b > abs(x*b-y*a)*res[1]:
res = (a,b)
print(*res,sep='/')
s()
| {
"input": [
"7 2 4\n",
"3 7 6\n"
],
"output": [
"7/2\n",
"2/5\n"
]
} |
3,095 | 7 | In mathematics, the Pythagorean theorem β is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states:
In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle).
The theorem can be written as an equation relating the lengths of the sides a, b and c, often called the Pythagorean equation:
a2 + b2 = c2
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides.
<image>
Given n, your task is to count how many right-angled triangles with side-lengths a, b and c that satisfied an inequality 1 β€ a β€ b β€ c β€ n.
Input
The only line contains one integer n (1 β€ n β€ 104) as we mentioned above.
Output
Print a single integer β the answer to the problem.
Examples
Input
5
Output
1
Input
74
Output
35 | def gcd(m, n):
return m if not n else gcd(n, m%n)
n = int(input())
cnt = 0
for i in range(2, int(n**0.5)+2):
for j in range(1+i%2, i, 2):
if gcd(i,j)==1:
cnt += n//(i*i+j*j)
print(cnt) | {
"input": [
"5\n",
"74\n"
],
"output": [
"1",
"35"
]
} |
3,096 | 8 | A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given m pairs of cities β roads cannot be constructed between these pairs of cities.
Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.
Input
The first line consists of two integers n and m <image>.
Then m lines follow, each consisting of two integers ai and bi (1 β€ ai, bi β€ n, ai β bi), which means that it is not possible to construct a road connecting cities ai and bi. Consider the cities are numbered from 1 to n.
It is guaranteed that every pair of cities will appear at most once in the input.
Output
You should print an integer s: the minimum number of roads that should be constructed, in the first line. Then s lines should follow, each consisting of two integers ai and bi (1 β€ ai, bi β€ n, ai β bi), which means that a road should be constructed between cities ai and bi.
If there are several solutions, you may print any of them.
Examples
Input
4 1
1 3
Output
3
1 2
4 2
2 3
Note
This is one possible solution of the example:
<image>
These are examples of wrong solutions:
<image> The above solution is wrong because it doesn't use the minimum number of edges (4 vs 3). In addition, it also tries to construct a road between cities 1 and 3, while the input specifies that it is not allowed to construct a road between the pair. <image> The above solution is wrong because you need to traverse at least 3 roads to go from city 1 to city 3, whereas in your country it must be possible to go from any city to another by traversing at most 2 roads. <image> Finally, the above solution is wrong because it must be possible to go from any city to another, whereas it is not possible in this country to go from city 1 to 3, 2 to 3, and 4 to 3. | import sys
def get_ints(): return map(int, sys.stdin.readline().split())
n,m=get_ints()
a=[0]*(n+1)
for _ in range(m):
x,y=get_ints()
a[x]+=1
a[y]+=1
j=-2
#print(a)
for i in range(1,n+1):
if a[i]==0:
j=i
break
print(n-1)
for q in range(1,n+1):
if q==j:
continue
print(j,q)
| {
"input": [
"4 1\n1 3\n"
],
"output": [
"3\n2 1\n2 3\n2 4\n"
]
} |
3,097 | 7 | You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image> | def main():
s = input()
res = 0
for i, c in enumerate(s, -s.find('^')):
if c.isdigit():
res += i * int(c)
print(('left', 'right', 'balance')[(not res) * 2 + (res > 0)])
if __name__ == '__main__':
main() | {
"input": [
"=^==\n",
"2==^7==\n",
"41^52==\n",
"9===^==1\n"
],
"output": [
"balance",
"right",
"balance",
"left"
]
} |
3,098 | 10 | The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.
But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:
* each cup contains a mark β a number from 1 to n; all marks on the cups are distinct;
* the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).
When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.
Input
The first line contains integers n and m (1 β€ n, m β€ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 β€ xi, yi β€ n) β the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.
Output
If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.
If there are multiple correct answers, you should print the lexicographically minimum one.
Examples
Input
2 1
2 1
Output
2 1
Input
3 2
1 2
1 1
Output
2 1 3
Input
3 3
1 3
2 3
1 3
Output
-1 | import io
import os
# List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class UnsortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
# self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
# _mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
# _mins[pos] = _lists[pos][0]
pass
else:
del _lists[pos]
del _list_lens[pos]
# del _mins[pos]
self._rebuild = True
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __setitem__(self, index, value):
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._lists[pos][idx] = value
def insert(self, index, value):
_load = self._load
_lists = self._lists
_list_lens = self._list_lens
if _lists:
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_list_lens.append(1)
self._rebuild = True
self._len += 1
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
def solve(N, M, queries):
idToMark = [-1 for i in range(N)]
cups = UnsortedList([i for i in range(N)])
for mark, pos in queries:
pos -= 1 # 0-indexed
cupId = cups[pos]
del cups[pos]
cups.insert(0, cupId)
if idToMark[cupId] == -1:
idToMark[cupId] = mark
elif idToMark[cupId] != mark:
return b"-1"
markToCounts = [0 for i in range(N + 1)]
for cupId, mark in enumerate(idToMark):
if mark != -1:
markToCounts[mark] += 1
if markToCounts[mark] > 1:
return b"-1"
j = 1
ans = []
for cupId, mark in enumerate(idToMark):
if mark != -1:
ans.append(mark)
else:
while markToCounts[j] > 0:
j += 1
ans.append(j)
j += 1
return b" ".join(str(x).encode("ascii") for x in ans)
if False:
N, M = 10 ** 6, 10 ** 6
queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)]
ans = solve(N, M, queries)
# print(ans)
assert ans != b"-1"
exit()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
queries = ((int(x) for x in input().split()) for i in range(M))
ans = solve(N, M, queries)
os.write(1, ans)
| {
"input": [
"2 1\n2 1\n",
"3 2\n1 2\n1 1\n",
"3 3\n1 3\n2 3\n1 3\n"
],
"output": [
"2 1",
"2 1 3",
"-1"
]
} |
3,099 | 8 | DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41. | def readln(): return tuple(map(int, input().split()))
s = input()
k, = readln()
w = readln()
ans = sum([(i + 1) * w[ord(c) - ord('a')] for i, c in enumerate(s)])
print(ans + max(w) * (2 * len(s) + k + 1) * k // 2) | {
"input": [
"abc\n3\n1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n"
],
"output": [
"41\n"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.