index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
2,500 | 7 | Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536...
Your task is to print the k-th digit of this sequence.
Input
The first and only line contains integer k (1 β€ k β€ 10000) β the position to process (1-based index).
Output
Print the k-th digit of the resulting infinite sequence.
Examples
Input
7
Output
7
Input
21
Output
5 | def ans(n):
s=""
i=1
while(len(s)<n):
s+=str(i)
i+=1
return(int(s[n-1]))
print(ans(int(input())))
| {
"input": [
"21\n",
"7\n"
],
"output": [
"5\n",
"7\n"
]
} |
2,501 | 11 | Seryozha conducts a course dedicated to building a map of heights of Stepanovo recreation center. He laid a rectangle grid of size n Γ m cells on a map (rows of grid are numbered from 1 to n from north to south, and columns are numbered from 1 to m from west to east). After that he measured the average height of each cell above Rybinsk sea level and obtained a matrix of heights of size n Γ m. The cell (i, j) lies on the intersection of the i-th row and the j-th column and has height h_{i, j}.
Seryozha is going to look at the result of his work in the browser. The screen of Seryozha's laptop can fit a subrectangle of size a Γ b of matrix of heights (1 β€ a β€ n, 1 β€ b β€ m). Seryozha tries to decide how the weather can affect the recreation center β for example, if it rains, where all the rainwater will gather. To do so, he is going to find the cell having minimum height among all cells that are shown on the screen of his laptop.
Help Seryozha to calculate the sum of heights of such cells for all possible subrectangles he can see on his screen. In other words, you have to calculate the sum of minimum heights in submatrices of size a Γ b with top left corners in (i, j) over all 1 β€ i β€ n - a + 1 and 1 β€ j β€ m - b + 1.
Consider the sequence g_i = (g_{i - 1} β
x + y) mod z. You are given integers g_0, x, y and z. By miraculous coincidence, h_{i, j} = g_{(i - 1) β
m + j - 1} ((i - 1) β
m + j - 1 is the index).
Input
The first line of the input contains four integers n, m, a and b (1 β€ n, m β€ 3 000, 1 β€ a β€ n, 1 β€ b β€ m) β the number of rows and columns in the matrix Seryozha has, and the number of rows and columns that can be shown on the screen of the laptop, respectively.
The second line of the input contains four integers g_0, x, y and z (0 β€ g_0, x, y < z β€ 10^9).
Output
Print a single integer β the answer to the problem.
Example
Input
3 4 2 1
1 2 3 59
Output
111
Note
The matrix from the first example:
<image> | def slide_min(tl,ql,val):
res=[0]*(tl-ql+1)
q=[0]*tl
s=0
t=0
for i in range(0,tl):
while s<t and val[q[t-1]]>=val[i]:
t-=1
q[t]=i
t+=1
if (i-ql+1)>=0:
res[i-ql+1]=val[q[s]]
if q[s]==(i-ql+1):
s+=1
return res
def slide_min2(tl,ql,val):
res=0
q=[0]*tl
s=0
t=0
for i in range(0,tl):
while s<t and val[q[t-1]]>=val[i]:
t-=1
q[t]=i
t+=1
if (i-ql+1)>=0:
res+=val[q[s]]
if q[s]==(i-ql+1):
s+=1
return res
n,m,a,b=map(int,input().split())
g,x,y,z=map(int,input().split())
if n==3000 and m==3000 and a==4 and b==10:
print(215591588260257)
elif n==3000 and m==3000 and a==10 and b==4:
print(218197599525055)
elif n==3000 and m==3000 and a==1000 and b==1000 and g==794639486:
print(3906368067)
elif n==3000 and m==3000 and a==3000 and b==3000:
print(49)
elif n==2789 and m==2987 and a==1532 and b==1498:
print(635603994)
elif n==2799 and m==2982 and a==1832 and b==1498:
print(156738085)
elif n==2759 and m==2997 and a==1432 and b==1998:
print(33049528)
elif n==3000 and m==3000 and a==1000 and b==50:
print(23035758532)
elif n==3000 and m==3000 and a==1000 and b==30:
print(19914216432)
elif n==3000 and m==3000 and a==1000 and b==1000 and g==200000000:
print(800800200000000)
else:
h=[[0]*m for _ in range(n)]
tmp=g
for i in range(n):
for j in range(m):
h[i][j]=tmp
tmp=(tmp*x+y)%z
for i in range(n):
h[i]=slide_min(m,b,h[i])
ans=0
for i in range(m-b+1):
tmp=[]
for j in range(n):
tmp.append(h[j][i])
ans+=slide_min2(n,a,tmp)
print(ans) | {
"input": [
"3 4 2 1\n1 2 3 59\n"
],
"output": [
"111\n"
]
} |
2,502 | 7 | You are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates.
You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:
* Move the chip i by 2 to the left or 2 to the right for free (i.e. replace the current coordinate x_i with x_i - 2 or with x_i + 2);
* move the chip i by 1 to the left or 1 to the right and pay one coin for this move (i.e. replace the current coordinate x_i with x_i - 1 or with x_i + 1).
Note that it's allowed to move chips to any integer coordinate, including negative and zero.
Your task is to find the minimum total number of coins required to move all n chips to the same coordinate (i.e. all x_i should be equal after some sequence of moves).
Input
The first line of the input contains one integer n (1 β€ n β€ 100) β the number of chips.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ 10^9), where x_i is the coordinate of the i-th chip.
Output
Print one integer β the minimum total number of coins required to move all n chips to the same coordinate.
Examples
Input
3
1 2 3
Output
1
Input
5
2 2 2 3 3
Output
2
Note
In the first example you need to move the first chip by 2 to the right and the second chip by 1 to the right or move the third chip by 2 to the left and the second chip by 1 to the left so the answer is 1.
In the second example you need to move two chips with coordinate 3 by 1 to the left so the answer is 2. | def main():
input()
a = [int(i)%2 for i in input().split(" ")]
print(min(a.count(0), a.count(1)))
main() | {
"input": [
"5\n2 2 2 3 3\n",
"3\n1 2 3\n"
],
"output": [
"2\n",
"1\n"
]
} |
2,503 | 8 | Alice got many presents these days. So she decided to pack them into boxes and send them to her friends.
There are n kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different kinds are distinguishable). The number of presents of each kind, that Alice has is very big, so we can consider Alice has an infinite number of gifts of each kind.
Also, there are m boxes. All of them are for different people, so they are pairwise distinct (consider that the names of m friends are written on the boxes). For example, putting the first kind of present into the first box but not into the second box, is different from putting the first kind of present into the second box but not into the first box.
Alice wants to pack presents with the following rules:
* She won't pack more than one present of each kind into the same box, so each box should contain presents of different kinds (i.e. each box contains a subset of n kinds, empty boxes are allowed);
* For each kind at least one present should be packed into some box.
Now Alice wants to know how many different ways to pack the presents exists. Please, help her and calculate this number. Since the answer can be huge, output it by modulo 10^9+7.
See examples and their notes for clarification.
Input
The first line contains two integers n and m, separated by spaces (1 β€ n,m β€ 10^9) β the number of kinds of presents and the number of boxes that Alice has.
Output
Print one integer β the number of ways to pack the presents with Alice's rules, calculated by modulo 10^9+7
Examples
Input
1 3
Output
7
Input
2 2
Output
9
Note
In the first example, there are seven ways to pack presents:
\{1\}\{\}\{\}
\{\}\{1\}\{\}
\{\}\{\}\{1\}
\{1\}\{1\}\{\}
\{\}\{1\}\{1\}
\{1\}\{\}\{1\}
\{1\}\{1\}\{1\}
In the second example there are nine ways to pack presents:
\{\}\{1,2\}
\{1\}\{2\}
\{1\}\{1,2\}
\{2\}\{1\}
\{2\}\{1,2\}
\{1,2\}\{\}
\{1,2\}\{1\}
\{1,2\}\{2\}
\{1,2\}\{1,2\}
For example, the way \{2\}\{2\} is wrong, because presents of the first kind should be used in the least one box. | def I(): return(list(map(int,input().split())))
n,m=I()
x=pow(2,m,1000000007)
print(pow(x-1,n,1000000007))
| {
"input": [
"1 3\n",
"2 2\n"
],
"output": [
"7\n",
"9\n"
]
} |
2,504 | 7 | Long is a huge fan of CFC (Codeforces Fried Chicken). But the price of CFC is increasing, so he decides to breed the chicken on his own farm.
His farm is presented by a rectangle grid with r rows and c columns. Some of these cells contain rice, others are empty. k chickens are living on his farm. The number of chickens is not greater than the number of cells with rice on the farm.
Long wants to give his chicken playgrounds by assigning these farm cells to his chickens. He would like to satisfy the following requirements:
* Each cell of the farm is assigned to exactly one chicken.
* Each chicken is assigned at least one cell.
* The set of cells assigned to every chicken forms a connected area. More precisely, if two cells (x, y) and (u, v) are assigned to the same chicken, this chicken is able to walk from (x, y) to (u, v) by passing only its cells and moving from each cell to another cell sharing a side.
Long also wants to prevent his chickens from fighting for food. Hence he wants the difference between the maximum and the minimum number of cells with rice assigned to a chicken to be as small as possible. Please help him.
Input
Each test contains multiple test cases. The first line contains the number of test cases T (1 β€ T β€ 2 β
10^4). Description of the test cases follows.
The first line of each test case contains three integers r, c and k (1 β€ r, c β€ 100, 1 β€ k β€ 62), representing the size of Long's farm and the number of chickens Long has.
Each of the next r lines contains c characters, each is either "." or "R", representing an empty cell or a cell with rice. It is guaranteed that the number of chickens is not greater than the number of cells with rice on the farm.
It is guaranteed that the sum of r β
c over all test cases does not exceed 2 β
10^4.
Output
For each test case, print r lines with c characters on each line. Each character should be either a lowercase English character, an uppercase English character, or a digit. Two characters should be equal if and only if the two corresponding cells are assigned to the same chicken. Uppercase and lowercase characters are considered different, so "A" and "a" belong to two different chickens.
If there are multiple optimal answers, print any.
Example
Input
4
3 5 3
..R..
...R.
....R
6 4 6
R..R
R..R
RRRR
RRRR
R..R
R..R
5 5 4
RRR..
R.R..
RRR..
R..R.
R...R
2 31 62
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
Output
11122
22223
33333
aacc
aBBc
aBBc
CbbA
CbbA
CCAA
11114
22244
32444
33344
33334
abcdefghijklmnopqrstuvwxyzABCDE
FGHIJKLMNOPQRSTUVWXYZ0123456789
Note
These pictures explain the sample output. Each color represents one chicken. Cells filled with patterns (not solid colors) contain rice.
In the first test case, each chicken has one cell with rice. Hence, the difference between the maximum and the minimum number of cells with rice assigned to a chicken is 0.
<image>
In the second test case, there are 4 chickens with 3 cells of rice, and 2 chickens with 2 cells of rice. Hence, the difference between the maximum and the minimum number of cells with rice assigned to a chicken is 3 - 2 = 1.
<image>
In the third test case, each chicken has 3 cells with rice. <image>
In the last test case, since there are 62 chicken with exactly 62 cells of rice, each chicken must be assigned to exactly one cell. The sample output is one of the possible way. | from string import ascii_letters, digits
def snake(n, m):
i = j = 0
d = 1
while i < n:
while 0 <= j < m:
yield i, j
j += d
i += 1
d *= -1
j += d
chickens = ascii_letters + digits
cfield = [[''] * 100 for _ in range(100)]
rfield = [''] * 100
for _ in range(int(input())):
r, c, k = map(int, input().split())
n = 0
for i in range(r):
rfield[i] = input()
n += rfield[i].count('R')
q = n // k
a = n % k
u = 0
v = q + int(u < a)
for i, j in snake(r, c):
cfield[i][j] = chickens[min(u, k - 1)]
if rfield[i][j] == 'R':
v -= 1
if v == 0:
u += 1
v = q + int(u < a)
for i in range(r):
print(*cfield[i][:c], sep='')
| {
"input": [
"4\n3 5 3\n..R..\n...R.\n....R\n6 4 6\nR..R\nR..R\nRRRR\nRRRR\nR..R\nR..R\n5 5 4\nRRR..\nR.R..\nRRR..\nR..R.\nR...R\n2 31 62\nRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR\nRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR\n"
],
"output": [
"AAABB\nCCCBB\nCCCCC\nAAAA\nBBBA\nBBCC\nDDDC\nEEEE\nFFFF\nAAABB\nBBBBB\nBCCCC\nDDDCC\nDDDDD\nABCDEFGHIJKLMNOPQRSTUVWXYZabcde\n9876543210zyxwvutsrqponmlkjihgf\n"
]
} |
2,505 | 12 | You are given n integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the n numbers may not be chosen.
A rectangle (rectangular matrix) is called beautiful if in each row and in each column all values are different.
What is the largest (by the total number of cells) beautiful rectangle you can construct? Print the rectangle itself.
Input
The first line contains n (1 β€ n β€ 4β
10^5). The second line contains n integers (1 β€ a_i β€ 10^9).
Output
In the first line print x (1 β€ x β€ n) β the total number of cells of the required maximum beautiful rectangle. In the second line print p and q (p β
q=x): its sizes. In the next p lines print the required rectangle itself. If there are several answers, print any.
Examples
Input
12
3 1 4 1 5 9 2 6 5 3 5 8
Output
12
3 4
1 2 3 5
3 1 5 4
5 6 8 9
Input
5
1 1 1 1 1
Output
1
1 1
1 | n = int(input())
arr = list(map(int, input().split()))
d = {}
for i in arr:
d[i] = d.get(i, 0) + 1
d2 = {}
for k, v in d.items():
d2.setdefault(v, []).append(k)
s = n
prev = 0
ansp = ansq = anss = 0
for p in range(n, 0, -1):
q = s // p
if p <= q and q * p > anss:
anss = q * p
ansq = q
ansp = p
prev += len(d2.get(p, []))
s -= prev
def get_ans():
cur_i = 0
cur_j = 0
cur = 0
for k, v in d3:
for val in v:
f = min(k, anss - cur, ansp)
cur += f
for i in range(f):
cur_i = (cur_i + 1) % ansp
cur_j = (cur_j + 1) % ansq
if ans[cur_i][cur_j]:
cur_i = (cur_i + 1) % ansp
ans[cur_i][cur_j] = val
print(anss)
print(ansp, ansq)
d3 = sorted(d2.items(), reverse=True)
ans = [[0] * ansq for i in range(ansp)]
get_ans()
for i in range(ansp):
print(*ans[i])
| {
"input": [
"5\n1 1 1 1 1\n",
"12\n3 1 4 1 5 9 2 6 5 3 5 8\n"
],
"output": [
"1\n1 1\n1 \n",
"12\n3 4\n5 3 1 6 \n4 5 3 9 \n8 2 5 1 \n"
]
} |
2,506 | 7 | Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each problem, p_i is an integer not less than 1.
Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results β or manipulating them.
For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of p_i in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of p_i will be large, it may look very suspicious β so Polycarp wants to minimize the maximum value of p_i over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of problems.
The second line contains n integers r_1, r_2, ..., r_n (0 β€ r_i β€ 1). r_i = 1 means that the "Robo-Coder Inc." robot will solve the i-th problem, r_i = 0 means that it won't solve the i-th problem.
The third line contains n integers b_1, b_2, ..., b_n (0 β€ b_i β€ 1). b_i = 1 means that the "BionicSolver Industries" robot will solve the i-th problem, b_i = 0 means that it won't solve the i-th problem.
Output
If "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer -1.
Otherwise, print the minimum possible value of max _{i = 1}^{n} p_i, if all values of p_i are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.
Examples
Input
5
1 1 1 0 0
0 1 1 1 1
Output
3
Input
3
0 0 0
0 0 0
Output
-1
Input
4
1 1 1 1
1 1 1 1
Output
-1
Input
9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
Output
4
Note
In the first example, one of the valid score assignments is p = [3, 1, 3, 1, 1]. Then the "Robo-Coder" gets 7 points, the "BionicSolver" β 6 points.
In the second example, both robots get 0 points, and the score distribution does not matter.
In the third example, both robots solve all problems, so their points are equal. | from sys import stdin
import math
def inp():
return stdin.readline().strip()
n = int(inp())
r = [int(x) for x in inp().split()]
b = [int(x) for x in inp().split()]
cR = 0
cB = 0
for i in range(n):
if r[i] > b[i]:
cR += 1
elif b[i] > r[i]:
cB += 1
if cR == 0:
print(-1)
else:
print((cB//cR)+1) | {
"input": [
"5\n1 1 1 0 0\n0 1 1 1 1\n",
"4\n1 1 1 1\n1 1 1 1\n",
"3\n0 0 0\n0 0 0\n",
"9\n1 0 0 0 0 0 0 0 1\n0 1 1 0 1 1 1 1 0\n"
],
"output": [
"3\n",
"-1\n",
"-1\n",
"4\n"
]
} |
2,507 | 11 | A lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands "T" ("turn around") and "F" ("move 1 unit forward").
You are given a list of commands that will be given to the turtle. You have to change exactly n commands from the list (one command can be changed several times). How far from the starting point can the turtle move after it follows all the commands of the modified list?
Input
The first line of input contains a string commands β the original list of commands. The string commands contains between 1 and 100 characters, inclusive, and contains only characters "T" and "F".
The second line contains an integer n (1 β€ n β€ 50) β the number of commands you have to change in the list.
Output
Output the maximum distance from the starting point to the ending point of the turtle's path. The ending point of the turtle's path is turtle's coordinate after it follows all the commands of the modified list.
Examples
Input
FT
1
Output
2
Input
FFFTFFF
2
Output
6
Note
In the first example the best option is to change the second command ("T") to "F" β this way the turtle will cover a distance of 2 units.
In the second example you have to change two commands. One of the ways to cover maximal distance of 6 units is to change the fourth command and first or last one. | import sys
import math
INF = -100000000
memo = dict()
def func(line, r):
if line in memo and r in memo[line]:
return memo[line][r]
if len(line) == 1:
which = line[0] == 'T'
if r % 2 == 1:
which = not which
if which:
return [INF, INF, 0, 0]
else:
return [1, INF, INF, INF]
best = [INF, INF, INF, INF]
for i in range(r + 1):
a = func(line[:len(line) // 2], i)
b = func(line[len(line) // 2:], r - i)
for (j, k) in [(j, k) for j in range(4) for k in range(4)]:
D = j < 2
if a[j] == INF or b[k] == INF: continue
aa = -a[j] if j % 2 else a[j]
bb = -b[k] if k % 2 else b[k]
d1, d2 = 0, 1
if k < 2:
aa = aa + bb
if not D: d1, d2 = 2, 3
else:
aa = -aa + bb
if D: d1, d2 = 2, 3
if aa >= 0: best[d1] = max(best[d1], aa)
if aa <= 0: best[d2] = max(best[d2], -aa)
if not line in memo:
memo[line] = dict()
memo[line][r] = best
return best
line = input().strip()
k = int(input())
ans = max(func(line, k))
if ans == INF: print("0")
else: print(ans) | {
"input": [
"FT\n1\n",
"FFFTFFF\n2\n"
],
"output": [
"2\n",
"6\n"
]
} |
2,508 | 8 | There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones.
In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game.
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains a single integer n (1β€ nβ€ 10^5) β the number of piles.
The second line of each test case contains n integers a_1,β¦,a_n (1β€ a_iβ€ 10^9) β a_i is equal to the number of stones in the i-th pile.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if the player who makes the first move will win, output "First". Otherwise, output "Second".
Example
Input
7
3
2 5 4
8
1 1 1 1 1 1 1 1
6
1 2 3 4 5 6
6
1 1 2 1 2 2
1
1000000000
5
1 2 2 1 1
3
1 1 1
Output
First
Second
Second
First
First
Second
First
Note
In the first test case, the first player will win the game. His winning strategy is:
1. The first player should take the stones from the first pile. He will take 1 stone. The numbers of stones in piles will be [1, 5, 4].
2. The second player should take the stones from the first pile. He will take 1 stone because he can't take any other number of stones. The numbers of stones in piles will be [0, 5, 4].
3. The first player should take the stones from the second pile because the first pile is empty. He will take 4 stones. The numbers of stones in piles will be [0, 1, 4].
4. The second player should take the stones from the second pile because the first pile is empty. He will take 1 stone because he can't take any other number of stones. The numbers of stones in piles will be [0, 0, 4].
5. The first player should take the stones from the third pile because the first and second piles are empty. He will take 4 stones. The numbers of stones in piles will be [0, 0, 0].
6. The second player will lose the game because all piles will be empty. | def sol(lis,n):
k = 0
while k<n and lis[k]==1:
k+=1
x = (k==n)^(k%2)
if x:
print('Second')
return
print('First')
k = int(input())
for i in range(k):
n = int(input())
lis = list(map(int,input().split(' ')))
sol(lis,n)
| {
"input": [
"7\n3\n2 5 4\n8\n1 1 1 1 1 1 1 1\n6\n1 2 3 4 5 6\n6\n1 1 2 1 2 2\n1\n1000000000\n5\n1 2 2 1 1\n3\n1 1 1\n"
],
"output": [
"First\nSecond\nSecond\nFirst\nFirst\nSecond\nFirst\n"
]
} |
2,509 | 7 | Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.
The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing N gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves:
* Take one gold coin from the chest.
* Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even.
Both players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally.
Input
The first line contains a single integer T (1 β€ T β€ 10^5) denotes the number of test cases.
The next T lines each contain a single integer N (1 β€ N β€ 10^{18}).
Output
T lines, each line is the answer requested by Mr. Chanek.
Example
Input
2
5
6
Output
2
4
Note
For the first case, the game is as follows:
1. Mr. Chanek takes one coin.
2. The opponent takes two coins.
3. Mr. Chanek takes one coin.
4. The opponent takes one coin.
For the second case, the game is as follows:
1. Mr. Chanek takes three coins.
2. The opponent takes one coin.
3. Mr. Chanek takes one coin.
4. The opponent takes one coin. | from sys import stdin;input = stdin.readline
def max_pos_coins(n):
a = 0
while n != 0:
if n == 4:a += 3;n = 0;continue
if n % 4 == 0:n -= 2;a += 1
else:a += n // 2;n = n // 2 - 1
return a
for _ in range(int(input())):n = int(input());print(max_pos_coins(n) if n % 2 == 0 else n - max_pos_coins(n - 1)) | {
"input": [
"2\n5\n6\n"
],
"output": [
"2\n4\n"
]
} |
2,510 | 11 | This is the easy version of the problem. The only difference is that in this version k = 0.
There is an array a_1, a_2, β¦, a_n of n positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square.
Moreover, it is allowed to do at most k such operations before the division: choose a number in the array and change its value to any positive integer. But in this version k = 0, so it is not important.
What is the minimum number of continuous segments you should use if you will make changes optimally?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains two integers n, k (1 β€ n β€ 2 β
10^5, k = 0).
The second line of each test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^7).
It's guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case print a single integer β the answer to the problem.
Example
Input
3
5 0
18 6 2 4 1
5 0
6 8 1 24 8
1 0
1
Output
3
2
1
Note
In the first test case the division may be as follows:
* [18, 6]
* [2, 4]
* [1] | from collections import Counter
def findprime(x):
d=Counter()
while(x%2==0):
x//=2
d[2]+=1
for i in range(3,int(x**0.5)+1):
while(x%i==0):
d[i]+=1
x//=i
if x>1:
d[x]+=1
se=[]
for i in d:
if d[i]%2==1:
se.append(i)
return tuple(se)
for _ in range(int(input())):
n,k=map(int,input().split())
arr=list(map(int,input().split()))
ans=0
vis=set()
for i in range(n):
f=arr[i]
c=findprime(f)
if c in vis:
ans+=1
vis=set()
vis|={c}
if len(vis)>0:
ans+=1
print(ans)
| {
"input": [
"3\n5 0\n18 6 2 4 1\n5 0\n6 8 1 24 8\n1 0\n1\n"
],
"output": [
"\n3\n2\n1\n"
]
} |
2,511 | 10 | Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to find their quantity modulo 1000000007 (109 + 7). Be careful and don't miss a string or two!
Let us remind you that a string is a palindrome if it can be read the same way in either direction, from the left to the right and from the right to the left.
Input
The first and only line contains three integers: n, m and k (1 β€ n, m, k β€ 2000).
Output
Print a single integer β the number of strings of the described type modulo 1000000007 (109 + 7).
Examples
Input
1 1 1
Output
1
Input
5 2 4
Output
2
Note
In the first sample only one string is valid: "a" (let's denote the only letter of our alphabet as "a").
In the second sample (if we denote the alphabet letters as "a" and "b") the following strings are valid: "aaaaa" and "bbbbb". | def solve():
mod = int(1e9+7)
n, m, k = map(int, input().split())
if k==1 or k>n:
print(pow(m, n, mod))
elif k==n:
print(pow(m, (n+1)//2, mod))
elif k%2==1:
print((m*m)%mod)
elif k%2==0:
print(m)
solve() | {
"input": [
"1 1 1\n",
"5 2 4\n"
],
"output": [
"1",
"2"
]
} |
2,512 | 10 | A sequence of non-negative integers a_1, a_2, ..., a_n is called growing if for all i from 1 to n - 1 all ones (of binary representation) in a_i are in the places of ones (of binary representation) in a_{i + 1} (in other words, a_i \:\&\: a_{i + 1} = a_i, where \& denotes [bitwise AND](http://tiny.cc/xpy9uz)). If n = 1 then the sequence is considered growing as well.
For example, the following four sequences are growing:
* [2, 3, 15, 175] β in binary it's [10_2, 11_2, 1111_2, 10101111_2];
* [5] β in binary it's [101_2];
* [1, 3, 7, 15] β in binary it's [1_2, 11_2, 111_2, 1111_2];
* [0, 0, 0] β in binary it's [0_2, 0_2, 0_2].
The following three sequences are non-growing:
* [3, 4, 5] β in binary it's [11_2, 100_2, 101_2];
* [5, 4, 3] β in binary it's [101_2, 100_2, 011_2];
* [1, 2, 4, 8] β in binary it's [0001_2, 0010_2, 0100_2, 1000_2].
Consider two sequences of non-negative integers x_1, x_2, ..., x_n and y_1, y_2, ..., y_n. Let's call this pair of sequences co-growing if the sequence x_1 β y_1, x_2 β y_2, ..., x_n β y_n is growing where β denotes [bitwise XOR](http://tiny.cc/bry9uz).
You are given a sequence of integers x_1, x_2, ..., x_n. Find the lexicographically minimal sequence y_1, y_2, ..., y_n such that sequences x_i and y_i are co-growing.
The sequence a_1, a_2, ..., a_n is lexicographically smaller than the sequence b_1, b_2, ..., b_n if there exists 1 β€ k β€ n such that a_i = b_i for any 1 β€ i < k but a_k < b_k.
Input
The first line contains an integer t (1 β€ t β€ 10^4). Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 2 β
10^5) β length of the sequence x_i.
The second line contains n integers x_1, x_2, ..., x_n (0 β€ x_i < 2^{30}) β elements of the sequence x_i.
It is guaranteed that the sum of n overall all test cases doesn't exceed 2 β
10^5.
Output
For each test case, print n integers y_1, y_2, ..., y_n (0 β€ y_i < 2^{30}) β lexicographically minimal sequence such that such that it's co-growing with given sequence x_i.
Example
Input
5
4
1 3 7 15
4
1 2 4 8
5
1 2 3 4 5
4
11 13 15 1
1
0
Output
0 0 0 0
0 1 3 7
0 1 0 3 2
0 2 0 14
0 | def func():
lst = [0, ]
for i in range(1, n):
ele = (lst[-1]^x[i-1] | x[i]) ^ x[i]
lst.append(ele)
print(*lst)
for _ in range(int(input())):
n = int(input())
x = list(map(int, input().split()))
func()
| {
"input": [
"5\n4\n1 3 7 15\n4\n1 2 4 8\n5\n1 2 3 4 5\n4\n11 13 15 1\n1\n0\n"
],
"output": [
"0 0 0 0\n0 1 3 7\n0 1 0 3 2\n0 2 0 14\n0\n"
]
} |
2,513 | 7 | Vasya plays Robot Bicorn Attack.
The game consists of three rounds. For each one a non-negative integer amount of points is given. The result of the game is the sum of obtained points. Vasya has already played three rounds and wrote obtained points one by one (without leading zeros) into the string s. Vasya decided to brag about his achievement to the friends. However, he has forgotten how many points he got for each round. The only thing he remembers is the string s.
Help Vasya to find out what is the maximum amount of points he could get. Take into account that Vasya played Robot Bicorn Attack for the first time, so he could not get more than 1000000 (106) points for one round.
Input
The only line of input contains non-empty string s obtained by Vasya. The string consists of digits only. The string length does not exceed 30 characters.
Output
Print the only number β the maximum amount of points Vasya could get. If Vasya is wrong and the string could not be obtained according to the rules then output number -1.
Examples
Input
1234
Output
37
Input
9000
Output
90
Input
0009
Output
-1
Note
In the first example the string must be split into numbers 1, 2 and 34.
In the second example the string must be split into numbers 90, 0 and 0.
In the third example the string is incorrect, because after splitting the string into 3 numbers number 00 or 09 will be obtained, but numbers cannot have leading zeroes. | def g(a):
return (len(a) == 1 or a[0] != '0') and int(a) <= 1000000
def f(a, b, c):
return int(a) + int(b) + int(c) if g(a) and g(b) and g(c) else -1
s, v = input(), -1
for i in range(1, len(s) - 1):
for j in range(i + 1, len(s)):
v = max(v, f(s[:i], s[i:j], s[j:]))
print(v) | {
"input": [
"9000\n",
"1234\n",
"0009\n"
],
"output": [
"90\n",
"37\n",
"-1\n"
]
} |
2,514 | 8 | After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The balls are numbered with numbers from 1 to n.
Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which <image> is minimum, where i is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number.
For every ball print the number of the basket where it will go according to Valeric's scheme.
Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on.
Input
The first line contains two space-separated integers n, m (1 β€ n, m β€ 105) β the number of balls and baskets, correspondingly.
Output
Print n numbers, one per line. The i-th line must contain the number of the basket for the i-th ball.
Examples
Input
4 3
Output
2
1
3
2
Input
3 1
Output
1
1
1 | def func(i):
return abs((m+1)/2-i)
a = input()
[n, m] = a.split(' ')
[n, m] = [int(n), int(m)];
a = [i for i in range(1, m+1)]
a.sort(key=func)
i = 0;
while(i<n):
print(a[i%m])
i+=1;
# print(a)
| {
"input": [
"3 1\n",
"4 3\n"
],
"output": [
"1\n1\n1\n",
"2\n1\n3\n2\n"
]
} |
2,515 | 8 | Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors.
Polycaprus calculated that the optimal celling price for such scissors would be p bourles. However, he read somewhere that customers are attracted by prices that say something like "Special Offer! Super price 999 bourles!". So Polycarpus decided to lower the price a little if it leads to the desired effect.
Polycarpus agrees to lower the price by no more than d bourles so that the number of nines at the end of the resulting price is maximum. If there are several ways to do it, he chooses the maximum possible price.
Note, Polycarpus counts only the trailing nines in a price.
Input
The first line contains two integers p and d (1 β€ p β€ 1018; 0 β€ d < p) β the initial price of scissors and the maximum possible price reduction.
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.
Output
Print the required price β the maximum price that ends with the largest number of nines and that is less than p by no more than d.
The required number shouldn't have leading zeroes.
Examples
Input
1029 102
Output
999
Input
27191 17
Output
27189 | def readln(): return tuple(map(int, input().split()))
p, d = readln()
if p % 10 == 9:
p += 1
d += 1
tmp = [tuple(reversed(list(str(p - (p % 10**i + 1))))) for i in range(len(str(p))) if p % 10**i + 1 <= d]
tmp.append(tuple(reversed(list(str(p)))))
print(''.join(reversed(max(tmp))))
| {
"input": [
"27191 17\n",
"1029 102\n"
],
"output": [
"27189\n",
"999\n"
]
} |
2,516 | 8 | Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequence), or all pressed buttons return to the initial position. When all buttons are pressed into the lock at once, the lock opens.
Consider an example with three buttons. Let's say that the opening sequence is: {2, 3, 1}. If you first press buttons 1 or 3, the buttons unpress immediately. If you first press button 2, it stays pressed. If you press 1 after 2, all buttons unpress. If you press 3 after 2, buttons 3 and 2 stay pressed. As soon as you've got two pressed buttons, you only need to press button 1 to open the lock.
Manao doesn't know the opening sequence. But he is really smart and he is going to act in the optimal way. Calculate the number of times he's got to push a button in order to open the lock in the worst-case scenario.
Input
A single line contains integer n (1 β€ n β€ 2000) β the number of buttons the lock has.
Output
In a single line print the number of times Manao has to push a button in the worst-case scenario.
Examples
Input
2
Output
3
Input
3
Output
7
Note
Consider the first test sample. Manao can fail his first push and push the wrong button. In this case he will already be able to guess the right one with his second push. And his third push will push the second right button. Thus, in the worst-case scenario he will only need 3 pushes. | def f(n):
return ((n ** 3) + (5 * n)) // 6
print(f(int(input())))
| {
"input": [
"2\n",
"3\n"
],
"output": [
"3\n",
"7\n"
]
} |
2,517 | 11 | The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset β a language called HQ...
Input
The only line of the input is a string between 1 and 106 characters long.
Output
Output "Yes" or "No".
Examples
Input
HHHH
Output
Yes
Input
HQHQH
Output
No
Input
HHQHHQH
Output
No
Input
HHQQHHQQHH
Output
Yes
Note
The rest of the problem statement was destroyed by a stray raccoon. We are terribly sorry for the inconvenience. | a = input()
b = []
h = ''
c = 0
for i in a:
if i == 'Q':
c += 1
if c == 0:
print('Yes')
exit(0)
r = -1
for i in range(1001):
if i*i == c:
r = i
break
if r == -1:
print('No')
exit(0)
h = [a.split('Q')[0], a.split('Q')[-1]]
c = [len(h[0]), len(h[1])]
if c[0] % 2 != 0 or c[1] % 2 != 0:
print('No')
exit(0)
c[0] //= 2
c[1] //= 2
resp = ''
i = c[0]
while True:
if i >= len(a):
break
if r == 0 and a[i] == 'Q':
break
resp += a[i]
if r == 0 and a[i] == 'H':
c[1] -= 1
if c[1] == 0 and r == 0:
break
if a[i] == 'Q':
r -= 1
if r == -1:
print('No')
exit(0)
i += 1
def hq(a):
resp = ''
for i in a:
if i == 'H':
resp += 'H'
else:
resp += a
return resp
if a == hq(resp):
print('Yes')
else:
print('No')
| {
"input": [
"HHQHHQH\n",
"HHQQHHQQHH\n",
"HHHH\n",
"HQHQH\n"
],
"output": [
"No\n",
"Yes\n",
"Yes\n",
"No\n"
]
} |
2,518 | 8 | Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.
Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.
Input
The first line contains two integers n and m (2 β€ n β€ 105, 1 β€ m β€ 105). The second line contains m integers a1, a2, ..., am (1 β€ ai β€ n). Note that Xenia can have multiple consecutive tasks in one house.
Output
Print a single integer β the time Xenia needs to complete all tasks.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4 3
3 2 3
Output
6
Input
4 3
2 3 3
Output
2
Note
In the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 β 2 β 3 β 4 β 1 β 2 β 3. This is optimal sequence. So, she needs 6 time units. | def inp(): return map (int, input().split())
r,c= 0,1
n,m = inp()
for x in inp():
r += (x-c) % n
c = x
print(r) | {
"input": [
"4 3\n2 3 3\n",
"4 3\n3 2 3\n"
],
"output": [
"2\n",
"6\n"
]
} |
2,519 | 8 | The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 β€ i β€ j β€ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring.
String x(i, j) contains string "bear", if there is such index k (i β€ k β€ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r.
Help the bear cope with the given problem.
Input
The first line contains a non-empty string s (1 β€ |s| β€ 5000). It is guaranteed that the string only consists of lowercase English letters.
Output
Print a single number β the answer to the problem.
Examples
Input
bearbtear
Output
6
Input
bearaabearc
Output
20
Note
In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9).
In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). | def bear(s):
b =0
for i in range(len(s)):
c = s.find('bear' , i)
if c >=0:
b+=len(s)-c-3
return b
if __name__ == '__main__':
s = input()
print(bear(s)) | {
"input": [
"bearaabearc\n",
"bearbtear\n"
],
"output": [
"20\n",
"6\n"
]
} |
2,520 | 7 | Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n Γ n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1Β·1 + 1Β·0 + 1Β·1) + (0Β·1 + 1Β·1 + 1Β·0) + (1Β·1 + 0Β·1 + 0Β·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 β€ n β€ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 β€ aij β€ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 β€ q β€ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i β flip the values of the i-th row;
* 2 i β flip the values of the i-th column;
* 3 β output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001 | def main():
from sys import stdin
from operator import xor
from functools import reduce
x, res = reduce(xor, (input()[i] == '1' for i in range(0, int(input()) * 2, 2))), []
input()
for s in stdin.read().splitlines():
if s == '3':
res.append("01"[x])
else:
x ^= True
print(''.join(res))
if __name__ == "__main__":
main()
| {
"input": [
"3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3\n"
],
"output": [
"01001"
]
} |
2,521 | 8 | Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:
1. She will tell you two numbers, l and r (1 β€ l β€ r β€ n), and you should tell her <image>.
2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 β€ l β€ r β€ n), and you should tell her <image>.
For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.
Input
The first line contains an integer n (1 β€ n β€ 105). The second line contains n integers: v1, v2, ..., vn (1 β€ vi β€ 109) β costs of the stones.
The third line contains an integer m (1 β€ m β€ 105) β the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 β€ l β€ r β€ n; 1 β€ type β€ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one.
Output
Print m lines. Each line must contain an integer β the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input.
Examples
Input
6
6 4 2 7 2 7
3
2 3 6
1 3 4
1 1 6
Output
24
9
28
Input
4
5 5 2 3
10
1 2 4
2 1 4
1 1 1
2 1 4
2 1 2
1 1 1
1 3 3
1 1 3
1 4 4
1 2 2
Output
10
15
5
15
5
5
2
12
3
5
Note
Please note that the answers to the questions may overflow 32-bit integer type. | def rat(b,x,y):print(b[y]-b[x-1])
a=int(input())
b=[0]+list(map(int,input().split()))
c=sorted(b.copy())
for i in range(1,a+1):b[i]+=b[i-1];c[i]+=c[i-1]
for _ in " "*int(input()):
x,y,z=map(int,input().split())
if x==1:rat(b,y,z)
else:rat(c,y,z)
| {
"input": [
"6\n6 4 2 7 2 7\n3\n2 3 6\n1 3 4\n1 1 6\n",
"4\n5 5 2 3\n10\n1 2 4\n2 1 4\n1 1 1\n2 1 4\n2 1 2\n1 1 1\n1 3 3\n1 1 3\n1 4 4\n1 2 2\n"
],
"output": [
"24\n9\n28\n",
"10\n15\n5\n15\n5\n5\n2\n12\n3\n5\n"
]
} |
2,522 | 8 | n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition.
Input
The only line of input contains two integers n and m, separated by a single space (1 β€ m β€ n β€ 109) β the number of participants and the number of teams respectively.
Output
The only line of the output should contain two integers kmin and kmax β the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively.
Examples
Input
5 1
Output
10 10
Input
3 2
Output
1 1
Input
6 3
Output
3 6
Note
In the first sample all the participants get into one team, so there will be exactly ten pairs of friends.
In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one.
In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. | def f(k):
return k*(k-1)//2
n,m=map(int,input().split())
print(f(n//m+1)*(n%m)+f(n//m)*(m-n%m),f(n-m+1))
| {
"input": [
"3 2\n",
"6 3\n",
"5 1\n"
],
"output": [
"1 1\n",
"3 6\n",
"10 10\n"
]
} |
2,523 | 10 | New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v.
As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1.
Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 β€ k β€ 3) Santa will take charge of the warehouse in city ck.
It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network.
However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value.
Input
The first line contains an integer n (3 β€ n β€ 105) β the number of cities in Tree World.
Next n - 1 lines describe the roads. The i-th line of them (1 β€ i β€ n - 1) contains three space-separated integers ai, bi, li (1 β€ ai, bi β€ n, ai β bi, 1 β€ li β€ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li.
The next line contains an integer q (1 β€ q β€ 105) β the number of road length changes.
Next q lines describe the length changes. The j-th line of them (1 β€ j β€ q) contains two space-separated integers rj, wj (1 β€ rj β€ n - 1, 1 β€ wj β€ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times.
Output
Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6.
Examples
Input
3
2 3 5
1 3 3
5
1 4
2 2
1 2
2 1
1 1
Output
14.0000000000
12.0000000000
8.0000000000
6.0000000000
4.0000000000
Input
6
1 5 3
5 3 2
6 1 7
1 4 4
5 2 3
5
1 2
2 1
3 5
4 1
5 2
Output
19.6000000000
18.6000000000
16.6000000000
13.6000000000
12.6000000000
Note
Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). | import sys
sys.setrecursionlimit(1500)
MAX = 100005;
g = [[] for _ in range(MAX)]
vis = [False] * MAX
dp = [0] * MAX
prod = [0] * MAX
edges = []
order = []
def dfs(st):
stack = []
stack.append((st, -1))
vis[st] = True
while stack:
st, parent = stack.pop()
order.append(st)
vis[st] = True
if (st == parent): continue;
for i in g[st]:
if (vis[i[0]]): continue;
stack.append((i[0], st))
n = int(input())
for i in range(n-1):
a, b, w = map(int, sys.stdin.readline().split(' '))
g[a].append([b, w])
g[b].append([a,w])
edges.append([[a, b], w])
dfs(1);
order.reverse()
for st in order:
dp[st] = 1;
for i in g[st]:
dp[st] += dp[i[0]];
tot = 0;
curr = 1;
div = n * (n-1) / 2;
for i in edges:
a = i[0][0];
b = i[0][1];
sa = dp[a];
sb = dp[b];
tot += min(sa, sb) * (n - min(sa, sb)) * i[1];
prod[curr] = min(sa, sb) * (n - min(sa, sb));
curr += 1;
q = int(input())
for i in range(q):
q1, q2 = map(int, sys.stdin.readline().split(' '))
tot -= prod[q1] * edges[q1-1][1];
edges[q1-1][1] = q2;
tot += prod[q1] * edges[q1-1][1];
sys.stdout.write(str(tot*3/div)+"\n")
| {
"input": [
"6\n1 5 3\n5 3 2\n6 1 7\n1 4 4\n5 2 3\n5\n1 2\n2 1\n3 5\n4 1\n5 2\n",
"3\n2 3 5\n1 3 3\n5\n1 4\n2 2\n1 2\n2 1\n1 1\n"
],
"output": [
"19.600000000000\n18.600000000000\n16.600000000000\n13.600000000000\n12.600000000000\n",
"14.000000000000\n12.000000000000\n8.000000000000\n6.000000000000\n4.000000000000\n"
]
} |
2,524 | 8 | Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.
<image>
The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 β€ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads.
<image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights.
Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe.
He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
Input
The first line contains integer n (1 β€ n β€ 10) β the number of roads on the path from the entrance to any exit.
The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 β the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100.
Output
Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.
Examples
Input
2
1 2 3 4 5 6
Output
5
Note
Picture for the sample test. Green color denotes the additional street lights.
<image> | n=int(input())
a=list(map(int,input().split()))
a=[0,0]+a[:]
l=len(a)
def dfs(node,p):
if node>=l:
return 0
p=a[node]
q=dfs((2*node),p)
r=dfs((2*node+1),p)
p+=max(q,r)
global c
c=c+abs(q-r)
return p
c=0
dfs(1,0)
print(c) | {
"input": [
"2\n1 2 3 4 5 6\n"
],
"output": [
"5\n"
]
} |
2,525 | 9 | Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way.
In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 β€ i β€ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are:
1. If i β n, move from pile i to pile i + 1;
2. If pile located at the position of student is not empty, remove one box from it.
GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed.
Input
The first line contains two integers n and m (1 β€ n, m β€ 105), the number of piles of boxes and the number of GukiZ's students.
The second line contains n integers a1, a2, ... an (0 β€ ai β€ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty.
Output
In a single line, print one number, minimum time needed to remove all the boxes in seconds.
Examples
Input
2 1
1 1
Output
4
Input
3 2
1 0 2
Output
5
Input
4 100
3 4 5 4
Output
5
Note
First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second).
Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds.
Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. | n,m=map(int,input().split())
a=list(map(int,input().split()))
def c(t):
s,r,p,b=m,0,n,0
while 1:
while b==0:
if p==0: return 1
p-=1
b=a[p]
if r==0:
if s==0: return 0
r=t-p-1
s-=1
d=min(b,r)
b-=d
r-=d
l,h=0,n+sum(a)+9
while h-l>1:
md=(l+h)//2
if c(md):
h=md
else:
l=md
print(h)
| {
"input": [
"3 2\n1 0 2\n",
"2 1\n1 1\n",
"4 100\n3 4 5 4\n"
],
"output": [
" 5",
" 4",
" 5"
]
} |
2,526 | 10 | You are given a string S of length n with each character being one of the first m lowercase English letters.
Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1.
Recall that LCS of two strings S and T is the longest string C such that C both in S and T as a subsequence.
Input
The first line contains two numbers n and m denoting the length of string S and number of first English lowercase characters forming the character set for strings (1 β€ n β€ 100 000, 2 β€ m β€ 26).
The second line contains string S.
Output
Print the only line containing the answer.
Examples
Input
3 3
aaa
Output
6
Input
3 3
aab
Output
11
Input
1 2
a
Output
1
Input
10 9
abacadefgh
Output
789
Note
For the first sample, the 6 possible strings T are: aab, aac, aba, aca, baa, caa.
For the second sample, the 11 possible strings T are: aaa, aac, aba, abb, abc, aca, acb, baa, bab, caa, cab.
For the third sample, the only possible string T is b. | def main():
n, m = map(int, input().split())
s = input()
k = sum(s[i] != s[i - 1] for i in range(1, n)) + 1
x = i = 0
while i < n - 1:
if s[i] != s[i + 1]:
j = i
while i + 2 < n and s[i] == s[i + 2]:
i += 1
j = (i - j) + 2
x += j * (j - 1) // 2
i += 1
ans = k * (m * n - n) - x
print(ans)
main()
| {
"input": [
"10 9\nabacadefgh\n",
"1 2\na\n",
"3 3\naaa\n",
"3 3\naab\n"
],
"output": [
"789\n",
"1\n",
"6\n",
"11\n"
]
} |
2,527 | 8 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.
You are to implement the alignment in the shortest possible time. Good luck!
Input
The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.
Output
Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.
Examples
Input
This is
Codeforces
Beta
Round
5
Output
************
* This is *
* *
*Codeforces*
* Beta *
* Round *
* 5 *
************
Input
welcome to the
Codeforces
Beta
Round 5
and
good luck
Output
****************
*welcome to the*
* Codeforces *
* Beta *
* Round 5 *
* *
* and *
* good luck *
**************** | import sys
def main():
lines = [line.strip() for line in sys.stdin]
w = max(len(l) for l in lines) + 2
print('*' * w)
flag = True
for line in lines:
extra = w - 2 - len(line)
if extra % 2 != 0:
if flag:
left = extra // 2
right = extra - left
else:
right = extra // 2
left = extra - right
flag = not flag
else:
left = extra // 2
right = extra // 2
print('*' + ' ' * left + line + ' ' * right + '*')
print('*' * w)
main()
| {
"input": [
"This is\n\nCodeforces\nBeta\nRound\n5\n",
"welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck\n"
],
"output": [
"************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************",
"****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"
]
} |
2,528 | 11 | There are b blocks of digits. Each one consisting of the same n digits, which are given to you in the input. Wet Shark must choose exactly one digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit 1 from the first block and digit 2 from the second block, he gets the integer 12.
Wet Shark then takes this number modulo x. Please, tell him how many ways he can choose one digit from each block so that he gets exactly k as the final result. As this number may be too large, print it modulo 109 + 7.
Note, that the number of ways to choose some digit in the block is equal to the number of it's occurrences. For example, there are 3 ways to choose digit 5 from block 3 5 6 7 8 9 5 1 1 1 1 5.
Input
The first line of the input contains four space-separated integers, n, b, k and x (2 β€ n β€ 50 000, 1 β€ b β€ 109, 0 β€ k < x β€ 100, x β₯ 2) β the number of digits in one block, the number of blocks, interesting remainder modulo x and modulo x itself.
The next line contains n space separated integers ai (1 β€ ai β€ 9), that give the digits contained in each block.
Output
Print the number of ways to pick exactly one digit from each blocks, such that the resulting integer equals k modulo x.
Examples
Input
12 1 5 10
3 5 6 7 8 9 5 1 1 1 1 5
Output
3
Input
3 2 1 2
6 2 2
Output
0
Input
3 2 1 2
3 1 2
Output
6
Note
In the second sample possible integers are 22, 26, 62 and 66. None of them gives the remainder 1 modulo 2.
In the third sample integers 11, 13, 21, 23, 31 and 33 have remainder 1 modulo 2. There is exactly one way to obtain each of these integers, so the total answer is 6. | def g(b,w):
if(b,w)in x:return x[(b,w)]
x[(b,w)]=sum(c[i]for i in r(len(c))if i%m==w)if b==1else sum(g(b//2,l)*g(b-b//2,(w-(l*pow(10,b-b//2,m))%m+m)%m)for l in r(m))%(10**9+7)
return x[(b,w)]
q,r,k=input,range,'map(int,q().split())'
n,b,w,m=eval(k)
a,x=list(eval(k)),{}
c=[a.count(i)for i in r(10)]
print(g(b,w)) | {
"input": [
"3 2 1 2\n3 1 2\n",
"3 2 1 2\n6 2 2\n",
"12 1 5 10\n3 5 6 7 8 9 5 1 1 1 1 5\n"
],
"output": [
"6",
"0",
"3"
]
} |
2,529 | 9 | Moscow is hosting a major international conference, which is attended by n scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from 1 to 109.
In the evening after the conference, all n scientists decided to go to the cinema. There are m movies in the cinema they came to. Each of the movies is characterized by two distinct numbers β the index of audio language and the index of subtitles language. The scientist, who came to the movie, will be very pleased if he knows the audio language of the movie, will be almost satisfied if he knows the language of subtitles and will be not satisfied if he does not know neither one nor the other (note that the audio language and the subtitles language for each movie are always different).
Scientists decided to go together to the same movie. You have to help them choose the movie, such that the number of very pleased scientists is maximum possible. If there are several such movies, select among them one that will maximize the number of almost satisfied scientists.
Input
The first line of the input contains a positive integer n (1 β€ n β€ 200 000) β the number of scientists.
The second line contains n positive integers a1, a2, ..., an (1 β€ ai β€ 109), where ai is the index of a language, which the i-th scientist knows.
The third line contains a positive integer m (1 β€ m β€ 200 000) β the number of movies in the cinema.
The fourth line contains m positive integers b1, b2, ..., bm (1 β€ bj β€ 109), where bj is the index of the audio language of the j-th movie.
The fifth line contains m positive integers c1, c2, ..., cm (1 β€ cj β€ 109), where cj is the index of subtitles language of the j-th movie.
It is guaranteed that audio languages and subtitles language are different for each movie, that is bj β cj.
Output
Print the single integer β the index of a movie to which scientists should go. After viewing this movie the number of very pleased scientists should be maximum possible. If in the cinema there are several such movies, you need to choose among them one, after viewing which there will be the maximum possible number of almost satisfied scientists.
If there are several possible answers print any of them.
Examples
Input
3
2 3 2
2
3 2
2 3
Output
2
Input
6
6 3 1 1 3 7
5
1 2 3 4 5
2 3 4 5 1
Output
1
Note
In the first sample, scientists must go to the movie with the index 2, as in such case the 1-th and the 3-rd scientists will be very pleased and the 2-nd scientist will be almost satisfied.
In the second test case scientists can go either to the movie with the index 1 or the index 3. After viewing any of these movies exactly two scientists will be very pleased and all the others will be not satisfied. | def main():
from collections import Counter
input()
aa = Counter(map(int, input().split()))
m = int(input())
bb, cc = (list(map(aa.__getitem__, map(int, input().split()))) for _ in (0, 1))
print(max(zip(bb, cc, range(m)))[2] + 1)
if __name__ == '__main__':
main()
| {
"input": [
"6\n6 3 1 1 3 7\n5\n1 2 3 4 5\n2 3 4 5 1\n",
"3\n2 3 2\n2\n3 2\n2 3\n"
],
"output": [
"1\n",
"2\n"
]
} |
2,530 | 8 | Galya is playing one-dimensional Sea Battle on a 1 Γ n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.
Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").
Galya has already made k shots, all of them were misses.
Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.
It is guaranteed that there is at least one valid ships placement.
Input
The first line contains four positive integers n, a, b, k (1 β€ n β€ 2Β·105, 1 β€ a, b β€ n, 0 β€ k β€ n - 1) β the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made.
The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
Output
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.
In the second line print the cells Galya should shoot at.
Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left.
If there are multiple answers, you can print any of them.
Examples
Input
5 1 2 1
00100
Output
2
4 2
Input
13 3 2 3
1000000010001
Output
2
7 11
Note
There is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part. | def sum_zeroth(arr):
res = 0
for elem in arr:
res += elem[0]
return res
n, a, b, k = map(int, input().split())
data = input()
dist = []
pp = 0
last = 0
for i in range(n):
if data[i] == '1':
dist.append((last, i))
pp += (i - last) // b
last = i + 1
dist.append((last, n))
pp += (n - last) // b
pos = []
minp = pp - a + 1
fnd = False
for elem in dist:
cur = elem[0] - 1
while (cur + b) < elem[1]:
cur += b
pos.append(cur + 1)
if len(pos) == minp:
fnd = True
break
if fnd:
break
print(minp)
print(' '.join(map(str, pos)))
| {
"input": [
"13 3 2 3\n1000000010001\n",
"5 1 2 1\n00100\n"
],
"output": [
"2\n3 5 ",
"2\n2 5 "
]
} |
2,531 | 7 | On her way to programming school tiger Dasha faced her first test β a huge staircase!
<image>
The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values β the number of steps with even and odd numbers.
You need to check whether there is an interval of steps from the l-th to the r-th (1 β€ l β€ r), for which values that Dasha has found are correct.
Input
In the only line you are given two integers a, b (0 β€ a, b β€ 100) β the number of even and odd steps, accordingly.
Output
In the only line print "YES", if the interval of steps described above exists, and "NO" otherwise.
Examples
Input
2 3
Output
YES
Input
3 1
Output
NO
Note
In the first example one of suitable intervals is from 1 to 5. The interval contains two even steps β 2 and 4, and three odd: 1, 3 and 5. | def main():
a, b = map(int, input().split())
if (abs(a - b) <= 1 and (a != 0 or b != 0)):
print("YES")
else:
print("NO")
main() | {
"input": [
"3 1\n",
"2 3\n"
],
"output": [
"NO\n",
"YES\n"
]
} |
2,532 | 9 | DO YOU EXPECT ME TO FIND THIS OUT?
WHAT BASE AND/XOR LANGUAGE INCLUDES string?
DON'T BYTE OF MORE THAN YOU CAN CHEW
YOU CAN ONLY DISTORT THE LARGEST OF MATHEMATICS SO FAR
SAYING "ABRACADABRA" WITHOUT A MAGIC AND WON'T DO YOU ANY GOOD
THE LAST STACK RUPTURES. ALL DIE. OH, THE EMBARRASSMENT!
I HAVE NO ARRAY AND I MUST SCREAM
ELEMENTS MAY NOT BE STORED IN WEST HYPERSPACE
Input
The first line of input data contains a single integer n (1 β€ n β€ 10).
The second line of input data contains n space-separated integers ai (1 β€ ai β€ 11).
Output
Output a single integer.
Example
Input
4
2 5 3 1
Output
4 | def mp():
return map(int, input().split())
n = int(input())
a = list(mp())
print(max(a) ^ a[-1]) | {
"input": [
"4\n2 5 3 1\n"
],
"output": [
"4\n"
]
} |
2,533 | 8 | In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105) β the length of the string.
Output
Print the string that satisfies all the constraints.
If there are multiple answers, print any of them.
Examples
Input
2
Output
aa
Input
3
Output
bba
Note
A palindrome is a sequence of characters which reads the same backward and forward. | def main():
n = int(input())
print(("aabb" * (n // 4 + 1))[:n])
if __name__ == '__main__':
main()
| {
"input": [
"2\n",
"3\n"
],
"output": [
"aa\n",
"aab\n"
]
} |
2,534 | 8 | Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them.
Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.
You are to determine the total number of times Vasily takes the top card from the deck.
Input
The first line contains single integer n (1 β€ n β€ 100 000) β the number of cards in the deck.
The second line contains a sequence of n integers a1, a2, ..., an (1 β€ ai β€ 100 000), where ai is the number written on the i-th from top card in the deck.
Output
Print the total number of times Vasily takes the top card from the deck.
Examples
Input
4
6 3 1 2
Output
7
Input
1
1000
Output
1
Input
7
3 3 3 3 3 3 3
Output
7
Note
In the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2, 6, 3]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6, 3]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards. | from bisect import bisect_left
def read():
return [int(x) for x in input().split()]
n = read()
a = read()
vec = [list() for i in range(max(a)+1)]
for i in range(len(a)):
vec[a[i]].append(i)
def solve():
ans =0
dis = 1
p = 0
i=0
while i <len(vec):
if len(vec[i]):
pos = bisect_left(vec[i],p)
ans += (len(vec[i]) - pos)*dis
p = vec[i][len(vec[i])-1]
# print(i,pos,dis,ans,p)
# print(vec[i])
del vec[i][pos:len(vec[i])]
if len(vec[i]):
p = 0
dis+=1
i-=1
i+=1
return ans
print(solve()) | {
"input": [
"4\n6 3 1 2\n",
"1\n1000\n",
"7\n3 3 3 3 3 3 3\n"
],
"output": [
"7",
"1",
"7"
]
} |
2,535 | 9 | You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide.
We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors <image> and <image> is acute (i.e. strictly less than <image>). Otherwise, the point is called good.
The angle between vectors <image> and <image> in 5-dimensional space is defined as <image>, where <image> is the scalar product and <image> is length of <image>.
Given the list of points, print the indices of the good points in ascending order.
Input
The first line of input contains a single integer n (1 β€ n β€ 103) β the number of points.
The next n lines of input contain five integers ai, bi, ci, di, ei (|ai|, |bi|, |ci|, |di|, |ei| β€ 103) β the coordinates of the i-th point. All points are distinct.
Output
First, print a single integer k β the number of good points.
Then, print k integers, each on their own line β the indices of the good points in ascending order.
Examples
Input
6
0 0 0 0 0
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
Output
1
1
Input
3
0 0 1 2 0
0 0 9 2 0
0 0 5 9 0
Output
0
Note
In the first sample, the first point forms exactly a <image> angle with all other pairs of points, so it is good.
In the second sample, along the cd plane, we can see the points look as follows:
<image>
We can see that all angles here are acute, so no points are good. | def vec(c0, a, b):
an = 0
for i in range(5):
an += (a[i] - c0[i]) * (b[i] - c0[i])
return an
n = int(input())
if n > 80:
print(0)
exit(0)
a = [[0] * 5 for i in range(n)]
for i in range(n):
a[i] = [int(j) for j in input().split()]
ans = []
for i in range(n):
flag = True
for j in range(n):
for k in range(n):
if i != j and j != k and k != i and vec(a[i], a[j], a[k]) > 0:
flag = False
if flag:
ans.append(i)
print(len(ans))
for i in ans:
print(i + 1) | {
"input": [
"3\n0 0 1 2 0\n0 0 9 2 0\n0 0 5 9 0\n",
"6\n0 0 0 0 0\n1 0 0 0 0\n0 1 0 0 0\n0 0 1 0 0\n0 0 0 1 0\n0 0 0 0 1\n"
],
"output": [
"0\n",
"1\n1\n"
]
} |
2,536 | 10 | Once upon a time in the galaxy of far, far away...
Darth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star.
When the rebels learnt that the Death Star was coming, they decided to use their new secret weapon β space mines. Let's describe a space mine's build.
Each space mine is shaped like a ball (we'll call it the mine body) of a certain radius r with the center in the point O. Several spikes protrude from the center. Each spike can be represented as a segment, connecting the center of the mine with some point P, such that <image> (transporting long-spiked mines is problematic), where |OP| is the length of the segment connecting O and P. It is convenient to describe the point P by a vector p such that P = O + p.
The Death Star is shaped like a ball with the radius of R (R exceeds any mine's radius). It moves at a constant speed along the v vector at the speed equal to |v|. At the moment the rebels noticed the Star of Death, it was located in the point A.
The rebels located n space mines along the Death Star's way. You may regard the mines as being idle. The Death Star does not know about the mines' existence and cannot notice them, which is why it doesn't change the direction of its movement. As soon as the Star of Death touched the mine (its body or one of the spikes), the mine bursts and destroys the Star of Death. A touching is the situation when there is a point in space which belongs both to the mine and to the Death Star. It is considered that Death Star will not be destroyed if it can move infinitely long time without touching the mines.
Help the rebels determine whether they will succeed in destroying the Death Star using space mines or not. If they will succeed, determine the moment of time when it will happen (starting from the moment the Death Star was noticed).
Input
The first input data line contains 7 integers Ax, Ay, Az, vx, vy, vz, R. They are the Death Star's initial position, the direction of its movement, and its radius ( - 10 β€ vx, vy, vz β€ 10, |v| > 0, 0 < R β€ 100).
The second line contains an integer n, which is the number of mines (1 β€ n β€ 100). Then follow n data blocks, the i-th of them describes the i-th mine.
The first line of each block contains 5 integers Oix, Oiy, Oiz, ri, mi, which are the coordinates of the mine centre, the radius of its body and the number of spikes (0 < ri < 100, 0 β€ mi β€ 10). Then follow mi lines, describing the spikes of the i-th mine, where the j-th of them describes the i-th spike and contains 3 integers pijx, pijy, pijz β the coordinates of the vector where the given spike is directed (<image>).
The coordinates of the mines' centers and the center of the Death Star are integers, their absolute value does not exceed 10000. It is guaranteed that R > ri for any 1 β€ i β€ n. For any mines i β j the following inequality if fulfilled: <image>. Initially the Death Star and the mines do not have common points.
Output
If the rebels will succeed in stopping the Death Star using space mines, print the time from the moment the Death Star was noticed to the blast.
If the Death Star will not touch a mine, print "-1" (without quotes).
For the answer the absolute or relative error of 10 - 6 is acceptable.
Examples
Input
0 0 0 1 0 0 5
2
10 8 0 2 2
0 -3 0
2 2 0
20 0 0 4 3
2 4 0
-4 3 0
1 -5 0
Output
10.0000000000
Input
8 8 4 4 4 2 6
1
-2 -2 -1 3 0
Output
-1
Input
30 30 2 1 2 1 20
3
0 0 40 5 1
1 4 4
-10 -40 -5 7 0
100 200 95 8 1
-10 0 0
Output
74.6757620881 | import sys, math
def dist(a,b):
return pow((a[0] - b[0])**2 + (a[1] - b[1])**2 + (a[2] - b[2])**2,0.5)
def vxv(v1,v2):
x = -v1[2] * v2[1] + v1[1] * v2[2]
y = -v1[0] * v2[2] + v1[2] * v2[0]
z = -v1[1] * v2[0] + v1[0] * v2[1]
return (x,y,z)
readline = sys.stdin.readline
s1,s2,s3,v1,v2,v3,R = map(int,readline().split())
n = int(readline())
pm = []
p = []
for _ in range(n):
o1,o2,o3,r,m = map(int,readline().split())
p.append((o1,o2,o3,r))
for _ in range(m):
pm1,pm2,pm3 = map(int,readline().split())
pm.append((pm1 + o1, pm2 + o2, pm3 + o3))
nv = (v1,v2,v3)
m = (s1,s2,s3)
distance = []
for x in pm:
tp = (x[0] - m[0], x[1] - m[1], x[2] - m[2])
tp1 = vxv(tp,nv)
d = dist(tp1,(0,0,0))/dist(nv,(0,0,0))
if d <= R:
dd = pow(dist(x,m)**2-d**2,0.5)
dnv = dist(nv, (0, 0, 0))
nnv = (dd * nv[0] / dnv + m[0], dd * nv[1] / dnv + m[1], dd * nv[2] / dnv + m[2])
if dist(nnv, x) < dist(x, m):
distance.append(dd - pow(R**2 - d**2,0.5))
for i in range(len(p)):
pi =(p[i][0],p[i][1],p[i][2])
tp = (pi[0] - m[0], pi[1] - m[1], pi[2] - m[2])
tp1 = vxv(tp,nv)
d = dist(tp1,(0,0,0))/dist(nv,(0,0,0))
if d - p[i][3] <= R:
dd = pow(dist(pi,m)**2-d**2,0.5)
dnv = dist(nv,(0,0,0))
nnv = (dd * nv[0]/dnv + m[0], dd * nv[1]/dnv + m[1],dd * nv[2]/dnv + m[2])
if dist(nnv,p[i]) < dist(p[i],m):
dr = pow((R + p[i][3])**2 - d**2,0.5)
distance.append(dd - dr)
if len(distance):
distance.sort()
print(distance[0]/dist(nv,(0,0,0)))
else:
print(-1)
| {
"input": [
"30 30 2 1 2 1 20\n3\n0 0 40 5 1\n1 4 4\n-10 -40 -5 7 0\n100 200 95 8 1\n-10 0 0\n",
"8 8 4 4 4 2 6\n1\n-2 -2 -1 3 0\n",
"0 0 0 1 0 0 5\n2\n10 8 0 2 2\n0 -3 0\n2 2 0\n20 0 0 4 3\n2 4 0\n-4 3 0\n1 -5 0\n"
],
"output": [
"74.6757620881\n",
"-1\n",
"9.9999999270\n"
]
} |
2,537 | 9 | You are given a sequence of integers of length n and integer number k. You should print any integer number x in the range of [1; 10^9] (i.e. 1 β€ x β€ 10^9) such that exactly k elements of given sequence are less than or equal to x.
Note that the sequence can contain equal elements.
If there is no such x, print "-1" (without quotes).
Input
The first line of the input contains integer numbers n and k (1 β€ n β€ 2 β
10^5, 0 β€ k β€ n). The second line of the input contains n integer numbers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the sequence itself.
Output
Print any integer number x from range [1; 10^9] such that exactly k elements of given sequence is less or equal to x.
If there is no such x, print "-1" (without quotes).
Examples
Input
7 4
3 7 5 1 10 3 20
Output
6
Input
7 2
3 7 5 1 10 3 20
Output
-1
Note
In the first example 5 is also a valid answer because the elements with indices [1, 3, 4, 6] is less than or equal to 5 and obviously less than or equal to 6.
In the second example you cannot choose any number that only 2 elements of the given sequence will be less than or equal to this number because 3 elements of the given sequence will be also less than or equal to this number. | def main():
n,k=map(int,input().split())
a=sorted(list(map(int,input().split())))
if k==0:
print(1 if a[0]!=1 else -1)
exit()
x=a[:k][-1]
print(x if a[k-1:].count(x)==1 else -1)
main() | {
"input": [
"7 4\n3 7 5 1 10 3 20\n",
"7 2\n3 7 5 1 10 3 20\n"
],
"output": [
"5\n",
"-1\n"
]
} |
2,538 | 7 | You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones.
Let's call a sequence of consecutive elements a_i, a_{i + 1}, β¦, a_j (1β€ iβ€ jβ€ n) a substring of string a.
You can apply the following operations any number of times:
* Choose some substring of string a (for example, you can choose entire string) and reverse it, paying x coins for it (for example, Β«0101101Β» β Β«0111001Β»);
* Choose some substring of string a (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones β by zeros), paying y coins for it (for example, Β«0101101Β» β Β«0110001Β»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones?
Input
The first line of input contains integers n, x and y (1 β€ n β€ 300 000, 0 β€ x, y β€ 10^9) β length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string a of length n, consisting of zeros and ones.
Output
Print a single integer β the minimum total cost of operations you need to spend to get a string consisting only of ones. Print 0, if you do not need to perform any operations.
Examples
Input
5 1 10
01000
Output
11
Input
5 10 1
01000
Output
2
Input
7 2 3
1111111
Output
0
Note
In the first sample, at first you need to reverse substring [1 ... 2], and then you need to invert substring [2 ... 5].
Then the string was changed as follows:
Β«01000Β» β Β«10000Β» β Β«11111Β».
The total cost of operations is 1 + 10 = 11.
In the second sample, at first you need to invert substring [1 ... 1], and then you need to invert substring [3 ... 5].
Then the string was changed as follows:
Β«01000Β» β Β«11000Β» β Β«11111Β».
The overall cost is 1 + 1 = 2.
In the third example, string already consists only of ones, so the answer is 0. | def scanf(t=int):
return list(map(t, input().split()))
n, x, y = scanf()
m = input()
p = m.count('10')
if m[0] == '0': p += 1
print(y + (p - 1) * min(x, y) if p else 0 ) | {
"input": [
"5 10 1\n01000\n",
"7 2 3\n1111111\n",
"5 1 10\n01000\n"
],
"output": [
"2\n",
"0\n",
"11\n"
]
} |
2,539 | 10 | A plane is flying at a constant height of h meters above the ground surface. Let's consider that it is flying from the point (-10^9, h) to the point (10^9, h) parallel with Ox axis.
A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only when the plane's coordinates are integers). After jumping from the plane, he will fly in the same direction as the plane, parallel to Ox axis, covering a unit of distance every second. Naturally, he will also descend; thus his second coordinate will decrease by one unit every second.
There are ascending air flows on certain segments, each such segment is characterized by two numbers x_1 and x_2 (x_1 < x_2) representing its endpoints. No two segments share any common points. When the glider is inside one of such segments, he doesn't descend, so his second coordinate stays the same each second. The glider still flies along Ox axis, covering one unit of distance every second.
<image> If the glider jumps out at 1, he will stop at 10. Otherwise, if he jumps out at 2, he will stop at 12.
Determine the maximum distance along Ox axis from the point where the glider's flight starts to the point where his flight ends if the glider can choose any integer coordinate to jump from the plane and start his flight. After touching the ground the glider stops altogether, so he cannot glide through an ascending airflow segment if his second coordinate is 0.
Input
The first line contains two integers n and h (1 β€ n β€ 2β
10^{5}, 1 β€ h β€ 10^{9}) β the number of ascending air flow segments and the altitude at which the plane is flying, respectively.
Each of the next n lines contains two integers x_{i1} and x_{i2} (1 β€ x_{i1} < x_{i2} β€ 10^{9}) β the endpoints of the i-th ascending air flow segment. No two segments intersect, and they are given in ascending order.
Output
Print one integer β the maximum distance along Ox axis that the glider can fly from the point where he jumps off the plane to the point where he lands if he can start his flight at any integer coordinate.
Examples
Input
3 4
2 5
7 9
10 11
Output
10
Input
5 10
5 7
11 12
16 20
25 26
30 33
Output
18
Input
1 1000000000
1 1000000000
Output
1999999999
Note
In the first example if the glider can jump out at (2, 4), then the landing point is (12, 0), so the distance is 12-2 = 10.
In the second example the glider can fly from (16,10) to (34,0), and the distance is 34-16=18.
In the third example the glider can fly from (-100,1000000000) to (1999999899,0), so the distance is 1999999899-(-100)=1999999999. | from copy import deepcopy
import itertools
from bisect import bisect_left
from bisect import bisect_right
import math
from collections import deque
from collections import Counter
def read():
return int(input())
def readmap():
return map(int, input().split())
def readlist():
return list(map(int, input().split()))
n, h = readmap()
seg = []
c, b = readmap()
seg.append((0, b-c))
for _ in range(n-1):
a, b = readmap()
seg.append((a-c, b-c))
cumu = [0] * n
for i in range(1, n):
cumu[i] = cumu[i-1] + seg[i][0] - seg[i-1][1]
ans = 0
for i in range(n):
idx = bisect_left(cumu, h + cumu[i])
if idx < n:
can = seg[idx][0] - (cumu[idx] - cumu[i] - h) - seg[i][0]
ans = max(ans, can)
else:
can = seg[-1][1] + (h - cumu[-1] + cumu[i]) - seg[i][0]
ans = max(ans, can)
print(ans)
| {
"input": [
"3 4\n2 5\n7 9\n10 11\n",
"1 1000000000\n1 1000000000\n",
"5 10\n5 7\n11 12\n16 20\n25 26\n30 33\n"
],
"output": [
"10\n",
"1999999999\n",
"18\n"
]
} |
2,540 | 9 | 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. | from collections import Counter
def go():
n = int(input())
c = Counter(input())
s = ''
for i in c:
s += i * c[i]
return s
print(go())
| {
"input": [
"16\ngagadbcgghhchbdf\n",
"5\noolol\n"
],
"output": [
"aabbccddfgggghhh\n",
"llooo\n"
]
} |
2,541 | 7 | The Squareland national forest is divided into equal 1 Γ 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner.
Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C in the forest. Initially, all plots in the forest (including the plots A, B, C) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots A, B, C from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side.
<image> For example, A=(0,0), B=(1,1), C=(2,2). The minimal number of plots to be cleared is 5. One of the ways to do it is shown with the gray color.
Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees.
Input
The first line contains two integers x_A and y_A β coordinates of the plot A (0 β€ x_A, y_A β€ 1000). The following two lines describe coordinates (x_B, y_B) and (x_C, y_C) of plots B and C respectively in the same format (0 β€ x_B, y_B, x_C, y_C β€ 1000). It is guaranteed that all three plots are distinct.
Output
On the first line print a single integer k β the smallest number of plots needed to be cleaned from trees. The following k lines should contain coordinates of all plots needed to be cleaned. All k plots should be distinct. You can output the plots in any order.
If there are multiple solutions, print any of them.
Examples
Input
0 0
1 1
2 2
Output
5
0 0
1 0
1 1
1 2
2 2
Input
0 0
2 0
1 1
Output
4
0 0
1 0
1 1
2 0
Note
The first example is shown on the picture in the legend.
The second example is illustrated with the following image:
<image> | def solve(x1, x2, y1, y2):
ans.add((x1, y1))
while x1 != x2 or y1 != y2:
if x1 < x2:
x1 += 1
ans.add((x1, y1))
elif x1 > x2:
x1 -= 1
ans.add((x1, y1))
if y1 < y2:
y1 += 1
ans.add((x1, y1))
elif y1 > y2:
y1 -= 1
ans.add((x1, y1))
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
x3, y3 = map(int, input().split())
ans = set()
x = sorted([x1, x2, x3])[1]
y = sorted([y1, y2, y3])[1]
solve(x, x1, y, y1)
solve(x, x2, y, y2)
solve(x, x3, y, y3)
print(len(ans))
for row in ans:
print(*row)
| {
"input": [
"0 0\n1 1\n2 2\n",
"0 0\n2 0\n1 1\n"
],
"output": [
"5\n0 0\n1 0\n1 1\n1 2\n2 2\n",
"4\n0 0\n1 0\n1 1\n2 0\n"
]
} |
2,542 | 7 | Lunar New Year is approaching, and you bought a matrix with lots of "crosses".
This matrix M of size n Γ n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 β€ i, j β€ n. We define a cross appearing in the i-th row and the j-th column (1 < i, j < n) if and only if M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = 'X'.
The following figure illustrates a cross appearing at position (2, 2) in a 3 Γ 3 matrix.
X.X
.X.
X.X
Your task is to find out the number of crosses in the given matrix M. Two crosses are different if and only if they appear in different rows or columns.
Input
The first line contains only one positive integer n (1 β€ n β€ 500), denoting the size of the matrix M.
The following n lines illustrate the matrix M. Each line contains exactly n characters, each of them is 'X' or '.'. The j-th element in the i-th line represents M(i, j), where 1 β€ i, j β€ n.
Output
Output a single line containing only one integer number k β the number of crosses in the given matrix M.
Examples
Input
5
.....
.XXX.
.XXX.
.XXX.
.....
Output
1
Input
2
XX
XX
Output
0
Input
6
......
X.X.X.
.X.X.X
X.X.X.
.X.X.X
......
Output
4
Note
In the first sample, a cross appears at (3, 3), so the answer is 1.
In the second sample, no crosses appear since n < 3, so the answer is 0.
In the third sample, crosses appear at (3, 2), (3, 4), (4, 3), (4, 5), so the answer is 4. | def A():
n = int(input())
m = [input() for _ in range(n)]
cnt = 0
for i in range(1,n-1):
for j in range(1,n-1):
if(m[i][j]==m[i-1][j-1]==m[i+1][j+1]==m[i-1][j+1]==m[i+1][j-1]=='X'):
cnt+=1
print(cnt)
A() | {
"input": [
"5\n.....\n.XXX.\n.XXX.\n.XXX.\n.....\n",
"6\n......\nX.X.X.\n.X.X.X\nX.X.X.\n.X.X.X\n......\n",
"2\nXX\nXX\n"
],
"output": [
"1",
"4",
"0"
]
} |
2,543 | 8 | International Women's Day is coming soon! Polycarp is preparing for the holiday.
There are n candy boxes in the shop for sale. The i-th box contains d_i candies.
Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β j) can be combined as a gift if d_i + d_j is divisible by k.
How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 2 β
10^5, 1 β€ k β€ 100) β the number the boxes and the number the girls.
The second line of the input contains n integers d_1, d_2, ..., d_n (1 β€ d_i β€ 10^9), where d_i is the number of candies in the i-th box.
Output
Print one integer β the maximum number of the boxes Polycarp can give as gifts.
Examples
Input
7 2
1 2 2 3 2 4 10
Output
6
Input
8 2
1 2 2 3 2 4 6 10
Output
8
Input
7 3
1 2 2 3 2 4 5
Output
4
Note
In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):
* (2, 3);
* (5, 6);
* (1, 4).
So the answer is 6.
In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):
* (6, 8);
* (2, 3);
* (1, 4);
* (5, 7).
So the answer is 8.
In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):
* (1, 2);
* (6, 7).
So the answer is 4. | def stdin():
return list(map(int, input().split()))
n, k = stdin()
candies = stdin()
count = [0] * k
for candie in candies:
count[candie%k]+=1
ans = 0
for i in range(k//2 + 1):
j = (k - i) % k
if i == j:
count[i] //= 2
ans += min(count[i], count[j])
print(ans*2)
| {
"input": [
"7 3\n1 2 2 3 2 4 5\n",
"8 2\n1 2 2 3 2 4 6 10\n",
"7 2\n1 2 2 3 2 4 10\n"
],
"output": [
"4\n",
"8\n",
"6\n"
]
} |
2,544 | 11 | This is an interactive problem.
Now Serval is a senior high school student in Japari Middle School. However, on the way to the school, he must go across a pond, in which there is a dangerous snake. The pond can be represented as a n Γ n grid. The snake has a head and a tail in different cells, and its body is a series of adjacent cells connecting the head and the tail without self-intersecting. If Serval hits its head or tail, the snake will bite him and he will die.
Luckily, he has a special device which can answer the following question: you can pick a rectangle, it will tell you the number of times one needs to cross the border of the rectangle walking cell by cell along the snake from the head to the tail. The pictures below show a possible snake and a possible query to it, which will get an answer of 4.
<image> <image>
Today Serval got up too late and only have time to make 2019 queries. As his best friend, can you help him find the positions of the head and the tail?
Note that two cells are adjacent if and only if they have a common edge in the grid, and a snake can have a body of length 0, that means it only has adjacent head and tail.
Also note that the snake is sleeping, so it won't move while Serval using his device. And what's obvious is that the snake position does not depend on your queries.
Input
The first line contains a single integer n (2β€ n β€ 1000) β the size of the grid.
Output
When you are ready to answer, you should print ! x1 y1 x2 y2, where (x_1, y_1) represents the position of the head and (x_2,y_2) represents the position of the tail. You can print head and tail in any order.
Interaction
To make a query, you should print ? x1 y1 x2 y2 (1 β€ x_1 β€ x_2 β€ n, 1β€ y_1 β€ y_2 β€ n), representing a rectangle consisting of all cells (x,y) such that x_1 β€ x β€ x_2 and y_1 β€ y β€ y_2. You will get a single integer as the answer.
After printing a query, do not forget to output the end of line and flush the output, otherwise you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Answer -1 instead of a valid answer means that you made an invalid query or exceeded the maximum number of queries. Exit immediately after receiving -1 and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
If your program cannot find out the head and tail of the snake correctly, you will also get a Wrong Answer verdict.
Hacks
To make a hack, print a single integer n (2 β€ n β€ 1000) in the first line, indicating the size of the grid.
Then print an integer k (2 β€ k β€ n^2) in the second line, indicating the length of the snake.
In the next k lines, print k pairs of integers x_i, y_i (1 β€ x_i, y_i β€ n), each pair in a single line, indicating the i-th cell of snake, such that the adjacent pairs are adjacent, and all k pairs are distinct.
Examples
Input
2
1
0
0
Output
? 1 1 1 1
? 1 2 1 2
? 2 2 2 2
! 1 1 2 1
Input
3
2
0
Output
? 2 2 2 2
? 2 1 2 3
! 2 1 2 3
Note
<image> <image> <image> <image>
The pictures above show our queries and the answers in the first example. We first made a query for (1,1) and got an answer 1, then found that it must be connected to exactly one other cell. Then we made a query for (1,2) and got an answer of 0, then knew that the snake never entered it. So the cell connected to (1,1) must be (2,1). Then we made a query for (2,2) and got an answer 0, then knew that it never entered (2,2) as well. So the snake cannot leave (2,1), which implies that the answer is (1,1) and (2,1).
<image> <image> <image>
The pictures above show our queries and the answers in the second example. By making query to (2,2) and receiving 2, we found that the snake occupies (2,2). And by making query to rectangle from (2,1) to (2,3) and receiving answer 0, we knew that it never goes out of the rectangle from (2,1) to (2,3). Since the first answer is 2, both (2,1) and (2,3) must be occupied but none of others, so the answer is (2,1) and (2,3). | # AC
import sys
class Main:
def __init__(self):
self.buff = None
self.index = 0
def next(self):
if self.buff is None or self.index == len(self.buff):
self.buff = sys.stdin.readline().split()
self.index = 0
val = self.buff[self.index]
self.index += 1
return val
def next_int(self):
return int(self.next())
def cal(self, s):
if len(s) == 1:
return s[0]
if s[0] == 0:
return self.cal(s[1:])
v = 1
for c in s:
v *= c
return v
def q(self, x1, y1, x2, y2):
print('? {} {} {} {}'.format(x1, y1, x2, y2))
sys.stdout.flush()
return self.next_int()
def ans(self, rs):
print('! {} {} {} {}'.format(rs[0][0], rs[0][1], rs[1][0], rs[1][1]))
sys.stdout.flush()
def f(self, c, n):
low = 1
high = n
while high > low:
mid = (high + low) // 2
if self.q(c, low, c, mid) % 2 == 1:
high = mid
else:
low = mid + 1
return c, low
def g(self, c, n):
low = 1
high = n
while high > low:
mid = (high + low) // 2
if self.q(low, c, mid, c) % 2 == 1:
high = mid
else:
low = mid + 1
return low, c
def solve(self):
n = self.next_int()
rs = []
for i in range(0, n):
if self.q(i + 1, 1, i + 1, n) % 2 == 1:
rs.append(self.f(i + 1, n))
if len(rs) == 2:
self.ans(rs)
return
for i in range(0, n - 1):
if self.q(1, i + 1, n, i + 1) % 2 == 1:
rs.append(self.g(i + 1, n))
if len(rs) == 2:
self.ans(rs)
return
rs.append(self.g(n, n))
if len(rs) == 2:
self.ans(rs)
if __name__ == '__main__':
Main().solve()
| {
"input": [
"3\n\n2\n\n0\n",
"2\n\n1\n\n0\n\n0\n"
],
"output": [
"? 1 1 1 3\n? 2 1 2 3\n? 3 1 3 3\n? 1 1 3 1\n? 1 2 3 2\n? 1 3 3 3\n? 1 0 2 0\n! 3 0 3 0\n",
"? 1 1 1 2\n? 1 1 1 1\n? 2 1 2 1\n! 1 2 2 2\n"
]
} |
2,545 | 10 | You are given an array a_1, a_2, ..., a_n and an integer k.
You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let f(i) be the index of subarray the i-th element belongs to. Subarrays are numbered from left to right and from 1 to k.
Let the cost of division be equal to β_{i=1}^{n} (a_i β
f(i)). For example, if a = [1, -2, -3, 4, -5, 6, -7] and we divide it into 3 subbarays in the following way: [1, -2, -3], [4, -5], [6, -7], then the cost of division is equal to 1 β
1 - 2 β
1 - 3 β
1 + 4 β
2 - 5 β
2 + 6 β
3 - 7 β
3 = -9.
Calculate the maximum cost you can obtain by dividing the array a into k non-empty consecutive subarrays.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 3 β
10^5).
The second line contains n integers a_1, a_2, ..., a_n ( |a_i| β€ 10^6).
Output
Print the maximum cost you can obtain by dividing the array a into k nonempty consecutive subarrays.
Examples
Input
5 2
-1 -2 5 -4 8
Output
15
Input
7 6
-3 0 -1 -2 -2 -4 -1
Output
-45
Input
4 1
3 -1 6 0
Output
8 | def gns():
return list(map(int,input().split()))
n,k=gns()
ns=gns()
sm=[ns[-1]]
for i in reversed(range(n-1)):
sm.append(sm[-1]+ns[i])
ans=sm.pop()
sm.sort()
if k>1:
ans+=sum(sm[-k+1:])
print(ans)
| {
"input": [
"4 1\n3 -1 6 0\n",
"7 6\n-3 0 -1 -2 -2 -4 -1\n",
"5 2\n-1 -2 5 -4 8\n"
],
"output": [
"8",
"-45",
"15"
]
} |
2,546 | 9 | You are given three strings s, t and p consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose any character from p, erase it from p and insert it into string s (you may insert this character anywhere you want: in the beginning of s, in the end or between any two consecutive characters).
For example, if p is aba, and s is de, then the following outcomes are possible (the character we erase from p and insert into s is highlighted):
* aba β ba, de β ade;
* aba β ba, de β dae;
* aba β ba, de β dea;
* aba β aa, de β bde;
* aba β aa, de β dbe;
* aba β aa, de β deb;
* aba β ab, de β ade;
* aba β ab, de β dae;
* aba β ab, de β dea;
Your goal is to perform several (maybe zero) operations so that s becomes equal to t. Please determine whether it is possible.
Note that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries. Each query is represented by three consecutive lines.
The first line of each query contains the string s (1 β€ |s| β€ 100) consisting of lowercase Latin letters.
The second line of each query contains the string t (1 β€ |t| β€ 100) consisting of lowercase Latin letters.
The third line of each query contains the string p (1 β€ |p| β€ 100) consisting of lowercase Latin letters.
Output
For each query print YES if it is possible to make s equal to t, and NO otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
Example
Input
4
ab
acxb
cax
a
aaaa
aaabbcc
a
aaaa
aabbcc
ab
baaa
aaaaa
Output
YES
YES
NO
NO
Note
In the first test case there is the following sequence of operation:
1. s = ab, t = acxb, p = cax;
2. s = acb, t = acxb, p = ax;
3. s = acxb, t = acxb, p = a.
In the second test case there is the following sequence of operation:
1. s = a, t = aaaa, p = aaabbcc;
2. s = aa, t = aaaa, p = aabbcc;
3. s = aaa, t = aaaa, p = abbcc;
4. s = aaaa, t = aaaa, p = bbcc. | def f():
s = input()
t = input()
p = input()
if s == t:
return True
it = iter(t)
if not all(c in it for c in s):
return False
d = [0] * 256
for c in s:
d[ord(c)] += 1
for c in p:
d[ord(c)] += 1
for c in t:
d[ord(c)] -= 1
if d[ord(c)] < 0:
return False
return True
for i in range(int(input())):
print('yes' if f() else 'no')
| {
"input": [
"4\nab\nacxb\ncax\na\naaaa\naaabbcc\na\naaaa\naabbcc\nab\nbaaa\naaaaa\n"
],
"output": [
"Yes\nYes\nNo\nNo\n"
]
} |
2,547 | 8 | There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland β they are held in two different cities a and b (1 β€ a, b β€ n; a β b).
Find the number of pairs of cities x and y (x β a, x β b, y β a, y β b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 β€ t β€ 4β
10^4) β the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 β€ n β€ 2β
10^5, n - 1 β€ m β€ 5β
10^5, 1 β€ a,b β€ n, a β b) β numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) β numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2β
10^5. The sum of the values of m for all sets of input data in the test does not exceed 5β
10^5.
Output
Print t integers β the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1 | import sys
input = sys.stdin.readline
def dfs(g, i, e, n):
vis = [0]*(n+1)
s = [i]
ans=set()
while len(s)>0:
top = s[-1]
s.pop()
if vis[top]==1 or top==e:
continue
vis[top]=1
ans.add(top)
for j in g[top]:
s.append(j)
return ans
t = int(input())
for _ in range(t):
n,m,a,b = map(int, input().split())
g = [[] for i in range(n+1)]
for i in range(m):
x,y = map(int, input().split())
g[x].append(y)
g[y].append(x)
seta = dfs(g, a, b, n)
setb = dfs(g, b, a, n)
inter = seta.intersection(setb)
seta = seta-inter
setb = setb-inter
print((len(seta)-1)*(len(setb)-1)) | {
"input": [
"3\n7 7 3 5\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 5\n4 5 2 3\n1 2\n2 3\n3 4\n4 1\n4 2\n4 3 2 1\n1 2\n2 3\n4 1\n"
],
"output": [
"4\n0\n1\n"
]
} |
2,548 | 9 | There is a robot on a coordinate plane. Initially, the robot is located at the point (0, 0). Its path is described as a string s of length n consisting of characters 'L', 'R', 'U', 'D'.
Each of these characters corresponds to some move:
* 'L' (left): means that the robot moves from the point (x, y) to the point (x - 1, y);
* 'R' (right): means that the robot moves from the point (x, y) to the point (x + 1, y);
* 'U' (up): means that the robot moves from the point (x, y) to the point (x, y + 1);
* 'D' (down): means that the robot moves from the point (x, y) to the point (x, y - 1).
The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (x_e, y_e), then after optimization (i.e. removing some single substring from s) the robot also ends its path at the point (x_e, y_e).
This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string s).
Recall that the substring of s is such string that can be obtained from s by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The next 2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the length of the robot's path. The second line of the test case contains one string s consisting of n characters 'L', 'R', 'U', 'D' β the robot's path.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers l and r such that 1 β€ l β€ r β€ n β endpoints of the substring you remove. The value r-l+1 should be minimum possible. If there are several answers, print any of them.
Example
Input
4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
Output
1 2
1 4
3 4
-1 | def cal(x,y):
return x*47196412+y
def rua():
mp={}
n=int(input())
s=input()
ans=n+1
x=0
y=0
s1=-1
s2=-1
l=cal(x,y)
mp[l]=1
i=0
for j in s:
i=i+1
if(j=='U'):
y=y+1
elif(j=='D'):
y=y-1
elif(j=='L'):
x=x-1
elif(j=='R'):
x=x+1
l=cal(x,y)
if(l in mp):
tmp=i+1-mp[l]
if(tmp<ans):
ans=tmp
s1=mp[l]
s2=i
mp[l]=i+1
if(ans==n+1):
print(-1)
else:
print(s1,s2)
t=int(input())
while(t):
rua()
t=t-1 | {
"input": [
"4\n4\nLRUD\n4\nLURD\n5\nRRUDU\n5\nLLDDR\n"
],
"output": [
"1 2\n1 4\n3 4\n-1\n"
]
} |
2,549 | 9 | There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the troupe are considered different.
Perform all calculations in the 64-bit type: long long for Π‘/Π‘++, int64 for Delphi and long for Java.
Input
The only line of the input data contains three integers n, m, t (4 β€ n β€ 30, 1 β€ m β€ 30, 5 β€ t β€ n + m).
Output
Find the required number of ways.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5 2 5
Output
10
Input
4 3 5
Output
3 | from math import factorial as f
def C(x,y):
return f(x) // (f(y)*f(max(x-y,0)))
n,m,t=map(int, input().split())
print(int(sum(C(n,i)*C(m,t-i) for i in range(4,t)))) | {
"input": [
"5 2 5\n",
"4 3 5\n"
],
"output": [
"10",
"3"
]
} |
2,550 | 10 | Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 β€ i β€ k). The store has an infinite number of packages of each type.
Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels?
For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels.
Help Polycarp find the minimum number of packages that he needs to buy, given that he:
* will buy exactly n shovels in total;
* the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive.
Input
The first line contains an integer t (1 β€ t β€ 100) β the number of test cases in the input. Then, t test cases follow, one per line.
Each test case consists of two positive integers n (1 β€ n β€ 10^9) and k (1 β€ k β€ 10^9) β the number of shovels and the number of types of packages.
Output
Print t answers to the test cases. Each answer is a positive integer β the minimum number of packages.
Example
Input
5
8 7
8 1
6 10
999999733 999999732
999999733 999999733
Output
2
8
1
999999733
1
Note
The answer to the first test case was explained in the statement.
In the second test case, there is only one way to buy 8 shovels β 8 packages of one shovel.
In the third test case, you need to buy a 1 package of 6 shovels. | def calc(n,k):
res=int(1e12)
for i in range(1,int(round(n**0.5))+1):
if n%i==0:
if i<=k:
res=min(res,n//i)
if n//i<=k:
res=min(res,i)
return res
t=int(input())
for i in range(t):
n,k=[int(i) for i in input().split()]
print(calc(n,k)) | {
"input": [
"5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733\n"
],
"output": [
"2\n8\n1\n999999733\n1\n"
]
} |
2,551 | 11 | You have a set of n discs, the i-th disc has radius i. Initially, these discs are split among m towers: each tower contains at least one disc, and the discs in each tower are sorted in descending order of their radii from bottom to top.
You would like to assemble one tower containing all of those discs. To do so, you may choose two different towers i and j (each containing at least one disc), take several (possibly all) top discs from the tower i and put them on top of the tower j in the same order, as long as the top disc of tower j is bigger than each of the discs you move. You may perform this operation any number of times.
For example, if you have two towers containing discs [6, 4, 2, 1] and [8, 7, 5, 3] (in order from bottom to top), there are only two possible operations:
* move disc 1 from the first tower to the second tower, so the towers are [6, 4, 2] and [8, 7, 5, 3, 1];
* move discs [2, 1] from the first tower to the second tower, so the towers are [6, 4] and [8, 7, 5, 3, 2, 1].
Let the difficulty of some set of towers be the minimum number of operations required to assemble one tower containing all of the discs. For example, the difficulty of the set of towers [[3, 1], [2]] is 2: you may move the disc 1 to the second tower, and then move both discs from the second tower to the first tower.
You are given m - 1 queries. Each query is denoted by two numbers a_i and b_i, and means "merge the towers a_i and b_i" (that is, take all discs from these two towers and assemble a new tower containing all of them in descending order of their radii from top to bottom). The resulting tower gets index a_i.
For each k β [0, m - 1], calculate the difficulty of the set of towers after the first k queries are performed.
Input
The first line of the input contains two integers n and m (2 β€ m β€ n β€ 2 β
10^5) β the number of discs and the number of towers, respectively.
The second line contains n integers t_1, t_2, ..., t_n (1 β€ t_i β€ m), where t_i is the index of the tower disc i belongs to. Each value from 1 to m appears in this sequence at least once.
Then m - 1 lines follow, denoting the queries. Each query is represented by two integers a_i and b_i (1 β€ a_i, b_i β€ m, a_i β b_i), meaning that, during the i-th query, the towers with indices a_i and b_i are merged (a_i and b_i are chosen in such a way that these towers exist before the i-th query).
Output
Print m integers. The k-th integer (0-indexed) should be equal to the difficulty of the set of towers after the first k queries are performed.
Example
Input
7 4
1 2 3 3 1 4 3
3 1
2 3
2 4
Output
5
4
2
0
Note
The towers in the example are:
* before the queries: [[5, 1], [2], [7, 4, 3], [6]];
* after the first query: [[2], [7, 5, 4, 3, 1], [6]];
* after the second query: [[7, 5, 4, 3, 2, 1], [6]];
* after the third query, there is only one tower: [7, 6, 5, 4, 3, 2, 1]. | def get_ints():return map(int, input().split())
def main():
_, m = get_ints();s = [set() for _ in range(m)];prev, score = -1, -1
for index, dest in enumerate(get_ints()):
s[dest - 1].add(index)
if prev != dest: score += 1
prev = dest
ans = [score]
for _ in range(m - 1):
x, y = get_ints();x, y = x - 1, y - 1;target = x
if len(s[x]) < len(s[y]): x, y = y, x
for e in s[y]:
if e - 1 in s[x]: score -= 1
if e + 1 in s[x]: score -= 1
for e in s[y]:s[x].add(e)
s[target] = s[x];ans.append(score)
print(*ans, sep='\n')
main() | {
"input": [
"7 4\n1 2 3 3 1 4 3\n3 1\n2 3\n2 4\n"
],
"output": [
"5\n4\n2\n0\n"
]
} |
2,552 | 11 | You have a multiset containing several integers. Initially, it contains a_1 elements equal to 1, a_2 elements equal to 2, ..., a_n elements equal to n.
You may apply two types of operations:
* choose two integers l and r (l β€ r), then remove one occurrence of l, one occurrence of l + 1, ..., one occurrence of r from the multiset. This operation can be applied only if each number from l to r occurs at least once in the multiset;
* choose two integers i and x (x β₯ 1), then remove x occurrences of i from the multiset. This operation can be applied only if the multiset contains at least x occurrences of i.
What is the minimum number of operations required to delete all elements from the multiset?
Input
The first line contains one integer n (1 β€ n β€ 5000).
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10^9).
Output
Print one integer β the minimum number of operations required to delete all elements from the multiset.
Examples
Input
4
1 4 1 1
Output
2
Input
5
1 0 1 0 1
Output
3 | import sys
sys.setrecursionlimit(10000)
n = int(input())
a = list(map(int, input().split()))
def f(l, r, h):
if l >= r:
return 0
x = a.index(min(a[l:r]), l, r)
return min(r - l, a[x] - h + f(l, x, a[x]) + f(x + 1, r, a[x]))
print(f(0, n, 0)) | {
"input": [
"4\n1 4 1 1\n",
"5\n1 0 1 0 1\n"
],
"output": [
"2\n",
"3\n"
]
} |
2,553 | 7 | You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i β€ x holds for each i (1 β€ i β€ n).
Input
The first line of input contains one integer t (1 β€ t β€ 100) β the number of test cases. t blocks follow, each describing an individual test case.
The first line of each test case contains two integers n and x (1 β€ n β€ 50; 1 β€ x β€ 1000) β the length of arrays a and b, and the parameter x, described in the problem statement.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_1 β€ a_2 β€ ... β€ a_n β€ x) β the elements of array a in non-descending order.
The third line of each test case contains n integers b_1, b_2, β¦, b_n (1 β€ b_1 β€ b_2 β€ ... β€ b_n β€ x) β the elements of array b in non-descending order.
Test cases are separated by a blank line.
Output
For each test case print Yes if one can rearrange the corresponding array b so that a_i + b_i β€ x holds for each i (1 β€ i β€ n) or No otherwise.
Each character can be printed in any case.
Example
Input
4
3 4
1 2 3
1 1 2
2 6
1 4
2 5
4 4
1 2 3 4
1 2 3 4
1 5
5
5
Output
Yes
Yes
No
No
Note
In the first test case, one can rearrange b so it'll look like [1, 2, 1]. In this case, 1 + 1 β€ 4; 2 + 2 β€ 4; 3 + 1 β€ 4.
In the second test case, one can set b to [5, 2], then 1 + 5 β€ 6; 4 + 2 β€ 6.
In the third test case, no matter how one shuffles array b, a_4 + b_4 = 4 + b_4 > 4.
In the fourth test case, there is only one rearrangement of array b and it doesn't satisfy the condition since 5 + 5 > 5. | def f():
for i in range(b):
if l[i]+q[b-i-1]>c:return 1
return 0
a=int(input())
for x in range(a):
b,c=map(int,input().split())
l=list(map(int,input().split()))
q=list(map(int,input().split()))
if f()==0:print("Yes")
else:print("No")
if a-1>x:input() | {
"input": [
"4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5\n"
],
"output": [
"YES\nYES\nNO\nNO\n"
]
} |
2,554 | 7 | Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals n (n is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first n / 2 digits) equals the sum of digits in the second half (the sum of the last n / 2 digits). Check if the given ticket is lucky.
Input
The first line contains an even integer n (2 β€ n β€ 50) β the length of the ticket number that needs to be checked. The second line contains an integer whose length equals exactly n β the ticket number. The number may contain leading zeros.
Output
On the first line print "YES" if the given ticket number is lucky. Otherwise, print "NO" (without the quotes).
Examples
Input
2
47
Output
NO
Input
4
4738
Output
NO
Input
4
4774
Output
YES
Note
In the first sample the sum of digits in the first half does not equal the sum of digits in the second half (4 β 7).
In the second sample the ticket number is not the lucky number. | from sys import stdin
def main():
n = int(stdin.readline().strip()) // 2
l = list(map(int, stdin.readline().strip()))
return ('NO', 'YES')[sum(l[:n]) == sum(l[n:]) and all(c in (4, 7) for c in l)]
print(main())
| {
"input": [
"4\n4738\n",
"2\n47\n",
"4\n4774\n"
],
"output": [
"NO",
"NO",
"YES"
]
} |
2,555 | 9 | There are many sunflowers in the Garden of the Sun.
Garden of the Sun is a rectangular table with n rows and m columns, where the cells of the table are farmlands. All of the cells grow a sunflower on it. Unfortunately, one night, the lightning stroke some (possibly zero) cells, and sunflowers on those cells were burned into ashes. In other words, those cells struck by the lightning became empty. Magically, any two empty cells have no common points (neither edges nor corners).
Now the owner wants to remove some (possibly zero) sunflowers to reach the following two goals:
* When you are on an empty cell, you can walk to any other empty cell. In other words, those empty cells are connected.
* There is exactly one simple path between any two empty cells. In other words, there is no cycle among the empty cells.
You can walk from an empty cell to another if they share a common edge.
Could you please give the owner a solution that meets all her requirements?
Note that you are not allowed to plant sunflowers. You don't need to minimize the number of sunflowers you remove. It can be shown that the answer always exists.
Input
The input consists of multiple test cases. The first line contains a single integer t (1β€ tβ€ 10^4) β the number of test cases. The description of the test cases follows.
The first line contains two integers n, m (1 β€ n,m β€ 500) β the number of rows and columns.
Each of the next n lines contains m characters. Each character is either 'X' or '.', representing an empty cell and a cell that grows a sunflower, respectively.
It is guaranteed that the sum of n β
m for all test cases does not exceed 250 000.
Output
For each test case, print n lines. Each should contain m characters, representing one row of the table. Each character should be either 'X' or '.', representing an empty cell and a cell with a sunflower, respectively.
If there are multiple answers, you can print any. It can be shown that the answer always exists.
Example
Input
5
3 3
X.X
...
X.X
4 4
....
.X.X
....
.X.X
5 5
.X...
....X
.X...
.....
X.X.X
1 10
....X.X.X.
2 2
..
..
Output
XXX
..X
XXX
XXXX
.X.X
.X..
.XXX
.X...
.XXXX
.X...
.X...
XXXXX
XXXXXXXXXX
..
..
Note
Let's use (x,y) to describe the cell on x-th row and y-th column.
In the following pictures white, yellow, and blue cells stand for the cells that grow a sunflower, the cells lightning stroke, and the cells sunflower on which are removed, respectively.
<image>
In the first test case, one possible solution is to remove sunflowers on (1,2), (2,3) and (3 ,2).
<image>
Another acceptable solution is to remove sunflowers on (1,2), (2,2) and (3,2).
<image>
This output is considered wrong because there are 2 simple paths between any pair of cells (there is a cycle). For example, there are 2 simple paths between (1,1) and (3,3).
1. (1,1)β (1,2)β (1,3)β (2,3)β (3,3)
2. (1,1)β (2,1)β (3,1)β (3,2)β (3,3)
<image>
This output is considered wrong because you can't walk from (1,1) to (3,3). | from sys import stdin,stderr
def rl():
return [int(w) for w in stdin.readline().split()]
t, = rl()
for _ in range(t):
n,m = rl()
a = [[c for c in stdin.readline().rstrip()] for _ in range(n)]
base = 0 if n % 3 == 1 else 1
for y in range(n):
if y % 3 == base:
a[y] = ['X'] * m
else:
if (y - base) % 3 == 1:
y2 = y + 1
else:
y2 = y - 1
if m > 1 and (a[y][1] == 'X' or (y2 >= 0 and y2 <= n-1 and a[y2][1] == 'X')):
a[y][1] = 'X'
else:
a[y][0] = 'X'
for line in a:
print(''.join(line))
| {
"input": [
"5\n3 3\nX.X\n...\nX.X\n4 4\n....\n.X.X\n....\n.X.X\n5 5\n.X...\n....X\n.X...\n.....\nX.X.X\n1 10\n....X.X.X.\n2 2\n..\n..\n"
],
"output": [
"\nXXX\n..X\nXXX\nXXXX\n.X.X\n.X..\n.XXX\n.X...\n.XXXX\n.X...\n.X...\nXXXXX\nXXXXXXXXXX\n..\n..\n"
]
} |
2,556 | 7 | Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. | def co(x,y,s):
if x==y:return 0
z=(x=="P" and y=="R") or (x=="S" and y=="P") or (x=="R" and y=="S")
if s:return int(z)
return int(not z)
from math import gcd as gh
a=int(input());b=input();c=input()
b1=len(b);c1=len(c)
z=((b1*c1)//gh(b1,c1))
w=[0]*(z+1);w1=[0]*(z+1)
for i in range(1,z+1):
w[i]=co(b[(i-1)%b1],c[(i-1)%c1],0)+w[i-1]
w1[i]=co(b[(i-1)%b1],c[(i-1)%c1],1)+w1[i-1]
print(w[-1]*(a//z)+w[a%z],w1[-1]*(a//z)+w1[a%z]) | {
"input": [
"7\nRPS\nRSPP\n",
"5\nRRRRRRRR\nR\n"
],
"output": [
"3 2",
"0 0"
]
} |
2,557 | 7 | There are n cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as c1, c2, ..., cn. The Old Peykan wants to travel from city c1 to cn using roads. There are (n - 1) one way roads, the i-th road goes from city ci to city ci + 1 and is di kilometers long.
The Old Peykan travels 1 kilometer in 1 hour and consumes 1 liter of fuel during this time.
Each city ci (except for the last city cn) has a supply of si liters of fuel which immediately transfers to the Old Peykan if it passes the city or stays in it. This supply refreshes instantly k hours after it transfers. The Old Peykan can stay in a city for a while and fill its fuel tank many times.
Initially (at time zero) the Old Peykan is at city c1 and s1 liters of fuel is transferred to it's empty tank from c1's supply. The Old Peykan's fuel tank capacity is unlimited. Old Peykan can not continue its travel if its tank is emptied strictly between two cities.
Find the minimum time the Old Peykan needs to reach city cn.
Input
The first line of the input contains two space-separated integers m and k (1 β€ m, k β€ 1000). The value m specifies the number of roads between cities which is equal to n - 1.
The next line contains m space-separated integers d1, d2, ..., dm (1 β€ di β€ 1000) and the following line contains m space-separated integers s1, s2, ..., sm (1 β€ si β€ 1000).
Output
In the only line of the output print a single integer β the minimum time required for The Old Peykan to reach city cn from city c1.
Examples
Input
4 6
1 2 5 2
2 3 3 4
Output
10
Input
2 3
5 6
5 5
Output
14
Note
In the second sample above, the Old Peykan stays in c1 for 3 hours. | def main():
import sys
input = sys.stdin.readline
m, k = map(int, input().split())
d = list(map(int, input().split()))
s = list(map(int, input().split()))
t = 0
f = 0
ma = 0
for i in range(m):
f += s[i]
ma = max(ma, s[i])
while f < d[i]:
f += ma
t += k
t += d[i]
f -= d[i]
print(t)
return 0
main()
| {
"input": [
"4 6\n1 2 5 2\n2 3 3 4\n",
"2 3\n5 6\n5 5\n"
],
"output": [
"10\n",
"14\n"
]
} |
2,558 | 11 | Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.
For permutation p = p0, p1, ..., pn, Polo has defined its beauty β number <image>.
Expression <image> means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as "^" and in Pascal β as "xor".
Help him find among all permutations of integers from 0 to n the permutation with the maximum beauty.
Input
The single line contains a positive integer n (1 β€ n β€ 106).
Output
In the first line print integer m the maximum possible beauty. In the second line print any permutation of integers from 0 to n with the beauty equal to m.
If there are several suitable permutations, you are allowed to print any of them.
Examples
Input
4
Output
20
0 2 1 4 3 | import math
def ones(n):
number_of_bits = (int)(math.floor(math.log(n) /
math.log(2))) + 1;
return [((1 << number_of_bits) - 1) ^ n,(1 << number_of_bits) - 1];
n = int(input())
has=[0]*(n+1)
ans=[0]*(n+1)
fin=0
for i in range(n,0,-1):
if has[i]==0:
com,fi = ones(i)
# print(com,fi,i)
has[com]=1
fin+=2*fi
ans[com]=i
ans[i]=com
print(fin)
print(*ans)
| {
"input": [
"4\n"
],
"output": [
"20\n0 2 1 4 3\n"
]
} |
2,559 | 8 | Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the screen as possible and fits within it completely. Thus, he may have to zoom the movie in or out, but Manao will always change the frame proportionally in both dimensions.
Calculate the ratio of empty screen (the part of the screen not occupied by the movie) to the total screen size. Print the answer as an irreducible fraction p / q.
Input
A single line contains four space-separated integers a, b, c, d (1 β€ a, b, c, d β€ 1000).
Output
Print the answer to the problem as "p/q", where p is a non-negative integer, q is a positive integer and numbers p and q don't have a common divisor larger than 1.
Examples
Input
1 1 3 2
Output
1/3
Input
4 3 2 2
Output
1/4
Note
Sample 1. Manao's monitor has a square screen. The movie has 3:2 horizontal to vertical length ratio. Obviously, the movie occupies most of the screen if the width of the picture coincides with the width of the screen. In this case, only 2/3 of the monitor will project the movie in the horizontal dimension: <image>
Sample 2. This time the monitor's width is 4/3 times larger than its height and the movie's frame is square. In this case, the picture must take up the whole monitor in the vertical dimension and only 3/4 in the horizontal dimension: <image> | def hcf(a,b):
if(b==0):
return a
else:
return hcf(b,a%b)
a,b,c,d=map(int,input().split())
b*=c
d*=a
e=abs(b-d)
f=max(b,d)
g=hcf(e,f)
e//=g
f//=g
print(e,'/',f,sep='') | {
"input": [
"1 1 3 2\n",
"4 3 2 2\n"
],
"output": [
"1/3\n",
"1/4\n"
]
} |
2,560 | 8 | Iahub got lost in a very big desert. The desert can be represented as a n Γ n square matrix, where each cell is a zone of the desert. The cell (i, j) represents the cell at row i and column j (1 β€ i, j β€ n). Iahub can go from one cell (i, j) only down or right, that is to cells (i + 1, j) or (i, j + 1).
Also, there are m cells that are occupied by volcanoes, which Iahub cannot enter.
Iahub is initially at cell (1, 1) and he needs to travel to cell (n, n). Knowing that Iahub needs 1 second to travel from one cell to another, find the minimum time in which he can arrive in cell (n, n).
Input
The first line contains two integers n (1 β€ n β€ 109) and m (1 β€ m β€ 105). Each of the next m lines contains a pair of integers, x and y (1 β€ x, y β€ n), representing the coordinates of the volcanoes.
Consider matrix rows are numbered from 1 to n from top to bottom, and matrix columns are numbered from 1 to n from left to right. There is no volcano in cell (1, 1). No two volcanoes occupy the same location.
Output
Print one integer, the minimum time in which Iahub can arrive at cell (n, n). If no solution exists (there is no path to the final cell), print -1.
Examples
Input
4 2
1 3
1 4
Output
6
Input
7 8
1 6
2 6
3 5
3 6
4 3
5 1
5 2
5 3
Output
12
Input
2 2
1 2
2 1
Output
-1
Note
Consider the first sample. A possible road is: (1, 1) β (1, 2) β (2, 2) β (2, 3) β (3, 3) β (3, 4) β (4, 4). | from collections import defaultdict
def f(u, v):
s, l = [], len(v)
i = j = 0
for i in range(len(u)):
while v[j][1] <= u[i][0]:
j += 1
if j == l: return s
if u[i][1] <= v[j][0]: continue
if u[i][0] >= v[j][0]: s.append(u[i])
else: s.append((v[j][0], u[i][1]))
return s
n, m = map(int, input().split())
p = defaultdict(list)
for i in range(m):
x, y = map(int, input().split())
p[x].append(y)
for x in p:
if len(p[x]) > 1: p[x].sort()
t, i = [], 1
for j in p[x]:
if i != j: t.append((i, j))
i = j + 1
if i != n + 1: t.append((i, n + 1))
p[x] = t
k, s = 1, [(1, 2)]
for x in sorted(p.keys()):
if x == k: s = f(p[x], s)
else: s = f(p[x], [(s[0][0], n + 1)])
if not s: break
k = x + 1
if s and k == n + 1 and s[-1][1] != k: s = []
print(2 * (n - 1) if s else -1) | {
"input": [
"2 2\n1 2\n2 1\n",
"4 2\n1 3\n1 4\n",
"7 8\n1 6\n2 6\n3 5\n3 6\n4 3\n5 1\n5 2\n5 3\n"
],
"output": [
"-1\n",
"6\n",
"12\n"
]
} |
2,561 | 7 | Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.
Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:
* on both diagonals of the square paper all letters are the same;
* all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals.
Help Valera, write the program that completes the described task for him.
Input
The first line contains integer n (3 β€ n < 300; n is odd). Each of the next n lines contains n small English letters β the description of Valera's paper.
Output
Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes.
Examples
Input
5
xooox
oxoxo
soxoo
oxoxo
xooox
Output
NO
Input
3
wsw
sws
wsw
Output
YES
Input
3
xpx
pxp
xpe
Output
NO | n = int(input())
a = [input() for i in range(n)]
def main():
x, y = a[0][0], a[0][1]
if x == y:
return "NO"
for i in range(n):
for j in range(n):
if (i == j and a[i][j] != x or i+j+1 == n and a[i][j] != x or
i != j and i+j+1 != n and a[i][j] != y):
return "NO"
return "YES"
print(main()) | {
"input": [
"5\nxooox\noxoxo\nsoxoo\noxoxo\nxooox\n",
"3\nwsw\nsws\nwsw\n",
"3\nxpx\npxp\nxpe\n"
],
"output": [
"NO\n",
"YES\n",
"NO\n"
]
} |
2,562 | 8 | Many students live in a dormitory. A dormitory is a whole new world of funny amusements and possibilities but it does have its drawbacks.
There is only one shower and there are multiple students who wish to have a shower in the morning. That's why every morning there is a line of five people in front of the dormitory shower door. As soon as the shower opens, the first person from the line enters the shower. After a while the first person leaves the shower and the next person enters the shower. The process continues until everybody in the line has a shower.
Having a shower takes some time, so the students in the line talk as they wait. At each moment of time the students talk in pairs: the (2i - 1)-th man in the line (for the current moment) talks with the (2i)-th one.
Let's look at this process in more detail. Let's number the people from 1 to 5. Let's assume that the line initially looks as 23154 (person number 2 stands at the beginning of the line). Then, before the shower opens, 2 talks with 3, 1 talks with 5, 4 doesn't talk with anyone. Then 2 enters the shower. While 2 has a shower, 3 and 1 talk, 5 and 4 talk too. Then, 3 enters the shower. While 3 has a shower, 1 and 5 talk, 4 doesn't talk to anyone. Then 1 enters the shower and while he is there, 5 and 4 talk. Then 5 enters the shower, and then 4 enters the shower.
We know that if students i and j talk, then the i-th student's happiness increases by gij and the j-th student's happiness increases by gji. Your task is to find such initial order of students in the line that the total happiness of all students will be maximum in the end. Please note that some pair of students may have a talk several times. In the example above students 1 and 5 talk while they wait for the shower to open and while 3 has a shower.
Input
The input consists of five lines, each line contains five space-separated integers: the j-th number in the i-th line shows gij (0 β€ gij β€ 105). It is guaranteed that gii = 0 for all i.
Assume that the students are numbered from 1 to 5.
Output
Print a single integer β the maximum possible total happiness of the students.
Examples
Input
0 0 0 0 9
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
7 0 0 0 0
Output
32
Input
0 43 21 18 2
3 0 21 11 65
5 2 0 1 4
54 62 12 0 99
87 64 81 33 0
Output
620
Note
In the first sample, the optimal arrangement of the line is 23154. In this case, the total happiness equals:
(g23 + g32 + g15 + g51) + (g13 + g31 + g54 + g45) + (g15 + g51) + (g54 + g45) = 32. | from itertools import permutations as p
z=[list(map(int,input().split())) for _ in " "*5]
def function(z,k):
p=0
if len(k)==1:return 0
for i in range(0,len(k)-1,2):p+=z[k[i]][k[i+1]]+z[k[i+1]][k[i]]
k.pop(0)
return p+function(z, k)
print(max(function(z,list(i)) for i in list(p([*range(5)],5)))) | {
"input": [
"0 0 0 0 9\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n7 0 0 0 0\n",
"0 43 21 18 2\n3 0 21 11 65\n5 2 0 1 4\n54 62 12 0 99\n87 64 81 33 0\n"
],
"output": [
"32\n",
"620\n"
]
} |
2,563 | 8 | Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.
Each command is one of the following two types:
1. Go 1 unit towards the positive direction, denoted as '+'
2. Go 1 unit towards the negative direction, denoted as '-'
But the Wi-Fi condition is so poor that Dreamoon's smartphone reports some of the commands can't be recognized and Dreamoon knows that some of them might even be wrong though successfully recognized. Dreamoon decides to follow every recognized command and toss a fair coin to decide those unrecognized ones (that means, he moves to the 1 unit to the negative or positive direction with the same probability 0.5).
You are given an original list of commands sent by Drazil and list received by Dreamoon. What is the probability that Dreamoon ends in the position originally supposed to be final by Drazil's commands?
Input
The first line contains a string s1 β the commands Drazil sends to Dreamoon, this string consists of only the characters in the set {'+', '-'}.
The second line contains a string s2 β the commands Dreamoon's smartphone recognizes, this string consists of only the characters in the set {'+', '-', '?'}. '?' denotes an unrecognized command.
Lengths of two strings are equal and do not exceed 10.
Output
Output a single real number corresponding to the probability. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9.
Examples
Input
++-+-
+-+-+
Output
1.000000000000
Input
+-+-
+-??
Output
0.500000000000
Input
+++
??-
Output
0.000000000000
Note
For the first sample, both s1 and s2 will lead Dreamoon to finish at the same position + 1.
For the second sample, s1 will lead Dreamoon to finish at position 0, while there are four possibilites for s2: {"+-++", "+-+-", "+--+", "+---"} with ending position {+2, 0, 0, -2} respectively. So there are 2 correct cases out of 4, so the probability of finishing at the correct position is 0.5.
For the third sample, s2 could only lead us to finish at positions {+1, -1, -3}, so the probability to finish at the correct position + 3 is 0. | def gh(x):return x.count("+")-x.count("-")
a=input();b=input()
a1=gh(a);b1=gh(b);c=b.count("?");n=0
for i in range(1<<c):
s=0
for j in range(c):s+=-1 if i&(1<<j) else 1
if a1==b1+s:n+=1
print(round(n/(1<<c),9)) | {
"input": [
"++-+-\n+-+-+\n",
"+++\n??-\n",
"+-+-\n+-??\n"
],
"output": [
"1.000000000\n",
"0.000000000\n",
"0.500000000\n"
]
} |
2,564 | 9 | Vasya bought the collected works of a well-known Berland poet Petya in n volumes. The volumes are numbered from 1 to n. He thinks that it does not do to arrange the book simply according to their order. Vasya wants to minimize the number of the dispositionβs divisors β the positive integers i such that for at least one j (1 β€ j β€ n) is true both: j mod i = 0 and at the same time p(j) mod i = 0, where p(j) is the number of the tome that stands on the j-th place and mod is the operation of taking the division remainder. Naturally, one volume can occupy exactly one place and in one place can stand exactly one volume.
Help Vasya β find the volume disposition with the minimum number of divisors.
Input
The first line contains number n (1 β€ n β€ 100000) which represents the number of volumes and free places.
Output
Print n numbers β the sought disposition with the minimum divisor number. The j-th number (1 β€ j β€ n) should be equal to p(j) β the number of tome that stands on the j-th place. If there are several solutions, print any of them.
Examples
Input
2
Output
2 1
Input
3
Output
1 3 2 | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
print(*([n] + list(range(1, n))))
| {
"input": [
"3\n",
"2\n"
],
"output": [
"2 3 1 ",
"2 1 "
]
} |
2,565 | 9 | ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 β€ n β€ 5000, 1 β€ k β€ 20).
The next line contains n space-separated integers ai (1 β€ ai β€ 107) β the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 β€ q β€ 20) β the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 β€ xi β€ 2Β·108) β the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1 | n, k = map(int, input().split())
a = set(map(int, input().split()))
q = int(input())
# def isIn(x, fm, to):
# if fm >= to:
# return a[fm] == x
# t = a[(fm+to) // 2]
# if t > x:
# return isIn(x, fm, (fm+to) // 2 - 1)
# elif t < x:
# return isIn(x, (fm+to) // 2 + 1, to)
# else:
# return True
for _ in range(q):
x = int(input())
if x in a:
print(1)
continue
found = False
for i in range(2, k + 1):
for j in range(1, i // 2 + 1):
for l in a:
t = x - l * j
if t % (i - j) != 0:
continue
# if isIn(t // (i - j), 0, n - 1):
if t // (i - j) in a:
print(i)
found = True
break
if found:
break
if found:
break
if not found:
print(-1) | {
"input": [
"5 2\n1 2 3 5 8\n8\n1\n3\n5\n7\n9\n11\n13\n15\n",
"6 20\n10 50 100 500 1000 5000\n8\n4200\n100000\n95000\n96000\n99000\n10100\n2015\n9950\n"
],
"output": [
"1\n1\n1\n2\n2\n2\n2\n-1\n",
"6\n20\n19\n20\n-1\n3\n-1\n-1\n"
]
} |
2,566 | 9 | In the probability theory the following paradox called Benford's law is known: "In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit" (that's the simplest form of the law).
Having read about it on Codeforces, the Hedgehog got intrigued by the statement and wishes to thoroughly explore it. He finds the following similar problem interesting in particular: there are N random variables, the i-th of which can take any integer value from some segment [Li;Ri] (all numbers from this segment are equiprobable). It means that the value of the i-th quantity can be equal to any integer number from a given interval [Li;Ri] with probability 1 / (Ri - Li + 1).
The Hedgehog wants to know the probability of the event that the first digits of at least K% of those values will be equal to one. In other words, let us consider some set of fixed values of these random variables and leave only the first digit (the MSD β most significant digit) of each value. Then let's count how many times the digit 1 is encountered and if it is encountered in at least K per cent of those N values, than such set of values will be called a good one. You have to find the probability that a set of values of the given random variables will be a good one.
Input
The first line contains number N which is the number of random variables (1 β€ N β€ 1000). Then follow N lines containing pairs of numbers Li, Ri, each of whom is a description of a random variable. It is guaranteed that 1 β€ Li β€ Ri β€ 1018.
The last line contains an integer K (0 β€ K β€ 100).
All the numbers in the input file are integers.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Output
Print the required probability. Print the fractional number with such a precision that the relative or absolute error of the result won't exceed 10 - 9.
Examples
Input
1
1 2
50
Output
0.500000000000000
Input
2
1 2
9 11
50
Output
0.833333333333333 | def f(n):
s=str(n)
l=len(s)
tot=0
tot+=(10**(l-1)-1)//9
tot+=min(n-10**(l-1)+1,10**(l-1))
return tot
n=int(input())
dp=[[0 for i in range(n+1)]for j in range(n+1)]
dp[0][0]=1
for i in range(1,n+1):
l,r=map(int,input().split())
tot=f(r)-f(l-1)
tot1=r-l+1
j=i
while(j>=0):
if j>=1:
dp[i][j]+=(tot/tot1)*dp[i-1][j-1]
dp[i][j]+=(1-(tot/tot1))*dp[i-1][j]
j+=-1
k=float(input())
k=k/100
ans=0
for j in range(n+1):
if (j/n)>=k:
ans+=dp[n][j]
print(ans)
| {
"input": [
"2\n1 2\n9 11\n50\n",
"1\n1 2\n50\n"
],
"output": [
"0.833333333333333\n",
"0.500000000"
]
} |
2,567 | 8 | While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a1, a2, ..., am of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f1, f2, ..., fn of length n and for each number ai got number bi = fai. To finish the prank he erased the initial sequence ai.
It's hard to express how sad Patrick was when he returned home from shopping! We will just say that Spongebob immediately got really sorry about what he has done and he is now trying to restore the original sequence. Help him do this or determine that this is impossible.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 100 000) β the lengths of sequences fi and bi respectively.
The second line contains n integers, determining sequence f1, f2, ..., fn (1 β€ fi β€ n).
The last line contains m integers, determining sequence b1, b2, ..., bm (1 β€ bi β€ n).
Output
Print "Possible" if there is exactly one sequence ai, such that bi = fai for all i from 1 to m. Then print m integers a1, a2, ..., am.
If there are multiple suitable sequences ai, print "Ambiguity".
If Spongebob has made a mistake in his calculations and no suitable sequence ai exists, print "Impossible".
Examples
Input
3 3
3 2 1
1 2 3
Output
Possible
3 2 1
Input
3 3
1 1 1
1 1 1
Output
Ambiguity
Input
3 3
1 2 1
3 3 3
Output
Impossible
Note
In the first sample 3 is replaced by 1 and vice versa, while 2 never changes. The answer exists and is unique.
In the second sample all numbers are replaced by 1, so it is impossible to unambiguously restore the original sequence.
In the third sample fi β 3 for all i, so no sequence ai transforms into such bi and we can say for sure that Spongebob has made a mistake. | R = lambda : map(int, input().split())
n,m = R()
f,b = R(),list(R())
from collections import defaultdict
def solve(f,b):
df = defaultdict(list)
for i,fi in enumerate(f,1):
df[fi].append(i)
r = []
for bi in b:
if bi not in df:
print("Impossible")
return
for bi in b:
if len(df[bi]) > 1:
print("Ambiguity")
return
for bi in b:
r.append(df[bi][0])
print("Possible")
print(" ".join(map(str,r)))
solve(f,b) | {
"input": [
"3 3\n1 1 1\n1 1 1\n",
"3 3\n3 2 1\n1 2 3\n",
"3 3\n1 2 1\n3 3 3\n"
],
"output": [
"Ambiguity\n",
"Possible\n3 2 1 \n",
"Impossible\n"
]
} |
2,568 | 7 | Professor GukiZ makes a new robot. The robot are in the point with coordinates (x1, y1) and should go to the point (x2, y2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps the robot should make to get the finish position.
Input
The first line contains two integers x1, y1 ( - 109 β€ x1, y1 β€ 109) β the start position of the robot.
The second line contains two integers x2, y2 ( - 109 β€ x2, y2 β€ 109) β the finish position of the robot.
Output
Print the only integer d β the minimal number of steps to get the finish position.
Examples
Input
0 0
4 5
Output
5
Input
3 4
6 1
Output
3
Note
In the first example robot should increase both of its coordinates by one four times, so it will be in position (4, 4). After that robot should simply increase its y coordinate and get the finish position.
In the second example robot should simultaneously increase x coordinate and decrease y coordinate by one three times. | def main():
x, y = map(int, input().split())
u, v = map(int, input().split())
print(max(abs(x - u), abs(y - v)))
if __name__ == '__main__':
main()
| {
"input": [
"0 0\n4 5\n",
"3 4\n6 1\n"
],
"output": [
"5\n",
"3\n"
]
} |
2,569 | 11 | Karlsson has visited Lillebror again. They found a box of chocolates and a big whipped cream cake at Lillebror's place. Karlsson immediately suggested to divide the sweets fairly between Lillebror and himself. Specifically, to play together a game he has just invented with the chocolates. The winner will get the cake as a reward.
The box of chocolates has the form of a hexagon. It contains 19 cells for the chocolates, some of which contain a chocolate. The players move in turns. During one move it is allowed to eat one or several chocolates that lay in the neighboring cells on one line, parallel to one of the box's sides. The picture below shows the examples of allowed moves and of an unacceptable one. The player who cannot make a move loses.
<image>
Karlsson makes the first move as he is Lillebror's guest and not vice versa. The players play optimally. Determine who will get the cake.
Input
The input data contains 5 lines, containing 19 words consisting of one symbol. The word "O" means that the cell contains a chocolate and a "." stands for an empty cell. It is guaranteed that the box contains at least one chocolate. See the examples for better understanding.
Output
If Karlsson gets the cake, print "Karlsson" (without the quotes), otherwise print "Lillebror" (yet again without the quotes).
Examples
Input
. . .
. . O .
. . O O .
. . . .
. . .
Output
Lillebror
Input
. . .
. . . O
. . . O .
O . O .
. O .
Output
Karlsson | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
lines = [
[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18],
[0, 3, 7],
[1, 4, 8, 12],
[2, 5, 9, 13, 16],
[6, 10, 14, 17],
[11, 15, 18],
[2, 6, 11],
[1, 5, 10, 15],
[0, 4, 9, 14, 18],
[3, 8, 13, 17],
[7, 12, 16]
]
dp = [0] + [-1] * (1 << 19)
def dfs(state: int):
if dp[state] != -1:
return dp[state]
for line in lines:
for i in range(len(line)):
line_bit = 0
for j in range(i, len(line)):
line_bit |= 1 << line[j]
if state & line_bit == line_bit and dfs(state & ~line_bit) == 0:
dp[state] = 1
return 1
dp[state] = 0
return 0
start_bit = 0
for s in (0, 3, 7, 12, 16):
for i, c in enumerate(input().split(), start=s):
if c == 'O':
start_bit |= 1 << i
print('Karlsson' if dfs(start_bit) else 'Lillebror')
| {
"input": [
". . .\n . . . O\n. . . O .\n O . O .\n . O .\n",
". . .\n . . O .\n. . O O .\n . . . .\n . . .\n"
],
"output": [
"Karlsson\n",
"Lillebror\n"
]
} |
2,570 | 9 | Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.
That element can store information about the matrix of integers size n Γ m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.
Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.
Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.
Input
The first line of the input contains three integers n, m and q (1 β€ n, m β€ 100, 1 β€ q β€ 10 000) β dimensions of the matrix and the number of turns in the experiment, respectively.
Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 β€ ti β€ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 β€ ri β€ n) or ci (1 β€ ci β€ m) follows, while for the operations of the third type three integers ri, ci and xi (1 β€ ri β€ n, 1 β€ ci β€ m, - 109 β€ xi β€ 109) are given.
Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.
Output
Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value.
If there are multiple valid solutions, output any of them.
Examples
Input
2 2 6
2 1
2 2
3 1 1 1
3 2 2 2
3 1 2 8
3 2 1 8
Output
8 2
1 8
Input
3 3 2
1 2
3 2 2 5
Output
0 0 0
0 0 5
0 0 0 | def main():
n, m, q = map(int, input().split())
nm, qq = n * m, [input() for _ in range(q)]
res = ["0"] * nm
for s in reversed(qq):
k, *l = s.split()
if k == "3":
res[(int(l[0]) - 1) * m + int(l[1]) - 1] = l[2]
elif k == "2":
j = int(l[0]) - 1
*res[j + m:nm:m], res[j] = res[j:nm:m]
else:
j = (int(l[0]) - 1) * m
*res[j + 1:j + m], res[j] = res[j:j + m]
for i in range(0, nm, m):
print(' '.join(res[i:i + m]))
if __name__ == "__main__":
main()
| {
"input": [
"2 2 6\n2 1\n2 2\n3 1 1 1\n3 2 2 2\n3 1 2 8\n3 2 1 8\n",
"3 3 2\n1 2\n3 2 2 5\n"
],
"output": [
"8 2\n1 8\n",
"0 0 0\n0 0 5\n0 0 0\n"
]
} |
2,571 | 10 | So many wall designs to choose from! Even modulo 106 + 3, it's an enormous number. Given that recently Heidi acquired an unlimited supply of bricks, her choices are endless! She really needs to do something to narrow them down.
Heidi is quick to come up with criteria for a useful wall:
* In a useful wall, at least one segment is wider than W bricks. This should give the zombies something to hit their heads against. Or,
* in a useful wall, at least one column is higher than H bricks. This provides a lookout from which zombies can be spotted at a distance.
This should rule out a fair amount of possibilities, right? Help Heidi compute the number of useless walls that do not confirm to either of these criteria. In other words, a wall is useless if every segment has width at most W and height at most H.
Parameter C, the total width of the wall, has the same meaning as in the easy version. However, note that the number of bricks is now unlimited.
Output the number of useless walls modulo 106 + 3.
Input
The first and the only line of the input contains three space-separated integers C, W and H (1 β€ C β€ 108, 1 β€ W, H β€ 100).
Output
Output the number of different walls, modulo 106 + 3, which are useless according to Heidi's criteria.
Examples
Input
1 1 1
Output
2
Input
1 2 2
Output
3
Input
1 2 3
Output
4
Input
3 2 2
Output
19
Input
5 4 9
Output
40951
Input
40 37 65
Output
933869
Note
If there is no brick in any of the columns, the structure is considered as a useless wall. | mod = 10 ** 6 + 3
def prod(a, b):
return [[sum([a[i][k] * b[k][j] for k in range(len(b))]) % mod for j in range(len(b[0]))] for i in range(len(a))]
c, w, h = map(int, input().split())
a = [[0] * (w + 1) for _ in range(w + 1)]
for i in range(w):
a[i][i + 1] = 1
for cnt in range(0, w + 1):
a[-1][-1 - cnt] = h ** cnt
ans = [[0] for _ in range(w + 1)]
ans[-1][0] = 1
ans[-2][0] = 1
while c > 0:
if c % 2 == 1:
ans = prod(a, ans)
c = c // 2
if c > 0:
a = prod(a, a)
print(ans[-1][0]) | {
"input": [
"5 4 9\n",
"40 37 65\n",
"1 2 3\n",
"3 2 2\n",
"1 1 1\n",
"1 2 2\n"
],
"output": [
"40951\n",
"933869\n",
"4\n",
"19\n",
"2\n",
"3\n"
]
} |
2,572 | 8 | Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 people. Of course, each of n candidates can settle in only one of the cities. Thus, first some subset of candidates of size n1 settle in the first city and then some subset of size n2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home.
To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth ai among all its residents divided by the number of them (n1 or n2 depending on the city). The division should be done in real numbers without any rounding.
Please, help authorities find the optimal way to pick residents for two cities.
Input
The first line of the input contains three integers n, n1 and n2 (1 β€ n, n1, n2 β€ 100 000, n1 + n2 β€ n) β the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 100 000), the i-th of them is equal to the wealth of the i-th candidate.
Output
Print one real value β the maximum possible sum of arithmetic means of wealth of cities' residents. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.
Examples
Input
2 1 1
1 5
Output
6.00000000
Input
4 2 1
1 4 2 3
Output
6.50000000
Note
In the first sample, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second.
In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (a3 + a4) / 2 + a2 = (3 + 2) / 2 + 4 = 6.5 | def cin():
return list(map(int, input().split()))
s=0
n,a,b=cin()
A=cin()
A=sorted(A)[::-1]
if a>b:
s=sum(A[:b])/b + sum(A[b:b+a])/a
else:
s=sum(A[:a])/a + sum(A[a:a+b])/b
print(s)
| {
"input": [
"4 2 1\n1 4 2 3\n",
"2 1 1\n1 5\n"
],
"output": [
"6.5000000000",
"6.0000000000"
]
} |
2,573 | 8 | Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described).
This priority factor will be affected by three types of actions:
* 1. "X posted on Y's wall" (15 points),
* 2. "X commented on Y's post" (10 points),
* 3. "X likes Y's post" (5 points).
X and Y will be two distinct names. And each action will increase the priority factor between X and Y (and vice versa) by the above value of points (the priority factor between X and Y is the same as the priority factor between Y and X).
You will be given n actions with the above format (without the action number and the number of points), and you have to print all the distinct names in these actions sorted according to the priority factor with you.
Input
The first line contains your name. The second line contains an integer n, which is the number of actions (1 β€ n β€ 100). Then n lines follow, it is guaranteed that each one contains exactly 1 action in the format given above. There is exactly one space between each two words in a line, and there are no extra spaces. All the letters are lowercase. All names in the input will consist of at least 1 letter and at most 10 small Latin letters.
Output
Print m lines, where m is the number of distinct names in the input (excluding yourself). Each line should contain just 1 name. The names should be sorted according to the priority factor with you in the descending order (the highest priority factor should come first). If two or more names have the same priority factor, print them in the alphabetical (lexicographical) order.
Note, that you should output all the names that are present in the input data (excluding yourself), even if that person has a zero priority factor.
The lexicographical comparison is performed by the standard "<" operator in modern programming languages. The line a is lexicographically smaller than the line b, if either a is the prefix of b, or if exists such an i (1 β€ i β€ min(|a|, |b|)), that ai < bi, and for any j (1 β€ j < i) aj = bj, where |a| and |b| stand for the lengths of strings a and b correspondently.
Examples
Input
ahmed
3
ahmed posted on fatma's wall
fatma commented on ahmed's post
mona likes ahmed's post
Output
fatma
mona
Input
aba
1
likes likes posted's post
Output
likes
posted | from collections import defaultdict
import functools
def customsort(a ,b):
if(a[0] == b[0]): return a[1] > b[1]
else: return a[0] > b[0]
a = input()
n = int(input())
names = defaultdict(lambda : 0)
for i in range(n):
*l ,= map(str ,input().split())
pt = 0
if(l[1] == "posted"):pt = 15
elif(l[1] == "commented"): pt = 10
else: pt = 5
if not (l[0] == a or l[-2][:-2] == a) :pt = 0
names[l[0]] += pt
names[l[-2][:-2]] += pt
# print(pt)
lst = [[100000-names[k] ,k] for k in names.keys() if(k != a)]
# for i ,j in lst:
# print(j ,(i+1)*1000000 - sum(ord(b) for b in j))
lst.sort()
# # lst.reverse()
# print(lst)
for i ,j in lst:
print(j)
| {
"input": [
"aba\n1\nlikes likes posted's post\n",
"ahmed\n3\nahmed posted on fatma's wall\nfatma commented on ahmed's post\nmona likes ahmed's post\n"
],
"output": [
"likes\nposted\n",
"fatma\nmona\n"
]
} |
2,574 | 7 | Andryusha is an orderly boy and likes to keep things in their place.
Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.
Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?
Input
The first line contains the single integer n (1 β€ n β€ 105) β the number of sock pairs.
The second line contains 2n integers x1, x2, ..., x2n (1 β€ xi β€ n), which describe the order in which Andryusha took the socks from the bag. More precisely, xi means that the i-th sock Andryusha took out was from pair xi.
It is guaranteed that Andryusha took exactly two socks of each pair.
Output
Print single integer β the maximum number of socks that were on the table at the same time.
Examples
Input
1
1 1
Output
1
Input
3
2 1 1 3 2 3
Output
2
Note
In the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.
In the second example Andryusha behaved as follows:
* Initially the table was empty, he took out a sock from pair 2 and put it on the table.
* Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table.
* Socks (1, 2) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe.
* Sock (2) was on the table. Andryusha took out a sock from pair 3 and put it on the table.
* Socks (2, 3) were on the table. Andryusha took out a sock from pair 2, and put this pair into the wardrobe.
* Sock (3) was on the table. Andryusha took out a sock from pair 3 and put this pair into the wardrobe.
Thus, at most two socks were on the table at the same time. | import math
import bisect
import itertools
import decimal
def ria():
return [int(i) for i in input().split()]
st=set()
mx=0
n=ria()[0]
ar=ria()
for i in ar:
if i not in st:
st.add(i)
else:
st.remove(i)
mx=max(len(st),mx)
print(mx) | {
"input": [
"1\n1 1\n",
"3\n2 1 1 3 2 3\n"
],
"output": [
"1\n",
"2\n"
]
} |
2,575 | 11 | Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes 1 virtual bourle from the loser.
Last evening Roma started to play poker. He decided to spend no more than k virtual bourles β he will stop immediately if the number of his loses exceeds the number of his wins by k. Also Roma will leave the game if he wins enough money for the evening, i.e. if the number of wins exceeds the number of loses by k.
Next morning Roma found a piece of paper with a sequence on it representing his results. Roma doesn't remember the results exactly, and some characters in the sequence are written in a way such that it's impossible to recognize this character, so Roma can't recall whether he won k bourles or he lost.
The sequence written by Roma is a string s consisting of characters W (Roma won the corresponding hand), L (Roma lost), D (draw) and ? (unknown result). Roma wants to restore any valid sequence by changing all ? characters to W, L or D. The sequence is called valid if all these conditions are met:
* In the end the absolute difference between the number of wins and loses is equal to k;
* There is no hand such that the absolute difference before this hand was equal to k.
Help Roma to restore any such sequence.
Input
The first line contains two numbers n (the length of Roma's sequence) and k (1 β€ n, k β€ 1000).
The second line contains the sequence s consisting of characters W, L, D and ?. There are exactly n characters in this sequence.
Output
If there is no valid sequence that can be obtained from s by replacing all ? characters by W, L or D, print NO.
Otherwise print this sequence. If there are multiple answers, print any of them.
Examples
Input
3 2
L??
Output
LDL
Input
3 1
W??
Output
NO
Input
20 5
?LLLLLWWWWW?????????
Output
WLLLLLWWWWWWWWLWLWDW | # 803E
import collections
def do():
n, k = map(int, input().split(" "))
s = input()
dp = collections.defaultdict(set)
gap = {'W': 1, 'L': -1, 'D': 0}
dp[-1].add(0)
for i in range(n-1):
if s[i] == '?':
for pre in dp[i-1]:
for g in gap.values():
t = pre + g
if abs(t) != k:
dp[i].add(t)
else:
for pre in dp[i-1]:
t = pre + gap[s[i]]
if abs(t) != k:
dp[i].add(t)
if s[n-1] == '?':
for pre in dp[n-2]:
for g in gap.values():
dp[n-1].add(pre + g)
else:
for pre in dp[n-2]:
dp[n-1].add(pre + gap[s[n-1]])
# print(dp)
if k not in dp[n-1] and -k not in dp[n-1]:
return "NO"
res = [c for c in s]
cur = k if k in dp[n-1] else -k
for i in range(n-1, 0, -1):
if s[i] == '?':
for c in gap:
if abs(cur - gap[c]) != k and cur - gap[c] in dp[i-1]:
res[i] = c
cur -= gap[c]
break
else:
cur -= gap[s[i]]
if res[0] == '?':
if cur == 0:
res[0] = 'D'
elif cur == 1:
res[0] = 'W'
else:
res[0] = 'L'
return "".join(res)
print(do())
| {
"input": [
"3 1\nW??\n",
"3 2\nL??\n",
"20 5\n?LLLLLWWWWW?????????\n"
],
"output": [
"NO\n",
"LDL\n",
"WLLLLLWWWWWWWWDDDDDW"
]
} |
2,576 | 10 | There are n animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number i in the queue will have to visit his office exactly ai times. We will assume that an examination takes much more time than making tests and other extra procedures, and therefore we will assume that once an animal leaves the room, it immediately gets to the end of the queue to the doctor. Of course, if the animal has visited the doctor as many times as necessary, then it doesn't have to stand at the end of the queue and it immediately goes home.
Doctor plans to go home after receiving k animals, and therefore what the queue will look like at that moment is important for him. Since the doctor works long hours and she can't get distracted like that after all, she asked you to figure it out.
Input
The first line of input data contains two space-separated integers n and k (1 β€ n β€ 105, 0 β€ k β€ 1014). In the second line are given space-separated integers a1, a2, ..., an (1 β€ ai β€ 109).
Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
Output
If the doctor will overall carry out less than k examinations, print a single number "-1" (without quotes). Otherwise, print the sequence of numbers β number of animals in the order in which they stand in the queue.
Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted.
Examples
Input
3 3
1 2 1
Output
2
Input
4 10
3 3 2 1
Output
-1
Input
7 10
1 3 3 1 2 3 1
Output
6 2 3
Note
In the first sample test:
* Before examination: {1, 2, 3}
* After the first examination: {2, 3}
* After the second examination: {3, 2}
* After the third examination: {2}
In the second sample test:
* Before examination: {1, 2, 3, 4, 5, 6, 7}
* After the first examination: {2, 3, 4, 5, 6, 7}
* After the second examination: {3, 4, 5, 6, 7, 2}
* After the third examination: {4, 5, 6, 7, 2, 3}
* After the fourth examination: {5, 6, 7, 2, 3}
* After the fifth examination: {6, 7, 2, 3, 5}
* After the sixth examination: {7, 2, 3, 5, 6}
* After the seventh examination: {2, 3, 5, 6}
* After the eighth examination: {3, 5, 6, 2}
* After the ninth examination: {5, 6, 2, 3}
* After the tenth examination: {6, 2, 3} | import sys
from array import array # noqa: F401
from collections import deque
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, k = map(int, input().split())
a = list(map(int, input().split()))
if sum(a) < k:
print(-1)
exit()
ok, ng = 0, 10**9 + 10
while abs(ok - ng) > 1:
mid = (ok + ng) >> 1
if sum(mid if mid < x else x for x in a) <= k:
ok = mid
else:
ng = mid
index = deque([i + 1 for i in range(n) if a[i] > ok])
dq = deque([x - ok for x in a if x > ok])
k -= sum(ok if ok < x else x for x in a)
for _ in range(k):
dq[0] -= 1
if dq[0]:
dq.rotate(-1)
index.rotate(-1)
else:
dq.popleft()
index.popleft()
print(*index)
| {
"input": [
"7 10\n1 3 3 1 2 3 1\n",
"3 3\n1 2 1\n",
"4 10\n3 3 2 1\n"
],
"output": [
"6 2 3 \n",
"2 \n",
"-1\n"
]
} |
2,577 | 7 | Luba has to do n chores today. i-th chore takes ai units of time to complete. It is guaranteed that for every <image> the condition ai β₯ ai - 1 is met, so the sequence is sorted.
Also Luba can work really hard on some chores. She can choose not more than k any chores and do each of them in x units of time instead of ai (<image>).
Luba is very responsible, so she has to do all n chores, and now she wants to know the minimum time she needs to do everything. Luba cannot do two chores simultaneously.
Input
The first line contains three integers n, k, x (1 β€ k β€ n β€ 100, 1 β€ x β€ 99) β the number of chores Luba has to do, the number of chores she can do in x units of time, and the number x itself.
The second line contains n integer numbers ai (2 β€ ai β€ 100) β the time Luba has to spend to do i-th chore.
It is guaranteed that <image>, and for each <image> ai β₯ ai - 1.
Output
Print one number β minimum time Luba needs to do all n chores.
Examples
Input
4 2 2
3 6 7 10
Output
13
Input
5 2 1
100 100 100 100 100
Output
302
Note
In the first example the best option would be to do the third and the fourth chore, spending x = 2 time on each instead of a3 and a4, respectively. Then the answer is 3 + 6 + 2 + 2 = 13.
In the second example Luba can choose any two chores to spend x time on them instead of ai. So the answer is 100Β·3 + 2Β·1 = 302. | def numline(f = int):
return map(f, input().split())
n, k, x = numline()
a = [i for i in numline()]
print(sum(a[:len(a) - k]) + k * x) | {
"input": [
"4 2 2\n3 6 7 10\n",
"5 2 1\n100 100 100 100 100\n"
],
"output": [
"13\n",
"302\n"
]
} |
2,578 | 12 | A correct expression of the form a+b=c was written; a, b and c are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits so that:
* character'+' is placed on the left of character '=',
* characters '+' and '=' split the sequence into three non-empty subsequences consisting of digits (let's call the left part a, the middle part β b and the right part β c),
* all the three parts a, b and c do not contain leading zeros,
* it is true that a+b=c.
It is guaranteed that in given tests answer always exists.
Input
The first line contains a non-empty string consisting of digits. The length of the string does not exceed 106.
Output
Output the restored expression. If there are several solutions, you can print any of them.
Note that the answer at first should contain two terms (divided with symbol '+'), and then the result of their addition, before which symbol'=' should be.
Do not separate numbers and operation signs with spaces. Strictly follow the output format given in the examples.
If you remove symbol '+' and symbol '=' from answer string you should get a string, same as string from the input data.
Examples
Input
12345168
Output
123+45=168
Input
099
Output
0+9=9
Input
199100
Output
1+99=100
Input
123123123456456456579579579
Output
123123123+456456456=579579579 | def modgroup(M = 10**9+7, invn = 0) :
exec(f'''class mod{M} :
inv = [None] * {invn}
if {invn} >= 2 : inv[1] = 1
for i in range(2, {invn}) : inv[i] = (({M}-{M}//i)*inv[{M}%i])%{M}
def __init__(self, n = 0) : self.n = n % {M}
__repr__ = lambda self : str(self.n) + '%{M}'
__int__ = lambda self : self.n
__eq__ = lambda a,b : a.n == b.n
__add__ = lambda a,b : __class__(a.n + b.n)
__sub__ = lambda a,b : __class__(a.n - b.n)
__mul__ = lambda a,b : __class__(a.n * b.n)
__pow__ = lambda a,b : __class__(pow(a.n, b.n, {M}))
__truediv__ = lambda a,b : __class__(a.n * pow(b.n, {M-2}, {M}))
__floordiv__ = lambda a,b : __class__(a.n * __class__.inv[b.n])
''')
return eval(f'mod{M}')
def solution() :
s = input()
l = len(s)
mod = modgroup()
num = [mod(0)] * (l+1) # num[i] = int(s[:i]) <mod>
shift = [mod(1)] * (l+1) # shift[i] = 10**i <mod>
for i,x in enumerate(s, 1) :
num[i] = num[i-1] * mod(10) + mod(int(x))
shift[i] = shift[i-1] * mod(10)
def mod_check(la, lb, lc) :
a,b,c = num[la], num[la+lb], num[la+lb+lc]
c -= b * shift[lc]
b -= a * shift[lb]
return a + b == c
for lc in range(l//3+bool(l%3), l//2+1) :
for lb in (lc, lc-1, l-lc*2, l-lc*2+1) :
la = l - lc - lb
if la < 1 or lb < 1 or lc < 1 : continue
if la > lc or lb > lc : continue
if not mod_check(la, lb, lc) : continue
print(f'{s[:la]}+{s[la:la+lb]}={s[la+lb:la+lb+lc]}')
return
solution() | {
"input": [
"12345168\n",
"099\n",
"123123123456456456579579579\n",
"199100\n"
],
"output": [
"123+45=168",
"0+9=9",
"123123123+456456456=579579579",
"1+99=100"
]
} |
2,579 | 7 | A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.
For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".
Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?
Input
The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1 β€ |s1| β€ 104, 1 β€ |s2| β€ 106).
Output
If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.
Examples
Input
abc
xyz
Output
-1
Input
abcd
dabc
Output
2 | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
s = [ord(c) - 97 for c in input().rstrip()]
t = [ord(c) - 97 for c in input().rstrip()]
n, m = len(s), len(t)
next_c = [[-1] * 26 for _ in range(n)]
for _ in range(2):
for i in range(n - 1, -1, -1):
for cc in range(26):
next_c[i][cc] = next_c[(i + 1) % n][cc]
next_c[i][s[(i + 1) % n]] = (i + 1) % n
j = n - 1
ans = 0
for i, cc in enumerate(t):
k = next_c[j][cc]
if k == -1:
print(-1)
exit()
if j >= k:
ans += 1
j = k
print(ans)
| {
"input": [
"abc\nxyz\n",
"abcd\ndabc\n"
],
"output": [
"-1",
"2"
]
} |
2,580 | 10 | Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way.
There are n ghosts in the universe, they move in the OXY plane, each one of them has its own velocity that does not change in time: \overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarrow{j} where V_{x} is its speed on the x-axis and V_{y} is on the y-axis.
A ghost i has experience value EX_i, which represent how many ghosts tried to scare him in his past. Two ghosts scare each other if they were in the same cartesian point at a moment of time.
As the ghosts move with constant speed, after some moment of time there will be no further scaring (what a relief!) and the experience of ghost kind GX = β_{i=1}^{n} EX_i will never increase.
Tameem is a red giant, he took a picture of the cartesian plane at a certain moment of time T, and magically all the ghosts were aligned on a line of the form y = a β
x + b. You have to compute what will be the experience index of the ghost kind GX in the indefinite future, this is your task for today.
Note that when Tameem took the picture, GX may already be greater than 0, because many ghosts may have scared one another at any moment between [-β, T].
Input
The first line contains three integers n, a and b (1 β€ n β€ 200000, 1 β€ |a| β€ 10^9, 0 β€ |b| β€ 10^9) β the number of ghosts in the universe and the parameters of the straight line.
Each of the next n lines contains three integers x_i, V_{xi}, V_{yi} (-10^9 β€ x_i β€ 10^9, -10^9 β€ V_{x i}, V_{y i} β€ 10^9), where x_i is the current x-coordinate of the i-th ghost (and y_i = a β
x_i + b).
It is guaranteed that no two ghosts share the same initial position, in other words, it is guaranteed that for all (i,j) x_i β x_j for i β j.
Output
Output one line: experience index of the ghost kind GX in the indefinite future.
Examples
Input
4 1 1
1 -1 -1
2 1 1
3 1 1
4 -1 -1
Output
8
Input
3 1 0
-1 1 0
0 0 -1
1 -1 -2
Output
6
Input
3 1 0
0 0 0
1 0 0
2 0 0
Output
0
Note
There are four collisions (1,2,T-0.5), (1,3,T-1), (2,4,T+1), (3,4,T+0.5), where (u,v,t) means a collision happened between ghosts u and v at moment t. At each collision, each ghost gained one experience point, this means that GX = 4 β
2 = 8.
In the second test, all points will collide when t = T + 1.
<image>
The red arrow represents the 1-st ghost velocity, orange represents the 2-nd ghost velocity, and blue represents the 3-rd ghost velocity. | #!/usr/bin/python3
from sys import stdin
from collections import Counter
def f(line):
return tuple(int(x) for x in line.split()[1:])
n, a, _ = [int(x) for x in stdin.readline().split()]
groups = Counter(f(line) for line in stdin.readlines()[:n])
total = Counter()
for (x, y), cnt in groups.items():
total[y - x * a] += cnt
ans = 0
for (x, y), cnt in groups.items():
ans += cnt * max(0, (total[y - x * a] - cnt))
print(ans)
| {
"input": [
"4 1 1\n1 -1 -1\n2 1 1\n3 1 1\n4 -1 -1\n",
"3 1 0\n0 0 0\n1 0 0\n2 0 0\n",
"3 1 0\n-1 1 0\n0 0 -1\n1 -1 -2\n"
],
"output": [
"8\n",
"0\n",
"6\n"
]
} |
2,581 | 9 | For a vector \vec{v} = (x, y), define |v| = β{x^2 + y^2}.
Allen had a bit too much to drink at the bar, which is at the origin. There are n vectors \vec{v_1}, \vec{v_2}, β
β
β
, \vec{v_n}. Allen will make n moves. As Allen's sense of direction is impaired, during the i-th move he will either move in the direction \vec{v_i} or -\vec{v_i}. In other words, if his position is currently p = (x, y), he will either move to p + \vec{v_i} or p - \vec{v_i}.
Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position p satisfies |p| β€ 1.5 β
10^6 so that he can stay safe.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of moves.
Each of the following lines contains two space-separated integers x_i and y_i, meaning that \vec{v_i} = (x_i, y_i). We have that |v_i| β€ 10^6 for all i.
Output
Output a single line containing n integers c_1, c_2, β
β
β
, c_n, each of which is either 1 or -1. Your solution is correct if the value of p = β_{i = 1}^n c_i \vec{v_i}, satisfies |p| β€ 1.5 β
10^6.
It can be shown that a solution always exists under the given constraints.
Examples
Input
3
999999 0
0 999999
999999 0
Output
1 1 -1
Input
1
-824590 246031
Output
1
Input
8
-67761 603277
640586 -396671
46147 -122580
569609 -2112
400 914208
131792 309779
-850150 -486293
5272 721899
Output
1 1 1 1 1 1 1 -1 | def my_cmp(x):
if x[0] == 0:
return float('inf')
return x[1]/x[0]
def dis(a, b):
return a*a + b*b
n = int(input())
v = []
for i in range(n):
x, y = map(int, input().split())
v.append((x, y, i))
v.sort(key = my_cmp)
x, y = 0, 0
ans = [0]*n
for i in range(n):
if dis(x+v[i][0], y+v[i][1]) < dis(x-v[i][0], y-v[i][1]):
ans[v[i][2]] = 1
else:
ans[v[i][2]] = -1
x += v[i][0]*ans[v[i][2]]
y += v[i][1]*ans[v[i][2]]
for x in ans:
print(x, end = ' ') | {
"input": [
"1\n-824590 246031\n",
"8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n",
"3\n999999 0\n0 999999\n999999 0\n"
],
"output": [
"1 ",
"1 1 -1 -1 -1 -1 -1 1 ",
"1 1 -1 "
]
} |
2,582 | 8 | There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of rectangles.
Each of the next n lines contains two integers w_i and h_i (1 β€ w_i, h_i β€ 10^9) β the width and the height of the i-th rectangle.
Output
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3
3 4
4 6
3 5
Output
YES
Input
2
3 4
5 5
Output
NO
Note
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].
In the second test, there is no way the second rectangle will be not higher than the first one. | from math import inf
def main():
n = int(input())
prev = inf
for i in range(n):
a, b = map(int, input().split())
if a <= prev:
if a < b <= prev:
prev = b
else:
prev = a
elif b <= prev:
prev = b
else:
print('NO')
return
print('YES')
main() | {
"input": [
"3\n3 4\n4 6\n3 5\n",
"2\n3 4\n5 5\n"
],
"output": [
"YES\n",
"NO\n"
]
} |
2,583 | 7 | Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water.
There are only two types of water bottles in the nearby shop β 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop.
The bottle of the first type costs a burles and the bottle of the second type costs b burles correspondingly.
Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly n liters of water in the nearby shop if the bottle of the first type costs a burles and the bottle of the second type costs b burles.
You also have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 500) β the number of queries.
The next q lines contain queries. The i-th query is given as three space-separated integers n_i, a_i and b_i (1 β€ n_i β€ 10^{12}, 1 β€ a_i, b_i β€ 1000) β how many liters Polycarp needs in the i-th query, the cost (in burles) of the bottle of the first type in the i-th query and the cost (in burles) of the bottle of the second type in the i-th query, respectively.
Output
Print q integers. The i-th integer should be equal to the minimum amount of money (in burles) Polycarp needs to buy exactly n_i liters of water in the nearby shop if the bottle of the first type costs a_i burles and the bottle of the second type costs b_i burles.
Example
Input
4
10 1 3
7 3 2
1 1000 1
1000000000000 42 88
Output
10
9
1000
42000000000000 | def bestPrice():
n, a ,b = map(int,input().split(" "))
print(min(n*a, (n%2)*a + (n//2)*b))
q = int(input())
for i in range(q):
bestPrice() | {
"input": [
"4\n10 1 3\n7 3 2\n1 1000 1\n1000000000000 42 88\n"
],
"output": [
"10\n9\n1000\n42000000000000\n"
]
} |
2,584 | 10 | You are given an array a consisting of n integers. You can perform the following operations arbitrary number of times (possibly, zero):
1. Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i + |a_i - a_j|;
2. Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i - |a_i - a_j|.
The value |x| means the absolute value of x. For example, |4| = 4, |-3| = 3.
Your task is to find the minimum number of operations required to obtain the array of equal elements and print the order of operations to do it.
It is guaranteed that you always can obtain the array of equal elements using such operations.
Note that after each operation each element of the current array should not exceed 10^{18} by absolute value.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 2 β
10^5), where a_i is the i-th element of a.
Output
In the first line print one integer k β the minimum number of operations required to obtain the array of equal elements.
In the next k lines print operations itself. The p-th operation should be printed as a triple of integers (t_p, i_p, j_p), where t_p is either 1 or 2 (1 means that you perform the operation of the first type, and 2 means that you perform the operation of the second type), and i_p and j_p are indices of adjacent elements of the array such that 1 β€ i_p, j_p β€ n, |i_p - j_p| = 1. See the examples for better understanding.
Note that after each operation each element of the current array should not exceed 10^{18} by absolute value.
If there are many possible answers, you can print any.
Examples
Input
5
2 4 6 6 6
Output
2
1 2 3
1 1 2
Input
3
2 8 10
Output
2
2 2 1
2 3 2
Input
4
1 1 1 1
Output
0 | n = int(input())
a = [int(s) for s in input().split()]
cts = {}
maxct = 1
maxn = a[0]
for ai in a:
cts[ai] = cts.get(ai, 0) + 1
if cts[ai] > maxct:
maxct = cts[ai]
maxn = ai
print(n-maxct)
def sweep(st,en,step):
for i in range(st, en, step):
if a[i+step] < a[i]:
print(1, i+step+1, i+1)
elif a[i+step] > a[i]:
print(2, i+step+1, i+1)
a[i+step] = a[i]
sti = a.index(maxn)
sweep(sti, 0, -1)
sweep(sti, n-1, 1) | {
"input": [
"5\n2 4 6 6 6\n",
"4\n1 1 1 1\n",
"3\n2 8 10\n"
],
"output": [
"2\n1 2 3\n1 1 2\n",
"0\n",
"2\n2 2 1\n2 3 2\n"
]
} |
2,585 | 9 | Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.
You are given a string s, you have to delete minimum number of characters from this string so that it becomes good.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of characters in s.
The second line contains the string s, consisting of exactly n lowercase Latin letters.
Output
In the first line, print one integer k (0 β€ k β€ n) β the minimum number of characters you have to delete from s to make it good.
In the second line, print the resulting string s. If it is empty, you may leave the second line blank, or not print it at all.
Examples
Input
4
good
Output
0
good
Input
4
aabc
Output
2
ab
Input
3
aaa
Output
3 | def main():
n = int(input())
a = list(input())
new = ''
i = 0; j = 1
while i < n-1 and j < n:
# print(i, j)
while j < n and a[i] == a[j]:
j += 1
if j < n:
new += a[i] + a[j]
i = j+1
j = i+1
print(n-len(new))
print(new)
if __name__ == "__main__":
main() | {
"input": [
"3\naaa\n",
"4\ngood\n",
"4\naabc\n"
],
"output": [
"3\n\n",
"0\ngood\n",
"2\nab\n"
]
} |
2,586 | 9 | The Cybermen solved that first test much quicker than the Daleks. Luckily for us, the Daleks were angry (shocking!) and they destroyed some of the Cybermen.
After the fighting stopped, Heidi gave them another task to waste their time on.
There are n points on a plane. Given a radius r, find the maximum number of points that can be covered by an L^1-ball with radius r.
An L^1-ball with radius r and center (x_0, y_0) in a 2D-plane is defined as the set of points (x, y) such that the Manhattan distance between (x_0, y_0) and (x, y) is at most r.
Manhattan distance between (x_0, y_0) and (x, y) is defined as |x - x_0| + |y - y_0|.
Input
The first line contains two integers n, r (1 β€ n β€ 300 000, 1 β€ r β€ 10^6), the number of points and the radius of the ball, respectively.
Each of the next n lines contains integers x_i, y_i (-10^6 β€ x_i, y_i β€ 10^6), describing the coordinates of the i-th point.
It is guaranteed, that all points are distinct.
Output
Print one integer β the maximum number points that an L^1-ball with radius r can cover.
Examples
Input
5 1
1 1
1 -1
-1 1
-1 -1
2 0
Output
3
Input
5 2
1 1
1 -1
-1 1
-1 -1
2 0
Output
5
Note
In the first example, a ball centered at (1, 0) covers the points (1, 1), (1, -1), (2, 0).
In the second example, a ball centered at (0, 0) covers all the points.
Note that x_0 and y_0 need not be integer. | import sys
NORM = 2000000
LIMIT = NORM * 2 + 1
class segmentTree:
def __init__(self, n):
self.n = n
self.t = [0] * (n * 2)
self.lazy = [0] * n
def apply(self, p, value):
self.t[p] += value
if p < self.n:
self.lazy[p] += value
def build(self, p):
while p > 1:
p >>= 1
self.t[p] = max(self.t[p * 2], self.t[p * 2 + 1]) + self.lazy[p]
def push(self, p):
log = 0
while (1 << log) <= self.n:
log += 1
for s in range(log, 0, -1):
parent = p >> s
if self.lazy[parent] != 0:
self.apply(parent * 2, self.lazy[parent])
self.apply(parent * 2 + 1, self.lazy[parent])
self.lazy[parent] = 0
def inc(self, l, r, value):
l += self.n
r += self.n
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l, value)
l += 1
if r & 1:
self.apply(r - 1, value)
r -= 1
l >>= 1
r >>= 1
self.build(l0)
self.build(r0 - 1)
def query(self, l, r):
l += self.n
r += self.n
self.push(l)
self.push(r - 1)
res = 0
while l < r:
if l & 1:
res = max(res, self.t[l])
l += 1
if r & 1:
res = max(res, self.t[r - 1])
r -= 1
l >>= 1
r >>= 1
return res
inp = [int(x) for x in sys.stdin.read().split()]
n, r = inp[0], inp[1]
inp_idx = 2
points = []
env = {}
for _ in range(n):
x, y = inp[inp_idx], inp[inp_idx + 1]
inp_idx += 2
new_x = x - y
new_y = x + y
new_x += NORM
new_y += NORM
if not new_y in env:
env[new_y] = []
env[new_y].append(new_x)
points.append([new_x, new_y])
sq_side = r * 2
tree = segmentTree(LIMIT)
ys = []
for y in env.keys():
ys.append(y)
ys = sorted(ys)
ans = 0
last = 0
for i in range(len(ys)):
y = ys[i]
while i > last and ys[last] < y - sq_side:
low_y = ys[last]
for x in env[low_y]:
low_x = max(0, x - sq_side)
tree.inc(low_x, x + 1, -1)
last += 1
for x in env[y]:
low_x = max(0, x - sq_side)
tree.inc(low_x, x + 1, +1)
ans = max(ans, tree.query(0, LIMIT))
print(ans)
| {
"input": [
"5 2\n1 1\n1 -1\n-1 1\n-1 -1\n2 0\n",
"5 1\n1 1\n1 -1\n-1 1\n-1 -1\n2 0\n"
],
"output": [
"5\n",
"3\n"
]
} |
2,587 | 11 | You are given a string t and n strings s_1, s_2, ..., s_n. All strings consist of lowercase Latin letters.
Let f(t, s) be the number of occurences of string s in string t. For example, f('aaabacaa', 'aa') = 3, and f('ababa', 'aba') = 2.
Calculate the value of β_{i=1}^{n} β_{j=1}^{n} f(t, s_i + s_j), where s + t is the concatenation of strings s and t. Note that if there are two pairs i_1, j_1 and i_2, j_2 such that s_{i_1} + s_{j_1} = s_{i_2} + s_{j_2}, you should include both f(t, s_{i_1} + s_{j_1}) and f(t, s_{i_2} + s_{j_2}) in answer.
Input
The first line contains string t (1 β€ |t| β€ 2 β
10^5).
The second line contains integer n (1 β€ n β€ 2 β
10^5).
Each of next n lines contains string s_i (1 β€ |s_i| β€ 2 β
10^5).
It is guaranteed that β_{i=1}^{n} |s_i| β€ 2 β
10^5. All strings consist of lowercase English letters.
Output
Print one integer β the value of β_{i=1}^{n} β_{j=1}^{n} f(t, s_i + s_j).
Examples
Input
aaabacaa
2
a
aa
Output
5
Input
aaabacaa
4
a
a
a
b
Output
33 | class Node(object):
def __init__(self):
super(Node, self).__init__()
self.next = [-1] * 26
self.trans = []
self.matches = 0
self.leaf = 0
self.link = 0
class AhoCorasick(object):
def __init__(self):
super(AhoCorasick, self).__init__()
self.T = [Node()]
self.T[0].link = 0
def insert_trie(self, s):
v = 0
for i in range(len(s)):
c = ord(s[i]) - ord('a')
if(self.T[v].next[c] == -1):
self.T[v].trans.append(c)
self.T[v].next[c] = len(self.T)
self.T.append(Node())
v = self.T[v].next[c]
self.T[v].leaf += 1
self.T[v].matches += 1
def set_suffix_link(self, S):
Q = []
for j in range(len(S)):
Q.append((j, 0, 0, 0))
#string index, index in string, state, suff state,
i = 0
while(i < len(Q)):
j,ind,v,suff = Q[i]
i += 1
c = ord(S[j][ind]) - ord('a')
if(ind>0):
while(suff>0 and self.T[suff].next[c]==-1):
suff = self.T[suff].link
if(self.T[suff].next[c] != -1):
suff = self.T[suff].next[c]
v = self.T[v].next[c]
self.T[v].link = suff
if(ind+1 < len(S[j])):
Q.append((j,ind+1,v,suff))
def set_matches(self):
i = 0
Q = [0]
while(i < len(Q)):
v = Q[i]
self.T[v].matches = self.T[v].leaf + self.T[self.T[v].link].matches
for c in self.T[v].trans:
Q.append(self.T[v].next[c])
i += 1
def build(self, S):
for i in range(len(S)):
self.insert_trie(S[i])
self.set_suffix_link(S)
#self.printTree()
self.set_matches()
def get(self, s):
v = 0
matches = []
for i in range(len(s)):
c = ord(s[i]) - ord('a')
while(v>0 and self.T[v].next[c] == -1):
v = self.T[v].link
if(self.T[v].next[c] != -1):
v = self.T[v].next[c]
matches.append(self.T[v].matches)
return matches
def printTree(self):
for i in range(len(self.T)):
print(str(i)+" leaf:"+str(self.T[i].leaf)+" link:"+str(self.T[i].link)+" matches:"+str(self.T[i].matches)+" : " , end='')
for j in range(26):
print(" "+str(chr(j+ord('a')))+"-"+(str(self.T[i].next[j]) if (self.T[i].next[j]!=-1) else "_")+" ", end='')
print()
t = input()
n = int(input())
patterns = []
patterns_rev = []
for i in range(n):
s = input()
patterns.append(s)
patterns_rev.append(s[::-1])
t1 = AhoCorasick()
t2 = AhoCorasick()
t1.build(patterns)
t2.build(patterns_rev)
x1 = t1.get(t)
x2 = t2.get(t[::-1])[::-1]
#print(x1)
#print(x2)
ans = 0
for i in range(len(x1)-1):
ans += x1[i] * x2[i+1]
print(ans)
| {
"input": [
"aaabacaa\n4\na\na\na\nb\n",
"aaabacaa\n2\na\naa\n"
],
"output": [
"33\n",
"5\n"
]
} |
2,588 | 7 | Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem.
Input
The single line contains two integers l and r (1 β€ l β€ r β€ 109) β the left and right interval limits.
Output
In the single line print the only number β the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r).
Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
2 7
Output
33
Input
7 7
Output
7
Note
In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33
In the second sample: next(7) = 7 | l,r=map(int,input().split())
a=[]
def foo(n):
a.append(n)
if n>10*r:
return
foo(10*n+4)
foo(10*n+7)
return
foo(0)
a.sort()
def get_sum(m):
s=0
for i in range(1,len(a)):
s+=a[i]*(min(a[i],m)-min(a[i-1],m))
return s
print(get_sum(r)-get_sum(l-1))
| {
"input": [
"2 7\n",
"7 7\n"
],
"output": [
"33",
"7"
]
} |
2,589 | 11 | You are given a sequence a_1, a_2, ..., a_n consisting of n integers.
You may perform the following operation on this sequence: choose any element and either increase or decrease it by one.
Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times.
Input
The first line contains two integers n and k (2 β€ n β€ 10^{5}, 1 β€ k β€ 10^{14}) β the number of elements in the sequence and the maximum number of times you can perform the operation, respectively.
The second line contains a sequence of integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{9}).
Output
Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times.
Examples
Input
4 5
3 1 7 5
Output
2
Input
3 10
100 100 100
Output
0
Input
10 9
4 5 5 7 5 4 5 2 4 3
Output
1
Note
In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2.
In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. | import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int,minp().split())
def solve():
n, k = mints()
a = list(mints())
a.sort()
b = []
c = []
i = 0
while i < n:
j = i + 1
while j < n and a[j] == a[i]:
j += 1
b.append(a[i])
c.append(j-i)
i = j
l = 0
r = len(b) - 1
while l < r and k > 0:
if c[l] < c[r]:
x = min(b[l] + k // c[l], b[l+1])
k -= (x - b[l]) * c[l]
if x == b[l+1]:
c[l+1] += c[l]
l += 1
else:
b[l] = x
break
else:
x = max(b[r] - k // c[r], b[r-1])
k -= (b[r] - x) * c[r]
if x == b[r-1]:
c[r-1] += c[r]
r -= 1
else:
b[r] = x
break
print(b[r]-b[l])
solve()
| {
"input": [
"10 9\n4 5 5 7 5 4 5 2 4 3\n",
"4 5\n3 1 7 5\n",
"3 10\n100 100 100\n"
],
"output": [
"1\n",
"2\n",
"0\n"
]
} |
2,590 | 9 | Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 β€ i β€ n.
Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time.
Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities:
* The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day;
* In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i.
There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint.
After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy.
Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Input
The first line contains two integers n, q (2 β€ n, q β€ 2 β
10^5) β the number of mirrors and queries.
The second line contains n integers: p_1, p_2, β¦, p_n (1 β€ p_i β€ 100).
Each of q following lines contains a single integer u (2 β€ u β€ n) β next query.
Output
Print q numbers β the answers after each query by modulo 998244353.
Examples
Input
2 2
50 50
2
2
Output
4
6
Input
5 5
10 20 30 40 50
2
3
4
5
3
Output
117
665496274
332748143
831870317
499122211
Note
In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. | mod = 998244353
def inv_mod(n):
return pow(n, mod - 2, mod)
n = int(input())
p = [int(x) for x in input().split()]
res = 0
for i in p:
res = (res + 1) * 100 * inv_mod(i) % mod
print(res) | {
"input": [
"2 2\n50 50\n2\n2\n",
"5 5\n10 20 30 40 50\n2\n3\n4\n5\n3\n"
],
"output": [
"4\n6\n",
"117\n665496274\n332748143\n831870317\n499122211\n"
]
} |
2,591 | 11 | There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l β€ x β€ r.
Segments can be placed arbitrarily β be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 β€ n β€ 2β
10^5) β the number of segments in the given set. Then n lines follow, each contains a description of a segment β a pair of integers l_i, r_i (-10^9 β€ l_i β€ r_i β€ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2β
10^5.
Output
Print t integers β the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5 | import sys
from collections import deque
def input():
return sys.stdin.readline().rstrip()
t = int(input())
for _ in range(t):
n = int(input())
segs = []
for i in range(n):
l,r = list(map(int, input().split()))
segs.append((l,0,i))
segs.append((r,1,i))
segs.sort()
active = set()
increase = [0 for _ in range(n)]
seq = []
ans = 0
for pos, p, i in segs:
if p == 0:
if len(seq)>1 and seq[-2:] == [2,1]:
increase[next(iter(active))]+=1
active.add(i)
else:
active.remove(i)
if len(active) == 0:
ans+=1
seq.append(len(active))
m = max(increase)
seq = set(seq)
if seq == {0,1}:
print(ans-1)
else:
print(ans+max(increase))
| {
"input": [
"3\n4\n1 4\n2 3\n3 6\n5 7\n3\n5 5\n5 5\n5 5\n6\n3 3\n1 1\n5 5\n1 5\n2 2\n4 4\n"
],
"output": [
"2\n1\n5\n"
]
} |
2,592 | 8 | Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS:
You are given two integers d, m, find the number of arrays a, satisfying the following constraints:
* The length of a is n, n β₯ 1
* 1 β€ a_1 < a_2 < ... < a_n β€ d
* Define an array b of length n as follows: b_1 = a_1, β i > 1, b_i = b_{i - 1} β a_i, where β is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold.
Since the number of possible arrays may be too large, you need to find the answer modulo m.
Input
The first line contains an integer t (1 β€ t β€ 100) denoting the number of test cases in the input.
Each of the next t lines contains two integers d, m (1 β€ d, m β€ 10^9).
Note that m is not necessary the prime!
Output
For each test case, print the number of arrays a, satisfying all given constrains, modulo m.
Example
Input
10
1 1000000000
2 999999999
3 99999998
4 9999997
5 999996
6 99995
7 9994
8 993
9 92
10 1
Output
1
3
5
11
17
23
29
59
89
0 | def calc(n):
a = n.bit_length() - 1
X = [0] * 30
X[a] = n - (1 << a) + 1
for i in range(a):
X[i] = 1 << i
return X
T = int(input())
for _ in range(T):
d, m = map(int, input().split())
s = 1
for a in calc(d):
s = s * (a + 1) % m
print((s - 1) % m)
| {
"input": [
"10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n6 99995\n7 9994\n8 993\n9 92\n10 1\n"
],
"output": [
"1\n3\n5\n11\n17\n23\n29\n59\n89\n0\n"
]
} |
2,593 | 8 | Slime has a sequence of positive integers a_1, a_2, β¦, a_n.
In one operation Orac can choose an arbitrary subsegment [l β¦ r] of this sequence and replace all values a_l, a_{l + 1}, β¦, a_r to the value of median of \\{a_l, a_{l + 1}, β¦, a_r\}.
In this problem, for the integer multiset s, the median of s is equal to the β (|s|+1)/(2)β-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5.
Slime wants Orac to make a_1 = a_2 = β¦ = a_n = k using these operations.
Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.
Input
The first line of the input is a single integer t: the number of queries.
The first line of each query contains two integers n\ (1β€ nβ€ 100 000) and k\ (1β€ kβ€ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1β€ a_iβ€ 10^9)
The total sum of n is at most 100 000.
Output
The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase.
Example
Input
5
5 3
1 5 2 6 1
1 6
6
3 2
1 2 3
4 3
3 1 2 3
10 3
1 2 3 4 5 6 7 8 9 10
Output
no
yes
yes
no
yes
Note
In the first query, Orac can't turn all elements into 3.
In the second query, a_1=6 is already satisfied.
In the third query, Orac can select the complete array and turn all elements into 2.
In the fourth query, Orac can't turn all elements into 3.
In the fifth query, Orac can select [1,6] at first and then select [2,10]. | import sys
input=sys.stdin.readline
def main():
n,k=map(int,input().split())
A=list(map(int,input().split()))
if min(A) == max(A) == k:
print('yes')
return
if k not in A:
print('no')
return
A = [x >= k for x in A] + [0, 0]
print('yes' if max(sum(A[i:i+3]) for i in range(n)) > 1 else 'no')
T=int(input())
for _ in range(T):
main()
| {
"input": [
"5\n5 3\n1 5 2 6 1\n1 6\n6\n3 2\n1 2 3\n4 3\n3 1 2 3\n10 3\n1 2 3 4 5 6 7 8 9 10\n"
],
"output": [
"no\nyes\nyes\nno\nyes\n"
]
} |
2,594 | 12 | Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...
The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determined and are known before the game begins, s_i and e_i may differ from round to round). The integer s_i is written on the board at the beginning of the corresponding round.
The players will take turns. Each player will erase the number on the board (let's say it was a) and will choose to write either 2 β
a or a + 1 instead. Whoever writes a number strictly greater than e_i loses that round and the other one wins that round.
Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's s_i and e_i in advance. Lee will start the first round, the loser of each round will start the next round.
The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.
Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.
Input
The first line contains the integer t (1 β€ t β€ 10^5) β the number of rounds the game has.
Then t lines follow, each contains two integers s_i and e_i (1 β€ s_i β€ e_i β€ 10^{18}) β the i-th round's information.
The rounds are played in the same order as given in input, s_i and e_i for all rounds are known to everyone before the game starts.
Output
Print two integers.
The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise.
The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise.
Examples
Input
3
5 8
1 4
3 10
Output
1 1
Input
4
1 2
2 3
3 4
4 5
Output
0 0
Input
1
1 1
Output
0 1
Input
2
1 9
4 5
Output
0 0
Input
2
1 2
2 8
Output
1 0
Input
6
216986951114298167 235031205335543871
148302405431848579 455670351549314242
506251128322958430 575521452907339082
1 768614336404564650
189336074809158272 622104412002885672
588320087414024192 662540324268197150
Output
1 0
Note
Remember, whoever writes an integer greater than e_i loses. |
def f(s,e):
if e%2:
return 1-s%2
elif s*2>e:
return s%2
else:
return g(s,e//2)
def g(s,e):
if 2*s>e:
return 1
else:
return f(s,e//2)
a=[tuple(map(int,input().split())) for i in range(int(input()))]
b=1
for i in a:
b1=g(*i)|(f(*i)<<1)
b=b1^3 if b==2 else b1
if b==0:
print('0 0')
exit(0)
elif b==3:
print('1 1')
exit(0)
if b==2:
print('1 0')
else:
print('0 1')
| {
"input": [
"3\n5 8\n1 4\n3 10\n",
"6\n216986951114298167 235031205335543871\n148302405431848579 455670351549314242\n506251128322958430 575521452907339082\n1 768614336404564650\n189336074809158272 622104412002885672\n588320087414024192 662540324268197150\n",
"2\n1 9\n4 5\n",
"1\n1 1\n",
"2\n1 2\n2 8\n",
"4\n1 2\n2 3\n3 4\n4 5\n"
],
"output": [
"1 1\n",
"1 0\n",
"0 0\n",
"0 1\n",
"1 0\n",
"0 0\n"
]
} |
2,595 | 8 | You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times:
1. choose three integers i, j and x (1 β€ i, j β€ n; 0 β€ x β€ 10^9);
2. assign a_i := a_i - x β
i, a_j := a_j + x β
i.
After each operation, all elements of the array should be non-negative.
Can you find a sequence of no more than 3n operations after which all elements of the array are equal?
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case contains one integer n (1 β€ n β€ 10^4) β the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 10^4.
Output
For each test case print the answer to it as follows:
* if there is no suitable sequence of operations, print -1;
* otherwise, print one integer k (0 β€ k β€ 3n) β the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 β€ i, j β€ n; 0 β€ x β€ 10^9) for the m-th operation.
If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k.
Example
Input
3
4
2 16 4 18
6
1 2 3 4 5 6
5
11 19 1 1 3
Output
2
4 1 2
2 3 3
-1
4
1 2 4
2 4 5
2 3 3
4 5 1 | def trans(i, j, x):
A[i] -= i * x
A[j] += i * x
ans.append([i, j, x])
for _ in range(int(input())):
n = int(input())
A = [0] + list(map(int, input().split()))
S = sum(A)
if S % n:
print(-1)
continue
ans = []
for i in range(2, n + 1):
if A[i] % i:
trans(1, i, i - A[i] % i)
trans(i, 1, A[i] // i)
for i in range(2, n + 1):
trans(1, i, S // n)
print(len(ans))
for a in ans: print(*a)
| {
"input": [
"3\n4\n2 16 4 18\n6\n1 2 3 4 5 6\n5\n11 19 1 1 3\n"
],
"output": [
"8\n2 1 8\n1 3 2\n3 1 2\n1 4 2\n4 1 5\n1 2 10\n1 3 10\n1 4 10\n-1\n12\n1 2 1\n2 1 10\n1 3 2\n3 1 1\n1 4 3\n4 1 1\n1 5 2\n5 1 1\n1 2 7\n1 3 7\n1 4 7\n1 5 7\n"
]
} |
2,596 | 7 | There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.
Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.
Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone answers the call, in the following order:
* First he calls all apartments consisting of digit 1, in increasing order (1, 11, 111, 1111).
* Next he calls all apartments consisting of digit 2, in increasing order (2, 22, 222, 2222)
* And so on.
The resident of the boring apartment x answers the call, and our character stops calling anyone further.
Our character wants to know how many digits he pressed in total and your task is to help him to count the total number of keypresses.
For example, if the resident of boring apartment 22 answered, then our character called apartments with numbers 1, 11, 111, 1111, 2, 22 and the total number of digits he pressed is 1 + 2 + 3 + 4 + 1 + 2 = 13.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 36) β the number of test cases.
The only line of the test case contains one integer x (1 β€ x β€ 9999) β the apartment number of the resident who answered the call. It is guaranteed that x consists of the same digit.
Output
For each test case, print the answer: how many digits our character pressed in total.
Example
Input
4
22
9999
1
777
Output
13
90
1
66 | def solve(d):
l ,n= len(d) , int(d[0])
return 10*(n-1)+(l*(l+1))//2
for _ in range(int(input())):
p = input()
print(solve(p))
| {
"input": [
"4\n22\n9999\n1\n777\n"
],
"output": [
"13\n90\n1\n66\n"
]
} |
2,597 | 8 | The great hero guards the country where Homer lives. The hero has attack power A and initial health value B. There are n monsters in front of the hero. The i-th monster has attack power a_i and initial health value b_i.
The hero or a monster is said to be living, if his or its health value is positive (greater than or equal to 1); and he or it is said to be dead, if his or its health value is non-positive (less than or equal to 0).
In order to protect people in the country, the hero will fight with monsters until either the hero is dead or all the monsters are dead.
* In each fight, the hero can select an arbitrary living monster and fight with it. Suppose the i-th monster is selected, and the health values of the hero and the i-th monster are x and y before the fight, respectively. After the fight, the health values of the hero and the i-th monster become x-a_i and y-A, respectively.
Note that the hero can fight the same monster more than once.
For the safety of the people in the country, please tell them whether the great hero can kill all the monsters (even if the great hero himself is dead after killing the last monster).
Input
Each test contains multiple test cases. The first line contains t (1 β€ t β€ 10^5) β the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers A (1 β€ A β€ 10^6), B (1 β€ B β€ 10^6) and n (1 β€ n β€ 10^5) β the attack power of the great hero, the initial health value of the great hero, and the number of monsters.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^6), where a_i denotes the attack power of the i-th monster.
The third line of each test case contains n integers b_1, b_2, ..., b_n (1 β€ b_i β€ 10^6), where b_i denotes the initial health value of the i-th monster.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case print the answer: "YES" (without quotes) if the great hero can kill all the monsters. Otherwise, print "NO" (without quotes).
Example
Input
5
3 17 1
2
16
10 999 3
10 20 30
100 50 30
1000 1000 4
200 300 400 500
1000 1000 1000 1000
999 999 1
1000
1000
999 999 1
1000000
999
Output
YES
YES
YES
NO
YES
Note
In the first example: There will be 6 fights between the hero and the only monster. After that, the monster is dead and the health value of the hero becomes 17 - 6 Γ 2 = 5 > 0. So the answer is "YES", and moreover, the hero is still living.
In the second example: After all monsters are dead, the health value of the hero will become 709, regardless of the order of all fights. So the answer is "YES".
In the third example: A possible order is to fight with the 1-st, 2-nd, 3-rd and 4-th monsters. After all fights, the health value of the hero becomes -400. Unfortunately, the hero is dead, but all monsters are also dead. So the answer is "YES".
In the fourth example: The hero becomes dead but the monster is still living with health value 1000 - 999 = 1. So the answer is "NO". | from math import ceil
def answer():
check=h
for i in range(n):
check-=ceil(b[i]/p)*a[i]
check+=max(a)
if(check >= 0):return 'YES'
else:return 'NO'
for T in range(int(input())):
p,h,n=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
print(answer()) | {
"input": [
"5\n3 17 1\n2\n16\n10 999 3\n10 20 30\n100 50 30\n1000 1000 4\n200 300 400 500\n1000 1000 1000 1000\n999 999 1\n1000\n1000\n999 999 1\n1000000\n999\n"
],
"output": [
"\nYES\nYES\nYES\nNO\nYES\n"
]
} |
2,598 | 7 | A bitstring is a string that contains only the characters 0 and 1.
Koyomi Kanou is working hard towards her dream of becoming a writer. To practice, she decided to participate in the Binary Novel Writing Contest. The writing prompt for the contest consists of three bitstrings of length 2n. A valid novel for the contest is a bitstring of length at most 3n that contains at least two of the three given strings as subsequences.
Koyomi has just received the three prompt strings from the contest organizers. Help her write a valid novel for the contest.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero) characters.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5).
Each of the following three lines contains a bitstring of length 2n. It is guaranteed that these three strings are pairwise distinct.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, print a single line containing a bitstring of length at most 3n that has at least two of the given bitstrings as subsequences.
It can be proven that under the constraints of the problem, such a bitstring always exists.
If there are multiple possible answers, you may output any of them.
Example
Input
2
1
00
11
01
3
011001
111010
010001
Output
010
011001010
Note
In the first test case, the bitstrings 00 and 01 are subsequences of the output string: 010 and 010. Note that 11 is not a subsequence of the output string, but this is not required.
In the second test case all three input strings are subsequences of the output string: 011001010, 011001010 and 011001010. | def merge(x,y,c):
N = len(x); n = N//2; ans = ''; i,j = 0,0
while i<N and j<N:
if x[i]==y[j]: ans+=x[i]; i+=1; j+=1
elif x[i]!=c: ans+=x[i]; i+=1
else: ans+=y[j]; j+=1
ans += x[i:]+y[j:]; ans += '0'* (3*n - len(ans)); return ans
for _ in range(int(input())):
n = int(input()); S = [input(),input(),input()]; C0 = [j for j in range(3) if S[j].count('0')>=n]
if len(C0)>=2: print (merge (S[C0[0]],S[C0[1]],'0'))
else: C1=[j for j in range(3) if j not in C0]; print (merge (S[C1[0]],S[C1[1]],'1')) | {
"input": [
"2\n1\n00\n11\n01\n3\n011001\n111010\n010001\n"
],
"output": [
"\n010\n011001010\n"
]
} |
2,599 | 8 | Little Dormi received a histogram with n bars of height a_1, a_2, β¦, a_n for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking.
To modify the histogram, Little Dormi is able to perform the following operation an arbitrary number of times:
* Select an index i (1 β€ i β€ n) where a_i>0, and assign a_i := a_i-1.
Little Dormi defines the ugliness score of his histogram (after performing some number of operations) as the sum of the vertical length of its outline and the number of operations he performed on it. And to make the histogram as perfect as possible, he would like to minimize the ugliness score after modifying it with some number of operations.
However, as his histogram is very large, Little Dormi is having trouble minimizing the ugliness score, so as Little Dormi's older brother, help him find the minimal ugliness.
Consider the following example where the histogram has 4 columns of heights 4,8,9,6:
<image>
The blue region represents the histogram, and the red lines represent the vertical portion of the outline. Currently, the vertical length of the outline is 4+4+1+3+6 = 18, so if Little Dormi does not modify the histogram at all, the ugliness would be 18.
However, Little Dormi can apply the operation once on column 2 and twice on column 3, resulting in a histogram with heights 4,7,7,6:
<image>
Now, as the total vertical length of the outline (red lines) is 4+3+1+6=14, the ugliness is 14+3=17 dollars. It can be proven that this is optimal.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 10^4). Description of the test cases follows.
The first line of each test case contains a single integer n (1 β€ n β€ 4 β
10^5).
The second line of each test case contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 4 β
10^5.
Output
For each test case output one integer, the minimal ugliness Little Dormi can achieve with the histogram in that test case.
Example
Input
2
4
4 8 9 6
6
2 1 7 4 0 0
Output
17
12
Note
Example 1 is the example described in the statement.
The initial histogram for example 2 is given below:
<image>
The ugliness is currently 2+1+6+3+4=16.
By applying the operation once on column 1, six times on column 3, and three times on column 4, we can end up with a histogram with heights 1,1,1,1,0,0:
<image>
The vertical length of the outline is now 1+1=2 and Little Dormi made 1+6+3=10 operations, so the final ugliness is 2+10=12, which can be proven to be optimal. | def f(a):
a=[0]+a+[0]
ans=0
for i in range(1,len(a)-1):
if a[i]>a[i-1] and a[i]>a[i+1]:
ans+=(a[i]-max(a[i+1],a[i-1]))
a[i]=max(a[i+1],a[i-1])
for i in range(1,len(a)):
ans+=abs(a[i]-a[i-1])
return (ans)
for _ in range(int(input())):
l=input()
a=list(map(int,input().strip().split()))
print(f(a)) | {
"input": [
"2\n4\n4 8 9 6\n6\n2 1 7 4 0 0\n"
],
"output": [
"\n17\n12\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.