index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
2,300 | 10 | Your program fails again. This time it gets "Wrong answer on test 233"
.
This is the easier version of the problem. In this version 1 β€ n β€ 2000. You can hack this problem only if you solve and lock both problems.
The problem is about a test containing n one-choice-questions. Each of the questions contains k options, and only one of them is correct. The answer to the i-th question is h_{i}, and if your answer of the question i is h_{i}, you earn 1 point, otherwise, you earn 0 points for this question. The values h_1, h_2, ..., h_n are known to you in this problem.
However, you have a mistake in your program. It moves the answer clockwise! Consider all the n answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.
Formally, the mistake moves the answer for the question i to the question i mod n + 1. So it moves the answer for the question 1 to question 2, the answer for the question 2 to the question 3, ..., the answer for the question n to the question 1.
We call all the n answers together an answer suit. There are k^n possible answer suits in total.
You're wondering, how many answer suits satisfy the following condition: after moving clockwise by 1, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo 998 244 353.
For example, if n = 5, and your answer suit is a=[1,2,3,4,5], it will submitted as a'=[5,1,2,3,4] because of a mistake. If the correct answer suit is h=[5,2,2,3,4], the answer suit a earns 1 point and the answer suite a' earns 4 points. Since 4 > 1, the answer suit a=[1,2,3,4,5] should be counted.
Input
The first line contains two integers n, k (1 β€ n β€ 2000, 1 β€ k β€ 10^9) β the number of questions and the number of possible answers to each question.
The following line contains n integers h_1, h_2, ..., h_n, (1 β€ h_{i} β€ k) β answers to the questions.
Output
Output one integer: the number of answers suits satisfying the given condition, modulo 998 244 353.
Examples
Input
3 3
1 3 1
Output
9
Input
5 5
1 1 4 2 2
Output
1000
Note
For the first example, valid answer suits are [2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,2,3]. | def main():
M=998244353
n,k,*h=map(int,open(0).read().split())
m=sum(i!=j for i,j in zip(h,h[1:]+h[:1]))
f=[0]*(m+1)
f[0]=b=1
for i in range(1,m+1):f[i]=b=b*i%M
inv=[0]*(m+1)
inv[m]=b=pow(f[m],M-2,M)
for i in range(m,0,-1):inv[i-1]=b=b*i%M
comb=lambda n,k:f[n]*inv[n-k]*inv[k]%M
print((pow(k,m,M)-sum(comb(m,i)*comb(m-i,i)*pow(k-2,m-i-i,M)for i in range(m//2+1)))*pow(k,n-m,M)*pow(2,M-2,M)%M)
main() | {
"input": [
"3 3\n1 3 1\n",
"5 5\n1 1 4 2 2\n"
],
"output": [
"9\n",
"1000\n"
]
} |
2,301 | 12 | Polycarp has decided to decorate his room because the New Year is soon. One of the main decorations that Polycarp will install is the garland he is going to solder himself.
Simple garlands consisting of several lamps connected by one wire are too boring for Polycarp. He is going to solder a garland consisting of n lamps and n - 1 wires. Exactly one lamp will be connected to power grid, and power will be transmitted from it to other lamps by the wires. Each wire connectes exactly two lamps; one lamp is called the main lamp for this wire (the one that gets power from some other wire and transmits it to this wire), the other one is called the auxiliary lamp (the one that gets power from this wire). Obviously, each lamp has at most one wire that brings power to it (and this lamp is the auxiliary lamp for this wire, and the main lamp for all other wires connected directly to it).
Each lamp has a brightness value associated with it, the i-th lamp has brightness 2^i. We define the importance of the wire as the sum of brightness values over all lamps that become disconnected from the grid if the wire is cut (and all other wires are still working).
Polycarp has drawn the scheme of the garland he wants to make (the scheme depicts all n lamp and n - 1 wires, and the lamp that will be connected directly to the grid is marked; the wires are placed in such a way that the power can be transmitted to each lamp). After that, Polycarp calculated the importance of each wire, enumerated them from 1 to n - 1 in descending order of their importance, and then wrote the index of the main lamp for each wire (in the order from the first wire to the last one).
The following day Polycarp bought all required components of the garland and decided to solder it β but he could not find the scheme. Fortunately, Polycarp found the list of indices of main lamps for all wires. Can you help him restore the original scheme?
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the number of lamps.
The second line contains n - 1 integers a_1, a_2, ..., a_{n - 1} (1 β€ a_i β€ n), where a_i is the index of the main lamp for the i-th wire (wires are numbered in descending order of importance).
Output
If it is impossible to restore the original scheme, print one integer -1.
Otherwise print the scheme as follows. In the first line, print one integer k (1 β€ k β€ n) β the index of the lamp that is connected to the power grid. Then print n - 1 lines, each containing two integers x_i and y_i (1 β€ x_i, y_i β€ n, x_i β y_i) β the indices of the lamps connected by some wire. The descriptions of the wires (and the lamps connected by a wire) can be printed in any order. The printed description must correspond to a scheme of a garland such that Polycarp could have written the list a_1, a_2, ..., a_{n - 1} from it. If there are multiple such schemes, output any of them.
Example
Input
6
3 6 3 1 5
Output
3
6 3
6 5
1 3
1 4
5 2
Note
The scheme for the first example (R denotes the lamp connected to the grid, the numbers on wires are their importance values):
<image> | from heapq import heappush, heappop
from collections import Counter
def main():
n = int(input())
aa = [int(a)-1 for a in input().split()]
saa = set(aa)
caa = Counter(aa)
ready = []
for i in range(n):
if i not in saa:
heappush(ready, (i,i))
print(aa[0] + 1)
for a in aa[::-1]:
imp, c = heappop(ready)
print(a+1, c+1)
caa[a] -=1
if caa[a] == 0:
heappush(ready, (max(a, imp), a))
if __name__ == "__main__":
main() | {
"input": [
"6\n3 6 3 1 5\n"
],
"output": [
"3\n3 6\n6 5\n3 1\n1 4\n5 2\n"
]
} |
2,302 | 8 | Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, ..., g are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
Input
The first line contains a single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next T lines contain test cases β one per line. Each line contains three integers n, g and b (1 β€ n, g, b β€ 10^9) β the length of the highway and the number of good and bad days respectively.
Output
Print T integers β one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
Example
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
Note
In the first test case, you can just lay new asphalt each day, since days 1, 3, 5 are good.
In the second test case, you can also lay new asphalt each day, since days 1-8 are good. | def solve():
n, g, b = map(int, input().split())
target = (n + 1) // 2
rounds = (target - 1) // g
days = target + rounds * b
print(max(n, days))
T = int(input())
for _ in range(T):
solve() | {
"input": [
"3\n5 1 1\n8 10 10\n1000000 1 1000000\n"
],
"output": [
"5\n8\n499999500000\n"
]
} |
2,303 | 9 | Petya has a rectangular Board of size n Γ m. Initially, k chips are placed on the board, i-th chip is located in the cell at the intersection of sx_i-th row and sy_i-th column.
In one action, Petya can move all the chips to the left, right, down or up by 1 cell.
If the chip was in the (x, y) cell, then after the operation:
* left, its coordinates will be (x, y - 1);
* right, its coordinates will be (x, y + 1);
* down, its coordinates will be (x + 1, y);
* up, its coordinates will be (x - 1, y).
If the chip is located by the wall of the board, and the action chosen by Petya moves it towards the wall, then the chip remains in its current position.
Note that several chips can be located in the same cell.
For each chip, Petya chose the position which it should visit. Note that it's not necessary for a chip to end up in this position.
Since Petya does not have a lot of free time, he is ready to do no more than 2nm actions.
You have to find out what actions Petya should do so that each chip visits the position that Petya selected for it at least once. Or determine that it is not possible to do this in 2nm actions.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 200) β the number of rows and columns of the board and the number of chips, respectively.
The next k lines contains two integers each sx_i, sy_i ( 1 β€ sx_i β€ n, 1 β€ sy_i β€ m) β the starting position of the i-th chip.
The next k lines contains two integers each fx_i, fy_i ( 1 β€ fx_i β€ n, 1 β€ fy_i β€ m) β the position that the i-chip should visit at least once.
Output
In the first line print the number of operations so that each chip visits the position that Petya selected for it at least once.
In the second line output the sequence of operations. To indicate operations left, right, down, and up, use the characters L, R, D, U respectively.
If the required sequence does not exist, print -1 in the single line.
Examples
Input
3 3 2
1 2
2 1
3 3
3 2
Output
3
DRD
Input
5 4 3
3 4
3 1
3 3
5 3
1 3
1 4
Output
9
DDLUUUURR | from sys import stdin, stdout
def main():
N,M,K=list(map(int,input().split()))
res='D'*(N-1)+'L'*(M-1)
for i in range(M):
if(i%2):
res+='D'*(N-1)
else:
res+='U'*(N-1)
res+='R'
print(len(res[:-1]))
print(res[:-1])
main() | {
"input": [
"5 4 3\n3 4\n3 1\n3 3\n5 3\n1 3\n1 4\n",
"3 3 2\n1 2\n2 1\n3 3\n3 2\n"
],
"output": [
"26\nUUUULLLRRRDLLLDRRRDLLLDRRR",
"12\nUULLRRDLLDRR"
]
} |
2,304 | 9 | Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.
To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the following conditions are satisfied:
* The picture is connected, that is, it is possible to get from any gray cell to any other by following a chain of gray cells, with each pair of adjacent cells in the path being neighbours (that is, sharing a side).
* Each gray cell has an even number of gray neighbours.
* There are exactly n gray cells with all gray neighbours. The number of other gray cells can be arbitrary (but reasonable, so that they can all be listed).
Leo Jr. is now struggling to draw a beautiful picture with a particular choice of n. Help him, and provide any example of a beautiful picture.
To output cell coordinates in your answer, assume that the sheet is provided with a Cartesian coordinate system such that one of the cells is chosen to be the origin (0, 0), axes 0x and 0y are orthogonal and parallel to grid lines, and a unit step along any axis in any direction takes you to a neighbouring cell.
Input
The only line contains a single integer n (1 β€ n β€ 500) β the number of gray cells with all gray neighbours in a beautiful picture.
Output
In the first line, print a single integer k β the number of gray cells in your picture. For technical reasons, k should not exceed 5 β
10^5.
Each of the following k lines should contain two integers β coordinates of a gray cell in your picture. All listed cells should be distinct, and the picture should satisdfy all the properties listed above. All coordinates should not exceed 10^9 by absolute value.
One can show that there exists an answer satisfying all requirements with a small enough k.
Example
Input
4
Output
12
1 0
2 0
0 1
1 1
2 1
3 1
0 2
1 2
2 2
3 2
1 3
2 3
Note
The answer for the sample is pictured below:
<image> | def cout(i):
print(str(i-1)+" "+str(i))
print(str(i)+" "+str(i-1))
print(str(i)+" "+str(i))
n=int(input())
print(4+n*3)
print("0 0")
for i in range(1,n+2):
cout(i)
| {
"input": [
"4\n"
],
"output": [
"16\n0 0\n0 1\n1 0\n1 1\n1 2\n2 1\n2 2\n2 3\n3 2\n3 3\n3 4\n4 3\n4 4\n4 5\n5 4\n5 5\n"
]
} |
2,305 | 11 | Berland year consists of m months with d days each. Months are numbered from 1 to m. Berland week consists of w days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than w days.
A pair (x, y) such that x < y is ambiguous if day x of month y is the same day of the week as day y of month x.
Count the number of ambiguous pairs.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Each of the next t lines contains three integers m, d and w (1 β€ m, d, w β€ 10^9) β the number of months in a year, the number of days in a month and the number of days in a week.
Output
Print t integers β for each testcase output the number of pairs (x, y) such that x < y and day x of month y is the same day of the week as day y of month x.
Example
Input
5
6 7 4
10 7 12
12 30 7
1 1 1
3247834 10298779 625324
Output
6
9
5
0
116461800
Note
Here are the pairs for the first test case:
<image> | def GCD(x, y):
while(y):x,y=y,x%y
return x
for i in ' '*int(input()):
m,d,w=map(int,input().split())
m=min(m,d)
g=GCD(d-1,w)
ww=w//g
k=m//ww
print(k*m-k*(k+1)//2*ww) | {
"input": [
"5\n6 7 4\n10 7 12\n12 30 7\n1 1 1\n3247834 10298779 625324\n"
],
"output": [
"6\n9\n5\n0\n116461800\n"
]
} |
2,306 | 8 | As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has n friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to n in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the i-th friend sent to Alexander a card number i.
Alexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules:
1. He will never send to a firend a card that this friend has sent to him.
2. Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most.
Alexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times.
Alexander and each his friend has the list of preferences, which is a permutation of integers from 1 to n. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card.
Your task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible.
Note that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.
Input
The first line contains an integer n (2 β€ n β€ 300) β the number of Alexander's friends, equal to the number of cards. Next n lines contain his friends' preference lists. Each list consists of n different integers from 1 to n. The last line contains Alexander's preference list in the same format.
Output
Print n space-separated numbers: the i-th number should be the number of the friend, whose card Alexander receives right before he should send a card to the i-th friend. If there are several solutions, print any of them.
Examples
Input
4
1 2 3 4
4 1 3 2
4 3 1 2
3 4 2 1
3 1 2 4
Output
2 1 1 4
Note
In the sample, the algorithm of actions Alexander and his friends perform is as follows:
1. Alexander receives card 1 from the first friend.
2. Alexander sends the card he has received (at the moment he only has one card, and therefore it is the most preferable for him) to friends with the numbers 2 and 3.
3. Alexander receives card 2 from the second friend, now he has two cards β 1 and 2.
4. Alexander sends a card to the first friend. Despite the fact that Alexander likes card 1 more, he sends card 2 as he cannot send a friend the card sent by that very friend.
5. Alexander receives card 3 from the third friend.
6. Alexander receives card 4 from the fourth friend.
7. Among the cards Alexander has number 3 is his favorite and he sends it to the fourth friend.
Note that Alexander can send cards to multiple friends at a time (in this case the second and the third one). Alexander can send card 3 to the fourth friend after he receives the third card or after he receives the fourth card (both variants are correct). | def f():
t = [0] * n
for i, j in enumerate(input().split()): t[int(j) - 1] = i
return t
n = int(input())
p = [f() for i in range(n)]
s = f()
for x, t in enumerate(p):
i = j = x < 1
for y in range(n):
if x != y and s[y] < s[i]: i = y
if t[i] < t[j]: j = i
print(j + 1) | {
"input": [
"4\n1 2 3 4\n4 1 3 2\n4 3 1 2\n3 4 2 1\n3 1 2 4\n"
],
"output": [
"2 1 1 3 \n"
]
} |
2,307 | 12 | Recently you've discovered a new shooter. They say it has realistic game mechanics.
Your character has a gun with magazine size equal to k and should exterminate n waves of monsters. The i-th wave consists of a_i monsters and happens from the l_i-th moment of time up to the r_i-th moments of time. All a_i monsters spawn at moment l_i and you have to exterminate all of them before the moment r_i ends (you can kill monsters right at moment r_i). For every two consecutive waves, the second wave starts not earlier than the first wave ends (though the second wave can start at the same moment when the first wave ends) β formally, the condition r_i β€ l_{i + 1} holds. Take a look at the notes for the examples to understand the process better.
You are confident in yours and your character's skills so you can assume that aiming and shooting are instant and you need exactly one bullet to kill one monster. But reloading takes exactly 1 unit of time.
One of the realistic mechanics is a mechanic of reloading: when you reload you throw away the old magazine with all remaining bullets in it. That's why constant reloads may cost you excessive amounts of spent bullets.
You've taken a liking to this mechanic so now you are wondering: what is the minimum possible number of bullets you need to spend (both used and thrown) to exterminate all waves.
Note that you don't throw the remaining bullets away after eradicating all monsters, and you start with a full magazine.
Input
The first line contains two integers n and k (1 β€ n β€ 2000; 1 β€ k β€ 10^9) β the number of waves and magazine size.
The next n lines contain descriptions of waves. The i-th line contains three integers l_i, r_i and a_i (1 β€ l_i β€ r_i β€ 10^9; 1 β€ a_i β€ 10^9) β the period of time when the i-th wave happens and the number of monsters in it.
It's guaranteed that waves don't overlap (but may touch) and are given in the order they occur, i. e. r_i β€ l_{i + 1}.
Output
If there is no way to clear all waves, print -1. Otherwise, print the minimum possible number of bullets you need to spend (both used and thrown) to clear all waves.
Examples
Input
2 3
2 3 6
3 4 3
Output
9
Input
2 5
3 7 11
10 12 15
Output
30
Input
5 42
42 42 42
42 43 42
43 44 42
44 45 42
45 45 1
Output
-1
Input
1 10
100 111 1
Output
1
Note
In the first example:
* At the moment 2, the first wave occurs and 6 monsters spawn. You kill 3 monsters and start reloading.
* At the moment 3, the second wave occurs and 3 more monsters spawn. You kill remaining 3 monsters from the first wave and start reloading.
* At the moment 4, you kill remaining 3 monsters from the second wave.
In total, you'll spend 9 bullets.
In the second example:
* At moment 3, the first wave occurs and 11 monsters spawn. You kill 5 monsters and start reloading.
* At moment 4, you kill 5 more monsters and start reloading.
* At moment 5, you kill the last monster and start reloading throwing away old magazine with 4 bullets.
* At moment 10, the second wave occurs and 15 monsters spawn. You kill 5 monsters and start reloading.
* At moment 11, you kill 5 more monsters and start reloading.
* At moment 12, you kill last 5 monsters.
In total, you'll spend 30 bullets. | import sys
from array import array # noqa: F401
import typing as Tp # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def output(*args):
sys.stdout.buffer.write(
('\n'.join(map(str, args)) + '\n').encode('utf-8')
)
def main():
n, k = map(int, input().split())
wave = [tuple(map(int, input().split())) for _ in range(n)]
ans = inf = 10**18
dp = [0] + [inf] * (n - 1)
for i in range(n):
if dp[i] == inf:
continue
time = wave[i][0]
bullet = k
cost = dp[i]
for j in range(i, n):
time = max(time, wave[j][0])
if bullet >= wave[j][2]:
bullet -= wave[j][2]
else:
ub = wave[j][1] - time
reload = (wave[j][2] - bullet - 1) // k + 1
if ub < reload:
break
time += reload
bullet = (-wave[j][2] + bullet) % k
cost += wave[j][2]
if j < n - 1 and time < wave[j + 1][0]:
dp[j + 1] = min(dp[j + 1], cost + bullet)
else:
ans = min(ans, cost)
print(ans if ans < inf else -1)
if __name__ == '__main__':
main()
| {
"input": [
"2 3\n2 3 6\n3 4 3\n",
"2 5\n3 7 11\n10 12 15\n",
"5 42\n42 42 42\n42 43 42\n43 44 42\n44 45 42\n45 45 1\n",
"1 10\n100 111 1\n"
],
"output": [
"9\n",
"30\n",
"-1\n",
"1\n"
]
} |
2,308 | 8 | There is a game called "Unique Bid Auction". You can read more about it here: https://en.wikipedia.org/wiki/Unique_bid_auction (though you don't have to do it to solve this problem).
Let's simplify this game a bit. Formally, there are n participants, the i-th participant chose the number a_i. The winner of the game is such a participant that the number he chose is unique (i. e. nobody else chose this number except him) and is minimal (i. e. among all unique values of a the minimum one is the winning one).
Your task is to find the index of the participant who won the game (or -1 if there is no winner). Indexing is 1-based, i. e. the participants are numbered from 1 to n.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of participants. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th participant chosen number.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the index of the participant who won the game (or -1 if there is no winner). Note that the answer is always unique.
Example
Input
6
2
1 1
3
2 1 3
4
2 2 2 3
1
1
5
2 3 2 4 2
6
1 1 5 5 4 4
Output
-1
2
4
1
2
-1 | def solve():
n = int(input())
a = list(map(int, input().split()))
cnt = [[] for _ in range(n)]
for i, x in enumerate(a):
cnt[x-1].append(i+1)
for i, l in enumerate(cnt):
if(len(l) == 1):
print(l[0])
return
print(-1)
t = int(input())
for _ in range(t):
solve()
| {
"input": [
"6\n2\n1 1\n3\n2 1 3\n4\n2 2 2 3\n1\n1\n5\n2 3 2 4 2\n6\n1 1 5 5 4 4\n"
],
"output": [
"\n-1\n2\n4\n1\n2\n-1\n"
]
} |
2,309 | 8 | Many people are aware of DMCA β Digital Millennium Copyright Act. But another recently proposed DMCA β Digital Millennium Calculation Act β is much less known.
In this problem you need to find a root of a number according to this new DMCA law.
Input
The input contains a single integer a (1 β€ a β€ 1000000).
Output
Output the result β an integer number.
Examples
Input
1
Output
1
Input
81
Output
9 | n = int(input())
def f(n):
ret = 0
for i in str(n):
ret += int(i)
return ret
while n > 9:
n = f(n)
print(n) | {
"input": [
"1\n",
"81\n"
],
"output": [
"\n1\n",
"\n9\n"
]
} |
2,310 | 9 | Soroush and Keshi each have a labeled and rooted tree on n vertices. Both of their trees are rooted from vertex 1.
Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph on n vertices.
They add an edge between vertices u and v in the memorial graph if both of the following conditions hold:
* One of u or v is the ancestor of the other in Soroush's tree.
* Neither of u or v is the ancestor of the other in Keshi's tree.
Here vertex u is considered ancestor of vertex v, if u lies on the path from 1 (the root) to the v.
Popping out of nowhere, Mashtali tried to find the maximum clique in the memorial graph for no reason. He failed because the graph was too big.
Help Mashtali by finding the size of the maximum clique in the memorial graph.
As a reminder, clique is a subset of vertices of the graph, each two of which are connected by an edge.
Input
The first line contains an integer t (1β€ tβ€ 3 β
10^5) β 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β€ 3 β
10^5).
The second line of each test case contains n-1 integers a_2, β¦, a_n (1 β€ a_i < i), a_i being the parent of the vertex i in Soroush's tree.
The third line of each test case contains n-1 integers b_2, β¦, b_n (1 β€ b_i < i), b_i being the parent of the vertex i in Keshi's tree.
It is guaranteed that the given graphs are trees.
It is guaranteed that the sum of n over all test cases doesn't exceed 3 β
10^5.
Output
For each test case print a single integer β the size of the maximum clique in the memorial graph.
Example
Input
4
4
1 2 3
1 2 3
5
1 2 3 4
1 1 1 1
6
1 1 1 1 2
1 2 1 2 2
7
1 1 3 4 4 5
1 2 1 4 2 5
Output
1
4
1
3
Note
In the first and third test cases, you can pick any vertex.
In the second test case, one of the maximum cliques is \{2, 3, 4, 5\}.
In the fourth test case, one of the maximum cliques is \{3, 4, 6\}. | import sys
input = sys.stdin.buffer.readline
class bit:
def __init__(self, n):
self.n = n
self.a = [0]*(n+1)
def add(self, idx, val):
idx += 1
while idx < self.n:
self.a[idx] += val
idx += idx & -idx
def sumr(self, idx):
idx += 1
tot = 0
while idx:
tot += self.a[idx]
idx -= idx & -idx
return tot
def sum(self, l, r):
return self.sumr(r) - self.sumr(l-1)
def add(i):
bit2.add(tin[i], 1)
bit1.add(tin[i], i)
bit1.add(tout[i] + 1, -i)
def remove(i):
bit2.add(tin[i], -1)
bit1.add(tin[i], -i)
bit1.add(tout[i] + 1, i)
for _ in range(int(input())):
n = int(input())
adj = [[[] for i in range(n+1)] for j in range(2)]
for k in range(2):
a = list(map(int,input().split()))
for i in range(2,n+1):
adj[k][a[i-2]].append(i)
ans = 0
# we use tin and tout so we can determine if a node is an ancestor of another
tin = [0]*(n+1)
tout = [0]*(n+1)
t = -1
s = [1]
visited = [0]*(n+1)
while s:
c = s[-1]
if not visited[c]:
t += 1
tin[c] = t
visited[c] = 1
for ne in adj[1][c]:
if not visited[ne]:
s.append(ne)
else:
tout[c] = t
s.pop()
curr_mx = 0
# we use the bits to keep track of the maximum set of nodes such that no node
# is an ancestor of another in keshi's tree
# the tin and tout form disjoint ranges and we keep the max width range if they intersect
bit1 = bit(n+1)
bit2 = bit(n+1)
ops = [] # to undo operations to bits [u,v] -> u was removed v was added
s = [1]
visited = [0] * (n + 1)
while s:
c = s[-1]
if not visited[c]:
visited[c] = 1
# update set of max elements (implicitly represented by bit1 and bit2)
u = bit1.sumr(tin[c])
if u:
# c is in the subtree of one of the nodes in the set, which we call u.
# range for c is smaller so add c and remove u
remove(u)
add(c)
ops.append([u,c])
elif bit2.sum(tin[c],tout[c]):
# c is the ancestor of one of the nodes in the set
# range for c is larger so don't add it
ops.append([0, 0])
else:
# c is a new disjoint range so add it
add(c)
curr_mx += 1
ops.append([0,c])
ans = max(ans, curr_mx)
for ne in adj[0][c]:
if not visited[ne]:
s.append(ne)
else:
u,v = ops.pop()
if u:
add(u)
curr_mx += 1
if v:
remove(v)
curr_mx -= 1
s.pop()
print(ans) | {
"input": [
"4\n4\n1 2 3\n1 2 3\n5\n1 2 3 4\n1 1 1 1\n6\n1 1 1 1 2\n1 2 1 2 2\n7\n1 1 3 4 4 5\n1 2 1 4 2 5\n"
],
"output": [
"\n1\n4\n1\n3\n"
]
} |
2,311 | 8 | Petya is the most responsible worker in the Research Institute. So he was asked to make a very important experiment: to melt the chocolate bar with a new laser device. The device consists of a rectangular field of n Γ m cells and a robotic arm. Each cell of the field is a 1 Γ 1 square. The robotic arm has two lasers pointed at the field perpendicularly to its surface. At any one time lasers are pointed at the centres of some two cells. Since the lasers are on the robotic hand, their movements are synchronized β if you move one of the lasers by a vector, another one moves by the same vector.
The following facts about the experiment are known:
* initially the whole field is covered with a chocolate bar of the size n Γ m, both lasers are located above the field and are active;
* the chocolate melts within one cell of the field at which the laser is pointed;
* all moves of the robotic arm should be parallel to the sides of the field, after each move the lasers should be pointed at the centres of some two cells;
* at any one time both lasers should be pointed at the field. Petya doesn't want to become a second Gordon Freeman.
You are given n, m and the cells (x1, y1) and (x2, y2), where the lasers are initially pointed at (xi is a column number, yi is a row number). Rows are numbered from 1 to m from top to bottom and columns are numbered from 1 to n from left to right. You are to find the amount of cells of the field on which the chocolate can't be melted in the given conditions.
Input
The first line contains one integer number t (1 β€ t β€ 10000) β the number of test sets. Each of the following t lines describes one test set. Each line contains integer numbers n, m, x1, y1, x2, y2, separated by a space (2 β€ n, m β€ 109, 1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m). Cells (x1, y1) and (x2, y2) are distinct.
Output
Each of the t lines of the output should contain the answer to the corresponding input test set.
Examples
Input
2
4 4 1 1 3 3
4 3 1 1 2 2
Output
8
2 | __author__ = 'Darren'
def solve():
t = int(input())
while t:
run()
t -= 1
def run():
n, m, x1, y1, x2, y2 = map(int, input().split())
width, height = abs(x1 - x2), abs(y1 - y2)
count = width * height * 2
x, y = width * 2 - n, height * 2 - m
if not (x < 0 and y < 0):
count -= x * y
print(count)
if __name__ == '__main__':
solve()
| {
"input": [
"2\n4 4 1 1 3 3\n4 3 1 1 2 2\n"
],
"output": [
"8\n2\n"
]
} |
2,312 | 11 | Once n people simultaneously signed in to the reception at the recently opened, but already thoroughly bureaucratic organization (abbreviated TBO). As the organization is thoroughly bureaucratic, it can accept and cater for exactly one person per day. As a consequence, each of n people made an appointment on one of the next n days, and no two persons have an appointment on the same day.
However, the organization workers are very irresponsible about their job, so none of the signed in people was told the exact date of the appointment. The only way to know when people should come is to write some requests to TBO.
The request form consists of m empty lines. Into each of these lines the name of a signed in person can be written (it can be left blank as well). Writing a person's name in the same form twice is forbidden, such requests are ignored. TBO responds very quickly to written requests, but the reply format is of very poor quality β that is, the response contains the correct appointment dates for all people from the request form, but the dates are in completely random order. Responds to all requests arrive simultaneously at the end of the day (each response specifies the request that it answers).
Fortunately, you aren't among these n lucky guys. As an observer, you have the following task β given n and m, determine the minimum number of requests to submit to TBO to clearly determine the appointment date for each person.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases. Each of the following t lines contains two integers n and m (1 β€ n, m β€ 109) β the number of people who have got an appointment at TBO and the number of empty lines in the request form, correspondingly.
Output
Print t lines, each containing an answer for the corresponding test case (in the order they are given in the input) β the minimum number of requests to submit to TBO.
Examples
Input
5
4 1
4 2
7 3
1 1
42 7
Output
3
2
3
0
11
Note
In the first sample, you need to submit three requests to TBO with three different names. When you learn the appointment dates of three people out of four, you can find out the fourth person's date by elimination, so you do not need a fourth request.
In the second sample you need only two requests. Let's number the persons from 1 to 4 and mention persons 1 and 2 in the first request and persons 1 and 3 in the second request. It is easy to see that after that we can clearly determine each person's appointment date regardless of the answers obtained from TBO.
In the fourth sample only one person signed up for an appointment. He doesn't need to submit any requests β his appointment date is tomorrow. |
def go(m, k):
rem, ans, binom = m*k, 0, 1
ones = 0
while ones <= k:
take = min(1 if ones == 0 else rem//ones, binom)
if take == 0:
break
ans += take
rem -= ones * take
binom = binom*(k-ones)//(ones+1)
ones += 1
return ans
def solve():
n, m = map(int, input().split())
ans = 1;
while go(m, ans) < n:
ans *= 2
jmp = ans
while jmp:
if go(m, ans-jmp) >= n:
ans -= jmp
jmp //= 2
print(ans)
t = int(input())
for _ in range(t):
solve()
| {
"input": [
"5\n4 1\n4 2\n7 3\n1 1\n42 7\n"
],
"output": [
"3\n2\n3\n0\n11\n"
]
} |
2,313 | 8 | An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons β 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full.
Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000" β "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address.
Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0.
You can see examples of zero block shortenings below:
* "a56f:00d3:0000:0124:0001:0000:0000:0000" β "a56f:00d3:0000:0124:0001::";
* "a56f:0000:0000:0124:0001:0000:1234:0ff0" β "a56f::0124:0001:0000:1234:0ff0";
* "a56f:0000:0000:0000:0001:0000:1234:0ff0" β "a56f:0000::0000:0001:0000:1234:0ff0";
* "a56f:00d3:0000:0124:0001:0000:0000:0000" β "a56f:00d3:0000:0124:0001::0000";
* "0000:0000:0000:0000:0000:0000:0000:0000" β "::".
It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.
The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.
You've got several short records of IPv6 addresses. Restore their full record.
Input
The first line contains a single integer n β the number of records to restore (1 β€ n β€ 100).
Each of the following n lines contains a string β the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:".
It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.
Output
For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.
Examples
Input
6
a56f:d3:0:0124:01:f19a:1000:00
a56f:00d3:0000:0124:0001::
a56f::0124:0001:0000:1234:0ff0
a56f:0000::0000:0001:0000:1234:0ff0
::
0ea::4d:f4:6:0
Output
a56f:00d3:0000:0124:0001:f19a:1000:0000
a56f:00d3:0000:0124:0001:0000:0000:0000
a56f:0000:0000:0124:0001:0000:1234:0ff0
a56f:0000:0000:0000:0001:0000:1234:0ff0
0000:0000:0000:0000:0000:0000:0000:0000
00ea:0000:0000:0000:004d:00f4:0006:0000 | def s():
n = int(input())
def st(x):
if x[0] == ':':
x = x[1:]
if x[-1] == ':':
x = x[:-1]
return x
for _ in range(n):
a = st(input()).split(':')
for i in range(len(a)):
if len(a[i]) == 0:
a[i] = '0000:'*(8-len(a))+'0000'
elif len(a[i])<4:
a[i] = '0'*(4-len(a[i]))+a[i]
print(*a,sep=':')
s() | {
"input": [
"6\na56f:d3:0:0124:01:f19a:1000:00\na56f:00d3:0000:0124:0001::\na56f::0124:0001:0000:1234:0ff0\na56f:0000::0000:0001:0000:1234:0ff0\n::\n0ea::4d:f4:6:0\n"
],
"output": [
"a56f:00d3:0000:0124:0001:f19a:1000:0000\na56f:00d3:0000:0124:0001:0000:0000:0000\na56f:0000:0000:0124:0001:0000:1234:0ff0\na56f:0000:0000:0000:0001:0000:1234:0ff0\n0000:0000:0000:0000:0000:0000:0000:0000\n00ea:0000:0000:0000:004d:00f4:0006:0000\n"
]
} |
2,314 | 9 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = xΒ·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 105, 1 β€ k β€ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 β€ ai β€ 109).
All the numbers in the lines are separated by single spaces.
Output
On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.
Examples
Input
6 2
2 3 6 5 4 10
Output
3
Note
In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | def solve():
n,k=map(int,input().split())
a=sorted([int(i) for i in input().split()])
b=set(a)
if k!=1:
for i in a:
if i in b:
b.discard(i*k)
print(len(b))
solve() | {
"input": [
"6 2\n2 3 6 5 4 10\n"
],
"output": [
"3\n"
]
} |
2,315 | 7 | It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).
If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
Input
The first line contains an integer n (2 β€ n β€ 100) β the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the elements of the set.
Output
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
Examples
Input
2
2 3
Output
Alice
Input
2
5 3
Output
Alice
Input
3
5 6 7
Output
Bob
Note
Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. | def gcd(a,b):
return a if b==0 else gcd(b,a%b)
n=int(input())
a=list(map(int,input().split()))
com=a[0]
for x in a:
com=gcd(com,x)
cnt=max(a)//com
print((cnt-n)%2==1 and 'Alice' or 'Bob') | {
"input": [
"2\n2 3\n",
"3\n5 6 7\n",
"2\n5 3\n"
],
"output": [
"Alice\n",
"Bob\n",
"Alice\n"
]
} |
2,316 | 8 | Petya has k matches, placed in n matchboxes lying in a line from left to right. We know that k is divisible by n. Petya wants all boxes to have the same number of matches inside. For that, he can move a match from its box to the adjacent one in one move. How many such moves does he need to achieve the desired configuration?
Input
The first line contains integer n (1 β€ n β€ 50000). The second line contains n non-negative numbers that do not exceed 109, the i-th written number is the number of matches in the i-th matchbox. It is guaranteed that the total number of matches is divisible by n.
Output
Print the total minimum number of moves.
Examples
Input
6
1 6 2 5 3 7
Output
12 | a=[]
def main():
n=int(input())
a.append(0)
B=input()
for x in B.split():
a.append(int(x))
a.append(0)
S=sum(a)
ave=int(S/n)
ans=0
for i in range(1,n+1,1):
if a[i] < ave:
ans += ave-a[i]
a[i+1] -= ave-a[i]
else:
ans += a[i]-ave
a[i+1] += a[i]-ave
print(ans)
main() | {
"input": [
"6\n1 6 2 5 3 7\n"
],
"output": [
"12\n"
]
} |
2,317 | 10 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.
Consider a set consisting of k (0 β€ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.
Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
Input
The first line contains an integer n (2 β€ n β€ 105) β the number of tree vertices.
The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 β€ pi β€ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1.
The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
Output
Output a single integer β the number of ways to split the tree modulo 1000000007 (109 + 7).
Examples
Input
3
0 0
0 1 1
Output
2
Input
6
0 1 1 0 4
1 1 0 0 1 0
Output
1
Input
10
0 1 2 1 4 4 4 0 8
0 0 0 1 0 1 1 0 0 1
Output
27 | n = int(input())
edges = [int(x) for x in input().split()]
color = [int(x) for x in input().split()]
graph = [[] for _ in range(n)]
for a,b in enumerate(edges):
graph[a+1].append(b)
graph[b].append(a+1)
dp = [[0]*2 for _ in range(n)]
visited = [0]*n
stack = [0]
while stack:
v = stack[-1]
visited[v] = -1
cn = 0
for u in graph[v]:
if visited[u] is not 0:
continue
else:
cn += 1
stack.append(u)
if not cn:
dp[v][0] = 1
dp[v][1] = 0
for u in graph[v]:
if visited[u] is -1:
continue
dp[v][1] *= dp[u][0]
dp[v][1] += dp[v][0] * dp[u][1]
dp[v][0] *= dp[u][0]
dp[v][1] %= 1000000007
dp[v][0] %= 1000000007
if color[v] is 1:
dp[v][1] = dp[v][0]
else:
dp[v][0] += dp[v][1]
dp[v][0] %= 1000000007
visited[v] = 1
stack.pop()
# def dfs(v):
# dp[v][0] = 1
# dp[v][1] = 0
# visited[v] = True
# for u in graph[v]:
# if visited[u] is True:
# continue
# dfs(u)
# dp[v][1] *= dp[u][0]
# dp[v][1] += dp[v][0] * dp[u][1]
# dp[v][0] *= dp[u][0]
# dp[v][1] %= 1000000007
# dp[v][0] %= 1000000007
# if color[v] is 1:
# dp[v][1] = dp[v][0]
# else:
# dp[v][0] += dp[v][1]
# dp[v][0] %= 1000000007
# dfs(0)
ans = dp[0][1]
print(ans)
| {
"input": [
"3\n0 0\n0 1 1\n",
"10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1\n",
"6\n0 1 1 0 4\n1 1 0 0 1 0\n"
],
"output": [
"2\n",
"27\n",
"1\n"
]
} |
2,318 | 9 | Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.
There is a cursor pointing at some symbol of the string. Suppose that cursor is at position i (1 β€ i β€ n, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position i - 1 if i > 1 or to the end of the string (i. e. position n) otherwise. The same holds when he presses the right arrow key (if i = n, the cursor appears at the beginning of the string).
When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.
Initially, the text cursor is at position p.
Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?
Input
The first line contains two space-separated integers n (1 β€ n β€ 105) and p (1 β€ p β€ n), the length of Nam's string and the initial position of the text cursor.
The next line contains n lowercase characters of Nam's string.
Output
Print the minimum number of presses needed to change string into a palindrome.
Examples
Input
8 3
aeabcaez
Output
6
Note
A string is a palindrome if it reads the same forward or reversed.
In the sample test, initial Nam's string is: <image> (cursor position is shown bold).
In optimal solution, Nam may do 6 following steps:
<image>
The result, <image>, is now a palindrome. | I=lambda : list(map(int,input().split()))
def ge(x):
return ord(x)-97
n,k=I()
s=input()
x=0;ind=[];k-=1
for i in range(n//2):
p=min((ge(s[i])-ge(s[n-i-1]))%26,(ge(s[n-i-1])-ge(s[i]))%26)
if p!=0:
ind.append(i if k<n//2 else n-i-1)
x+=p
if ind!=[]:
x+=min(abs(k-ind[-1])+abs(ind[-1]-ind[0]),abs(k-ind[0])+abs(ind[-1]-ind[0]))
print(x)
| {
"input": [
"8 3\naeabcaez\n"
],
"output": [
"6\n"
]
} |
2,319 | 8 | There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that
1. 1 β€ i, j β€ N
2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
Input
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
Output
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
Examples
Input
great10
Output
7
Input
aaaaaaaaaa
Output
100 | def f(x=input()):
d = dict()
for i in x:
if i in d: d[i]+=1
else: d[i] = 1
return sum([j*j for _,j in d.items()])
print(f()) | {
"input": [
"aaaaaaaaaa\n",
"great10\n"
],
"output": [
"100\n",
"7\n"
]
} |
2,320 | 10 | On February, 30th n students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came in stayed in CTOP until the end of the day and never left.
At any time any three students could join together and start participating in a team contest, which lasted until the end of the day. The team did not distract from the contest for a minute, so when another student came in and greeted those who were present, he did not shake hands with the members of the contest writing team. Each team consisted of exactly three students, and each student could not become a member of more than one team. Different teams could start writing contest at different times.
Given how many present people shook the hands of each student, get a possible order in which the students could have come to CTOP. If such an order does not exist, then print that this is impossible.
Please note that some students could work independently until the end of the day, without participating in a team contest.
Input
The first line contains integer n (1 β€ n β€ 2Β·105) β the number of students who came to CTOP. The next line contains n integers a1, a2, ..., an (0 β€ ai < n), where ai is the number of students with who the i-th student shook hands.
Output
If the sought order of students exists, print in the first line "Possible" and in the second line print the permutation of the students' numbers defining the order in which the students entered the center. Number i that stands to the left of number j in this permutation means that the i-th student came earlier than the j-th student. If there are multiple answers, print any of them.
If the sought order of students doesn't exist, in a single line print "Impossible".
Examples
Input
5
2 1 3 0 1
Output
Possible
4 5 1 3 2
Input
9
0 2 3 4 1 1 0 2 2
Output
Possible
7 5 2 1 6 8 3 4 9
Input
4
0 2 1 1
Output
Impossible
Note
In the first sample from the statement the order of events could be as follows:
* student 4 comes in (a4 = 0), he has no one to greet;
* student 5 comes in (a5 = 1), he shakes hands with student 4;
* student 1 comes in (a1 = 2), he shakes hands with two students (students 4, 5);
* student 3 comes in (a3 = 3), he shakes hands with three students (students 4, 5, 1);
* students 4, 5, 3 form a team and start writing a contest;
* student 2 comes in (a2 = 1), he shakes hands with one student (number 1).
In the second sample from the statement the order of events could be as follows:
* student 7 comes in (a7 = 0), he has nobody to greet;
* student 5 comes in (a5 = 1), he shakes hands with student 7;
* student 2 comes in (a2 = 2), he shakes hands with two students (students 7, 5);
* students 7, 5, 2 form a team and start writing a contest;
* student 1 comes in(a1 = 0), he has no one to greet (everyone is busy with the contest);
* student 6 comes in (a6 = 1), he shakes hands with student 1;
* student 8 comes in (a8 = 2), he shakes hands with two students (students 1, 6);
* student 3 comes in (a3 = 3), he shakes hands with three students (students 1, 6, 8);
* student 4 comes in (a4 = 4), he shakes hands with four students (students 1, 6, 8, 3);
* students 8, 3, 4 form a team and start writing a contest;
* student 9 comes in (a9 = 2), he shakes hands with two students (students 1, 6).
In the third sample from the statement the order of events is restored unambiguously:
* student 1 comes in (a1 = 0), he has no one to greet;
* student 3 comes in (or student 4) (a3 = a4 = 1), he shakes hands with student 1;
* student 2 comes in (a2 = 2), he shakes hands with two students (students 1, 3 (or 4));
* the remaining student 4 (or student 3), must shake one student's hand (a3 = a4 = 1) but it is impossible as there are only two scenarios: either a team formed and he doesn't greet anyone, or he greets all the three present people who work individually. | def main():
n = int(input())
a = list(map(int, input().split()))
dic = [[] for i in range(n)]
for i, item in enumerate(a, start=1):
dic[item].append(i)
if not dic[0]:
print("Impossible")
exit()
route = [dic[0].pop()]
s = 0
for i in range(1, n):
s += 1
while s >= 0:
if dic[s]:
route.append(dic[s].pop())
break
else:
s -= 3
else:
print("Impossible")
exit()
if len(route) == n:
print("Possible")
print(' '.join(str(i) for i in route))
else:
print("Impossible")
main()
| {
"input": [
"9\n0 2 3 4 1 1 0 2 2\n",
"5\n2 1 3 0 1\n",
"4\n0 2 1 1\n"
],
"output": [
"Possible\n7 6 9 3 4 8 1 5 2\n",
"Possible\n4 5 1 3 2\n",
"Impossible"
]
} |
2,321 | 8 | The mobile application store has a new game called "Subway Roller".
The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.
All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.
Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column.
<image>
Input
Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1 β€ t β€ 10 for pretests and tests or t = 1 for hacks; see the Notes section for details) β the number of sets.
Then follows the description of t sets of the input data.
The first line of the description of each set contains two integers n, k (2 β€ n β€ 100, 1 β€ k β€ 26) β the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains.
Output
For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise.
Examples
Input
2
16 4
...AAAAA........
s.BBB......CCCCC
........DDDDD...
16 4
...AAAAA........
s.BBB....CCCCC..
.......DDDDD....
Output
YES
NO
Input
2
10 4
s.ZZ......
.....AAABB
.YYYYYY...
10 4
s.ZZ......
....AAAABB
.YYYYYY...
Output
YES
NO
Note
In the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel.
Note that in this problem the challenges are restricted to tests that contain only one testset. | import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int,minp().split())
def main():
n,k = mints()
a = [list(minp()) for i in range(3)]
w = [[False]*(n+1) for i in range(3)]
for j in range(3):
if a[j][0] == 's':
a[j][0] = '.'
w[j][0] = True
for i in range(n):
for j in range(3):
if w[j][i]:
if i*3+1>=n or a[j][i*3+1] == '.':
for z in range(max(j-1,0),min(j+2,3)):
if (i*3+1>=n or a[z][i*3+1] == '.') and (i*3+2>=n or a[z][i*3+2] == '.') and (i*3+3>=n or a[z][i*3+3] == '.'):
w[z][i+1] = True
can = w[0][n] or w[1][n] or w[2][n]
#print(w)
if can:
print("YES")
else:
print("NO")
t = mint()
for i in range(t):
main() | {
"input": [
"2\n10 4\ns.ZZ......\n.....AAABB\n.YYYYYY...\n10 4\ns.ZZ......\n....AAAABB\n.YYYYYY...\n",
"2\n16 4\n...AAAAA........\ns.BBB......CCCCC\n........DDDDD...\n16 4\n...AAAAA........\ns.BBB....CCCCC..\n.......DDDDD....\n"
],
"output": [
"YES\nNO\n",
"YES\nNO\n"
]
} |
2,322 | 8 | Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.
In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?
Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.
Input
The first line of input contains a single integer n (1 β€ n β€ 500) β the number of gemstones.
The second line contains n space-separated integers, the i-th of which is ci (1 β€ ci β€ n) β the color of the i-th gemstone in a line.
Output
Print a single integer β the minimum number of seconds needed to destroy the entire line.
Examples
Input
3
1 2 1
Output
1
Input
3
1 2 3
Output
3
Input
7
1 4 4 2 3 2 1
Output
2
Note
In the first sample, Genos can destroy the entire line in one second.
In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.
In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1. | import sys
input=sys.stdin.readline
n=int(input())
c=list(map(int,input().split()))
dp=[[-1]*(n+1) for i in range(n+1)]
def calc(l,r):
if l>r:
return 0
elif l==r:
return 1
elif dp[l][r]!=-1:
return dp[l][r]
res=10**9
if c[l]==c[l+1]:
res=min(res,calc(l+2,r)+1)
for k in range(l+2,r+1):
if c[l]==c[k]:
res=min(res,calc(l+1,k-1)+calc(k+1,r))
dp[l][r]=min(res,1+calc(l+1,r))
return dp[l][r]
print(calc(0,n-1)) | {
"input": [
"3\n1 2 3\n",
"3\n1 2 1\n",
"7\n1 4 4 2 3 2 1\n"
],
"output": [
"3\n",
"1\n",
"2\n"
]
} |
2,323 | 7 | Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!
The cake is a n Γ n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?
Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.
Input
In the first line of the input, you are given a single integer n (1 β€ n β€ 100) β the length of the side of the cake.
Then follow n lines, each containing n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.
Output
Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.
Examples
Input
3
.CC
C..
C.C
Output
4
Input
4
CC..
C..C
.CC.
.CC.
Output
9
Note
If we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are:
1. (1, 2) and (1, 3)
2. (3, 1) and (3, 3)
Pieces that share the same column are:
1. (2, 1) and (3, 1)
2. (1, 3) and (3, 3) | n = int(input()); L = []; c = 0
for i in range(n): L.append(input())
def f(x): return x*(x-1)//2
for i in range(n): c += (f(L[i].count('C')) + f([L[x][i] for x in range(n)].count('C')))
print(c)
| {
"input": [
"4\nCC..\nC..C\n.CC.\n.CC.\n",
"3\n.CC\nC..\nC.C\n"
],
"output": [
"9\n",
"4\n"
]
} |
2,324 | 8 | Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.
When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.
Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
Input
The first line contains two integers n and q (2 β€ n β€ 6, 1 β€ q β€ 36) β the length of the initial string and the number of available operations.
The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai β aj for i β j and that all ai and bi consist of only first six lowercase English letters.
Output
Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.
Examples
Input
3 5
ab a
cc c
ca a
ee c
ff d
Output
4
Input
2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c
Output
1
Input
6 2
bb a
ba a
Output
0
Note
In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
* "cab" <image> "ab" <image> "a"
* "cca" <image> "ca" <image> "a"
* "eea" <image> "ca" <image> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". | links=[[],[],[],[],[],[]]
n,q=map(int,input().split())
for _ in range(q):
a,b=input().split()
links[ord(b)-ord('a')].append(a[0])
def func(b,depth):
if depth==n:
return 1
count=0
for a in links[ord(b)-ord('a')]:
count+=func(a,depth+1)
return count
print(func('a',1)) | {
"input": [
"6 2\nbb a\nba a\n",
"2 8\naf e\ndc d\ncc f\nbc b\nda b\neb a\nbb b\nff c\n",
"3 5\nab a\ncc c\nca a\nee c\nff d\n"
],
"output": [
"0\n",
"1\n",
"4\n"
]
} |
2,325 | 7 | There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.
Input
The first line of the input contains integer n (2 β€ n β€ 100) β the number of cards in the deck. It is guaranteed that n is even.
The second line contains the sequence of n positive integers a1, a2, ..., an (1 β€ ai β€ 100), where ai is equal to the number written on the i-th card.
Output
Print n / 2 pairs of integers, the i-th pair denote the cards that should be given to the i-th player. Each card should be given to exactly one player. Cards are numbered in the order they appear in the input.
It is guaranteed that solution exists. If there are several correct answers, you are allowed to print any of them.
Examples
Input
6
1 5 7 4 4 3
Output
1 3
6 2
4 5
Input
4
10 10 10 10
Output
1 2
3 4
Note
In the first sample, cards are distributed in such a way that each player has the sum of numbers written on his cards equal to 8.
In the second sample, all values ai are equal. Thus, any distribution is acceptable. | def division():
n = int(input())
a = [(int(num), i) for i, num in enumerate(input().split(), 1)]
a.sort()
for i in range(n // 2):
print(a[i][1], a[n - 1 - i][1])
division() | {
"input": [
"4\n10 10 10 10\n",
"6\n1 5 7 4 4 3\n"
],
"output": [
"1 2\n3 4\n",
"1 3\n6 2\n4 5\n"
]
} |
2,326 | 8 | Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English letters,
* underscore symbols (they are used as separators),
* parentheses (both opening and closing).
It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested.
For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)".
Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Input
The first line of the input contains a single integer n (1 β€ n β€ 255) β the length of the given string. The second line contains the string consisting of only lowercase and uppercase English letters, parentheses and underscore symbols.
Output
Print two space-separated integers:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Examples
Input
37
_Hello_Vasya(and_Petya)__bye_(and_OK)
Output
5 4
Input
37
_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__
Output
2 6
Input
27
(LoooonG)__shOrt__(LoooonG)
Output
5 2
Input
5
(___)
Output
0 0
Note
In the first sample, the words "Hello", "Vasya" and "bye" are outside any of the parentheses, and the words "and", "Petya", "and" and "OK" are inside. Note, that the word "and" is given twice and you should count it twice in the answer. | def main():
input()
l = [s for p in input().split('(') for s in p.split(')')]
print(max(map(len, (w for s in l[::2] for w in s.split('_')))),
len([w for s in l[1::2] for w in s.split('_') if w]))
if __name__ == '__main__':
main()
| {
"input": [
"37\n_Hello_Vasya(and_Petya)__bye_(and_OK)\n",
"27\n(LoooonG)__shOrt__(LoooonG)\n",
"5\n(___)\n",
"37\n_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__\n"
],
"output": [
"5 4\n",
"5 2\n",
"0 0\n",
"2 6\n"
]
} |
2,327 | 7 | Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy". | #CF YL1
s=input()
c={s}
def cyc(s2):return s2[-1]+s2[:-1]
for i in range(len(s)):
s=cyc(s)
c.add(s)
print(len(c))
| {
"input": [
"abcd\n",
"bbb\n",
"yzyz\n"
],
"output": [
"4\n",
"1\n",
"2\n"
]
} |
2,328 | 9 | Jon Snow now has to fight with White Walkers. He has n rangers, each of which has his own strength. Also Jon Snow has his favourite number x. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon now thinks that if he takes the bitwise XOR of strengths of some of rangers with his favourite number x, he might get soldiers of high strength. So, he decided to do the following operation k times:
1. Arrange all the rangers in a straight line in the order of increasing strengths.
2. Take the bitwise XOR (is written as <image>) of the strength of each alternate ranger with x and update it's strength.
Suppose, Jon has 5 rangers with strengths [9, 7, 11, 15, 5] and he performs the operation 1 time with x = 2. He first arranges them in the order of their strengths, [5, 7, 9, 11, 15]. Then he does the following:
1. The strength of first ranger is updated to <image>, i.e. 7.
2. The strength of second ranger remains the same, i.e. 7.
3. The strength of third ranger is updated to <image>, i.e. 11.
4. The strength of fourth ranger remains the same, i.e. 11.
5. The strength of fifth ranger is updated to <image>, i.e. 13.
The new strengths of the 5 rangers are [7, 7, 11, 11, 13]
Now, Jon wants to know the maximum and minimum strength of the rangers after performing the above operations k times. He wants your help for this task. Can you help him?
Input
First line consists of three integers n, k, x (1 β€ n β€ 105, 0 β€ k β€ 105, 0 β€ x β€ 103) β number of rangers Jon has, the number of times Jon will carry out the operation and Jon's favourite number respectively.
Second line consists of n integers representing the strengths of the rangers a1, a2, ..., an (0 β€ ai β€ 103).
Output
Output two integers, the maximum and the minimum strength of the rangers after performing the operation k times.
Examples
Input
5 1 2
9 7 11 15 5
Output
13 7
Input
2 100000 569
605 986
Output
986 605 | #!/usr/bin/env python3
from sys import stdin,stdout
def ri():
return map(int, input().split())
n, k, x = ri()
a = []
a.append(list(ri()))
t = 0
j = 0
goout = 0
for j in range(0,k):
a[j].sort()
if j != 0:
for t in range(j):
if a[t] == a[j]:
goout = 1
break
if goout:
break
a.append([a[j][i]^x if not i%2 else a[j][i] for i in range(n)])
else:
a[k].sort()
print(a[k][-1], a[k][0])
exit()
m = t + (k-t)%(j-t)
print(a[m][-1], a[m][0])
| {
"input": [
"2 100000 569\n605 986\n",
"5 1 2\n9 7 11 15 5\n"
],
"output": [
"986 605\n",
"13 7\n"
]
} |
2,329 | 8 | n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.
For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and ai = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.
You have to write a program which prints the number of the child to be eliminated on every step.
Input
The first line contains two integer numbers n and k (2 β€ n β€ 100, 1 β€ k β€ n - 1).
The next line contains k integer numbers a1, a2, ..., ak (1 β€ ai β€ 109).
Output
Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.
Examples
Input
7 5
10 4 11 4 1
Output
4 2 5 6 1
Input
3 2
2 5
Output
3 2
Note
Let's consider first example:
* In the first step child 4 is eliminated, child 5 becomes the leader.
* In the second step child 2 is eliminated, child 3 becomes the leader.
* In the third step child 5 is eliminated, child 6 becomes the leader.
* In the fourth step child 6 is eliminated, child 7 becomes the leader.
* In the final step child 1 is eliminated, child 3 becomes the leader. | def geti():
return map(int, input().split())
n, k = geti()
a = list(geti())
xk = [i+1 for i in range(n)]
t = 1
b = []
x = 0
for i in range(k):
x = ((x + a[i]) % len(xk))
b.append(xk[x])
xk.remove(xk[x])
for i in b:
print(i,end=' ')
| {
"input": [
"3 2\n2 5\n",
"7 5\n10 4 11 4 1\n"
],
"output": [
"3 2\n",
"4 2 5 6 1\n"
]
} |
2,330 | 10 | There is an airplane which has n rows from front to back. There will be m people boarding this airplane.
This airplane has an entrance at the very front and very back of the plane.
Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.
When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.
Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 109 + 7.
Input
The first line of input will contain two integers n, m (1 β€ m β€ n β€ 1 000 000), the number of seats, and the number of passengers, respectively.
Output
Print a single number, the number of ways, modulo 109 + 7.
Example
Input
3 3
Output
128
Note
Here, we will denote a passenger by which seat they were assigned, and which side they came from (either "F" or "B" for front or back, respectively).
For example, one valid way is 3B, 3B, 3B (i.e. all passengers were assigned seat 3 and came from the back entrance). Another valid way would be 2F, 1B, 3F.
One invalid way would be 2B, 2B, 2B, since the third passenger would get to the front without finding a seat. | mod = 1000000007
def power(a, p):
res = 1
while p > 0:
if p % 2 == 1:
res = (res * a) % mod
a = (a * a) % mod
p //= 2
return res
n, m = map(int, input().split())
n += 1
res = (power(n * 2, m - 1)) * (n - m) * 2
print((res % mod)) | {
"input": [
"3 3\n"
],
"output": [
"128\n"
]
} |
2,331 | 7 | This year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible contestant must either accept or decline the invitation. Whenever a contestant declines, the highest ranked contestant not yet invited is invited to take the place of the one that declined. This continues until 25 contestants have accepted invitations.
After the qualifying round completes, you know K of the onsite finalists, as well as their qualifying ranks (which start at 1, there are no ties). Determine the minimum possible number of contestants that declined the invitation to compete onsite in the final round.
Input
The first line of input contains K (1 β€ K β€ 25), the number of onsite finalists you know. The second line of input contains r1, r2, ..., rK (1 β€ ri β€ 106), the qualifying ranks of the finalists you know. All these ranks are distinct.
Output
Print the minimum possible number of contestants that declined the invitation to compete onsite.
Examples
Input
25
2 3 4 5 6 7 8 9 10 11 12 14 15 16 17 18 19 20 21 22 23 24 25 26 28
Output
3
Input
5
16 23 8 15 4
Output
0
Input
3
14 15 92
Output
67
Note
In the first example, you know all 25 onsite finalists. The contestants who ranked 1-st, 13-th, and 27-th must have declined, so the answer is 3. | def solve():
n = int(input())
l = list(map(int,input().split()))
print(max(max(l) - 25,0))
solve() | {
"input": [
"25\n2 3 4 5 6 7 8 9 10 11 12 14 15 16 17 18 19 20 21 22 23 24 25 26 28\n",
"3\n14 15 92\n",
"5\n16 23 8 15 4\n"
],
"output": [
"3",
"67",
"0"
]
} |
2,332 | 8 | Bob programmed a robot to navigate through a 2d maze.
The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.
There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.
The robot can only move up, left, right, or down.
When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.
The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.
Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.
Input
The first line of input will contain two integers n and m (2 β€ n, m β€ 50), denoting the dimensions of the maze.
The next n lines will contain exactly m characters each, denoting the maze.
Each character of the maze will be '.', '#', 'S', or 'E'.
There will be exactly one 'S' and exactly one 'E' in the maze.
The last line will contain a single string s (1 β€ |s| β€ 100) β the instructions given to the robot. Each character of s is a digit from 0 to 3.
Output
Print a single integer, the number of mappings of digits to directions that will lead the robot to the exit.
Examples
Input
5 6
.....#
S....#
.#....
.#....
...E..
333300012
Output
1
Input
6 6
......
......
..SE..
......
......
......
01232123212302123021
Output
14
Input
5 3
...
.S.
###
.E.
...
3
Output
0
Note
For the first sample, the only valid mapping is <image>, where D is down, L is left, U is up, R is right. | from itertools import *
n, m = map(int, input().split())
p = [[0] * (m + 1) for i in range(n)] + [[0] * m]
for i in range(n):
for j, q in enumerate(input()):
if q == 'S': a, b = i, j
p[i][j] = '#E'.find(q)
s = list(map(int, input()))
def f(d):
x, y = a, b
for k in s:
i, j = d[k]
x += i
y += j
if p[x][y] + 1: return p[x][y]
return 0
t = [(1, 0), (-1, 0), (0, 1), (0, -1)]
print(sum(f(d) for d in permutations(t))) | {
"input": [
"5 6\n.....#\nS....#\n.#....\n.#....\n...E..\n333300012\n",
"6 6\n......\n......\n..SE..\n......\n......\n......\n01232123212302123021\n",
"5 3\n...\n.S.\n###\n.E.\n...\n3\n"
],
"output": [
"1\n",
"14\n",
"0\n"
]
} |
2,333 | 7 | There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 β€ n β€ 50, 1 β€ m β€ 104) β the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip. | import math
def xx(a):
return (math.sqrt((8*a)+1)-1)//2
def yy(n):
return ((n+1)*n)//2
n,m=map(int,input().split())
b=m%yy(n)
x=xx(b)
print(int(b-yy(x)))
| {
"input": [
"4 11\n",
"17 107\n",
"3 8\n"
],
"output": [
"0",
"2",
"1"
]
} |
2,334 | 7 | You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 β€ p β€ 10^{18}, 1 β€ q β€ 10^{18}, 2 β€ b β€ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3 | # python3
def solve():
for __ in range(int(input())):
p, q, b = tuple(map(int, input().split()))
yield "Infinite" if p * pow(b, 63, q) % q else "Finite"
print("\n".join(solve()))
| {
"input": [
"2\n6 12 10\n4 3 10\n",
"4\n1 1 2\n9 36 2\n4 12 3\n3 5 4\n"
],
"output": [
"Finite\nInfinite\n",
"Finite\nFinite\nFinite\nInfinite\n"
]
} |
2,335 | 7 | A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them β a black one, and for the rest the suit will be bought in the future.
On the day when the suits were to be bought, the director was told that the participants of the olympiad will be happy if the colors of the suits on the scene will form a palindrome. A palindrome is a sequence that is the same when read from left to right and when read from right to left. The director liked the idea, and she wants to buy suits so that the color of the leftmost dancer's suit is the same as the color of the rightmost dancer's suit, the 2nd left is the same as 2nd right, and so on.
The director knows how many burls it costs to buy a white suit, and how many burls to buy a black suit. You need to find out whether it is possible to buy suits to form a palindrome, and if it's possible, what's the minimal cost of doing so. Remember that dancers can not change positions, and due to bureaucratic reasons it is not allowed to buy new suits for the dancers who already have suits, even if it reduces the overall spending.
Input
The first line contains three integers n, a, and b (1 β€ n β€ 20, 1 β€ a, b β€ 100) β the number of dancers, the cost of a white suit, and the cost of a black suit.
The next line contains n numbers c_i, i-th of which denotes the color of the suit of the i-th dancer. Number 0 denotes the white color, 1 β the black color, and 2 denotes that a suit for this dancer is still to be bought.
Output
If it is not possible to form a palindrome without swapping dancers and buying new suits for those who have one, then output -1. Otherwise, output the minimal price to get the desired visual effect.
Examples
Input
5 100 1
0 1 2 1 2
Output
101
Input
3 10 12
1 2 0
Output
-1
Input
3 12 1
0 1 0
Output
0
Note
In the first sample, the cheapest way to obtain palindromic colors is to buy a black suit for the third from left dancer and a white suit for the rightmost dancer.
In the second sample, the leftmost dancer's suit already differs from the rightmost dancer's suit so there is no way to obtain the desired coloring.
In the third sample, all suits are already bought and their colors form a palindrome. |
def mi():
return map(int, input().split())
n,w,b = mi()
a = list(mi())
if w<b:
mc = 0
else:
mc = 1
ans = 0
c = [w,b]
for i in range(n//2):
if a[i]==a[n-1-i]:
if a[i]==2:
ans+=2*min(w,b)
if a[i]!=a[n-1-i]:
if max(a[i],a[n-1-i])!=2:
print (-1)
exit(0)
ans+=c[min(a[i],a[n-1-i])]
if a[n//2]==2 and n%2:
ans+=min(w,b)
print (ans) | {
"input": [
"3 12 1\n0 1 0\n",
"5 100 1\n0 1 2 1 2\n",
"3 10 12\n1 2 0\n"
],
"output": [
"0\n",
"101\n",
"-1\n"
]
} |
2,336 | 7 | A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.
A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not.
Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is 6 because all its substrings are palindromes, and the palindromic count of the string "abc" is 3 because only its substrings of length 1 are palindromes.
You are given a string s. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.
Input
The first line contains an integer n (1 β€ n β€ 100 000) β the length of string s.
The second line contains string s that consists of exactly n lowercase characters of Latin alphabet.
Output
Print string t, which consists of the same set of characters (and each characters appears exactly the same number of times) as string s. Moreover, t should have the maximum possible value of palindromic count among all such strings strings.
If there are multiple such strings, print any of them.
Examples
Input
5
oolol
Output
ololo
Input
16
gagadbcgghhchbdf
Output
abccbaghghghgdfd
Note
In the first example, string "ololo" has 9 palindromic substrings: "o", "l", "o", "l", "o", "olo", "lol", "olo", "ololo". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string.
In the second example, the palindromic count of string "abccbaghghghgdfd" is 29. | def palindromes(s):
return ''.join(sorted(s))
n = int(input())
print(palindromes(input()))
| {
"input": [
"5\noolol\n",
"16\ngagadbcgghhchbdf\n"
],
"output": [
"llooo",
"aabbccddfgggghhh"
]
} |
2,337 | 9 | You are given a 4x4 grid. You play a game β there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.
Input
The only line contains a string s consisting of zeroes and ones (1 β€ |s| β€ 1000). Zero describes vertical tile, one describes horizontal tile.
Output
Output |s| lines β for each tile you should output two positive integers r,c, not exceeding 4, representing numbers of smallest row and column intersecting with it.
If there exist multiple solutions, print any of them.
Example
Input
010
Output
1 1
1 2
1 4
Note
Following image illustrates the example after placing all three tiles:
<image> Then the first row is deleted: <image> | def C():
s = input()
a , b = 0 , 0
for x in s:
if(x=='1'):
if(b%2==0):
print(4,3)
else:
print(4,1)
b+=1
else:
if(a%2==0):
print(1,1)
else:
print(3,1)
a+=1
C()
| {
"input": [
"010\n"
],
"output": [
"1 1\n3 1\n1 2\n"
]
} |
2,338 | 7 | A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; "))" and ")((" are bracket sequences (but not regular ones), and "(a)" and "(1)+(1)" are not bracket sequences at all.
You have a number of strings; each string is a bracket sequence of length 2. So, overall you have cnt_1 strings "((", cnt_2 strings "()", cnt_3 strings ")(" and cnt_4 strings "))". You want to write all these strings in some order, one after another; after that, you will get a long bracket sequence of length 2(cnt_1 + cnt_2 + cnt_3 + cnt_4). You wonder: is it possible to choose some order of the strings you have such that you will get a regular bracket sequence? Note that you may not remove any characters or strings, and you may not add anything either.
Input
The input consists of four lines, i-th of them contains one integer cnt_i (0 β€ cnt_i β€ 10^9).
Output
Print one integer: 1 if it is possible to form a regular bracket sequence by choosing the correct order of the given strings, 0 otherwise.
Examples
Input
3
1
4
3
Output
1
Input
0
0
0
0
Output
1
Input
1
2
3
4
Output
0
Note
In the first example it is possible to construct a string "(())()(()((()()()())))", which is a regular bracket sequence.
In the second example it is possible to construct a string "", which is a regular bracket sequence. | def sv():
c = [int(input()) for i in range(4)]
if c[0] != c[3]: return 0
if c[2] and not c[0]: return 0
return 1
print(sv())
| {
"input": [
"1\n2\n3\n4\n",
"3\n1\n4\n3\n",
"0\n0\n0\n0\n"
],
"output": [
"0\n",
"1\n",
"1\n"
]
} |
2,339 | 10 | Neko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys...
It took Neko an entire day to turn back to normal. Neko reported to Aki that he saw a lot of weird things, including a [trie](https://en.wikipedia.org/wiki/Trie) of all correct bracket sequences of length 2n.
The definition of correct bracket sequence is as follows:
* The empty sequence is a correct bracket sequence,
* If s is a correct bracket sequence, then (\,s ) is a correct bracket sequence,
* If s and t are a correct bracket sequence, then st is also a correct bracket sequence.
For example, the strings "(())", "()()" form a correct bracket sequence, while ")(" and "((" not.
Aki then came up with an interesting problem: What is the size of the maximum matching (the largest set of edges such that there are no two edges with a common vertex) in this trie? Since the answer can be quite large, print it modulo 10^9 + 7.
Input
The only line contains a single integer n (1 β€ n β€ 1000).
Output
Print exactly one integer β the size of the maximum matching in the trie. Since the answer can be quite large, print it modulo 10^9 + 7.
Examples
Input
1
Output
1
Input
2
Output
3
Input
3
Output
9
Note
The pictures below illustrate tries in the first two examples (for clarity, the round brackets are replaced with angle brackets). The maximum matching is highlighted with blue.
<image> <image> | def fine():
f, c, n = 1, 1, 1
yield 0
while True:
yield f
n += 1
c = c * (4 * n - 6) // n
f = (c - f) // 2
f = fine()
n = int(input())
print((sum(next(f) for _ in range(n + 3)) - 1) % (10**9 + 7))
| {
"input": [
"2\n",
"1\n",
"3\n"
],
"output": [
"3",
"1",
"9"
]
} |
2,340 | 8 | You're given an array a of length n. You can perform the following operation on it as many times as you want:
* Pick two integers i and j (1 β€ i,j β€ n) such that a_i+a_j is odd, then swap a_i and a_j.
What is lexicographically the smallest array you can obtain?
An array x is [lexicographically smaller](https://en.wikipedia.org/wiki/Lexicographical_order) than an array y if there exists an index i such that x_i<y_i, and x_j=y_j for all 1 β€ j < i. Less formally, at the first index i in which they differ, x_i<y_i
Input
The first line contains an integer n (1 β€ n β€ 10^5) β the number of elements in the array a.
The second line contains n space-separated integers a_1, a_2, β¦, a_{n} (1 β€ a_i β€ 10^9) β the elements of the array a.
Output
The only line contains n space-separated integers, the lexicographically smallest array you can obtain.
Examples
Input
3
4 1 7
Output
1 4 7
Input
2
1 1
Output
1 1
Note
In the first example, we can swap 1 and 4 since 1+4=5, which is odd. | def lexicographically(n,l):
for i in l:
if (i+l[0])%2==1:
l.sort()
break
print(*l)
n=int(input())
l=list(map(int,input().split()))
lexicographically(n,l) | {
"input": [
"3\n4 1 7\n",
"2\n1 1\n"
],
"output": [
"1 4 7\n",
"1 1\n"
]
} |
2,341 | 10 | Marcin is a coach in his university. There are n students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.
Let's focus on the students. They are indexed with integers from 1 to n. Each of them can be described with two integers a_i and b_i; b_i is equal to the skill level of the i-th student (the higher, the better). Also, there are 60 known algorithms, which are numbered with integers from 0 to 59. If the i-th student knows the j-th algorithm, then the j-th bit (2^j) is set in the binary representation of a_i. Otherwise, this bit is not set.
Student x thinks that he is better than student y if and only if x knows some algorithm which y doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.
Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
Input
The first line contains one integer n (1 β€ n β€ 7000) β the number of students interested in the camp.
The second line contains n integers. The i-th of them is a_i (0 β€ a_i < 2^{60}).
The third line contains n integers. The i-th of them is b_i (1 β€ b_i β€ 10^9).
Output
Output one integer which denotes the maximum sum of b_i over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.
Examples
Input
4
3 2 3 6
2 8 5 10
Output
15
Input
3
1 2 3
1 2 3
Output
0
Input
1
0
1
Output
0
Note
In the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of b_i.
In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset. | def is_subset(a, b):
return (~a & b) == 0
n = int(input())
a = map(int, input().split())
b = map(int, input().split())
vis = [False] * (n + 1)
st = list(zip(a, b))
st.sort()
st.reverse()
st.append((-1, -1))
ans = 0
for i in range(n):
if st[i][0] != st[i + 1][0]:
continue
for j in range(i, n):
if is_subset(st[i][0], st[j][0]):
vis[j] = True
for i in range(n):
ans += vis[i] * st[i][1]
print(ans)
| {
"input": [
"3\n1 2 3\n1 2 3\n",
"1\n0\n1\n",
"4\n3 2 3 6\n2 8 5 10\n"
],
"output": [
"0\n",
"0\n",
"15\n"
]
} |
2,342 | 7 | You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 10 decimal digits:
<image>
As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 1, you have to turn on 2 segments of the screen, and if you want to display 8, all 7 segments of some place to display a digit should be turned on.
You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than n segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than n segments.
Your program should be able to process t different test cases.
Input
The first line contains one integer t (1 β€ t β€ 100) β the number of test cases in the input.
Then the test cases follow, each of them is represented by a separate line containing one integer n (2 β€ n β€ 10^5) β the maximum number of segments that can be turned on in the corresponding testcase.
It is guaranteed that the sum of n over all test cases in the input does not exceed 10^5.
Output
For each test case, print the greatest integer that can be displayed by turning on no more than n segments of the screen. Note that the answer may not fit in the standard 32-bit or 64-bit integral data type.
Example
Input
2
3
4
Output
7
11 | def solve():
n = int(input())
s = ('7' if n % 2 else '1') + '1' * (n // 2 - 1)
print(s)
t = int(input())
for ti in range(t):
solve() | {
"input": [
"2\n3\n4\n"
],
"output": [
"7\n11\n"
]
} |
2,343 | 7 | n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students.
You can change each student's score as long as the following conditions are satisfied:
* All scores are integers
* 0 β€ a_{i} β€ m
* The average score of the class doesn't change.
You are student 1 and you would like to maximize your own score.
Find the highest possible score you can assign to yourself such that all conditions are satisfied.
Input
Each test contains multiple test cases.
The first line contains the number of test cases t (1 β€ t β€ 200). The description of the test cases follows.
The first line of each test case contains two integers n and m (1 β€ n β€ 10^{3}, 1 β€ m β€ 10^{5}) β the number of students and the highest possible score respectively.
The second line of each testcase contains n integers a_1, a_2, ..., a_n ( 0 β€ a_{i} β€ m) β scores of the students.
Output
For each testcase, output one integer β the highest possible score you can assign to yourself such that both conditions are satisfied._
Example
Input
2
4 10
1 2 3 4
4 5
1 2 3 4
Output
10
5
Note
In the first case, a = [1,2,3,4] , with average of 2.5. You can change array a to [10,0,0,0]. Average remains 2.5, and all conditions are satisfied.
In the second case, 0 β€ a_{i} β€ 5. You can change a to [5,1,1,3]. You cannot increase a_{1} further as it will violate condition 0β€ a_iβ€ m. | def solve():
x, y = map(int, input().split())
a = list(map(int, input().split()))
print(min(y, sum(a)))
for i in range(int(input())):
solve() | {
"input": [
"2\n4 10\n1 2 3 4\n4 5\n1 2 3 4\n"
],
"output": [
"10\n5\n"
]
} |
2,344 | 9 | Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2β€ nβ€ 2 β
10^5, 1β€ k< n) β the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1β€ u,vβ€ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer β the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2. | import sys
import threading
from collections import defaultdict
n,k=list(map(int,input().split()))
adj=defaultdict(list)
for _ in range(n-1):
a,b=list(map(int,input().split()))
adj[a].append(b)
adj[b].append(a)
li=[]
def fun(node,par,ht):
size=1
for ch in adj[node]:
if ch != par:
size+=fun(ch,node,ht+1)
li.append(ht-size)
return size
def main():
fun(1,-1,1)
li.sort(reverse=True)
print(sum(li[:k]))
if __name__=="__main__":
sys.setrecursionlimit(10**6)
threading.stack_size(10**8)
t = threading.Thread(target=main)
t.start()
t.join() | {
"input": [
"8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5\n",
"7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7\n",
"4 1\n1 2\n1 3\n2 4\n"
],
"output": [
"9\n",
"7\n",
"2\n"
]
} |
2,345 | 7 | Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all.
After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
Input
The first line contains a single integer n (1 β€ n β€ 105), which represents how many numbers the array has. The next line contains n space-separated integers β the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
Output
Print n space-separated integers β the minimum possible values of each array element after one replacement and the sorting are performed.
Examples
Input
5
1 2 3 4 5
Output
1 1 2 3 4
Input
5
2 3 4 5 6
Output
1 2 3 4 5
Input
3
2 2 2
Output
1 2 2 | def main():
input()
l = [1]
l.extend(map(int, input().split()))
l.sort()
if l[-1] == 1:
l[-2] = 2
del l[-1]
print(' '.join(map(str, l)))
if __name__ == '__main__':
main() | {
"input": [
"5\n1 2 3 4 5\n",
"5\n2 3 4 5 6\n",
"3\n2 2 2\n"
],
"output": [
"1 1 2 3 4\n",
"1 2 3 4 5\n",
"1 2 2\n"
]
} |
2,346 | 8 | "Hey, it's homework time" β thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).
Input
The first line of the input data contains an integer n (1 β€ n β€ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 β€ ai β€ 5000, 1 β€ i β€ n).
Output
Print the only number β the minimum number of changes needed to get the permutation.
Examples
Input
3
3 1 2
Output
0
Input
2
2 2
Output
1
Input
5
5 3 3 3 1
Output
2
Note
The first sample contains the permutation, which is why no replacements are required.
In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.
In the third sample we can replace the second element with number 4 and the fourth element with number 2. | def permutate(n, lst):
s = range(1, n + 1)
return len(set(s) - set(lst))
m = int(input())
a = [int(i) for i in input().split()]
print(permutate(m, a))
| {
"input": [
"2\n2 2\n",
"3\n3 1 2\n",
"5\n5 3 3 3 1\n"
],
"output": [
"1\n",
"0\n",
"2\n"
]
} |
2,347 | 8 | Little Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.
You are given three segments on the plane. They form the letter A if the following conditions hold:
* Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments.
* The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.
* The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4).
Input
The first line contains one integer t (1 β€ t β€ 10000) β the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers β coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.
Output
Output one line for each test case. Print Β«YESΒ» (without quotes), if the segments form the letter A and Β«NOΒ» otherwise.
Examples
Input
3
4 4 6 0
4 1 5 2
4 0 4 4
0 0 0 6
0 6 2 -4
1 1 0 1
0 0 0 5
0 5 2 -1
1 2 0 1
Output
YES
NO
YES | #13B - Letter A
import math
r = lambda: map(int,input().split())
#Function to check if the lines cross
def cross(a, b):
return a[0] * b[1] - a[1] * b[0]
def dot(a, b):
return a[0] * b[0] + a[1] * b[1]
# def l(v):
# return math.hypot(*v)
def on_line(a, b):
return dot(a, b) > 0 and cross(a, b) == 0 and abs(b[0]) <= abs(5 * a[0]) <= abs(4 * b[0]) and abs(b[1]) <= abs(5 * a[1]) <= abs(4 * b[1])
def is_A(a, b, c):
a, b = set(a), set(b)
if len(a & b) != 1:
return False
p1, = a & b
p2, p3 = a ^ b
v1 = (p2[0] - p1[0], p2[1] - p1[1])
v2 = (p3[0] - p1[0], p3[1] - p1[1])
if dot(v1, v2) < 0 or abs(cross(v1, v2)) == 0:
return False
v3 = (c[0][0] - p1[0], c[0][1] - p1[1])
v4 = (c[1][0] - p1[0], c[1][1] - p1[1])
return (on_line(v3, v1) and on_line(v4, v2)) or (on_line(v3, v2) and on_line(v4, v1))
for i in range(int(input())):
xa1, ya1, xa2, ya2 = r()
xb1, yb1, xb2, yb2 = r()
xc1, yc1, xc2, yc2 = r()
a, b, c = [(xa1, ya1), (xa2, ya2)], [(xb1, yb1), (xb2, yb2)], [(xc1, yc1), (xc2, yc2)]
print ("YES" if is_A(a, b, c) or is_A(a, c, b) or is_A(b, c, a) else "NO") | {
"input": [
"3\n4 4 6 0\n4 1 5 2\n4 0 4 4\n0 0 0 6\n0 6 2 -4\n1 1 0 1\n0 0 0 5\n0 5 2 -1\n1 2 0 1\n"
],
"output": [
"YES\nNO\nYES\n"
]
} |
2,348 | 10 | You are given an array a of n positive integers.
You can use the following operation as many times as you like: select any integer 1 β€ k β€ n and do one of two things:
* decrement by one k of the first elements of the array.
* decrement by one k of the last elements of the array.
For example, if n=5 and a=[3,2,2,1,4], then you can apply one of the following operations to it (not all possible options are listed below):
* decrement from the first two elements of the array. After this operation a=[2, 1, 2, 1, 4];
* decrement from the last three elements of the array. After this operation a=[3, 2, 1, 0, 3];
* decrement from the first five elements of the array. After this operation a=[2, 1, 1, 0, 3];
Determine if it is possible to make all the elements of the array equal to zero by applying a certain number of operations.
Input
The first line contains one positive integer t (1 β€ t β€ 30000) β the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1 β€ n β€ 30000) β the number of elements in the array.
The second line of each test case contains n integers a_1 β¦ a_n (1 β€ a_i β€ 10^6).
The sum of n over all test cases does not exceed 30000.
Output
For each test case, output on a separate line:
* YES, if it is possible to make all elements of the array equal to zero by applying a certain number of operations.
* NO, otherwise.
The letters in the words YES and NO can be outputed in any case.
Example
Input
4
3
1 2 1
5
11 7 9 6 8
5
1 3 1 3 1
4
5 2 1 10
Output
YES
YES
NO
YES | def solve(n,a):s = sum([max(0,a[i]-a[i+1]) for i in range(n-1)]);print('YES') if s <= a[0] else print('NO')
for j in range(int(input())):solve(int(input()),list(map(int,input().split()))) | {
"input": [
"4\n3\n1 2 1\n5\n11 7 9 6 8\n5\n1 3 1 3 1\n4\n5 2 1 10\n"
],
"output": [
"YES\nYES\nNO\nYES\n"
]
} |
2,349 | 7 | You are given a string a, consisting of n characters, n is even. For each i from 1 to n a_i is one of 'A', 'B' or 'C'.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
You want to find a string b that consists of n characters such that:
* b is a regular bracket sequence;
* if for some i and j (1 β€ i, j β€ n) a_i=a_j, then b_i=b_j.
In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.
Your task is to determine if such a string b exists.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string a. a consists only of uppercase letters 'A', 'B' and 'C'. Let n be the length of a. It is guaranteed that n is even and 2 β€ n β€ 50.
Output
For each testcase print "YES" if there exists such a string b that:
* b is a regular bracket sequence;
* if for some i and j (1 β€ i, j β€ n) a_i=a_j, then b_i=b_j.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
4
AABBAC
CACA
BBBBAC
ABCA
Output
YES
YES
NO
NO
Note
In the first testcase one of the possible strings b is "(())()".
In the second testcase one of the possible strings b is "()()". | def check(s):
ans = 0
for i in s:
if i=='(': ans+=1
else: ans-=1
if ans<0: return False
return ans==0
for _ in range(int(input())):
ip = input()
f = ip[0]
l = ip[-1]
ip = ip.replace(f,'(').replace(l,')')
r = list({'A','B','C'} - {f,l})[0]
if check(ip.replace(r,'(')) or check(ip.replace(r,')')):
print("YES")
else:
print("NO")
| {
"input": [
"4\nAABBAC\nCACA\nBBBBAC\nABCA\n"
],
"output": [
"\nYES\nYES\nNO\nNO\n"
]
} |
2,350 | 10 | This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array a of length n written on it, and then he does the following:
* he picks a range (l, r) and cuts the subsegment a_l, a_{l + 1}, β¦, a_r out, removing the rest of the array.
* he then cuts this range into multiple subranges.
* to add a number theory spice to it, he requires that the elements of every subrange must have their product equal to their [least common multiple (LCM)](https://en.wikipedia.org/wiki/Least_common_multiple).
Formally, he partitions the elements of a_l, a_{l + 1}, β¦, a_r into contiguous subarrays such that the product of every subarray is equal to its LCM. Now, for q independent ranges (l, r), tell Baby Ehab the minimum number of subarrays he needs.
Input
The first line contains 2 integers n and q (1 β€ n,q β€ 10^5) β the length of the array a and the number of queries.
The next line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^5) β the elements of the array a.
Each of the next q lines contains 2 integers l and r (1 β€ l β€ r β€ n) β the endpoints of this query's interval.
Output
For each query, print its answer on a new line.
Example
Input
6 3
2 3 10 7 5 14
1 6
2 4
3 5
Output
3
1
2
Note
The first query asks about the whole array. You can partition it into [2], [3,10,7], and [5,14]. The first subrange has product and LCM equal to 2. The second has product and LCM equal to 210. And the third has product and LCM equal to 70. Another possible partitioning is [2,3], [10,7], and [5,14].
The second query asks about the range (2,4). Its product is equal to its LCM, so you don't need to partition it further.
The last query asks about the range (3,5). You can partition it into [10,7] and [5]. | import sys
input = sys.stdin.buffer.readline
def I():return int(input())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
n, q = LI();prime_last_appear_at = dict();dp = [[n] * (n+1) for i in range(18)];arr = LI();have_primes = [ [ ]for _ in range(10**5+3)]
for p in range(2,10**5+2):
if not have_primes[p]:
prime_last_appear_at[p] = n; i = p
while i < len(have_primes): have_primes[i].append(p); i += p
for i in range(n-1,-1,-1):
dp[0][i] = dp[0][i+1]
for p in have_primes[arr[i]]: dp[0][i] = min(dp[0][i],prime_last_appear_at[p]); prime_last_appear_at[p] = i
for i in range(1,len(dp)):
for j in range(n): dp[i][j] = dp[i-1][dp[i-1][j]]
for _ in range(q):
l,r = LI_(); cur = l; res = 1
for jump in range(len(dp)-1,-1,-1):
if dp[jump][cur] <= r : res += 1 << jump; cur = dp[jump][cur]
print(res) | {
"input": [
"6 3\n2 3 10 7 5 14\n1 6\n2 4\n3 5\n"
],
"output": [
"\n3\n1\n2\n"
]
} |
2,351 | 12 | qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input
jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 β€ d β€ 11184) β jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output
ekjfkj q iydwbu dkcruh.
Examples
Input
1
Output
13 | def f(n):
i = 2
while i*i <= n:
if n%i == 0:
return False
i += 1
return True
n = int(input())
for i in range(10,1000000):
if i != int(str(i)[::-1]) and f(i) and f(int(str(i)[::-1])):
n -= 1
if n == 0:
print(i)
break | {
"input": [
"1\n"
],
"output": [
"13\n"
]
} |
2,352 | 10 | The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 β€ i β€ n) region has a stable temperature of ti degrees in summer.
This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is ti + k degrees.
Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit.
To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money.
Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.
Input
The first input line contains two integers n and m (1 β€ n β€ 105; 1 β€ m β€ 106) β the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next n lines contain four integers each: the i-th line contains ti, Ti, xi and costi (1 β€ ti, Ti, xi, costi β€ 106). The numbers in the lines are separated by single spaces.
Output
Print the only integer β the minimum number of roubles the organizers will have to spend to transport all schoolchildren.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
2 10
30 35 1 100
20 35 10 10
Output
120
Input
3 100
10 30 1000 1
5 10 1000 3
10 40 1000 100000
Output
200065
Note
In the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles. | #------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
n,m=value()
ans=0
for i in range(n):
t,T,x,cost=value()
here1=cost+(x*m)*int(t+m>T)
# print(t,T)
per_bus=T-t
if(per_bus<=0): here2=inf
else:
buses=Ceil(m,per_bus)
here2=cost*buses
ans+=min(here1,here2)
print(ans)
| {
"input": [
"3 100\n10 30 1000 1\n5 10 1000 3\n10 40 1000 100000\n",
"2 10\n30 35 1 100\n20 35 10 10\n"
],
"output": [
"200065\n",
"120\n"
]
} |
2,353 | 8 | Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.
Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:
* The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 β€ i β€ k - 1).
* No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 β€ i β€ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).
* All elements of the sequence are good integers.
Find the length of the longest good sequence.
Input
The input consists of two lines. The first line contains a single integer n (1 β€ n β€ 105) β the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 β€ ai β€ 105; ai < ai + 1).
Output
Print a single integer β the length of the longest good sequence.
Examples
Input
5
2 3 4 6 9
Output
4
Input
9
1 2 3 5 6 7 8 9 10
Output
4
Note
In the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4. | import math
a=int(input())
z=list(map(int,input().split()))
dp=[0 for i in range(max(z)+1)]
dp[0]=1
def fact(x):
ans=[]
for i in range(2,int(math.sqrt(x))+1):
if(x%i==0):
if(x//i!=i):
ans.append(i)
ans.append(x//i)
else:
ans.append(i)
ans.append(x)
return ans;
for i in range(len(z)):
t=fact(z[i])
maxa=0
for i in range(len(t)):
maxa=max(maxa,dp[t[i]])
for i in range(len(t)):
dp[t[i]]=maxa+1
print(max(dp))
| {
"input": [
"5\n2 3 4 6 9\n",
"9\n1 2 3 5 6 7 8 9 10\n"
],
"output": [
"4",
"4"
]
} |
2,354 | 8 | Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 β€ pi β€ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.
We know that:
1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 β€ n β€ 1000, 1 β€ k β€ min(8, n)) β the number of the houses and the number k from the statement.
Output
In a single line print a single integer β the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5 2
Output
54
Input
7 4
Output
1728 | mod=10**9+7
def power(x, a):
if(a==0):
return(1)
z=power(x, a//2)
z=(z*z)%mod
if(a%2):
z=(z*x)%mod
return(z)
[n, k]=list(map(int, input().split()))
print((power(n-k, n-k)*power(k, k-1))%mod) | {
"input": [
"7 4\n",
"5 2\n"
],
"output": [
"1728\n",
"54\n"
]
} |
2,355 | 8 | Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 β€ li < ri β€ n). The answer to the query li, ri is the number of such integers i (li β€ i < ri), that si = si + 1.
Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
Input
The first line contains string s of length n (2 β€ n β€ 105). It is guaranteed that the given string only consists of characters "." and "#".
The next line contains integer m (1 β€ m β€ 105) β the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 β€ li < ri β€ n).
Output
Print m integers β the answers to the queries in the order in which they are given in the input.
Examples
Input
......
4
3 4
2 3
1 6
2 6
Output
1
1
5
4
Input
#..###
5
1 3
5 6
1 5
3 6
3 4
Output
1
1
2
2
0 |
def solve():
s = input()
n = len(s) + 1
dp = [0]*(n)
for i in range(1, n):
dp[i] = dp[i - 1] + (s[i - 1] == s[i - 2])
t = int(input())
while t > 0:
x, y = map(int, input().split())
print(dp[y] - dp[x])
t = t - 1
solve()
| {
"input": [
"......\n4\n3 4\n2 3\n1 6\n2 6\n",
"#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4\n"
],
"output": [
"1\n1\n5\n4\n",
"1\n1\n2\n2\n0\n"
]
} |
2,356 | 9 | Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 β€ k β€ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.
Input
The first line contains a single integer t (1 β€ t β€ 5) β the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 β€ n β€ 24; p β₯ 0; <image>) β the number of vertices in the graph and the interest value for the appropriate test.
It is guaranteed that the required graph exists.
Output
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi) β two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.
Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
1
6 0
Output
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6 |
def solve(n, p):
cnt = 2 * n + p
for i in range(1, n+1):
for j in range(i+1, n+1):
print(i, j)
cnt -= 1
if cnt == 0:
return
def main():
t = int(input())
for _ in range(t):
n, p = map(int, input().split())
solve(n, p)
if __name__ == "__main__":
main() | {
"input": [
"1\n6 0\n"
],
"output": [
"1 2\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n"
]
} |
2,357 | 10 | Volodya has recently visited a very odd town. There are N tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing tour has the same total price! That is, if we choose any city sightseeing tour β a cycle which visits every attraction exactly once β the sum of the costs of the tour roads is independent of the tour. Volodya is curious if you can find such price system with all road prices not greater than 1000.
Input
Input contains just one natural number (3 β€ N β€ 20) β the number of town attractions.
Output
Output should contain N rows containing N positive integer numbers each β the adjacency matrix of the prices graph (thus, j-th number in i-th row should be equal to the price of the road between the j-th and the i-th attraction). Diagonal numbers should be equal to zero. All numbers should not be greater than 1000. All prices should be positive and pairwise distinct. If there are several solutions, output any of them.
Examples
Input
3
Output
0 3 4
3 0 5
4 5 0 | #codeforces 42d: strange town: math, constructive algorithm
def readGen(trans):
while 1:
for x in input().split():
yield(trans(x))
readint=readGen(int)
n=next(readint)
def constructRow(n):
can=[1 for i in range(1001)]
b=[0 for i in range(n+1)]
b[2]=1
b[3]=2
can[1]=0
can[2]=0
for k in range(4,n+1):
b[k]=b[k-1]+1
while (not can[b[k]]): b[k]+=1
can[b[k]]=0
for i in range(2,k):
for p in range(2,k):
can[b[k]+b[p]-b[i]]=0
return b
def constructMatrix(b,n):
can=[1 for i in range(1001)]
for i in range(2,n+1):
for j in range(2,n+1):
for p in range(2,n+1):
can[b[2]+b[3]+b[p]-b[i]-b[j]]=0
x=1
while (not can[x]): x+=1
a=[[0 for j in range(n+1)] for i in range(n+1)]
for i in range(n+1):
a[1][i]=a[i][1]=b[i]
for i in range(2,n+1):
for j in range(i+1,n+1):
a[i][j]=a[j][i]=b[i]+b[j]+x-b[2]-b[3]
return a
b=constructRow(n)
#print(b)
a=constructMatrix(b,n)
for i in range(1,n+1):
for j in range(1,n+1):
print("{:4}".format(a[i][j]),end='')
print()
| {
"input": [
"3\n"
],
"output": [
"0 3 4\n3 0 5\n4 5 0\n"
]
} |
2,358 | 8 | You are given a rectangular grid of lattice points from (0, 0) to (n, m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.
A polyline defined by points p1, p2, p3, p4 consists of the line segments p1 p2, p2 p3, p3 p4, and its length is the sum of the lengths of the individual line segments.
Input
The only line of the input contains two integers n and m (0 β€ n, m β€ 1000). It is guaranteed that grid contains at least 4 different points.
Output
Print 4 lines with two integers per line separated by space β coordinates of points p1, p2, p3, p4 in order which represent the longest possible polyline.
Judge program compares your answer and jury's answer with 10 - 6 precision.
Examples
Input
1 1
Output
1 1
0 0
1 0
0 1
Input
0 10
Output
0 1
0 10
0 0
0 9 | n,m=map(int,input().split())
v=set()
R=0,1
def f(a,b):
if 0<=a<=n and 0<=b<=m:v.add((a,b))
g=lambda x:sum((x[0][i]-x[1][i])**2 for i in R)**.5+g(x[1:])if len(x)>1else 0
r=[[0,0]]*4
for i in R:
for j in R:f(i,j);f(n-i,m-j);f(i,m-j);f(n-i,j)
for a in v:
for b in v:
for c in v:
for d in v:
if len(set([a,b,c,d]))==4 and g(r)<g([a,b,c,d]):r=a,b,c,d
for a,b in r:print(a,b) | {
"input": [
"0 10\n",
"1 1\n"
],
"output": [
"0 1\n0 10\n0 0\n0 9\n",
"0 0\n1 1\n0 1\n1 0\n"
]
} |
2,359 | 12 | Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 β€ i β€ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of Β«Hunger GamesΒ» for the ants. He chooses two numbers l and r (1 β€ l β€ r β€ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
Input
The first line contains one integer n (1 β€ n β€ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 β€ si β€ 109), the strengths of the ants.
The third line contains one integer t (1 β€ t β€ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 β€ li β€ ri β€ n), describing one query.
Output
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
Examples
Input
5
1 3 2 4 2
4
1 5
2 5
3 5
4 5
Output
4
4
1
1
Note
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4. | import sys
from math import gcd
from bisect import bisect_left,bisect_right
class SparseTable:
def func(self,a,b):
return gcd(a,b)
def __init__(self,arr):
n=len(arr)
max_k=(n-1).bit_length()-1
val=1
table=[[val]*(max_k+1) for i in range(n)]
for i in range(n):
table[i][0]=arr[i]
for k in range(1,max_k+1):
k2=1<<(k-1)
k3=1<<k-1
for i in range(n-k3):
table[i][k]=self.func(table[i][k-1],table[k2+i][k-1])
self.table=table
def query(self,l,r):
d=r-l
if d==1:
return self.table[l][0]
k=(d-1).bit_length()-1
k2=1<<k
return self.func(self.table[l][k],self.table[r-k2][k])
input=sys.stdin.readline
n=int(input())
s=list(map(int,input().split()))
sp_tab=SparseTable(s)
di={}
for i in range(n):
if s[i] in di:
di[s[i]].append(i)
else:
di[s[i]]=[i]
q=int(input())
for _ in range(q):
l,r=map(int,input().split())
l-=1;r-=1
g=sp_tab.query(l,r+1)
if g in di:
num=bisect_right(di[g],r)-bisect_left(di[g],l)
print(r-l+1-num)
else:
print(r-l+1) | {
"input": [
"5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5\n"
],
"output": [
"4\n4\n1\n1\n"
]
} |
2,360 | 7 | One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.
Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.
Input
The first line of the input contains integer n (1 β€ n β€ 200) β the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.
We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.
Output
Print a single integer β the maximum length of a repost chain.
Examples
Input
5
tourist reposted Polycarp
Petr reposted Tourist
WJMZBMR reposted Petr
sdya reposted wjmzbmr
vepifanov reposted sdya
Output
6
Input
6
Mike reposted Polycarp
Max reposted Polycarp
EveryOne reposted Polycarp
111 reposted Polycarp
VkCup reposted Polycarp
Codeforces reposted Polycarp
Output
2
Input
1
SoMeStRaNgEgUe reposted PoLyCaRp
Output
2 | s = {}
for i in range(int(input())):
u, k, v = input().lower().split()
s[v] = s.get(v, []) + [u]
def f(x): return max(f(y) for y in s[x]) + 1 if x in s else 1
print(f('polycarp')) | {
"input": [
"6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp\n",
"1\nSoMeStRaNgEgUe reposted PoLyCaRp\n",
"5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya\n"
],
"output": [
"2",
"2",
"6"
]
} |
2,361 | 9 | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.
The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.
Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.
Input
The first line contains two positive space-separated integers, n and k (1 β€ k β€ n β€ 2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends.
The second line contains n space-separated positive integers ai (1 β€ ai β€ 106), which represent the population of each city in Westeros.
Output
Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins.
Examples
Input
3 1
1 2 1
Output
Stannis
Input
3 1
2 2 1
Output
Daenerys
Input
6 3
5 20 12 7 14 101
Output
Stannis
Note
In the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.
In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | def win(n,k,a):
count = [0,0]
for x in a:
count[x&1] += 1
moves = n-k
if n==k:
return count[1]&1
if count[1] <= moves//2:
return False
if count[0] <= moves//2:
return k&1
else:
return moves&1
n,k = map(int,input().split())
print("Stannis" if win(n,k,map(int,input().split())) else "Daenerys") | {
"input": [
"3 1\n1 2 1\n",
"6 3\n5 20 12 7 14 101\n",
"3 1\n2 2 1\n"
],
"output": [
"Stannis\n",
"Stannis\n",
"Daenerys\n"
]
} |
2,362 | 9 | For the given sequence with n different elements find the number of increasing subsequences with k + 1 elements. It is guaranteed that the answer is not greater than 8Β·1018.
Input
First line contain two integer values n and k (1 β€ n β€ 105, 0 β€ k β€ 10) β the length of sequence and the number of elements in increasing subsequences.
Next n lines contains one integer ai (1 β€ ai β€ n) each β elements of sequence. All values ai are different.
Output
Print one integer β the answer to the problem.
Examples
Input
5 2
1
2
3
5
4
Output
7 | import os
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, k = map(int, input().split())
a = [int(input()) for i in range(n)]
dp = [[0] * (n + 1) for i in range(k + 1)]
def query(f, i):
r = 0
while i > 0:
r += f[i]
i -= i & -i
return r
def update(f, i, r):
while i <= n:
f[i] += r
i += i & -i
res = [1] * n
for i in range(n):
update(dp[0], a[i], 1)
for j in range(1, k + 1):
res[i] = query(dp[j - 1], a[i] - 1)
update(dp[j], a[i], res[i])
print(sum(res)) | {
"input": [
"5 2\n1\n2\n3\n5\n4\n"
],
"output": [
"7\n"
]
} |
2,363 | 11 | Roger is a robot. He has an arm that is a series of n segments connected to each other. The endpoints of the i-th segment are initially located at points (i - 1, 0) and (i, 0). The endpoint at (i - 1, 0) is colored red and the endpoint at (i, 0) is colored blue for all segments. Thus, the blue endpoint of the i-th segment is touching the red endpoint of the (i + 1)-th segment for all valid i.
Roger can move his arm in two different ways:
1. He can choose some segment and some value. This is denoted as choosing the segment number i and picking some positive l. This change happens as follows: the red endpoint of segment number i and segments from 1 to i - 1 are all fixed in place. Imagine a ray from the red endpoint to the blue endpoint. The blue endpoint and segments i + 1 through n are translated l units in the direction of this ray. <image> <image>
In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B gets translated.
2. He can choose a segment and rotate it. This is denoted as choosing the segment number i, and an angle a. The red endpoint of the i-th segment will stay fixed in place. The blue endpoint of that segment and segments i + 1 to n will rotate clockwise by an angle of a degrees around the red endpoint. <image> <image>
In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B get rotated around point A.
Roger will move his arm m times. These transformations are a bit complicated, and Roger easily loses track of where the blue endpoint of the last segment is. Help him compute the coordinates of the blue endpoint of the last segment after applying each operation. Note that these operations are cumulative, and Roger's arm may intersect itself arbitrarily during the moves.
Input
The first line of the input will contain two integers n and m (1 β€ n, m β€ 300 000) β the number of segments and the number of operations to perform.
Each of the next m lines contains three integers xi, yi and zi describing a move. If xi = 1, this line describes a move of type 1, where yi denotes the segment number and zi denotes the increase in the length. If xi = 2, this describes a move of type 2, where yi denotes the segment number, and zi denotes the angle in degrees. (1 β€ xi β€ 2, 1 β€ yi β€ n, 1 β€ zi β€ 359)
Output
Print m lines. The i-th line should contain two real values, denoting the coordinates of the blue endpoint of the last segment after applying operations 1, ..., i. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.
Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates.
Examples
Input
5 4
1 1 3
2 3 90
2 5 48
1 4 1
Output
8.0000000000 0.0000000000
5.0000000000 -3.0000000000
4.2568551745 -2.6691306064
4.2568551745 -3.6691306064
Note
The following pictures shows the state of the arm after each operation. The coordinates of point F are printed after applying each operation. For simplicity, we only show the blue endpoints of a segment (with the exception for the red endpoint of the first segment). For instance, the point labeled B is the blue endpoint for segment 1 and also the red endpoint for segment 2.
Initial state:
<image> Extend segment 1 by 3. <image> Rotate segment 3 by 90 degrees clockwise. <image> Rotate segment 5 by 48 degrees clockwise. <image> Extend segment 4 by 1. <image> | from cmath import rect
import sys
import math
from functools import reduce
class SegmentTree():
def __init__(self, L, function = lambda x,y: x+y):
self.function = function
N = self.size = len(L)
M = 1 << N.bit_length()
self.margin = 2*M - N
self.L = [None for i in range(self.margin)] + L
for i in range(M-1, 0, -1):
x, y = self.L[i<<1], self.L[i<<1|1]
self.L[i] = None if x is None or y is None else function(x, y)
def modify(self, pos, value):
p = pos + self.margin
self.L[p] = value
while p > 1:
x, y = self.L[p], self.L[p^1]
if p&1: x, y = y, x
self.L[p>>1] = None if x is None or y is None else self.function(x, y)
p>>=1
def query(self, left, right):
l, r = left + self.margin, right + self.margin
stack = []
void = True
while l < r:
if l&1:
if void:
result = self.L[l]
void = False
else:
result = self.function(result, self.L[l])
l+=1
if r&1:
r-=1
stack.append(self.L[r])
l>>=1
r>>=1
init = stack.pop() if void else result
return reduce(self.function, reversed(stack), init)
def degrect(r, phi):
return rect(r, math.radians(phi))
def vsum(u, v): #u = (x + y*1j, phi)
return (u[0] + v[0]*degrect(1, u[1]), (u[1] + v[1])%360)
def solve(f):
n, m = [int(x) for x in f.readline().split()]
segments = [[1,0] for i in range(n)]
arm = SegmentTree([(1,0) for i in range(n)], vsum)
for line in f:
q, i, a = [int(x) for x in line.split()]
if q == 1:
segments[i-1][0] += a
else:
segments[i-1][1] -= a
arm.modify(i-1, (degrect(segments[i-1][0], segments[i-1][1]), segments[i-1][1]))
query = arm.query(0,n)[0]
print(query.real, query.imag)
solve(sys.stdin)
| {
"input": [
"5 4\n1 1 3\n2 3 90\n2 5 48\n1 4 1\n"
],
"output": [
"8.000000000 0.000000000\n5.000000000 -3.000000000\n4.256855175 -2.669130606\n4.256855175 -3.669130606\n"
]
} |
2,364 | 8 | The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good.
Heidi knows that the lair can be represented as a rectangle on a lattice, with sides parallel to the axes. Each vertex of the polygon occupies an integer point on the lattice. For each cell of the lattice, Heidi can check the level of Zombie Contamination. This level is an integer between 0 and 4, equal to the number of corners of the cell that are inside or on the border of the rectangle.
As a test, Heidi wants to check that her Zombie Contamination level checker works. Given the output of the checker, Heidi wants to know whether it could have been produced by a single non-zero area rectangular-shaped lair (with axis-parallel sides). <image>
Input
The first line of each test case contains one integer N, the size of the lattice grid (5 β€ N β€ 50). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.
Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).
Output
The first line of the output should contain Yes if there exists a single non-zero area rectangular lair with corners on the grid for which checking the levels of Zombie Contamination gives the results given in the input, and No otherwise.
Example
Input
6
000000
000000
012100
024200
012100
000000
Output
Yes
Note
The lair, if it exists, has to be rectangular (that is, have corners at some grid points with coordinates (x1, y1), (x1, y2), (x2, y1), (x2, y2)), has a non-zero area and be contained inside of the grid (that is, 0 β€ x1 < x2 β€ N, 0 β€ y1 < y2 β€ N), and result in the levels of Zombie Contamination as reported in the input. | def check_cell(i, j, n):
k = 0
if i > 1 and field[i-1][j]: k += 1
if i < n-1 and field[i+1][j]: k += 1
if j > 1 and field[i][j-1]: k += 1
if j < n-1 and field[i][j+1]: k += 1
if k < 2:
return 0
elif k < 4:
return k-1
else:
return 4
n = int(input())
field = []
for i in range(n):
temp = [int(x) for x in input()]
field.append(temp)
def main():
for i in range(n):
for j in range(n):
if field[i][j] and not field[i][j] == check_cell(i, j, n):
print('No')
return 0
print('Yes')
main() | {
"input": [
"6\n000000\n000000\n012100\n024200\n012100\n000000\n"
],
"output": [
"Yes"
]
} |
2,365 | 10 | Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.
Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" <image> "nastya" <image> "nastya" <image> "nastya" <image> "nastya" <image> "nastya" <image> "nastya".
Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.
It is guaranteed that the word p can be obtained by removing the letters from word t.
Input
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 β€ |p| < |t| β€ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t.
Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 β€ ai β€ |t|, all ai are distinct).
Output
Print a single integer number, the maximum number of letters that Nastya can remove.
Examples
Input
ababcba
abb
5 3 4 1 7 6 2
Output
3
Input
bbbabb
bb
1 6 3 4 2 5
Output
4
Note
In the first sample test sequence of removing made by Nastya looks like this:
"ababcba" <image> "ababcba" <image> "ababcba" <image> "ababcba"
Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".
So, Nastya will remove only three letters. | s = input()
t = input()
a = [int(x) - 1 for x in input().split()]
def ok(n):
bad = set(a[:n])
it = (a for i, a in enumerate(s) if i not in bad)
return all(c in it for c in t)
low = 0
high = len(s)
while low < high:
mid = (high + low + 1) // 2
if (ok(mid)):
low = mid
else:
high = mid - 1
print (high) | {
"input": [
"bbbabb\nbb\n1 6 3 4 2 5\n",
"ababcba\nabb\n5 3 4 1 7 6 2\n"
],
"output": [
"4",
"3"
]
} |
2,366 | 7 | Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one.
Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more, he also remembers exactly ki positions where the string ti occurs in string s: these positions are xi, 1, xi, 2, ..., xi, ki. He remembers n such strings ti.
You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings ti and string s consist of small English letters only.
Input
The first line contains single integer n (1 β€ n β€ 105) β the number of strings Ivan remembers.
The next n lines contain information about the strings. The i-th of these lines contains non-empty string ti, then positive integer ki, which equal to the number of times the string ti occurs in string s, and then ki distinct positive integers xi, 1, xi, 2, ..., xi, ki in increasing order β positions, in which occurrences of the string ti in the string s start. It is guaranteed that the sum of lengths of strings ti doesn't exceed 106, 1 β€ xi, j β€ 106, 1 β€ ki β€ 106, and the sum of all ki doesn't exceed 106. The strings ti can coincide.
It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists.
Output
Print lexicographically minimal string that fits all the information Ivan remembers.
Examples
Input
3
a 4 1 3 5 7
ab 2 1 5
ca 1 4
Output
abacaba
Input
1
a 1 3
Output
aaa
Input
3
ab 1 1
aba 1 3
ab 2 3 5
Output
ababab | import sys
input = sys.stdin.readline
n = int(input())
L = 0
t, x = [], []
for i in range(n):
v = input().split()
t.append(v[0])
pos = list(map(lambda x: int(x) - 1, v[2:]))
x.append(pos)
L = max(L, pos[-1] + len(t[i]))
nxt = list(range(L + 1))
ans = ['a'] * L
def find(j):
jcopy = j
while nxt[j] != j:
j = nxt[j]
j, jcopy = jcopy, j
while nxt[j] != j:
tmp = nxt[j]
nxt[j] = jcopy
j = tmp
return j
for i in range(n):
for j in x[i]:
l = j
j = find(nxt[j])
while j < l + len(t[i]):
ans[j] = t[i][j - l]
nxt[j] = j + 1
j = find(nxt[j])
print(*ans, sep='')
| {
"input": [
"3\na 4 1 3 5 7\nab 2 1 5\nca 1 4\n",
"3\nab 1 1\naba 1 3\nab 2 3 5\n",
"1\na 1 3\n"
],
"output": [
"abacaba\n",
"ababab\n",
"aaa\n"
]
} |
2,367 | 7 | Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?
Given an integer sequence a1, a2, ..., an of length n. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.
A subsegment is a contiguous slice of the whole sequence. For example, {3, 4, 5} and {1} are subsegments of sequence {1, 2, 3, 4, 5, 6}, while {1, 2, 4} and {7} are not.
Input
The first line of input contains a non-negative integer n (1 β€ n β€ 100) β the length of the sequence.
The second line contains n space-separated non-negative integers a1, a2, ..., an (0 β€ ai β€ 100) β the elements of the sequence.
Output
Output "Yes" if it's possible to fulfill the requirements, and "No" otherwise.
You can output each letter in any case (upper or lower).
Examples
Input
3
1 3 5
Output
Yes
Input
5
1 0 1 5 1
Output
Yes
Input
3
4 3 1
Output
No
Input
4
3 9 9 3
Output
No
Note
In the first example, divide the sequence into 1 subsegment: {1, 3, 5} and the requirements will be met.
In the second example, divide the sequence into 3 subsegments: {1, 0, 1}, {5}, {1}.
In the third example, one of the subsegments must start with 4 which is an even number, thus the requirements cannot be met.
In the fourth example, the sequence can be divided into 2 subsegments: {3, 9, 9}, {3}, but this is not a valid solution because 2 is an even number. | def re():
return list(map(int, input().split()))
n = int(input())
a = re()
print("Yes" if a[0]&1 and a[-1]&1 and len(a)&1 else "No")
| {
"input": [
"4\n3 9 9 3\n",
"3\n4 3 1\n",
"5\n1 0 1 5 1\n",
"3\n1 3 5\n"
],
"output": [
"No\n",
"No\n",
"Yes\n",
"Yes\n"
]
} |
2,368 | 9 | What are you doing at the end of the world? Are you busy? Will you save us?
<image>
Nephren is playing a game with little leprechauns.
She gives them an infinite array of strings, f0... β.
f0 is "What are you doing at the end of the world? Are you busy? Will you save us?".
She wants to let more people know about it, so she defines fi = "What are you doing while sending "fi - 1"? Are you busy? Will you send "fi - 1"?" for all i β₯ 1.
For example, f1 is
"What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of f1.
It can be seen that the characters in fi are letters, question marks, (possibly) quotation marks and spaces.
Nephren will ask the little leprechauns q times. Each time she will let them find the k-th character of fn. The characters are indexed starting from 1. If fn consists of less than k characters, output '.' (without quotes).
Can you answer her queries?
Input
The first line contains one integer q (1 β€ q β€ 10) β the number of Nephren's questions.
Each of the next q lines describes Nephren's question and contains two integers n and k (0 β€ n β€ 105, 1 β€ k β€ 1018).
Output
One line containing q characters. The i-th character in it should be the answer for the i-th query.
Examples
Input
3
1 1
1 2
1 111111111111
Output
Wh.
Input
5
0 69
1 194
1 139
0 47
1 66
Output
abdef
Input
10
4 1825
3 75
3 530
4 1829
4 1651
3 187
4 584
4 255
4 774
2 474
Output
Areyoubusy
Note
For the first two examples, refer to f0 and f1 given in the legend. | s0 = 'What are you doing at the end of the world? Are you busy? Will you save us?'
s1 = 'What are you doing while sending "'
s2 = '"? Are you busy? Will you send "'
def get(h):
if h > 55: return 1<<99
return (143 << h) - 68
def solve(n, k):
if get(n) <= k: return '.'
while True:
if n == 0: return s0[k]
if k < 34: return s1[k]
k -= 34
if k < get(n-1):
n -= 1
continue
k -= get(n-1)
if k < 32: return s2[k]
k -= 32
if k < get(n-1): n -=1
else: return '"?'[k - get(n - 1)]
for i in range(int(input())):
n,k=list(map(int,input().split()))
print(solve(n,k-1),end='')
| {
"input": [
"10\n4 1825\n3 75\n3 530\n4 1829\n4 1651\n3 187\n4 584\n4 255\n4 774\n2 474\n",
"3\n1 1\n1 2\n1 111111111111\n",
"5\n0 69\n1 194\n1 139\n0 47\n1 66\n"
],
"output": [
"Areyoubusy",
"Wh.",
"abdef"
]
} |
2,369 | 10 | As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter.
<image>
Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time.
Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game?
You have to determine the winner of the game for all initial positions of the marbles.
Input
The first line of input contains two integers n and m (2 β€ n β€ 100, <image>).
The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 β€ v, u β€ n, v β u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic.
Output
Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise.
Examples
Input
4 4
1 2 b
1 3 a
2 4 c
3 4 b
Output
BAAA
ABAA
BBBA
BBBB
Input
5 8
5 3 h
1 2 c
3 1 c
3 2 r
5 1 r
4 3 z
5 4 r
5 2 h
Output
BABBB
BBBBB
AABBB
AAABA
AAAAB
Note
Here's the graph in the first sample test case:
<image>
Here's the graph in the second sample test case:
<image> | from functools import lru_cache
def readline(): return list(map(int, input().split()))
def main():
n, m = readline()
edges = [list() for __ in range(n)]
for __ in range(m):
tokens = input().split()
begin, end = map(int, tokens[:2])
weight = ord(tokens[2])
edges[begin - 1].append((end - 1, weight))
@lru_cache(maxsize=None)
def first_wins(first, second, lower=0):
for (nxt, w) in edges[first]:
if w >= lower:
if not first_wins(second, nxt, w):
return True
return False
for i in range(n):
print("".join("BA"[first_wins(i, j)] for j in range(n)))
main() | {
"input": [
"5 8\n5 3 h\n1 2 c\n3 1 c\n3 2 r\n5 1 r\n4 3 z\n5 4 r\n5 2 h\n",
"4 4\n1 2 b\n1 3 a\n2 4 c\n3 4 b\n"
],
"output": [
"BABBB\nBBBBB\nAABBB\nAAABA\nAAAAB\n",
"BAAA\nABAA\nBBBA\nBBBB\n"
]
} |
2,370 | 10 | "We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme."
"Little Alena got an array as a birthday present..."
The array b of length n is obtained from the array a of length n and two integers l and r (l β€ r) using the following procedure:
b1 = b2 = b3 = b4 = 0.
For all 5 β€ i β€ n:
* bi = 0 if ai, ai - 1, ai - 2, ai - 3, ai - 4 > r and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 1
* bi = 1 if ai, ai - 1, ai - 2, ai - 3, ai - 4 < l and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 0
* bi = bi - 1 otherwise
You are given arrays a and b' of the same length. Find two integers l and r (l β€ r), such that applying the algorithm described above will yield an array b equal to b'.
It's guaranteed that the answer exists.
Input
The first line of input contains a single integer n (5 β€ n β€ 105) β the length of a and b'.
The second line of input contains n space separated integers a1, ..., an ( - 109 β€ ai β€ 109) β the elements of a.
The third line of input contains a string of n characters, consisting of 0 and 1 β the elements of b'. Note that they are not separated by spaces.
Output
Output two integers l and r ( - 109 β€ l β€ r β€ 109), conforming to the requirements described above.
If there are multiple solutions, output any of them.
It's guaranteed that the answer exists.
Examples
Input
5
1 2 3 4 5
00001
Output
6 15
Input
10
-10 -9 -8 -7 -6 6 7 8 9 10
0000111110
Output
-5 5
Note
In the first test case any pair of l and r pair is valid, if 6 β€ l β€ r β€ 109, in that case b5 = 1, because a1, ..., a5 < l. | def check(lst, val):
return (lst[1:] == lst[:-1]) and (lst[0] == val)
n = int(input())
a= [int(s) for s in input().split(" ")]
b_= [int(s) for s in list(input())]
l = -10**9
r = 10**9
list_=b_[:4]
for i in range(4, len(b_)):
if check(list_,0):
if b_[i] == 1:
l = max(max(a[i-4:i+1]) + 1,l)
elif check(list_,1):
if b_[i] == 0:
r = min(r,min(a[i-4:i+1]) - 1)
list_.pop(0)
list_.insert(len(list_),b_[i])
print(str(l)+ " " + str(r))
| {
"input": [
"5\n1 2 3 4 5\n00001\n",
"10\n-10 -9 -8 -7 -6 6 7 8 9 10\n0000111110\n"
],
"output": [
"6 1000000000\n",
"-5 5\n"
]
} |
2,371 | 7 | Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.
Input
The first input line contains a non-empty string consisting of characters "0" and "1", which represents players. The length of the string does not exceed 100 characters. There's at least one player from each team present on the field.
Output
Print "YES" if the situation is dangerous. Otherwise, print "NO".
Examples
Input
001001
Output
NO
Input
1000000001
Output
YES | def cal(s):
if "1111111" in s or "0000000" in s:
return "YES"
return "NO"
s=input()
print(cal(s)) | {
"input": [
"1000000001\n",
"001001\n"
],
"output": [
"YES\n",
"NO\n"
]
} |
2,372 | 7 | You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.
Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subsequence of the sequence you have that only contains digits with fingerprints on the corresponding keys. Find such code.
Input
The first line contains two integers n and m (1 β€ n, m β€ 10) representing the number of digits in the sequence you have and the number of keys on the keypad that have fingerprints.
The next line contains n distinct space-separated integers x_1, x_2, β¦, x_n (0 β€ x_i β€ 9) representing the sequence.
The next line contains m distinct space-separated integers y_1, y_2, β¦, y_m (0 β€ y_i β€ 9) β the keys with fingerprints.
Output
In a single line print a space-separated sequence of integers representing the code. If the resulting sequence is empty, both printing nothing and printing a single line break is acceptable.
Examples
Input
7 3
3 5 7 1 6 2 8
1 2 7
Output
7 1 2
Input
4 4
3 4 1 0
0 1 7 9
Output
1 0
Note
In the first example, the only digits with fingerprints are 1, 2 and 7. All three of them appear in the sequence you know, 7 first, then 1 and then 2. Therefore the output is 7 1 2. Note that the order is important, and shall be the same as the order in the original sequence.
In the second example digits 0, 1, 7 and 9 have fingerprints, however only 0 and 1 appear in the original sequence. 1 appears earlier, so the output is 1 0. Again, the order is important. | def inp():
return map(int, input().split())
import sys;
import math;
n,m = inp();
a = list(inp())
b = list(inp())
ans = [];
for i in a:
if i in b:
ans.append(i);
print(*ans); | {
"input": [
"4 4\n3 4 1 0\n0 1 7 9\n",
"7 3\n3 5 7 1 6 2 8\n1 2 7\n"
],
"output": [
"1 0\n",
"7 1 2\n"
]
} |
2,373 | 8 | You are given a rectangular parallelepiped with sides of positive integer lengths A, B and C.
Find the number of different groups of three integers (a, b, c) such that 1β€ aβ€ bβ€ c and parallelepiped AΓ BΓ C can be paved with parallelepipeds aΓ bΓ c. Note, that all small parallelepipeds have to be rotated in the same direction.
For example, parallelepiped 1Γ 5Γ 6 can be divided into parallelepipeds 1Γ 3Γ 5, but can not be divided into parallelepipeds 1Γ 2Γ 3.
Input
The first line contains a single integer t (1 β€ t β€ 10^5) β the number of test cases.
Each of the next t lines contains three integers A, B and C (1 β€ A, B, C β€ 10^5) β the sizes of the parallelepiped.
Output
For each test case, print the number of different groups of three points that satisfy all given conditions.
Example
Input
4
1 1 1
1 6 1
2 2 2
100 100 100
Output
1
4
4
165
Note
In the first test case, rectangular parallelepiped (1, 1, 1) can be only divided into rectangular parallelepiped with sizes (1, 1, 1).
In the second test case, rectangular parallelepiped (1, 6, 1) can be divided into rectangular parallelepipeds with sizes (1, 1, 1), (1, 1, 2), (1, 1, 3) and (1, 1, 6).
In the third test case, rectangular parallelepiped (2, 2, 2) can be divided into rectangular parallelepipeds with sizes (1, 1, 1), (1, 1, 2), (1, 2, 2) and (2, 2, 2). | from sys import stdin
from math import gcd
def main():
input()
l = stdin.read().splitlines()
d = [3., 1., 2., 2., 2., 1.] * 16667
for i in range(4, 100001):
for j in range(i, 100001, i):
d[j] += 1.
for i, s in enumerate(l):
a, b, c = map(int, s.split())
k = gcd(b, c)
ab = d[gcd(a, b)]
ac = d[gcd(a, c)]
bc = d[k]
abc = d[gcd(a, k)]
asz = d[a] - ab - ac + abc
bsz = d[b] - bc - ab + abc
csz = d[c] - ac - bc + abc
absz = ab - abc
bcsz = bc - abc
acsz = ac - abc
l[i] = '%d' % (asz * bsz * csz +
(absz * (asz + bsz) * csz) +
(bcsz * (bsz + csz) * asz) +
(acsz * (asz + csz) * bsz) +
(abc * (asz * bsz + asz * csz + bsz * csz)) +
(abc * (absz + bcsz + acsz) * (asz + bsz + csz)) +
((asz + bsz + csz + absz + bcsz + acsz) * (abc * (abc + 1) * .5)) +
(absz * bcsz * acsz) +
((absz * (absz + 1.) * d[c]) +
(bcsz * (bcsz + 1.) * d[a]) +
(acsz * (acsz + 1.) * d[b])) * .5 +
((asz + bsz + csz + abc) * (absz * acsz + absz * bcsz + bcsz * acsz)) +
(abc + (abc * (abc - 1.)) + (abc * (abc - 1.) * (abc - 2.) / 6.)))
print('\n'.join(map(str, l)))
if __name__ == '__main__':
main()
# Made By Mostafa_Khaled | {
"input": [
"4\n1 1 1\n1 6 1\n2 2 2\n100 100 100\n"
],
"output": [
"1\n4\n4\n165\n"
]
} |
2,374 | 8 | Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.
Help Vasya! For each grasshopper determine if it is inside the field (including the border).
Input
The first line contains two integers n and d (1 β€ d < n β€ 100).
The second line contains a single integer m (1 β€ m β€ 100) β the number of grasshoppers.
The i-th of the next m lines contains two integers x_i and y_i (0 β€ x_i, y_i β€ n) β position of the i-th grasshopper.
Output
Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO".
You can print each letter in any case (upper or lower).
Examples
Input
7 2
4
2 4
4 1
6 3
4 5
Output
YES
NO
NO
YES
Input
8 7
4
4 4
2 8
8 1
6 1
Output
YES
NO
YES
YES
Note
The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield.
The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield.
<image> | def test(x,y):
if d<=x+y<=2*n-d and abs(x-y)<=d:
print("yes")
else:
print("no")
n,d=map(int,input().split())
for i in range(int(input())):
test(*[int(j) for j in input().split()]) | {
"input": [
"7 2\n4\n2 4\n4 1\n6 3\n4 5\n",
"8 7\n4\n4 4\n2 8\n8 1\n6 1\n"
],
"output": [
"YES\nNO\nNO\nYES\n",
"YES\nNO\nYES\nYES\n"
]
} |
2,375 | 7 | On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column.
The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)...
Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules:
As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time.
The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win.
Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited.
Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first.
Input
The first line contains a single integer n (2 β€ n β€ 10^{18}) β the length of the side of the chess field.
The second line contains two integers x and y (1 β€ x,y β€ n) β coordinates of the cell, where the coin fell.
Output
In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win.
You can print each letter in any case (upper or lower).
Examples
Input
4
2 3
Output
White
Input
5
3 5
Output
Black
Input
2
2 2
Output
Black
Note
An example of the race from the first sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (4,4) into the cell (3,3).
3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins.
<image>
An example of the race from the second sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (5,5) into the cell (4,4).
3. The white king moves from the cell (2,2) into the cell (3,3).
4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins.
<image>
In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins.
<image> | n = int(input())
x, y = map(int, input().split())
def d(a, b):
return a + b
if d(x-1, y-1) <= d(n-x, n-y):
print("White")
else:
print("Black") | {
"input": [
"4\n2 3\n",
"5\n3 5\n",
"2\n2 2\n"
],
"output": [
"White",
"Black",
"Black"
]
} |
2,376 | 8 | You are given a string s of length n consisting only of lowercase Latin letters.
A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not.
Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one).
It is guaranteed that there is at least two different characters in s.
Note that you can remove the whole string and it is correct. Also note that you should remove at least one character.
Since the answer can be rather large (not very large though) print it modulo 998244353.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains one integer n (2 β€ n β€ 2 β
10^5) β the length of the string s.
The second line of the input contains the string s of length n consisting only of lowercase Latin letters.
It is guaranteed that there is at least two different characters in s.
Output
Print one integer β the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal.
Examples
Input
4
abaa
Output
6
Input
7
aacdeee
Output
6
Input
2
az
Output
3
Note
Let s[l; r] be the substring of s from the position l to the position r inclusive.
Then in the first example you can remove the following substrings:
* s[1; 2];
* s[1; 3];
* s[1; 4];
* s[2; 2];
* s[2; 3];
* s[2; 4].
In the second example you can remove the following substrings:
* s[1; 4];
* s[1; 5];
* s[1; 6];
* s[1; 7];
* s[2; 7];
* s[3; 7].
In the third example you can remove the following substrings:
* s[1; 1];
* s[1; 2];
* s[2; 2]. | def main():
n = int(input())
s = input()
ans = 1
i = 0
while(s[i]==s[i+1]):
i+=1
i+=1
j = n-1
while(s[j]==s[j-1]):
j-=1
ans+=i+n-j
if s[0] == s[n-1]:
ans+=i*(n-j)
print(ans%998244353)
main()
| {
"input": [
"7\naacdeee\n",
"2\naz\n",
"4\nabaa\n"
],
"output": [
"6\n",
"3\n",
"6\n"
]
} |
2,377 | 9 | You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2).
You know the weather forecast β the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day β s_2, the n-th day β s_n and (n+1)-th day β s_1 again and so on.
Ship coordinates change the following way:
* if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1);
* if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1);
* if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y);
* if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y).
The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2).
You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2).
Input
The first line contains two integers x_1, y_1 (0 β€ x_1, y_1 β€ 10^9) β the initial coordinates of the ship.
The second line contains two integers x_2, y_2 (0 β€ x_2, y_2 β€ 10^9) β the coordinates of the destination point.
It is guaranteed that the initial coordinates and destination point coordinates are different.
The third line contains a single integer n (1 β€ n β€ 10^5) β the length of the string s.
The fourth line contains the string s itself, consisting only of letters U, D, L and R.
Output
The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2).
If it's impossible then print "-1".
Examples
Input
0 0
4 6
3
UUU
Output
5
Input
0 3
0 0
3
UDD
Output
3
Input
0 0
0 1
1
L
Output
-1
Note
In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) β (1, 1) β (2, 2) β (3, 3) β (4, 4) β (4, 6).
In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) β (0, 3) β (0, 1) β (0, 0).
In the third example the ship can never reach the point (0, 1). | def check(k,n,dx,dy):
x = (k//n)*px[n]
y = (k//n)*py[n]
x += px[k%n]
y += py[k%n]
if abs(x-dx)+abs(y-dy)<=k:
return 1
return 0
x1,y1=map(int,input().split())
x2,y2=map(int,input().split())
dx = x2-x1
dy = y2-y1
n=int(input())
s=input()
px=[0]*(n+5)
py = [0]*(n+5)
for i in range(1,n+1):
px[i] = px[i-1]
py[i] = py[i-1]
if s[i-1]=='U':
py[i]+=1
elif s[i-1]=='D':
py[i]-=1
elif s[i-1]=='L':
px[i]-=1
else:
px[i]+=1
s=0
e = int(10**18)
ans = -1
while s<=e:
m = (s+e)//2
if check(m,n,dx,dy):
ans = m
e = m-1
else:
s = m+1
print(ans)
| {
"input": [
"0 3\n0 0\n3\nUDD\n",
"0 0\n4 6\n3\nUUU\n",
"0 0\n0 1\n1\nL\n"
],
"output": [
"3\n",
"5\n",
"-1\n"
]
} |
2,378 | 11 | Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, β¦, p_n) is a permutation (p_i, p_{i + 1}, β¦, p_{n}, p_1, p_2, β¦, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, β¦, a_{i_k} for some i_1, i_2, β¦, i_k such that l β€ i_1 < i_2 < β¦ < i_k β€ r.
Input
The first line contains three integers n, m, q (1 β€ n, m, q β€ 2 β
10^5) β the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation. | # 注ζarray cacheι εΊ QQ
from math import log, floor
"""
class RMQ:
'''
maximum version rmq
query: max([l, r])
'''
def __init__(self, nums):
size = floor(log(len(nums)) // log(2)) + 1
self.nums = [nums]
for i in range(1, size):
last = self.nums[-1]
delta = 1 << (i-1)
self.nums.append([max(last[j], last[j + delta])
for j in range(len(nums) - 2 * delta + 1)])
def query(self, l, r):
delta = floor(log(r - l + 1) // log(2))
return max(self.nums[delta][l], self.nums[delta][r-2**delta+1])
"""
n, m, q = map(int, input().split())
perms = list(map(int, input().split()))
nums = list(map(int, input().split()))
logit = floor(log(n) // log(2)) + 1
current_max_index = [-1]*(n+1)
prevs = [[-1]*m for i in range(logit)]
prev_map = [-2]*(n+1)
for i, j in zip(perms[1:]+[perms[0]], perms):
prev_map[i] = j
# Update the one step case
for idx, ele in enumerate(nums):
prevs[0][idx] = current_max_index[prev_map[ele]]
current_max_index[ele] = idx
# Update the n_step table
for i in range(1, logit):
for idx, ele in enumerate(nums):
if prevs[i-1][idx] != -1:
prevs[i][idx] = prevs[i-1][prevs[i-1][idx]]
prev_n = []
# Create the update sequence
use = [i for i in range(n.bit_length()) if 1 & (n - 1) >> i]
max_pre = -1
ran = [-1] * (m+2)
for i in range(m):
t = i
for dim in use:
t = prevs[dim][t]
if t == -1:
break
max_pre = max(t, max_pre)
ran[i] = max_pre
"""
for i in range(m):
remain = n - 1
idx = i
while remain and idx != -1:
ma = floor(log(remain) // log(2))
idx = prevs[ma][idx]
remain -= 2**ma
prev_n.append(idx)
"""
#rmq = RMQ(prev_n)
ans = [None]*q
for i in range(q):
l, r = map(int, input().split())
ans[i] = str(int(l - 1 <= ran[r-1]))
print("".join(ans))
| {
"input": [
"2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4\n",
"3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5\n"
],
"output": [
"010\n",
"110\n"
]
} |
2,379 | 10 | During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string c consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters).
Katie has a favorite string s and a not-so-favorite string t and she would love to recover the mysterious code so that it has as many occurrences of s as possible and as little occurrences of t as possible. Formally, let's denote f(x, y) as the number of occurrences of y in x (for example, f(aababa, ab) = 2). Katie wants to recover the code c' conforming to the original c, such that f(c', s) - f(c', t) is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out.
Input
The first line contains string c (1 β€ |c| β€ 1000) β the mysterious code . It is guaranteed that c consists of lowercase English characters and asterisks "*" only.
The second and third line contain strings s and t respectively (1 β€ |s|, |t| β€ 50, s β t). It is guaranteed that s and t consist of lowercase English characters only.
Output
Print a single integer β the largest possible value of f(c', s) - f(c', t) of the recovered code.
Examples
Input
*****
katie
shiro
Output
1
Input
caat
caat
a
Output
-1
Input
*a*
bba
b
Output
0
Input
***
cc
z
Output
2
Note
In the first example, for c' equal to "katie" f(c', s) = 1 and f(c', t) = 0, which makes f(c', s) - f(c', t) = 1 which is the largest possible.
In the second example, the only c' conforming to the given c is "caat". The corresponding f(c', s) - f(c', t) = 1 - 2 = -1.
In the third example, there are multiple ways to recover the code such that f(c', s) - f(c', t) is largest possible, for example "aaa", "aac", or even "zaz". The value of f(c', s) - f(c', t) = 0 for all of these recovered codes.
In the fourth example, the optimal recovered code c' would be "ccc". The corresponding f(c', s) - f(c', t) = 2. | import sys
from array import array # noqa: F401
from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def build_next_table(s):
s = '*' + s + '*'
n = len(s) - 1
kmp = [0] * (n + 1)
next_table = [[0] * 26 for _ in range(n + 1)]
for i in range(2, n + 1):
cur = kmp[i - 1]
while cur > 0 and s[cur + 1] != s[i]:
cur = kmp[cur]
if s[cur + 1] == s[i]:
cur += 1
kmp[i] = cur
alphabet = [chr(cc) for cc in range(97, 123)]
for i in range(n):
for j, c in enumerate(alphabet):
cur = i
while 0 < cur and s[cur + 1] != c:
cur = kmp[cur]
if s[cur + 1] == c:
cur += 1
next_table[i][j] = cur
return next_table
def main():
code = input().rstrip()
s, t = input().rstrip(), input().rstrip()
table_s = build_next_table(s)
table_t = build_next_table(t)
n, m, l = len(code), len(s), len(t)
minf = -10**9
dp = [[array('i', [minf]) * (l + 1) for _ in range(m + 1)] for _ in range(n + 1)]
dp[0][0][0] = 0
alphabet = list(range(26))
for i in range(n):
itr = [ord(code[i]) - 97] if code[i] != '*' else alphabet
for j in range(m + 1):
for k in range(l + 1):
for cc in itr:
nj, nk = table_s[j][cc], table_t[k][cc]
dp[i + 1][nj][nk] = max(dp[i + 1][nj][nk], dp[i][j][k] + (1 if nj == m else 0) - (1 if nk == l else 0))
ans = minf
for j in range(m + 1):
for k in range(l + 1):
ans = max(ans, dp[n][j][k])
print(ans)
if __name__ == '__main__':
main()
| {
"input": [
"***\ncc\nz\n",
"*****\nkatie\nshiro\n",
"*a*\nbba\nb\n",
"caat\ncaat\na\n"
],
"output": [
"2\n",
"1\n",
"0\n",
"-1\n"
]
} |
2,380 | 11 | Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10. | import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
k = int(input())
d = {}
aa = []
sa = []
for i in range(k):
ni, *a = map(int, input().split())
for ai in a:
d[ai] = i
aa.append(a)
sa.append(sum(a))
s = sum(sa)
if s%k != 0:
print("No")
exit()
s //= k
def calc_next(i, aij):
bij = s-sa[i]+aij
if bij not in d:
return -1, bij
else:
return d[bij], bij
def loop_to_num(loop):
ret = 0
for i in reversed(range(k)):
ret <<= 1
ret += loop[i]
return ret
loop_dict = {}
used = set()
for i in range(k):
for aij in aa[i]:
if aij in used:
continue
loop = [0]*k
num = [float("Inf")]*k
start_i = i
start_aij = aij
j = i
loop[j] = 1
num[j] = aij
used.add(aij)
exist = False
for _ in range(100):
j, aij = calc_next(j, aij)
if j == -1:
break
#used.add(aij)
if loop[j] == 0:
loop[j] = 1
num[j] = aij
else:
if j == start_i and aij == start_aij:
exist = True
break
if exist:
m = loop_to_num(loop)
loop_dict[m] = tuple(num)
for numi in num:
if numi != float("inf"):
used.add(numi)
mask = 1<<k
for state in range(1, mask):
if state in loop_dict:
continue
j = (state-1)&state
while j:
i = state^j
if i in loop_dict and j in loop_dict:
tp = tuple(min(loop_dict[i][l], loop_dict[j][l]) for l in range(k))
loop_dict[state] = tp
break
j = (j-1)&state
if mask-1 not in loop_dict:
print("No")
else:
print("Yes")
t = loop_dict[mask-1]
ns = [sa[i]-t[i] for i in range(k)]
need = [s - ns[i] for i in range(k)]
for i in range(k):
print(t[i], need.index(t[i])+1) | {
"input": [
"2\n2 -10 10\n2 0 -20\n",
"2\n2 3 -2\n2 -1 5\n",
"4\n3 1 7 4\n2 3 2\n2 8 5\n1 10\n"
],
"output": [
"Yes\n-10 2\n-20 1\n",
"No\n",
"Yes\n7 2\n2 3\n5 1\n10 4\n"
]
} |
2,381 | 10 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords β strings, consists of small Latin letters.
Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows:
* two passwords a and b are equivalent if there is a letter, that exists in both a and b;
* two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b.
If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.
For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:
* admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";
* admin's password is "d", then you can access to system by using only "d".
Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
Input
The first line contain integer n (1 β€ n β€ 2 β
10^5) β number of passwords in the list. Next n lines contains passwords from the list β non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal.
It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters.
Output
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
Examples
Input
4
a
b
ab
d
Output
2
Input
3
ab
bc
abc
Output
1
Input
1
codeforces
Output
1
Note
In the second example hacker need to use any of the passwords to access the system. | import sys
input=sys.stdin.readline
n=int(input())
def find(x):
if x!=f[x]:
f[x]=find(f[x])
return f[x]
f=list(range(n+26))
for i in range(0,n):
for j in set(input().rstrip()):
f[find(ord(j)-97)]=find(i+26)
ans=0
for i in range(26,n+26):
if f[i]==i:
ans+=1
print(ans) | {
"input": [
"1\ncodeforces\n",
"3\nab\nbc\nabc\n",
"4\na\nb\nab\nd\n"
],
"output": [
"1\n",
"1\n",
"2\n"
]
} |
2,382 | 8 | Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
Input
The first line contains two integers n and m (1 β€ n β€ 100, 1 β€ m β€ 50) β the number of strings and the length of each string.
Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct.
Output
In the first line, print the length of the longest palindrome string you made.
In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.
Examples
Input
3 3
tab
one
bat
Output
6
tabbat
Input
4 2
oo
ox
xo
xx
Output
6
oxxxxo
Input
3 5
hello
codef
orces
Output
0
Input
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
Output
20
ababwxyzijjizyxwbaba
Note
In the first example, "battab" is also a valid answer.
In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.
In the third example, the empty string is the only valid palindrome string. | n, m = map(int, input().split())
ar = []
sm = []
m = ''
def palin(s):
return s == s[::-1]
for _ in range(n):
s = input()
if s[::-1] in ar:
sm.append(s)
sm.insert(0,s[::-1])
else:
if palin(s):
m = s
ar.append(s)
sm.insert(len(sm)//2,m)
s = ''.join(sm)
print(len(s))
print(s) | {
"input": [
"4 2\noo\nox\nxo\nxx\n",
"3 5\nhello\ncodef\norces\n",
"3 3\ntab\none\nbat\n",
"9 4\nabab\nbaba\nabcd\nbcde\ncdef\ndefg\nwxyz\nzyxw\nijji\n"
],
"output": [
"6\noxooxo\n",
"0\n",
"6\ntabbat\n",
"20\nababwxyzijjizyxwbaba\n"
]
} |
2,383 | 9 | A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.
You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.
Let's define the ternary XOR operation β of two ternary numbers a and b (both of length n) as a number c = a β b of length n, where c_i = (a_i + b_i) \% 3 (where \% is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by 3. For example, 10222 β 11021 = 21210.
Your task is to find such ternary numbers a and b both of length n and both without leading zeros that a β b = x and max(a, b) is the minimum possible.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 β€ n β€ 5 β
10^4) β the length of x. The second line of the test case contains ternary number x consisting of n digits 0, 1 or 2. It is guaranteed that the first digit of x is 2. It is guaranteed that the sum of n over all test cases does not exceed 5 β
10^4 (β n β€ 5 β
10^4).
Output
For each test case, print the answer β two ternary integers a and b both of length n and both without leading zeros such that a β b = x and max(a, b) is the minimum possible. If there are several answers, you can print any.
Example
Input
4
5
22222
5
21211
1
2
9
220222021
Output
11111
11111
11000
10211
1
1
110111011
110111010 | def solve():
n=int(input())
s=input()
a,b,t="","",1
for i in s:
if i=='2' and t:
a+="1";b+="1"
elif i=='1' and t:
a+="1";b+="0";t=0
else:
a+="0";b+=i
print(a,b,sep="\n")
for _ in range(int(input())):
solve()
| {
"input": [
"4\n5\n22222\n5\n21211\n1\n2\n9\n220222021\n"
],
"output": [
"11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010\n"
]
} |
2,384 | 9 | Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and rearrange the letters within each string a_i however he wants.
For example, if s = baba and k=2, Phoenix may distribute the letters of his string in many ways, such as:
* ba and ba
* a and abb
* ab and ab
* aa and bb
But these ways are invalid:
* baa and ba
* b and ba
* baba and empty string (a_i should be non-empty)
Phoenix wants to distribute the letters of his string s into k strings a_1, a_2, ..., a_k to minimize the lexicographically maximum string among them, i. e. minimize max(a_1, a_2, ..., a_k). Help him find the optimal distribution and print the minimal possible value of max(a_1, a_2, ..., a_k).
String x is lexicographically less than string y if either x is a prefix of y and x β y, or there exists an index i (1 β€ i β€ min(|x|, |y|)) such that x_i < y_i and for every j (1 β€ j < i) x_j = y_j. Here |x| denotes the length of the string x.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases. Each test case consists of two lines.
The first line of each test case consists of two integers n and k (1 β€ k β€ n β€ 10^5) β the length of string s and the number of non-empty strings, into which Phoenix wants to distribute letters of s, respectively.
The second line of each test case contains a string s of length n consisting only of lowercase Latin letters.
It is guaranteed that the sum of n over all test cases is β€ 10^5.
Output
Print t answers β one per test case. The i-th answer should be the minimal possible value of max(a_1, a_2, ..., a_k) in the i-th test case.
Example
Input
6
4 2
baba
5 2
baacb
5 3
baacb
5 3
aaaaa
6 4
aaxxzz
7 1
phoenix
Output
ab
abbc
b
aa
x
ehinopx
Note
In the first test case, one optimal solution is to distribute baba into ab and ab.
In the second test case, one optimal solution is to distribute baacb into abbc and a.
In the third test case, one optimal solution is to distribute baacb into ac, ab, and b.
In the fourth test case, one optimal solution is to distribute aaaaa into aa, aa, and a.
In the fifth test case, one optimal solution is to distribute aaxxzz into az, az, x, and x.
In the sixth test case, one optimal solution is to distribute phoenix into ehinopx. | def solve():
n,k=map(int,input().split())
s=''.join(sorted(input()))
if s[0]!=s[k-1] or k==n:
return s[k-1]
if s[k]==s[-1]:
return s[0]+s[k]*((n-1)//k)
return s[k-1:]
for _ in range(int(input())):
print(solve()) | {
"input": [
"6\n4 2\nbaba\n5 2\nbaacb\n5 3\nbaacb\n5 3\naaaaa\n6 4\naaxxzz\n7 1\nphoenix\n"
],
"output": [
"ab\nabbc\nb\naa\nx\nehinopx\n"
]
} |
2,385 | 7 | Lee is going to fashionably decorate his house for a party, using some regular convex polygons...
Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis at the same time.
Recall that a regular n-sided polygon is a convex polygon with n vertices such that all the edges and angles are equal.
Now he is shopping: the market has t regular polygons. For each of them print YES if it is beautiful and NO otherwise.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of polygons in the market.
Each of the next t lines contains a single integer n_i (3 β€ n_i β€ 10^9): it means that the i-th polygon is a regular n_i-sided polygon.
Output
For each polygon, print YES if it's beautiful or NO otherwise (case insensitive).
Example
Input
4
3
4
12
1000000000
Output
NO
YES
YES
YES
Note
In the example, there are 4 polygons in the market. It's easy to see that an equilateral triangle (a regular 3-sided polygon) is not beautiful, a square (a regular 4-sided polygon) is beautiful and a regular 12-sided polygon (is shown below) is beautiful as well.
<image> | def main():
n = int(input())
return (n % 4)==0
for _ in range(int(input())):
print('YES' if main() else 'NO')
| {
"input": [
"4\n3\n4\n12\n1000000000\n"
],
"output": [
"NO\nYES\nYES\nYES\n"
]
} |
2,386 | 9 | After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has 6 strings and an infinite number of frets numbered from 1. Fretting the fret number j on the i-th string produces the note a_{i} + j.
Tayuya wants to play a melody of n notes. Each note can be played on different string-fret combination. The easiness of performance depends on the difference between the maximal and the minimal indices of used frets. The less this difference is, the easier it is to perform the technique. Please determine the minimal possible difference.
For example, if a = [1, 1, 2, 2, 3, 3], and the sequence of notes is 4, 11, 11, 12, 12, 13, 13 (corresponding to the second example), we can play the first note on the first string, and all the other notes on the sixth string. Then the maximal fret will be 10, the minimal one will be 3, and the answer is 10 - 3 = 7, as shown on the picture.
<image>
Input
The first line contains 6 space-separated numbers a_{1}, a_{2}, ..., a_{6} (1 β€ a_{i} β€ 10^{9}) which describe the Tayuya's strings.
The second line contains the only integer n (1 β€ n β€ 100 000) standing for the number of notes in the melody.
The third line consists of n integers b_{1}, b_{2}, ..., b_{n} (1 β€ b_{i} β€ 10^{9}), separated by space. They describe the notes to be played. It's guaranteed that b_i > a_j for all 1β€ iβ€ n and 1β€ jβ€ 6, in other words, you can play each note on any string.
Output
Print the minimal possible difference of the maximal and the minimal indices of used frets.
Examples
Input
1 4 100 10 30 5
6
101 104 105 110 130 200
Output
0
Input
1 1 2 2 3 3
7
13 4 11 12 11 13 12
Output
7
Note
In the first sample test it is optimal to play the first note on the first string, the second note on the second string, the third note on the sixth string, the fourth note on the fourth string, the fifth note on the fifth string, and the sixth note on the third string. In this case the 100-th fret is used each time, so the difference is 100 - 100 = 0.
<image>
In the second test it's optimal, for example, to play the second note on the first string, and all the other notes on the sixth string. Then the maximal fret will be 10, the minimal one will be 3, and the answer is 10 - 3 = 7.
<image> | a=list(map(int,input().split()))
n=int(input())
s=list(map(int,input().split()))
b=[]
for i in range(n):
for j in a:
b.append((s[i]-j)*n+i)
b.sort()
cs={}
i=j=0
ans=10**18
def dd(w):
cs[w]=cs.get(w,0)+1
def em(w):
cs[w]-=1
if cs[w]==0:cs.pop(w)
dd(b[0]%n)
while j<len(b):
while j+1<len(b) and len(cs)<n:
j+=1
dd(b[j]%n)
while len(cs)==n:
ans=min(ans,b[j]//n-b[i]//n)
em(b[i]%n)
i+=1
if j+1==len(b):
break
print(ans) | {
"input": [
"1 4 100 10 30 5\n6\n101 104 105 110 130 200\n",
"1 1 2 2 3 3\n7\n13 4 11 12 11 13 12\n"
],
"output": [
"0",
"7"
]
} |
2,387 | 9 | Alice and Bob play ping-pong with simplified rules.
During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return.
The one who doesn't make a return loses this play. The winner of the play commences the next play. Alice starts the first play.
Alice has x stamina and Bob has y. To hit the ball (while serving or returning) each player spends 1 stamina, so if they don't have any stamina, they can't return the ball (and lose the play) or can't serve the ball (in this case, the other player serves the ball instead). If both players run out of stamina, the game is over.
Sometimes, it's strategically optimal not to return the ball, lose the current play, but save the stamina. On the contrary, when the server commences a play, they have to hit the ball, if they have some stamina left.
Both Alice and Bob play optimally and want to, firstly, maximize their number of wins and, secondly, minimize the number of wins of their opponent.
Calculate the resulting number of Alice's and Bob's wins.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first and only line of each test case contains two integers x and y (1 β€ x, y β€ 10^6) β Alice's and Bob's initial stamina.
Output
For each test case, print two integers β the resulting number of Alice's and Bob's wins, if both of them play optimally.
Example
Input
3
1 1
2 1
1 7
Output
0 1
1 1
0 7
Note
In the first test case, Alice serves the ball and spends 1 stamina. Then Bob returns the ball and also spends 1 stamina. Alice can't return the ball since she has no stamina left and loses the play. Both of them ran out of stamina, so the game is over with 0 Alice's wins and 1 Bob's wins.
In the second test case, Alice serves the ball and spends 1 stamina. Bob decides not to return the ball β he loses the play but saves stamina. Alice, as the winner of the last play, serves the ball in the next play and spends 1 more stamina. This time, Bob returns the ball and spends 1 stamina. Alice doesn't have any stamina left, so she can't return the ball and loses the play. Both of them ran out of stamina, so the game is over with 1 Alice's and 1 Bob's win.
In the third test case, Alice serves the ball and spends 1 stamina. Bob returns the ball and spends 1 stamina. Alice ran out of stamina, so she can't return the ball and loses the play. Bob, as a winner, serves the ball in the next 6 plays. Each time Alice can't return the ball and loses each play. The game is over with 0 Alice's and 7 Bob's wins. | def solve():
x,y=map(int,input().split())
print(x-1,y)
for _ in range(int(input())):
solve() | {
"input": [
"3\n1 1\n2 1\n1 7\n"
],
"output": [
"\n0 1\n1 1\n0 7\n"
]
} |
2,388 | 9 | You are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order:
* if |a| > 0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a_2 a_3 β¦ a_n;
* if |a| > 0, delete the last character of the string a, that is, replace a with a_1 a_2 β¦ a_{n-1};
* if |b| > 0 (the length of the string b is greater than zero), delete the first character of the string b, that is, replace b with b_2 b_3 β¦ b_n;
* if |b| > 0, delete the last character of the string b, that is, replace b with b_1 b_2 β¦ b_{n-1}.
Note that after each of the operations, the string a or b may become empty.
For example, if a="hello" and b="icpc", then you can apply the following sequence of operations:
* delete the first character of the string a β a="ello" and b="icpc";
* delete the first character of the string b β a="ello" and b="cpc";
* delete the first character of the string b β a="ello" and b="pc";
* delete the last character of the string a β a="ell" and b="pc";
* delete the last character of the string b β a="ell" and b="p".
For the given strings a and b, find the minimum number of operations for which you can make the strings a and b equal. Note that empty strings are also equal.
Input
The first line contains a single integer t (1 β€ t β€ 100). Then t test cases follow.
The first line of each test case contains the string a (1 β€ |a| β€ 20), consisting of lowercase Latin letters.
The second line of each test case contains the string b (1 β€ |b| β€ 20), consisting of lowercase Latin letters.
Output
For each test case, output the minimum number of operations that can make the strings a and b equal.
Example
Input
5
a
a
abcd
bc
hello
codeforces
hello
helo
dhjakjsnasjhfksafasd
adjsnasjhfksvdafdser
Output
0
2
13
3
20 | def f(a,b):
m=len(a)
n=len(b)
common=""
for i in range(0,m):
for j in range(0,n):
k=0
while(i+k<=m and j+k<=n and a[i:i+k]==b[j:j+k]):
if(len(a[i:i+k])>=len(common)):
common=a[i:i+k]
k+=1
return m+n-2*len(common)
t=int(input())
for i in range(0,t):
a=input()
b=input()
print(f(a,b))
print()
| {
"input": [
"5\na\na\nabcd\nbc\nhello\ncodeforces\nhello\nhelo\ndhjakjsnasjhfksafasd\nadjsnasjhfksvdafdser\n"
],
"output": [
"\n0\n2\n13\n3\n20\n"
]
} |
2,389 | 8 | One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple.
Vasya noticed that the yard is a rectangular n Γ m field. The squares have coordinates (x, y) (1 β€ x β€ n, 1 β€ y β€ m), where x is the index of the row and y is the index of the column.
Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps).
A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step.
Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
Input
The first input line contains two integers n and m (1 β€ n, m β€ 109) β the yard's sizes. The second line contains integers xc and yc β the initial square's coordinates (1 β€ xc β€ n, 1 β€ yc β€ m).
The third line contains an integer k (1 β€ k β€ 104) β the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| β€ 109, |dx| + |dy| β₯ 1).
Output
Print the single number β the number of steps Vasya had made.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
4 5
1 1
3
1 1
1 1
0 -2
Output
4
Input
10 10
1 2
1
-1 0
Output
0
Note
In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps.
In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. | import math
def step(f , r , k):
if k==0:
return math.inf
if k < 0:
return -int((r-1)/k)
return int((f-r)/k)
n , m = map(int,input().split())
x , y = map(int,input().split())
d = int(input())
ans = 0
for i in range(d):
i , j = map(int,input().split())
steps = min(step(n , x , i ) ,step(m , y , j))
x +=steps*i ; y +=steps*j
ans +=steps
print(ans) | {
"input": [
"10 10\n1 2\n1\n-1 0\n",
"4 5\n1 1\n3\n1 1\n1 1\n0 -2\n"
],
"output": [
"0\n",
"4\n"
]
} |
2,390 | 10 | You are given a connected weighted undirected graph without any loops and multiple edges.
Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique.
Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST.
Input
The first line contains two integers n and m (2 β€ n β€ 105, <image>) β the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers β the description of the graph's edges as "ai bi wi" (1 β€ ai, bi β€ n, 1 β€ wi β€ 106, ai β bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges.
Output
Print m lines β the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input.
Examples
Input
4 5
1 2 101
1 3 100
2 3 2
2 4 2
3 4 1
Output
none
any
at least one
at least one
any
Input
3 3
1 2 1
2 3 1
1 3 2
Output
any
any
none
Input
3 3
1 2 1
2 3 1
1 3 1
Output
at least one
at least one
at least one
Note
In the second sample the MST is unique for the given graph: it contains two first edges.
In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST. | from math import inf
import operator
from collections import defaultdict
import sys
time = 0
edges = []
ans = {}
orig_edges = []
l = {}
d = {}
f = {}
pi = {}
visited = {}
def process_edges(l, ds):
if len(l) == 1:
u,v = l[0]
b = ds.SetOf(u) == ds.SetOf(v)
ans[u,v] = "none" if b else "any"
if not b:
ds.Merge(u, v)
else:
dic = defaultdict(list)
g = defaultdict(set)
for e in l:
u,v = e
x = ds.SetOf(u)
y = ds.SetOf(v)
if x == y:
ans[e] = "none"
else:
x,y = tuple(sorted([x,y]))
dic[x,y].append(e)
g[x].add(y)
g[y].add(x)
a = DFS(g)
for e in a:
if len(dic[e]) == 1:
ans[dic[e][0]] = "any"
for e in l:
if ds.SetOf(e[1]) != ds.SetOf(e[0]):
ds.Merge(e[0],e[1])
def sol(n):
ds = DisjointSet(n)
global edges
prev_w = edges[0][1]
same_weight = []
for e, w in edges + [(1,None)]:
if w == prev_w:
same_weight.append(e)
else:
process_edges(same_weight, ds)
same_weight = [e]
prev_w = w
def DFS(graph):
time = 0
global l
global d
global f
global pi
global visited
visited = {key : False for key in graph}
l = {key : inf for key in graph}
d = {key : -1 for key in graph}
f = {key : -1 for key in graph}
pi = {key : key for key in graph}
a = []
for i in graph.keys():
if not visited[i]:
DFS_Visit(graph, i, a)
return a
def DFS_Visit(graph, v, a):
visited[v] = True
global time
time+=1
d[v] = l[v] = time
for i in graph[v]:
if not visited[i]:
pi[i] = v
DFS_Visit(graph, i, a)
l[v] = min(l[v], l[i])
elif pi[v] != i:
l[v] = min(l[v], d[i])
if pi[v] != v and l[v] >= d[v]:
a.append(tuple(sorted([v,pi[v]])))
time+=1
f[v] = time
# def DFS_Visit(graph, v, a):
# visited[v] = True
# global time
# time+=1
# d[v] = l[v] = time
# stack = [v]
# while stack:
# u = stack.pop()
# for i in graph[u]:
# if not visited[i]:
# pi[i] = v
# stack.append(i)
# # DFS_Visit(graph, i, a)
# l[u] = min(l[u], l[i])
# elif pi[u] != i:
# l[u] = min(l[u], d[i])
# if pi[u] != v and l[v] >= d[v]:
# a.append(tuple(sorted([v,pi[v]])))
# time+=1
# f[v] = time
def read():
global edges
n,m = map(int, sys.stdin.readline().split())
if m == n-1:
for _ in range(m):
print("any")
exit()
for i in range(m):
x,y,w = map(int, sys.stdin.readline().split())
x,y = x-1,y-1
e = tuple(sorted([x,y]))
ans[e] = "at least one"
orig_edges.append((e,w))
edges = sorted(orig_edges, key=lambda x:x[1])
return n
def main():
n = read()
sol(n)
for i in orig_edges:
print(ans[i[0]])
class DisjointSet:
def __init__(self, n):
self.count = [1 for i in range(n)]
self.father = [i for i in range(n)]
def SetOf(self, x):
if x == self.father[x]:
return x
return self.SetOf(self.father[x])
def Merge(self, x, y):
a = self.SetOf(x)
b = self.SetOf(y)
if self.count[a] > self.count[b]:
temp = a
a = b
b = temp
self.count[b] += self.count[a]
self.father[a] = b
main()
| {
"input": [
"3 3\n1 2 1\n2 3 1\n1 3 2\n",
"4 5\n1 2 101\n1 3 100\n2 3 2\n2 4 2\n3 4 1\n",
"3 3\n1 2 1\n2 3 1\n1 3 1\n"
],
"output": [
"any\nany\nnone\n",
"none\nany\nat least one\nat least one\nany\n",
"at least one\nat least one\nat least one\n"
]
} |
2,391 | 7 | In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to n. The disk has m recorded files, the i-th file occupies clusters with numbers ai, 1, ai, 2, ..., ai, ni. These clusters are not necessarily located consecutively on the disk, but the order in which they are given corresponds to their sequence in the file (cluster ai, 1 contains the first fragment of the i-th file, cluster ai, 2 has the second fragment, etc.). Also the disc must have one or several clusters which are free from files.
You are permitted to perform operations of copying the contents of cluster number i to cluster number j (i and j must be different). Moreover, if the cluster number j used to keep some information, it is lost forever. Clusters are not cleaned, but after the defragmentation is complete, some of them are simply declared unusable (although they may possibly still contain some fragments of files).
Your task is to use a sequence of copy operations to ensure that each file occupies a contiguous area of memory. Each file should occupy a consecutive cluster section, the files must follow one after another from the beginning of the hard disk. After defragmentation all free (unused) clusters should be at the end of the hard disk. After defragmenting files can be placed in an arbitrary order. Clusters of each file should go consecutively from first to last. See explanatory examples in the notes.
Print the sequence of operations leading to the disk defragmentation. Note that you do not have to minimize the number of operations, but it should not exceed 2n.
Input
The first line contains two integers n and m (1 β€ n, m β€ 200) β the number of clusters and the number of files, correspondingly. Next m lines contain descriptions of the files. The first number in the line is ni (ni β₯ 1), the number of clusters occupied by the i-th file. Then follow ni numbers ai, 1, ai, 2, ..., ai, ni (1 β€ ai, j β€ n). It is guaranteed that each cluster number occurs not more than once and <image>, that is, there exists at least one unused cluster. Numbers on each line are separated by spaces.
Output
In the first line print a single integer k (0 β€ k β€ 2n) β the number of operations needed to defragment the disk. Next k lines should contain the operations' descriptions as "i j" (copy the contents of the cluster number i to the cluster number j).
Examples
Input
7 2
2 1 2
3 3 4 5
Output
0
Input
7 2
2 1 3
3 2 4 5
Output
3
2 6
3 2
6 3
Note
Let's say that a disk consists of 8 clusters and contains two files. The first file occupies two clusters and the second file occupies three clusters. Let's look at examples of correct and incorrect positions of files after defragmentation.
<image>
Example 2: each file must occupy a contiguous area of memory.
Example 3: the order of files to each other is not important, at first the second file can be written, and then β the first one.
Example 4: violating the order of file fragments to each other is not allowed.
Example 5: unused clusters should be located at the end, and in this example the unused clusters are 3, 7, 8. | import sys
n, m, *inp = map(int, sys.stdin.read().split())
inp.reverse()
f = [[0 for x in range(201)] for y in range(201)] #2D Array
c = [(0,0)]*201
f_size = [0]*201
def putData(f_id, s_id, c_id):
global f, c
f[f_id][s_id] = c_id
c[c_id] = (f_id, s_id)
for f_id in range(1, m+1):
f_size[f_id] = inp.pop()
for s_id in range(1, f_size[f_id]+1):
c_id = inp.pop()
putData(f_id, s_id, c_id)
e_id = c[1:].index((0,0))+1
next_id = 1
op = []
for f_id in range(1, m+1):
for s_id in range(1, f_size[f_id]+1):
if c[next_id]==(f_id, s_id):
next_id += 1
continue
if c[next_id] != (0, 0):
op.append((next_id, e_id))
putData(c[next_id][0], c[next_id][1], e_id)
e_id = f[f_id][s_id]
c[e_id] = (0,0)
op.append((e_id, next_id))
putData(f_id, s_id, next_id)
next_id += 1
print(len(op))
for p in op:
print("%d %d" % p)
| {
"input": [
"7 2\n2 1 3\n3 2 4 5\n",
"7 2\n2 1 2\n3 3 4 5\n"
],
"output": [
"3\n2 6\n3 2\n6 3\n",
"0\n"
]
} |
2,392 | 8 | One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game.
He took a checkered white square piece of paper, consisting of n Γ n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him.
Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist.
Input
The first line contains two integers n and m (1 β€ n β€ 1000, 1 β€ m β€ min(nΒ·n, 105)) β the size of the squared piece of paper and the number of moves, correspondingly.
Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 β€ xi, yi β€ n) β the number of row and column of the square that gets painted on the i-th move.
All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom.
Output
On a single line print the answer to the problem β the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1.
Examples
Input
4 11
1 1
1 2
1 3
2 2
2 3
1 4
2 4
3 4
3 2
3 3
4 1
Output
10
Input
4 12
1 1
1 2
1 3
2 2
2 3
1 4
2 4
3 4
3 2
4 2
4 1
3 1
Output
-1 | def f():
n, m = map(int, input().split())
p = [[0] * (n + 2) for i in range(n + 2)]
for k in range(m):
x, y = map(int, input().split())
for i in range(x - 1, x + 2):
for j in range(y - 1, y + 2):
if p[i][j] == 8: return k + 1
p[i][j] += 1
return -1
print(f()) | {
"input": [
"4 11\n1 1\n1 2\n1 3\n2 2\n2 3\n1 4\n2 4\n3 4\n3 2\n3 3\n4 1\n",
"4 12\n1 1\n1 2\n1 3\n2 2\n2 3\n1 4\n2 4\n3 4\n3 2\n4 2\n4 1\n3 1\n"
],
"output": [
"10",
"-1"
]
} |
2,393 | 7 | Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.
Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
Input
The first line contains four space-separated integers s1, s2, s3, s4 (1 β€ s1, s2, s3, s4 β€ 109) β the colors of horseshoes Valera has.
Consider all possible colors indexed with integers.
Output
Print a single integer β the minimum number of horseshoes Valera needs to buy.
Examples
Input
1 7 3 3
Output
1
Input
7 7 7 7
Output
3 | def solve():
print(4 - len(set(map(int, input().split()))))
solve()
| {
"input": [
"7 7 7 7\n",
"1 7 3 3\n"
],
"output": [
"3\n",
"1\n"
]
} |
2,394 | 8 | A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on.
The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0.
What is the minimum time for the car to get from point A to point B without breaking the traffic rules?
Input
The first line contains integers l, d, v, g, r (1 β€ l, d, v, g, r β€ 1000, d < l) β the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light.
Output
Output a single number β the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6.
Examples
Input
2 1 3 4 5
Output
0.66666667
Input
5 4 3 1 1
Output
2.33333333 | from math import floor
def gt(t,g,r):
zt=floor(t)
rt=t-zt
zt%=(g+r)
t=zt+rt
if t<g:
return 0
else:
return r+g-t
l,d,v,g,r=[int(x) for x in input().split(' ')]
t=d/v
t+=gt(t,g,r)
t+=(l-d)/v
print(t) | {
"input": [
"5 4 3 1 1\n",
"2 1 3 4 5\n"
],
"output": [
"2.33333333333\n",
"0.666666666667\n"
]
} |
2,395 | 9 | It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).
If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
Input
The first line contains an integer n (2 β€ n β€ 100) β the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the elements of the set.
Output
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
Examples
Input
2
2 3
Output
Alice
Input
2
5 3
Output
Alice
Input
3
5 6 7
Output
Bob
Note
Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. | n=int(input())
A=list(map(int,input().split()))
def gcd(x,y):
while y:
x,y=y,x%y
return x
g=0
for a in A:
g=gcd(g,a)
u=max(A)//g-n
if u%2==0:
print("Bob")
else:
print("Alice") | {
"input": [
"3\n5 6 7\n",
"2\n5 3\n",
"2\n2 3\n"
],
"output": [
"Bob\n",
"Alice\n",
"Alice\n"
]
} |
2,396 | 10 | Innocentius has a problem β his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus.
Innocentius is touch-typing a program that paints a white square one-pixel wide frame on the black screen. As the monitor is broken, some pixels that should be white remain black. Polycarpus should look at what the program displayed on the screen and guess the position and size of the frame Innocentius has painted. Polycarpus doesn't like the game but Innocentius persuaded brother to play as "the game is good for the imagination and attention".
Help Polycarpus, automatize his part in the gaming process. Write the code that finds such possible square frame that:
* the frame's width is 1 pixel,
* the frame doesn't go beyond the borders of the screen,
* all white pixels of the monitor are located on the frame,
* of all frames that satisfy the previous three conditions, the required frame must have the smallest size.
Formally, a square frame is represented by such pixels of the solid square, that are on the square's border, that is, are not fully surrounded by the other pixels of the square. For example, if the frame's size is d = 3, then it consists of 8 pixels, if its size is d = 2, then it contains 4 pixels and if d = 1, then the frame is reduced to a single pixel.
Input
The first line contains the resolution of the monitor as a pair of integers n, m (1 β€ n, m β€ 2000). The next n lines contain exactly m characters each β the state of the monitor pixels at the moment of the game. Character "." (period, ASCII code 46) corresponds to the black pixel, and character "w" (lowercase English letter w) corresponds to the white pixel. It is guaranteed that at least one pixel of the monitor is white.
Output
Print the monitor screen. Represent the sought frame by characters "+" (the "plus" character). The pixels that has become white during the game mustn't be changed. Print them as "w". If there are multiple possible ways to position the frame of the minimum size, print any of them.
If the required frame doesn't exist, then print a single line containing number -1.
Examples
Input
4 8
..w..w..
........
........
..w..w..
Output
..w++w..
..+..+..
..+..+..
..w++w..
Input
5 6
......
.w....
......
..w...
......
Output
......
+w+...
+.+...
++w...
......
Input
2 4
....
.w..
Output
....
.w..
Input
2 6
w..w.w
...w..
Output
-1
Note
In the first sample the required size of the optimal frame equals 4. In the second sample the size of the optimal frame equals 3. In the third sample, the size of the optimal frame is 1. In the fourth sample, the required frame doesn't exist. | #!/usr/bin/python3
def readln(): return list(map(int, input().split()))
import sys
def exit():
print(-1)
sys.exit()
n, m = readln()
mon = [list(input()) for _ in range(n)]
hor = [i for i in range(n) if mon[i] != ['.'] * m]
rmon = list(zip(*mon))
ver = [j for j in range(m) if rmon[j] != ('.',) * n]
mini = hor[0]
maxi = hor[-1]
minj = ver[0]
maxj = ver[-1]
cnt_in = len([1 for i in range(mini + 1, maxi) for j in range(minj + 1, maxj) if mon[i][j] == 'w'])
cnt_l = len([1 for i in range(mini + 1, maxi) if mon[i][minj] == 'w'])
cnt_r = len([1 for i in range(mini + 1, maxi) if mon[i][maxj] == 'w'])
cnt_d = len([1 for j in range(minj + 1, maxj) if mon[mini][j] == 'w'])
cnt_u = len([1 for j in range(minj + 1, maxj) if mon[maxi][j] == 'w'])
if cnt_in:
exit()
if maxi - mini < maxj - minj:
k = maxj - minj + 1
if maxi == mini and cnt_d:
if mini >= k - 1:
mini -= k - 1
elif maxi + k - 1 < n:
maxi += k - 1
else:
exit()
else:
if not cnt_d:
mini = max(0, maxi - k + 1)
if maxi - maxi + 1 != k and not cnt_u:
maxi = min(mini + k - 1, n - 1)
if maxi - mini + 1 != k:
exit()
else:
k = maxi - mini + 1
if maxj == minj and cnt_l:
if minj >= k - 1:
minj -= k - 1
elif maxj + k - 1 < m:
maxj += k - 1
else:
exit()
else:
if not cnt_l:
minj = max(0, maxj - k + 1)
if maxj - minj + 1 != k and not cnt_r:
maxj = min(minj + k - 1, m - 1)
if maxj - minj + 1 != k:
exit()
for i in range(mini, maxi + 1):
if mon[i][minj] == '.':
mon[i][minj] = '+'
for i in range(mini, maxi + 1):
if mon[i][maxj] == '.':
mon[i][maxj] = '+'
for j in range(minj, maxj + 1):
if mon[mini][j] == '.':
mon[mini][j] = '+'
for j in range(minj, maxj + 1):
if mon[maxi][j] == '.':
mon[maxi][j] = '+'
print('\n'.join([''.join(row) for row in mon]))
| {
"input": [
"4 8\n..w..w..\n........\n........\n..w..w..\n",
"5 6\n......\n.w....\n......\n..w...\n......\n",
"2 4\n....\n.w..\n",
"2 6\nw..w.w\n...w..\n"
],
"output": [
"..w++w..\n..+..+..\n..+..+..\n..w++w..\n",
"......\n+w+...\n+.+...\n++w...\n......\n",
"....\n.w..\n",
"-1\n"
]
} |
2,397 | 7 | Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if:
* the Euclidean distance between A and B is one unit and neither A nor B is blocked;
* or there is some integral point C, such that A is 4-connected with C, and C is 4-connected with B.
Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than n, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?
Input
The first line contains an integer n (0 β€ n β€ 4Β·107).
Output
Print a single integer β the minimum number of points that should be blocked.
Examples
Input
1
Output
4
Input
2
Output
8
Input
3
Output
16 | from math import sqrt, floor
def calc(n):
if n == 0:
return 1
# y = n
# x = 1
# c = 0
# while x - y < 0:
# if x ** 2 + y ** 2 <= n ** 2:
# c += 1
# x += 1
# continue
# if x ** 2 + y ** 2 > n ** 2:
# y -= 1
x = floor(sqrt(n**2/2))
y = floor(sqrt(n**2-x**2))
#print(x, y)
if x == y:
return x*8
else:
return x * 8 +4
n = int(input())
print(calc(n)) | {
"input": [
"2\n",
"1\n",
"3\n"
],
"output": [
"8\n",
"4\n",
"16\n"
]
} |
2,398 | 8 | Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back w tokens then he'll get <image> dollars.
Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has n numbers x1, x2, ..., xn. Number xi is the number of tokens given to each worker on the i-th day. Help him calculate for each of n days the number of tokens he can save.
Input
The first line of input contains three space-separated integers n, a, b (1 β€ n β€ 105; 1 β€ a, b β€ 109). The second line of input contains n space-separated integers x1, x2, ..., xn (1 β€ xi β€ 109).
Output
Output n space-separated integers. The i-th of them is the number of tokens Mashmokh can save on the i-th day.
Examples
Input
5 1 4
12 6 11 9 1
Output
0 2 3 1 1
Input
3 1 2
1 2 3
Output
1 0 1
Input
1 1 1
1
Output
0 | def mymod(x,a,b):
import math
return x - math.ceil(int(x*a/b))*b/a
n,a,b = map(int,input().strip().split())
x= list(map(int,input().split()))
for q in x:
print(int(mymod(q,a,b)),end= ' ') | {
"input": [
"1 1 1\n1\n",
"3 1 2\n1 2 3\n",
"5 1 4\n12 6 11 9 1\n"
],
"output": [
"0\n",
"1 0 1\n",
"0 2 3 1 1\n"
]
} |
2,399 | 7 | Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.
Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
Input
The first line contains two space-separated integers: n and p (1 β€ n β€ 1000; 1 β€ p β€ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
Output
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
Examples
Input
3 3
cba
Output
NO
Input
3 4
cba
Output
cbd
Input
4 4
abcd
Output
abda
Note
String s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 > ti + 1.
The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.
A palindrome is a string that reads the same forward or reversed. | def trans(c):
return chr(ord(c) + 1)
n, p = list(map(int, input().split()))
s = list(input())
s[n-1] = trans(s[n-1])
i = n - 1
while i >= 0 and i < n:
if ord(s[i]) >= ord('a') + p:
s[i] = 'a'
i -= 1
s[i] = trans(s[i])
elif i > 0 and s[i] == s[i-1] or i > 1 and s[i] == s[i-2]:
s[i] = trans(s[i])
else:
i += 1
print("NO" if i < 0 else "".join(s)) | {
"input": [
"3 4\ncba\n",
"4 4\nabcd\n",
"3 3\ncba\n"
],
"output": [
"cbd\n",
"abda\n",
"NO\n"
]
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.