text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types:
* increase x by 1;
* decrease x by 1.
You are given m queries of the following format:
* query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order?
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases.
Then the description of t testcases follows.
The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of instructions in the program and the number of queries.
The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively.
Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the description of the query.
The sum of n over all testcases doesn't exceed 2 ⋅ 10^5. The sum of m over all testcases doesn't exceed 2 ⋅ 10^5.
Output
For each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order.
Example
Input
2
8 4
-+--+--+
1 8
2 8
2 5
1 1
4 10
+-++
1 1
1 2
2 2
1 3
2 3
3 3
1 4
2 4
3 4
4 4
Output
1
2
4
4
3
3
4
2
3
2
1
2
2
2
Note
The instructions that remain for each query of the first testcase are:
1. empty program — x was only equal to 0;
2. "-" — x had values 0 and -1;
3. "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them;
4. "+--+--+" — the distinct values are 1, 0, -1, -2.
Submitted Solution:
```
import math
import sys
input = sys.stdin.readline
T = int(input())
for t in range(T):
n,m=map(int,input().split())
script = input()
left=[(0,0,0)]
right=[[0,0]]
count=0
for i in range(len(script)):
if(script[i]=="+"):
count+=1
else:
count-=1
left.append((min(left[-1][0],count),count,max(left[-1][2],count)))
count=0
for i in range(len(script)-1,-1,-1):
k=[right[0][0],right[0][1]]
if(script[i]=="+"):
k[1]+=1
if(k[0]!=0):
k[0]+=1
else:
k[0]-=1
if(k[1]!=0):
k[1]-=1
right.insert(0,k)
for i in range(m):
a,b=map(int,input().split())
Min=min(left[a-1][0],left[a-1][1]+right[b][0])
Max=max(left[a-1][2],left[a-1][1]+right[b][1])
sys.stdout.write(str(Max-Min+1)+'\n')
```
No
| 95,500 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types:
* increase x by 1;
* decrease x by 1.
You are given m queries of the following format:
* query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order?
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases.
Then the description of t testcases follows.
The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of instructions in the program and the number of queries.
The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively.
Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the description of the query.
The sum of n over all testcases doesn't exceed 2 ⋅ 10^5. The sum of m over all testcases doesn't exceed 2 ⋅ 10^5.
Output
For each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order.
Example
Input
2
8 4
-+--+--+
1 8
2 8
2 5
1 1
4 10
+-++
1 1
1 2
2 2
1 3
2 3
3 3
1 4
2 4
3 4
4 4
Output
1
2
4
4
3
3
4
2
3
2
1
2
2
2
Note
The instructions that remain for each query of the first testcase are:
1. empty program — x was only equal to 0;
2. "-" — x had values 0 and -1;
3. "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them;
4. "+--+--+" — the distinct values are 1, 0, -1, -2.
Submitted Solution:
```
def solve():
n, q = map(int, input().split())
instructions = input()
a = [0]*n
x = 0
for i in range(n):
if instructions[i] == '-':
x -= 1
else:
x += 1
a[i] = x
lmis = [0]*n
lmas = [0]*n
rmis = [0]*n
rmas = [0]*n
for i in range(n):
if i == 0:
lmis[i] = min(a[i], 0)
lmas[i] = max(a[i], 0)
continue
if a[i] < lmis[i-1]:
lmis[i] = a[i]
else:
lmis[i] = lmis[i-1]
if a[i] > lmas[i-1]:
lmas[i] = a[i]
else:
lmas[i] = lmas[i-1]
for i in reversed(range(n)):
if i == n-1:
rmis[i] = a[i]
rmas[i] = a[i]
continue
if a[i] < rmis[i+1]:
rmis[i] = a[i]
else:
rmis[i] = rmis[i+1]
if a[i] > rmas[i+1]:
rmas[i] = a[i]
else:
rmas[i] = rmas[i+1]
for _ in range(q):
l, r = map(int, input().split())
r -= 1
l -= 1
delta = a[r] - a[l]
if instructions[l] == '+':
delta += 1
else:
delta -= 1
lmi = 0
lma = 0
if(l > 0):
lmi = lmis[l-1]
lma = lmas[l-1]
rmi = rmis[r]
rma = rmas[r]
rmi -= delta
rma -= delta
mi = min(lmi, rmi)
ma = max(lma, rma)
print('ans', ma-mi+1)
t = int(input())
for _ in range(t):
solve()
```
No
| 95,501 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer k and an undirected tree, consisting of n vertices.
The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of this tree.
You are about to remove a set of edges from the tree. The tree splits into multiple smaller trees when the edges are removed. The set of edges is valid if all the resulting trees have diameter less than or equal to k.
Two sets of edges are different if there is an edge such that it appears in only one of the sets.
Count the number of valid sets of edges modulo 998 244 353.
Input
The first line contains two integers n and k (2 ≤ n ≤ 5000, 0 ≤ k ≤ n - 1) — the number of vertices of the tree and the maximum allowed diameter, respectively.
Each of the next n-1 lines contains a description of an edge: two integers v and u (1 ≤ v, u ≤ n, v ≠ u).
The given edges form a tree.
Output
Print a single integer — the number of valid sets of edges modulo 998 244 353.
Examples
Input
4 3
1 2
1 3
1 4
Output
8
Input
2 0
1 2
Output
1
Input
6 2
1 6
2 4
2 6
3 6
5 6
Output
25
Input
6 3
1 2
1 5
2 3
3 4
5 6
Output
29
Note
In the first example the diameter of the given tree is already less than or equal to k. Thus, you can choose any set of edges to remove and the resulting trees will have diameter less than or equal to k. There are 2^3 sets, including the empty one.
In the second example you have to remove the only edge. Otherwise, the diameter will be 1, which is greater than 0.
Here are the trees for the third and the fourth examples:
<image>
Tags: combinatorics, dfs and similar, dp, trees
Correct Solution:
```
import sys
from collections import deque
input = lambda :sys.stdin.buffer.readline()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
mod = 998244353
N,K = mi()
edge = [[] for i in range(N)]
for _ in range(N-1):
a,b = mi()
edge[a-1].append(b-1)
edge[b-1].append(a-1)
parent = [-1 for i in range(N)]
deq = deque([0])
res = []
while deq:
v = deq.popleft()
res.append(v)
for nv in edge[v]:
if nv!=parent[v]:
parent[nv] = v
deq.append(nv)
dp = [[1] for i in range(N)]
def merge(v,nv):
res_dp = [0 for i in range(max(len(dp[v]),len(dp[nv])+1))]
for i in range(len(dp[v])):
for j in range(len(dp[nv])):
if j+1+i <= K:
res_dp[max(j+1,i)] += dp[v][i] * dp[nv][j]
res_dp[max(j+1,i)] %= mod
res_dp[i] += dp[v][i] * dp[nv][j]
res_dp[i] %= mod
dp[v] = res_dp
for v in res[::-1]:
for nv in edge[v]:
if nv==parent[v]:
continue
merge(v,nv)
print(sum(dp[0][i] for i in range(min(K+1,len(dp[0])))) % mod)
```
| 95,502 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer k and an undirected tree, consisting of n vertices.
The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of this tree.
You are about to remove a set of edges from the tree. The tree splits into multiple smaller trees when the edges are removed. The set of edges is valid if all the resulting trees have diameter less than or equal to k.
Two sets of edges are different if there is an edge such that it appears in only one of the sets.
Count the number of valid sets of edges modulo 998 244 353.
Input
The first line contains two integers n and k (2 ≤ n ≤ 5000, 0 ≤ k ≤ n - 1) — the number of vertices of the tree and the maximum allowed diameter, respectively.
Each of the next n-1 lines contains a description of an edge: two integers v and u (1 ≤ v, u ≤ n, v ≠ u).
The given edges form a tree.
Output
Print a single integer — the number of valid sets of edges modulo 998 244 353.
Examples
Input
4 3
1 2
1 3
1 4
Output
8
Input
2 0
1 2
Output
1
Input
6 2
1 6
2 4
2 6
3 6
5 6
Output
25
Input
6 3
1 2
1 5
2 3
3 4
5 6
Output
29
Note
In the first example the diameter of the given tree is already less than or equal to k. Thus, you can choose any set of edges to remove and the resulting trees will have diameter less than or equal to k. There are 2^3 sets, including the empty one.
In the second example you have to remove the only edge. Otherwise, the diameter will be 1, which is greater than 0.
Here are the trees for the third and the fourth examples:
<image>
Submitted Solution:
```
nk = input().split()
n, k = int(nk[0]), int(nk[1])
if n == 4 and k == 3: print(8)
if n == 2 and k == 0: print(1)
if n == 6 and k == 2: print(25)
if n == 6 and k == 3: print(29)
```
No
| 95,503 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
'''Author- Akshit Monga'''
# Don't know the proper proof
from sys import stdin, stdout
input = stdin.readline
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def detach(start,parent):
global removed
childs=list(graph[start])
for i in childs:
if i==parent:
continue
yield detach(i,start)
childs=graph[start].copy()
if parent:
childs.remove(parent)
childs=list(childs)
if len(childs)>=2:
if parent:
removed.append((start,parent))
graph[start].remove(parent)
graph[parent].remove(start)
for i in childs[2:]:
removed.append((start,i))
graph[start].remove(i)
graph[i].remove(start)
yield
@bootstrap
def dfs(start):
global check
vis.add(start)
count=0
for i in graph[start]:
count+=1
if i not in vis:
yield dfs(i)
if count==0:
leaves.append(start)
leaves.append(start)
elif count==1:
leaves.append(start)
yield
t = int(input())
for _ in range(t):
n=int(input())
graph=[set() for i in range(n+1)]
for i in range(n-1):
a,b=map(int,input().split())
graph[a].add(b)
graph[b].add(a)
removed=[]
added=[]
leaves=[]
detach(1,0)
vis=set()
for i in range(1,n+1):
if i not in vis:
dfs(i)
for i in range(1,len(leaves)-1,2):
added.append((leaves[i],leaves[i+1]))
x=len(removed)
print(x)
for i in range(x):
stdout.write(str(removed[i][0])+" "+str(removed[i][1])+" "+str(added[i][0])+" "+str(added[i][1])+'\n')
```
| 95,504 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
n = int(input())
edges = [list(map(int,input().split())) for i in range(n-1)]
adj = [set() for i in range(n+1)]
for a,b in edges:
adj[a].add(b)
adj[b].add(a)
operations = []
#removed_edge = [0]*(n-1)
visited = [0] * (n + 1)
parent = [0]*(n+1)
s = [1]
while s:
c = s[-1]
if not visited[c]:
visited[c] = 1
for ne in adj[c]:
if not visited[ne]:
parent[ne] = c
s.append(ne)
else:
if len(adj[c]) > 2:
if parent[c]:
operations.append([c,parent[c]])
adj[parent[c]].remove(c)
adj[c].remove(parent[c])
while len(adj[c]) > 2:
x = adj[c].pop()
adj[x].remove(c)
operations.append([x, c])
s.pop()
'''for i in range(n-1):
a,b = edges[i]
if len(adj[a]) > 2 and len(adj[b]) > 2:
operations.append([a,b])
adj[a].remove(b)
adj[b].remove(a)
removed_edge[i] = 1
for i in range(n-1):
a,b = edges[i]
if not removed_edge[i]:
if len(adj[a]) > 2:
operations.append([a,b])
adj[a].remove(b)
adj[b].remove(a)
if len(adj[b]) > 2:
operations.append([a, b])
adj[a].remove(b)
adj[b].remove(a)
'''
endpoints = []
visited = [0]*(n+1)
for i in range(1,n+1):
if not visited[i]:
endpoints.append([])
s = [i]
while s:
c = s[-1]
if not visited[c]:
visited[c] = 1
if len(adj[c]) <= 1:
endpoints[-1].append(c)
for ne in adj[c]:
s.append(ne)
else:
s.pop()
assert(len(operations) == len(endpoints) -1)
for i in range(len(endpoints)-1):
if len(endpoints[i]) == 1:
endpoints[i].append(endpoints[i][0])
operations[i].extend([endpoints[i][1],endpoints[i+1][0]])
print(len(operations))
for operation in operations:
print(*operation)
```
| 95,505 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
import sys
sys.setrecursionlimit(250010)
def dfs(x):
tag[x] = 1
ql = -1
tgs = (-1, -1)
l = 0
for v in lian[x]:
if tag[v] == 0:
t = dfs(v)
gs[v][0] = t[0]
gs[v][1] = t[1]
if gs[v][0] == -1 and ql == -1:
ql = v
q[x].append(v)
l += 1
if l == 0:
tag[x] = 0
return (-1, x)
if ql == -1:
for i in range(l-1):
ans[0] += 1
res[ans[0]-1] = (q[x][i], x, gs[q[x][i]][0], gs[q[x][i+1]][0])
gs[q[x][i+1]][0] = gs[q[x][i]][1]
ans[0] += 1
res[ans[0]-1] = (q[x][l-1], x, gs[q[x][l-1]][0], x)
tgs = (-1, gs[q[x][l-1]][1])
else:
v2 = ql
last = -1
for i in range(l):
if gs[q[x][i]][0] != -1:
ans[0] += 1
res[ans[0]-1] = (q[x][i], x, gs[q[x][i]][0], gs[v2][1])
gs[v2][1] = gs[q[x][i]][1]
else:
last = q[x][i]
for i in range(l):
if gs[q[x][i]][0] == -1 and q[x][i] != v2 and q[x][i] != last:
ans[0] += 1
res[ans[0]-1] = (q[x][i], x, q[x][i], gs[v2][1])
gs[v2][1] = gs[q[x][i]][1]
if last == v2:
tgs = (-1, gs[v2][1])
else:
tgs = (gs[v2][1], gs[last][1])
tag[x] = 0
return tgs
for _ in range(int(input())):
n = int(input())
q = [[] for i in range(n+1)]
lian = [[] for i in range(n+1)]
tag = [0] * (n+1)
res = [0]* (n+1)
ans = [0]
gs = [[-1,-1] for i in range(n+1)]
for i in range(n-1):
a,b = map(int, input().split())
lian[a].append(b)
lian[b].append(a)
dfs(1)
print(ans[0])
for t in range(ans[0]):
i = res[t]
print(i[0],i[1],i[2],i[3])
```
| 95,506 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
import io
import os
from collections import defaultdict
from types import GeneratorType
from heapq import heappush, heappop
# From https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def solve(N, edges):
graph = [[] for i in range(N)]
for (u, v) in edges:
graph[u].append(v)
graph[v].append(u)
dp1 = [0] * N
dp2 = [0] * N
bp1 = [()] * N # back pointers
bp2 = [()] * N
@bootstrap
def dfs(node, p):
for child in graph[node]:
if child != p:
yield dfs(child, node)
total = 0 # total if connected with no children
heap = [] # sorted connectable children
for child in graph[node]:
if child != p:
total += dp2[child]
heappush(heap, (dp2[child] - dp1[child], child))
if heap:
# Connect with 1 child
gain1, child1 = heappop(heap)
gain1 *= -1
score1 = 1 + total + gain1
if dp1[node] < score1:
dp1[node] = score1
bp1[node] = (child1,)
if dp2[node] < score1:
dp2[node] = score1
bp2[node] = (child1,)
if heap:
# Connect with 2 children
gain2, child2 = heappop(heap)
gain2 *= -1
assert gain2 <= gain1
score2 = 2 + total + gain1 + gain2
if dp2[node] < score2:
dp2[node] = score2
bp2[node] = (child1, child2)
assert dp1[node] <= dp2[node]
yield
dfs(0, -1)
disconnect = []
@bootstrap
def dfs2(node, p, isConnected):
if not isConnected and dp1[node] < dp2[node]:
connectedChild = bp2[node]
else:
connectedChild = bp1[node]
for child in graph[node]:
if child != p:
childConnected = child in connectedChild
if not childConnected:
disconnect.append((node, child))
yield dfs2(child, node, childConnected)
yield
dfs2(0, -1, False)
# Construct the paths
disconnect = set(disconnect)
uf = UnionFind(N)
degree = [0] * N
for u, v in edges:
if (u, v) in disconnect or (v, u) in disconnect:
continue
degree[u] += 1
degree[v] += 1
uf.union(u, v)
paths = defaultdict(list)
for u in range(N):
if degree[u] <= 1:
paths[uf.find(u)].append(u)
endpoints = list(paths.values())
# Join the endpoints
ops = []
for i in range(len(endpoints) - 1):
x = endpoints[i][-1]
y = endpoints[i + 1][0]
u, v = disconnect.pop()
ops.append(" ".join(str(i + 1) for i in [u, v, x, y]))
assert not disconnect
assert len(ops) == N - 1 - max(dp1[0], dp2[0])
return str(len(ops)) + "\n" + "\n".join(ops)
class UnionFind:
def __init__(self, N):
# Union find with component size
# Negative means is a root where value is component size
# Otherwise is index to parent
self.p = [-1 for i in range(N)]
def find(self, i):
# Find root with path compression
if self.p[i] >= 0:
self.p[i] = self.find(self.p[i])
return self.p[i]
else:
return i
def union(self, i, j):
# Union by size
root1 = self.find(j)
root2 = self.find(i)
if root1 == root2:
return
size1 = -self.p[root1]
size2 = -self.p[root2]
if size1 < size2:
self.p[root1] = root2
self.p[root2] = -(size1 + size2)
else:
self.p[root2] = root1
self.p[root1] = -(size1 + size2)
def getComponentSize(self, i):
return -self.p[self.find(i)]
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
(N,) = [int(x) for x in input().split()]
edges = [[int(x) - 1 for x in input().split()] for i in range(N - 1)]
ans = solve(N, edges)
print(ans)
```
| 95,507 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
def leaf(f,u):
if len(m[u])==1:
return u
else:
for v in m[u]:
if v!=f:
ans=leaf(u,v)
if ans:return ans
def cut():
stack=[]
stack.append([0,-1,leaf(-1,0)])
while len(stack):
a,*b=stack.pop()
f,u=b
if a==0:
stack.append([1,f,u])
for v in m[u]-{f}:
stack.append([0,u,v])
elif a==1:
du=len(m[u])
it=iter(m[u]-{f})
if du>=3:
while du>=4:
v=next(it)
ct.append((u+1,v+1))
m[v].remove(u)
m[u].remove(v)
du-=1
if f!=-1:
ct.append((f+1,u+1))
m[u].remove(f)
m[f].remove(u)
def link():
l=set()
node=-1
for i in range(n):
if len(m[i])<=1:
l.add(i)
v=next(iter(l))
l.discard(v)
u=end(v)
l.discard(u)
while len(l)!=0:
v=next(iter(l))
l.discard(v)
lk.append((u+1,v+1))
u=end(v)
l.discard(u)
def end(s):
if len(m[s])==0:return s
f=s
s=next(iter(m[s]))
while len(m[s])!=1:
f,s=s,next(iter(m[s]-{f}))
return s
for test in range(int(input())):
n=int(input())
m=[set() for i in range(n)]
ct=[]
lk=[]
for i in range(n-1):
a,b=(int(i)-1 for i in input().split())
m[a].add(b);m[b].add(a)
cut()
link()
op=zip(ct,lk)
print(len(ct))
for c,l in op:
print(*c,*l)
```
| 95,508 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
import sys
sys.setrecursionlimit(111111)
def dfs(x):
tag[x] = 1
q = []
ql = -1
tgs = [-1, -1]
for v in lian[x]:
if tag[v] == 0:
gs[v] = dfs(v)
if gs[v][0] == -1 and ql == -1:
ql = v
q.append(v)
if len(q) == 0:
return [-1, x]
if ql == -1:
for i in range(len(q)-1):
v1 = q[i]
v2 = q[i+1]
ans[0] += 1
res.append((v1, x, gs[v1][0], gs[v2][0]))
gs[v2][0] = gs[v1][1]
v = q[len(q)-1]
ans[0] += 1
res.append((v, x, gs[v][0], x))
tgs = [-1, gs[v][1]]
else:
v2 = ql
last = -1
for i in range(len(q)):
v1 = q[i]
if gs[v1][0] != -1:
ans[0] += 1
res.append((v1, x, gs[v1][0], gs[v2][1]))
gs[v2][1] = gs[v1][1]
else:
last = v1
for i in range(len(q)):
v1 = q[i]
if gs[v1][0] == -1 and v1 != v2 and v1 != last:
ans[0] += 1
res.append((v1, x, v1, gs[v2][1]))
gs[v2][1] = gs[v1][1]
if last == v2:
tgs = [-1, gs[v2][1]]
else:
tgs = [gs[v2][1], gs[last][1]]
return tgs
for i in range(len(q)-1):
v = q[i][1]
dus = q[i][0]
if dus == 3:
ans[0] += 1
for _ in range(int(input())):
n = int(input())
du = [0]*(n+1)
lian = [[] for i in range(n+1)]
tag = [0] * (n+1)
res = []
ans = [0]
gs = [[-1,-1] for i in range(n+1)]
for i in range(n-1):
a,b = map(int, input().split())
du[a] += 1
du[b] += 1
lian[a].append(b)
lian[b].append(a)
dfs(1)
print(ans[0])
for i in res:
print(i[0],i[1],i[2],i[3])
```
| 95,509 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
import time
#start_time = time.time()
#def TIME_(): print(time.time()-start_time)
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string, heapq as h
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def getInt(): return int(input())
def getStrs(): return input().split()
def getInts(): return list(map(int,input().split()))
def getStr(): return input()
def listStr(): return list(input())
def getMat(n): return [getInts() for _ in range(n)]
def getBin(): return list(map(int,list(input())))
def isInt(s): return '0' <= s[0] <= '9'
def ceil_(a,b): return a//b + (a%b > 0)
MOD = 10**9 + 7
"""
"""
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def solve():
N = getInt()
G = [[] for _ in range(N)]
deg = [0]*N
par = [-1]*N
for i in range(N-1):
a, b = getInts()
G[a-1].append(b-1)
G[b-1].append(a-1)
#to_remove = []
to_add = []
leaves = []
removed = set()
global count
count = 0
@bootstrap
def dfs(node):
global count
children = 0
for neigh in G[node]:
if neigh != par[node]:
par[neigh] = node
yield dfs(neigh)
if (node, neigh) not in removed: children += 1
if children == 2:
if par[node] != -1:
#to_remove.append((par[node],node))
count += 1
removed.add((par[node],node))
if children > 2:
if par[node] != -1:
count += 1
removed.add((par[node],node))
idx = len(G[node]) - 1
while children > 2:
if G[node][idx] == par[node]: idx -= 1
#to_remove.append((node,G[node][idx]))
count += 1
while (node,G[node][idx]) in removed or G[node][idx] == par[node]:
idx -= 1
removed.add((node,G[node][idx]))
children -= 1
idx -= 1
yield
dfs(0)
ends = []
used = [0]*N
global flag
@bootstrap
def dfs2(node):
global flag
if flag: neighs = 1
else: neighs = 0
flag = True
used[node] = 1
for neigh in G[node]:
if not used[neigh] and (node,neigh) not in removed and (neigh,node) not in removed:
neighs += 1
yield dfs2(neigh)
if neighs == 1:
ends.append(node)
elif neighs == 0:
ends.append(node)
ends.append(node)
yield
for i in range(N):
flag = False
if not used[i]:
dfs2(i)
removed = list(removed)
#print(removed)
#print(ends)
#print(len(ends))
print(len(removed))
j = 0
for i in range(1,len(ends)-1,2):
print(removed[j][0]+1,removed[j][1]+1,ends[i]+1,ends[i+1]+1)
j += 1
return
for _ in range(getInt()):
#print(solve())
solve()
#TIME_()
```
| 95,510 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
def dfs(x, e, v, g):
v[x] = True
c = 0
for y in e[x]:
if not y in v:
if dfs(y, e, v, g):
c += 1
if c > 2:
g.append((x, y))
else:
g.append((x, y))
if c < 2:
return True
if x != 1:
return False
def leaf(x, e):
p = 0
while True:
u = 0
for y in e[x]:
if y != p:
u = y
break
if u == 0: break
p = x
x = u
return x
def solve(n, e):
g = []
dfs(1, e, {}, g)
for x, y in g:
e[x].remove(y)
e[y].remove(x)
z = []
l = leaf(1, e)
for p, y, in g:
r = leaf(y, e)
z.append((p, y, l, r))
l = leaf(r, e)
print(len(z))
if len(z) > 0:
print('\n'.join(map(lambda x: ' '.join(map(str, x)), z)))
def main():
t = int(input())
for i in range(t):
n = int(input())
e = {}
for i in range(n - 1):
a, b = map(int, input().split())
if not a in e: e[a] = []
if not b in e: e[b] = []
e[a].append(b)
e[b].append(a)
solve(n, e)
import threading
import sys
sys.setrecursionlimit(10 ** 5 + 1)
threading.stack_size(262000)
main = threading.Thread(target=main)
main.start()
main.join()
```
| 95,511 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
'''
from bisect import bisect,bisect_left
from collections import *
from heapq import *
from math import gcd,ceil,sqrt,floor,inf
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *'''
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
mod=10**9+7
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
class ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]>self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
class UF:#秩+路径+容量,边数
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
self.size=AI(n,1)
self.edge=A(n)
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
self.edge[pu]+=1
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
self.edge[pu]+=self.edge[pv]+1
self.size[pu]+=self.size[pv]
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
self.edge[pv]+=self.edge[pu]+1
self.size[pv]+=self.size[pu]
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return flag
def dij(s,graph):
d=AI(n,inf)
d[s]=0
heap=[(0,s)]
vis=A(n)
while heap:
dis,u=heappop(heap)
if vis[u]:
continue
vis[u]=1
for v,w in graph[u]:
if d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def bell(s,g):#bellman-Ford
dis=AI(n,inf)
dis[s]=0
for i in range(n-1):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change=A(n)
for i in range(n):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change[v]=1
return dis
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j,n,m):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@bootstrap
def gdfs(r,p):
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
#from random import randint
from heapq import *
@bootstrap
def dfs(r,p):
s=0
one=[]
for ch in g[r]:
if ch!=p:
child[r].append(ch)
yield dfs(ch,r)
ma=max(dp[ch])
s+=ma
t1=dp[ch][1]
if t1+1>ma:
heappush(one,[ma-t1-1,ch])
#print(r,one)
if not one:
dp[r]=[s,s,s]
elif len(one)==1:
v,ch=heappop(one)
ma=max(dp[ch])
for i in range(3):
if dp[ch][i]==ma:
break
g1[r].append((ch,i))
dp[r]=[s,s-v,s-v]
else:
v,ch=heappop(one)
v2,ch2=heappop(one)
ma=max(dp[ch])
for i in range(3):
if dp[ch][i]==ma:
break
g1[r].append((ch,i))
g2[r].append((ch,i))
ma2=max(dp[ch2])
for i in range(3):
if dp[ch2][i]==ma2:
break
g2[r].append((ch2,i))
dp[r]=[s,s-v,s-v-v2]
yield None
@bootstrap
def dfs2(r,t):
used=set()
#print(r,t)
if t==1:
#print(r)
ch,i=g1[r][0]
used.add(ch)
x,y=r,ch
if x>y:
x,y=y,x
nedge.add((x,y))
yield dfs2(ch,i)
elif t==2:
for ch,i in g2[r]:
used.add(ch)
x,y=r,ch
if x>y:
x,y=y,x
nedge.add((x,y))
yield dfs2(ch,i)
for ch in child[r]:
if ch not in used:
ma=max(dp[ch])
for i in range(3):
if dp[ch][i]==ma:
break
#print(r,ch,i)
yield dfs2(ch,i)
yield None
t=N()
for i in range(t):
n=N()
g=G(n)
edge=[]
for i in range(n-1):
a,b=RL()
a-=1
b-=1
g[a].append(b)
g[b].append(a)
if a>b:
a,b=b,a
edge.append((a,b))
g1=G(n)
g2=G(n)
dp=[[0]*3 for i in range(n)]
child=G(n)
dfs(0,-1)
ma=max(dp[0])
for i in range(3):
if dp[0][i]==ma:
break
nedge=set()
#print(dp,i)
#print(g1)
#print(g2)
dfs2(0,i)
delt=[]
add=[]
for x,y in edge:
if (x,y) not in nedge:
delt.append((x,y))
na=G(n)
#ind=A(n)
for x,y in nedge:
na[x].append(y)
na[y].append(x)
#print(nedge,na)
vis=A(n)
for i in range(n):
if len(na[i])==0:
add.append((i,i))
elif len(na[i])==1 and not vis[i]:
#print(i)
u=i
vis[u]=1
v=na[u][0]
while len(na[v])!=1:
#print(i,v)
for ch in na[v]:
if ch!=i:
i,v=v,ch
#print(i,v)
break
add.append((u,v))
vis[v]=1
#print(u,v,vis)
#print(add,delt)
i=0
print(len(delt))
for i in range(len(delt)):
x2,y2=add[i][1],add[i+1][0]
x1,y1=delt[i]
print(x1+1,y1+1,x2+1,y2+1)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
```
Yes
| 95,512 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
def order(n,G):
ans = []
parent = [-1]*n
def dfs(x,par):
parent[x] = par
for y in G[x]:
if y == par:
continue
dfs(y,x)
ans.append(x)
dfs(1,-1)
return ans,parent
def solve(n,G,topo,parent):
to_remove = []
for x in topo:
p = parent[x]
num_child = len(G[x]) - (1 if p in G[x] else 0)
if num_child <= 1:
pass
else:
if p != -1:
to_remove.append((x,p))
G[x].remove(p)
G[p].remove(x)
to_select = 0
tmp = []
for y in G[x]:
if y == p:
continue
if to_select < 2:
to_select += 1
else:
to_remove.append((y,x))
tmp.append(y)
for y in tmp:
G[x].remove(y)
G[y].remove(x)
visited = [False]*n
def find_bamboo(x):
visited[x] = True
if not G[x]:
return x,x
par = x
while len(G[x]) > 1:
for y in G[x]:
if y != par:
par = x
x = y
break
par = x
cur = list(G[x])[0]
visited[x] = True
visited[cur] = True
while len(G[cur]) > 1:
for y in G[cur]:
if y != par:
par = cur
cur = y
visited[y] = True
break
return x,cur
bamboos = []
for x in range(n):
if not visited[x]:
u,v = find_bamboo(x)
bamboos.append((u,v))
k = len(to_remove)
print(k)
for i in range(k):
a,b = bamboos[i][1], bamboos[i+1][0]
u,v = to_remove[i]
print(u+1,v+1,a+1,b+1)
return
for nt in range(int(input())):
n = int(input())
G = [set() for _ in range(n)]
for _ in range(n-1):
a,b = map(int,input().split())
G[a-1].add(b-1)
G[b-1].add(a-1)
topo,parent = order(n,G)
solve(n,G,topo,parent)
```
Yes
| 95,513 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
import sys
def readline():
return map(int, input().split())
def solve():
n = int(input())
nbrs = [list() for __ in range(n)]
for __ in range(n - 1):
ai, bi = readline()
ai -= 1
bi -= 1
nbrs[ai].append(bi)
nbrs[bi].append(ai)
to_delete = list()
pos = 0
parent = -1
arr = list(nbrs[pos]) # copy
stack = [(pos, parent, arr)]
while stack:
pos, parent, arr = stack[-1]
if arr:
child = arr.pop()
if child != parent and len(nbrs[child]) > 1:
pos, parent = child, pos
stack.append((pos, parent, list(nbrs[pos])))
continue
else:
stack.pop()
if len(nbrs[pos]) > 2 and parent >= 0:
nbrs[pos].remove(parent)
nbrs[parent].remove(pos)
to_delete.append((pos, parent))
while len(nbrs[pos]) > 2:
child = nbrs[pos].pop()
nbrs[child].remove(pos)
to_delete.append((pos, child))
segments = list()
is_tail = [False] * n
for i in range(n):
p = len(nbrs[i])
assert p <= 2
if p == 0:
segments.append((i, i))
if is_tail[i] or p != 1:
continue
pos, = nbrs[i]
prev = i
while len(nbrs[pos]) == 2:
prev, pos = pos, sum(nbrs[pos]) - prev
assert len(nbrs[pos]) == 1
is_tail[pos] = True
segments.append((i, pos))
a, b = segments.pop()
k = len(to_delete)
assert k == len(segments)
print(k)
for ((x1, y1), (c, d)) in zip(to_delete, segments):
print(x1 + 1, y1 + 1, b + 1, d + 1)
b = c
def main():
t = int(input())
for __ in range(t):
solve()
if __name__ == '__main__':
main()
```
Yes
| 95,514 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import log,gcd
input = lambda :sys.stdin.buffer.readline()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
INF = 10**17
def test(n):
p = [i+1 for i in range(n)]
random.shuffle(p)
Edge = []
for i in range(1,n):
pv = random.randint(0,i-1)
Edge.append((p[pv],p[i]))
return Edge
def line(N):
node = [i+2 for i in range(N-1)]
random.shuffle(node)
node = [1] + node
edge=[]
for i in range(1,N):
edge.append((node[i-1],node[i]))
return edge
def star(N):
node = [i+1 for i in range(N)]
random.shuffle(node)
edge = []
for i in range(1,N):
if random.randint(0,9999)%2:
edge.append((node[0],node[i]))
else:
edge.append((node[i],node[0]))
return edge
for _ in range(int(input())):
n = int(input())
#Edge = test(n)
edge = [[] for i in range(n)]
for i in range(n-1):
a,b = mi()
edge[a-1].append(b-1)
edge[b-1].append(a-1)
deq = deque([0])
parent = [-1]*n
topo = []
while deq:
v = deq.popleft()
topo.append(v)
for nv in edge[v]:
if nv!=parent[v]:
parent[nv] = v
deq.append(nv)
topo = topo[::-1]
dp = [[0,INF,INF] for v in range(n)]
not_cut = [[None,-1,(-1,-1)] for v in range(n)]
def merge(v,nv):
a,b,c = dp[v]
dp[v][0] += min(dp[nv]) + 1
dp[v][1] += min(dp[nv]) + 1
dp[v][2] += min(dp[nv]) + 1
if b + min(dp[nv][0],dp[nv][1]) < dp[v][2]:
not_cut[v][2] = (not_cut[v][1],nv)
dp[v][2] = b + min(dp[nv][0],dp[nv][1])
if a + min(dp[nv][0],dp[nv][1]) < dp[v][1]:
not_cut[v][1] = nv
dp[v][1] = a + min(dp[nv][0],dp[nv][1])
for v in topo:
for nv in edge[v]:
if nv!=parent[v]:
merge(v,nv)
topo = topo[::-1]
limit = [2 for v in range(n)]
print(min(dp[0]))
CUT = []
_ADD = []
for v in topo:
if limit[v]==1:
if dp[v][1] < dp[v][0]:
for nv in edge[v]:
if nv!=parent[v]:
if nv!=not_cut[v][1]:
CUT.append((v,nv))
else:
limit[nv] = 1
else:
for nv in edge[v]:
if nv!=parent[v]:
CUT.append((v,nv))
else:
if dp[v][2] < dp[v][1]:
a,b = -1,-1
for nv in edge[v]:
if nv!=parent[v]:
if nv not in not_cut[v][2]:
CUT.append((v,nv))
else:
limit[nv] = 1
while not_cut[nv][1]!=-1:
if dp[nv][1] < dp[nv][0]:
nv = not_cut[nv][1]
else:
break
if a==-1:
a = nv
else:
b = nv
_ADD.append((a,b))
else:
if dp[v][1] < dp[v][0]:
a,b = v,-1
for nv in edge[v]:
if nv!=parent[v]:
if nv!=not_cut[v][1]:
CUT.append((v,nv))
else:
limit[nv] = 1
while not_cut[nv][1]!=-1:
if dp[nv][1] < dp[nv][0]:
nv = not_cut[nv][1]
else:
break
b = nv
_ADD.append((a,b))
else:
_ADD.append((v,v))
for nv in edge[v]:
if nv!=parent[v]:
CUT.append((v,nv))
for i in range(len(_ADD)-1):
a,b = _ADD[i]
c,d = _ADD[i+1]
u,v = CUT[i]
print(u+1,v+1,b+1,c+1)
assert len(CUT)==min(dp[0])
assert len(CUT)==len(_ADD)-1
```
Yes
| 95,515 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
import sys
# sys.stdin = open("actext.txt", "r")
t = int(input())
for tt in range(t):
n = int(input())
adj_list = [[] for i in range(n+1)]
for i in range(n-1):
x, y = map(int, input().split())
adj_list[x].append(y)
deg = []
for num, i in enumerate(adj_list[1:]):
if(num == 0):
deg.append(len(i))
else:
deg.append(len(i)+1)
ans = 0
toattach = -1
for num, j in enumerate(deg[1:]):
if(j == 1):
toattach = num+2
break
for i in deg:
ans += max(0, i-2)
print(ans)
# print(deg)
degg = list(zip(deg,[i for i in range(1,n+1)]))
degg.sort()
st = []
# print(degg)
# print(adj_list)
for k,kk in degg:
if(k>2):
st.append(kk)
# print(st)
for num in st:
if(num==1):
cnt = 2
else:
cnt=1
if(deg[num-1] > 2):
elem = adj_list[num][cnt:]
for j in elem:
print(num, j, toattach, j)
ff = j
while(len(adj_list[ff])!=0):
ff = adj_list[ff][0]
toattach = ff
```
No
| 95,516 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
how_much_t = int(input())
max_of_tops = 2#int(input("Введите максимальное количество вершин\n"))
for global_cycle in range(how_much_t):
this_tops = int(input())
quan_of_ribs = []
for cycle in range(this_tops - 1):
quan_of_ribs.append(list(map(int, input().split(" "))))
if this_tops == 7:
print("2")
print("2 1 5 6")
print("3 6 4 7")
elif this_tops == 4:
print("0")
```
No
| 95,517 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
def dfs1(n,G,x,par,B):
# return an endpoint of a bamboo
# push extra nodes to B
if len(G[x]) == 1:
return x
found = False
for y in G[x]:
if y == par:
continue
if not found:
found = True
ans = dfs1(n,G,y,x,B)
else:
B.append((y,x))
return ans
def dfs2(n,G,x,par,B):
# num_child >= 2
to_select = []
for y in G[x]:
if y == par:
continue
if len(to_select) < 2:
to_select.append(y)
else:
B.append((y,x))
a,b = to_select
u = dfs1(n,G,a,x,B)
v = dfs1(n,G,b,x,B)
return u,v
def solve(n,G):
B = [(0,-1)]
to_remove = []
bamboo = []
while B:
x,par = B.pop()
num_child = sum(1 for y in G[x] if y != par)
if par != -1:
to_remove.append((x,par))
if num_child == 1:
z = dfs1(n,G,x,par,B)
bamboo.append((z,x))
elif num_child >= 2:
u,v = dfs2(n,G,x,par,B)
bamboo.append((u,v))
else:
bamboo.append((x,x))
k = len(to_remove)
print(k)
for i in range(k):
x,y = to_remove[i]
a = bamboo[i][1]
b = bamboo[i+1][0]
print(x+1,y+1,a+1,b+1)
for nt in range(int(input())):
n = int(input())
G = [[] for _ in range(n)]
for _ in range(n-1):
a,b = map(int,input().split())
G[a-1].append(b-1)
G[b-1].append(a-1)
solve(n,G)
```
No
| 95,518 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
from collections import defaultdict, deque
from random import randint
def test(edges):
n = len(edges) + 1
v_by_v = defaultdict(list)
for edge in edges:
v1, v2 = edge
v_by_v[v1].append(v2)
v_by_v[v2].append(v1)
prevVert = dict()
def searchFar(i):
nonlocal prevVert
d = deque()
d.append(i)
dist = dict()
dist[i] = 0
while len(d) > 0:
currV = d.pop()
for v in v_by_v[currV]:
if v not in dist.keys():
d.append(v)
dist[v] = dist[currV] + 1
prevVert[v] = currV
vFar = max([i for i in range(1, n+1)], key = lambda x: dist[x])
return vFar
v1 = searchFar(1)
v2 =searchFar(v1)
x = v2
edgeSet = set()
vertSet = set()
while x != v1:
xPrev = prevVert[x]
edgeSet.add((xPrev, x))
edgeSet.add((x, xPrev))
vertSet.add(x)
x = xPrev
vertSet.add(v1)
vertSet = set(range(1, n + 1)) - vertSet
finish = v2
result = []
nextVerts = defaultdict(list)
for v in range(1, n + 1):
if v in prevVert.keys():
vPrev = prevVert[v]
nextVerts[vPrev].append(v)
nearVerts = [v for v in vertSet if prevVert[v] not in vertSet]
while len(nearVerts) > 0:
v = nearVerts.pop()
x1 = prevVert[v]
x2 = v
while len(nextVerts[v]) > 0:
nearVerts.extend(nextVerts[v][1:])
v = nextVerts[v][0]
result.append([x1, x2, finish, x2])
finish = v
return result
# def createTree(n):
# edges = deque()
# edges.append((1,2))
# for i in range(n-2):
# x2 = i + 3
# x1 = randint(1, i + 2)
# edges.append((x1, x2))
# return edges
# while True:
# edges = createTree(randint(2, 10))
# print('created tree',len(edges) + 1)
# for edge in edges:
# print(edge)
# result = test(edges)
# print(len(result))
# for x in result:
# x = map(str, x)
# print(' '.join(x))
# print('1 - stop, 0 - continue')
# stop = input()
# if stop == '1':
# assert False
t = int(input())
results = []
for _ in range(t):
n = int(input())
edges = [tuple(map(int, input().split(' '))) for _ in range(n-1)]
result = test(edges)
results.append(result)
for result in results:
print(len(result))
for x in result:
x = map(str, x)
print(' '.join(x))
```
No
| 95,519 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
mod = 10 ** 9 + 7
for t in range(int(input())):
n, l, r = map(int, input().split())
F = [0] * (n + 1)
F[0] = 1
for i in range(1, n + 1):
F[i] = i * F[i - 1] % mod
iF = [0] * (n + 1)
iF[-1] = pow(F[-1], mod - 2, mod)
for i in range(n - 1, -1, -1):
iF[i] = (i + 1) * iF[i + 1] % mod
def comb(n, m):
if m < 0 or m > n: return 0
return F[n] * iF[m] * iF[n - m] % mod
a, b = l - 1, r - n
c = min(-a, b)
ans = comb(n, n // 2) * (1 + n % 2) * c
d = c + 1
while True:
x = min(n, n - (l - 1 + d))
y = min(n, r - d)
if x < n // 2 or y < n // 2: break
ans += comb(x + y - n, n // 2 - (n - y))
if n % 2:
# ans += comb(x + y - n, n // 2 - (n - x))
ans += comb(x + y - n, (n + 1) // 2 - (n - y))
ans %= mod
d += 1
print(ans)
```
| 95,520 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
M = 10**9+7
MAX = 10**6+1
factor = [1]*MAX
for i in range(1,MAX):
factor[i] = (factor[i-1]*i)%M
def fastfrac(a,b,M):
numb = pow(b,M-2,M)
return ((a%M)*(numb%M))%M
def comb(m,n):
if n<0 or m<0: return 0
num1 = factor[m]
num2 = factor[n]
num3 = factor[m-n]
num = fastfrac(num1,num2,M)
num = fastfrac(num,num3,M)
return num
def getnum(n,mustl,mustr):
if mustl>mustr: mustl,mustr = mustr,mustl
if mustr>n//2+1: return 0
output = 0
freedom = n - mustl - mustr
if n%2==0:
pick = n//2 - mustr
output += comb(freedom,pick)
output = output %M
else:
pick1 = n//2 - mustr
pick2 = n//2 - mustr + 1
output += comb(freedom,pick1)
output = output %M
output += comb(freedom,pick2)
output = output %M
return output
T = int(input())
t = 1
while t<=T:
n,l,r = map(int,input().split())
lleft = l - 1
rleft = r - 1
lright = l - n
rright = r - n
ans = min(-lleft,rright) * getnum(n,0,0)
ans = ans%M
diff = abs(-lleft-rright)
mustl = 0
mustr = 0
while diff>0:
mustr += 1
ans += getnum(n,mustl,mustr)
if mustr>n: break
ans = ans%M
diff -= 1
while mustr<n:
mustl += 1
mustr += 1
ans += getnum(n,mustl,mustr)
ans = ans%M
print(ans)
t += 1
```
| 95,521 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
from bisect import bisect_left
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
import math
N = 200001
# array to store inverse of 1 to N
factorialNumInverse = [None] * (N + 1)
# array to precompute inverse of 1! to N!
naturalNumInverse = [None] * (N + 1)
# array to store factorial of
# first N numbers
fact = [None] * (N + 1)
# Function to precompute inverse of numbers
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
# Function to precompute inverse
# of factorials
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
# precompute inverse of natural numbers
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
# Function to calculate factorial of 1 to N
def factorial(p):
fact[0] = 1
# precompute factorials
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
# Function to return nCr % p in O(1) time
def Binomial(N, R, p):
# n C r = n!*inverse(r!)*inverse((n-r)!)
ans = ((fact[N] * factorialNumInverse[R]) % p *
factorialNumInverse[N - R]) % p
return ans
p=10**9+7
InverseofNumber(p)
InverseofFactorial(p)
factorial(p)
t=int(input())
for _ in range(t):
n,l,r=map(int,input().split())
mi=min(1-l,r-n)
ma=max(1-l,r-n)
ans=0
if (n%2==0):
cmi=n//2
cma=n//2
ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cmi]))%p
val=mi+1
while(cmi>0):
if val>mi:
cmi+=-1
if val>ma:
cma+=-1
ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p
val+=1
else:
cmi=(n-1)//2
cma=(n+1)//2
ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cma]))%p
val=mi+1
while(cmi>0 and cma>0):
if val>mi:
cmi+=-1
if val>ma:
cma+=-1
ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p
val+=1
cmi=(n+1)//2
cma=(n-1)//2
ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cma]))%p
val=mi+1
while(cmi>0 and cma>0):
if val>mi:
cmi+=-1
if val>ma:
cma+=-1
ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p
val+=1
print(ans%p)
#a=list(map(int,input().split()))
```
| 95,522 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers
Correct Solution:
```
def main():
from sys import stdin, setrecursionlimit
#from io import BytesIO
#from os import read, fstat
#from math import gcd
#from random import randint, choice, shuffle
#from itertools import combinations, product
#from functools import lru_cache
#from re import search, finditer
input = stdin.buffer.readline
#input = BytesIO(read(0, fstat(0).st_size)).readline
#setrecursionlimit(100000000)
def c(n, k):
if n < k or k < 0:
return 0
return f[n] * rev[k] * rev[n - k] % mod
mod = 10**9 + 7
f = [1]
for i in range(1, 200001):
f.append(f[-1] * i % mod)
rev = [pow(f[-1], mod - 2, mod)]
for i in range(200000, 0, -1):
rev.append(rev[-1] * i % mod)
rev = rev[::-1]
for _ in range(int(input())):
n, l, r = map(int, input().split())
h = n >> 1
s = min(1 - l, r - n)
ans = s * (c(n, h) + [0, c(n, h + 1)][n & 1])
x = s + 1
while 1:
ll = max(1, l + x)
rr = min(n, r - x)
if rr - ll + 1 < 0:
break
ans += c(rr - ll + 1, h - (ll - 1)) + [0, c(rr - ll + 1, h + 1 - (ll - 1))][n & 1]
x += 1
print(ans % mod)
main()
```
| 95,523 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
mod = 10 ** 9 + 7
for t in range(int(input())):
n, l, r = map(int, input().split())
F = [0] * (n + 1)
F[0] = 1
for i in range(1, n + 1):
F[i] = i * F[i - 1] % mod
iF = [0] * (n + 1)
iF[-1] = pow(F[-1], mod - 2, mod)
for i in range(n - 1, -1, -1):
iF[i] = (i + 1) * iF[i + 1] % mod
def comb(n, m):
if m < 0 or m > n: return 0
return F[n] * iF[m] * iF[n - m] % mod
a, b = l - 1, r - n
c = min(-a, b)
ans = comb(n, n // 2) * (1 + n % 2) * c
d = c + 1
while True:
x = min(n, n - (l - 1 + d))
y = min(n, r - d)
if x < 0 or y < 0: break
ans += comb(x + y - n, n // 2 - (n - y))
if n % 2:
# ans += comb(x + y - n, n // 2 - (n - x))
ans += comb(x + y - n, (n + 1) // 2 - (n - y))
ans %= mod
d += 1
print(ans)
```
| 95,524 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers
Correct Solution:
```
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n,mod=0):
self.BIT = [0]*(n+1)
self.num = n
self.mod = mod
def query(self,idx):
res_sum = 0
mod = self.mod
while idx > 0:
res_sum += self.BIT[idx]
if mod:
res_sum %= mod
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
mod = self.mod
while idx <= self.num:
self.BIT[idx] += x
if mod:
self.BIT[idx] %= mod
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
self.size = n
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
if r==self.size:
r = self.num
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] <= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] <=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return -1
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
"""
l <= -c+1 <= r
l <= -c+k <= r
l <= c+k+1 <= r
l <= c+2*k <= r
l <= -c+1 < c+n <= r
l <= 0 < 1+n <=r
l <= c+1 <= r
l <= c+k <= r
l <= -c+k+1 <= r
l <= -c+2*k <= r
l-1 <= c <= r-k
2*k - r <= c <= k+1-l
l <= 0 < 1+n <=r
l <= -c+x <= r
l <= -c+y <= r
l <= c+z <= r
l <= c+w <= r
max(y-r,l-z) <= c <= min(r-w,x-l)
for c in range(1,(r-l+1)//2+1):
#1 <= i <= c+l-1
+c 確定
#r+1-c <= i <= n
-c 確定
# c+l <= i <= r-c
どっちでも
if n%2==0:
res += cmb(r-l+1-2*c,k-(c+l-1))
else:
res += cmb(r-l+1-2*c,k-(c+l-1)) + cmb(r-l+1-2*c,k+1-(c+l-1))
for c in range(1,-l):
"""
def cmb(n, r, mod):
if ( r<0 or r>n ):
return 0
r = min(r, n-r)
return (g1[n] * g2[r] % mod) * g2[n-r] % mod
mod = 10**9 + 7
N = 2*10**5
g1 = [1]*(N+1)
g2 = [1]*(N+1)
inverse = [1]*(N+1)
for i in range( 2, N + 1 ):
g1[i]=( ( g1[i-1] * i ) % mod )
inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod )
g2[i]=( (g2[i-1] * inverse[i]) % mod )
inverse[0]=0
for _ in range(int(input())):
n,l,r = mi()
k = n//2
res = 0
#l<=-c-1 and c+n <= r <-> 1 <= c <= min(r-n,-l-1)
if 1 <= min(r-n,-l-1):
if n&1:
tmp = cmb(n,k,mod) + cmb(n,k+1,mod)
tmp %= mod
else:
tmp = cmb(n,k,mod)
res += tmp * (min(r-n,-l-1)) % mod
res %= mod
s = min(r-n,-l-1) + 1
else:
s = 1
for c in range(s,s+n+2):
# -c+i <= l-1 <-> 1 <= i <= l-1+c
plus = max(0,l-1+c)
# r+1 <= c+i <-> max(1,r+1-c) <= i <= n
minus = max(0,n-max(1,r+1-c)+1)
if plus + minus > n:
break
if n&1:
res += cmb(n-plus-minus,k-plus,mod) + cmb(n-plus-minus,k+1-plus,mod)
res %= mod
else:
res += cmb(n-plus-minus,k-plus,mod)
res %= mod
print(res)
```
| 95,525 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
mod = 10 ** 9 + 7
for t in range(int(input())):
n, l, r = map(int, input().split())
F = [0] * (n + 1)
F[0] = 1
for i in range(1, n + 1):
F[i] = i * F[i - 1] % mod
iF = [0] * (n + 1)
iF[-1] = pow(F[-1], mod - 2, mod)
for i in range(n - 1, -1, -1):
iF[i] = (i + 1) * iF[i + 1] % mod
def comb(n, m):
if m < 0 or m > n: return 0
return F[n] * iF[m] * iF[n - m] % mod
a, b = l - 1, r - n
c = min(-a, b)
ans = comb(n, n // 2) * (1 + n % 2) * c
d = c + 1
while True:
x = min(n, n - (l - 1 + d))
y = min(n, r - d)
if x < 0 or y < 0: break
ans += comb(x + y - n, n // 2 - (n - y))
if n % 2:
ans += comb(x + y - n, n // 2 - (n - x))
ans %= mod
d += 1
print(ans)
```
| 95,526 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers
Correct Solution:
```
import sys
from sys import stdin
def modfac(n, MOD):
f = 1
factorials = [1]
for m in range(1, n + 1):
f *= m
f %= MOD
factorials.append(f)
inv = pow(f, MOD - 2, MOD)
invs = [1] * (n + 1)
invs[n] = inv
for m in range(n, 1, -1):
inv *= m
inv %= MOD
invs[m - 1] = inv
return factorials, invs
def modnCr(n,r):
return fac[n] * inv[n-r] * inv[r] % mod
mod = 10**9+7
fac,inv = modfac(300000,mod)
tt = int(stdin.readline())
ANS = []
for loop in range(tt):
n,l,r = map(int,stdin.readline().split())
ans = 0
#dont
dmax = min(1-l,r-n)
if dmax >= 0:
if n % 2 == 0:
ans += dmax * modnCr(n,n//2) % mod
else:
ans += 2 * dmax * modnCr(n,n//2) % mod
#print (ans % mod,file=sys.stderr)
#rest
nd = dmax + 1
while True:
lrist = max(0,l+nd-1)
rrist = max(0,n-(r-nd))
#print (nd,lrist,rrist)
if lrist + rrist > n or min(lrist,rrist) > (n+1)//2:
break
if n%2 == 1:
#l is min
uprem = n//2 - lrist
downrem = (n+1)//2 - rrist
if min(uprem,downrem) >= 0:
ans += modnCr(uprem+downrem,uprem)
#other
uprem = (n+1)//2 - lrist
downrem = n//2 - rrist
if min(uprem,downrem) >= 0:
ans += modnCr(uprem+downrem,uprem)
else:
uprem = n//2 - lrist
downrem = n//2 - rrist
if min(uprem,downrem) >= 0:
ans += modnCr(uprem+downrem,uprem)
nd += 1
ANS.append(str(ans % mod))
print ("\n".join(ANS))
```
| 95,527 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
P = 10 ** 9 + 7
nn = 505050
fa = [1] * (nn+1)
fainv = [1] * (nn+1)
for i in range(nn):
fa[i+1] = fa[i] * (i+1) % P
fainv[-1] = pow(fa[-1], P-2, P)
for i in range(nn)[::-1]:
fainv[i] = fainv[i+1] * (i+1) % P
C = lambda a, b: fa[a] * fainv[b] % P * fainv[a-b] % P if 0 <= b <= a else 0
def calc(n, l, r):
a, b = 1 - l, r - n
aa, bb = r - 1, n - l
if a > b:
a, b = b, a
aa, bb = bb, aa
re = 0
if n % 2 == 0:
re += C(n, n // 2) * a
else:
re += (C(n, n // 2) + C(n, n // 2 + 1)) * a
if 0:
for k in range(a + 1, min(aa, bb, b) + 1):
if n % 2 == 0:
re += C(n - (k - a), n // 2 - (k - a))
else:
re += C(n - (k - a), n // 2 - (k - a)) + C(n - (k - a), n // 2 + 1 - (k - a))
elif 0:
for k in range(1, min(aa, bb, b) - a + 1):
if n % 2 == 0:
re += C(n - k, n // 2 - k)
else:
re += C(n - k, n // 2 - k) + C(n - k, n // 2 + 1 - k)
else:
kk = min(aa, bb, b) - a
m = n - kk
mm = n // 2 - kk
if n % 2 == 0:
re += C(m + kk, mm + kk - 1)
re -= C(m, mm - 1)
else:
re += C(m + kk, mm + kk - 1)
re -= C(m, mm - 1)
re += C(m + kk, mm + 1 + kk - 1)
re -= C(m, mm)
if 0:
for k in range(b + 1, min(aa, bb) + 1):
if n % 2 == 0:
re += C(n - (k - a) - (k - b), n // 2 - (k - a))
else:
re += C(n - (k - a) - (k - b), n // 2 - (k - a)) + C(n - (k - a) - (k - b), n // 2 + 1 - (k - a))
else:
kk = min(aa, bb) - b
m = n - (kk - a + b)
if n % 2 == 0:
for k in range(1, kk + 1):
re += C(n - (k - a + b) - k, n // 2 - (k - a + b))
else:
for k in range(1, kk + 1):
re += C(n - (k - a + b) - k, n // 2 - (k - a + b)) + C(n - (k - a + b) - k, n // 2 + 1 - (k - a + b))
return re % P
if 1:
T = int(input())
for _ in range(T):
n, l, r = map(int, input().split())
print(calc(n, l, r))
else:
from random import randrange
T = 100
for _ in range(T):
n = randrange(4, 20)
a = randrange(20)
b = randrange(20)
l, r = l - a, r + b
c1 = calc1(n, l, r)
c2 = calc(n, l, r)
if c1 != c2:
print("Error !")
print("n, l, r =", n, l, r)
print("c1, c2 =", c1, c2)
print("END")
```
Yes
| 95,528 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Submitted Solution:
```
import sys
input = sys.stdin.readline
mod = 10 ** 9 + 7
for t in range(int(input())):
n, l, r = map(int, input().split())
F = [0] * (n + 1)
F[0] = 1
for i in range(1, n + 1):
F[i] = i * F[i - 1] % mod
iF = [0] * (n + 1)
iF[-1] = pow(F[-1], mod - 2, mod)
for i in range(n - 1, -1, -1):
iF[i] = (i + 1) * iF[i + 1] % mod
def comb(n, m):
if m < 0 or m > n: return 0
return F[n] * iF[m] * iF[n - m] % mod
a, b = l - 1, r - n
c = min(-a, b)
ans = comb(n, n // 2) * (1 + n % 2) * c
d = c + 1
m = n // 2
while True:
x = min(n, n - (l - 1 + d))
y = min(n, r - d)
if x < m or y < m: break
ans += comb(x + y - n, m - (n - y))
if n % 2:
# ans += comb(x + y - n, m - (n - x))
ans += comb(x + y - n, m + 1 - (n - y))
ans %= mod
d += 1
print(ans)
```
Yes
| 95,529 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Submitted Solution:
```
import sys
# sys.setrecursionlimit(200005)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]
def SI(): return sys.stdin.readline().rstrip()
inf = 10**16
md = 10**9+7
# md = 998244353
def nCr(com_n, com_r):
if com_r < 0: return 0
if com_n < com_r: return 0
return fac[com_n]*ifac[com_r]%md*ifac[com_n-com_r]%md
# 準備
n_max = 200005
fac = [1]
for i in range(1, n_max+1): fac.append(fac[-1]*i%md)
ifac = [1]*(n_max+1)
ifac[n_max] = pow(fac[n_max], md-2, md)
for i in range(n_max-1, 1, -1): ifac[i] = ifac[i+1]*(i+1)%md
def solve():
n, l, r = LI()
ans = 0
mn = max(1, 1-r, l-n)
mx = min(1-l, r-n)
if mn <= mx:
if n & 1:
ans += nCr(n, n//2)*2*(mx-mn+1-(mn <= 0 <= mx))%md
else:
ans += nCr(n, n//2)*(mx-mn+1-(mn <= 0 <= mx))%md
s = mn-1
# print(mn, mx, ans)
while s > 0:
# (-sにできる)[L(どちらにもできる)R](sにできる)
L = max(1, l+s)
R = min(n, r-s)
# print(s, L, R)
ans += nCr(R-L+1, n//2-L+1)
if n & 1:
ans += nCr(R-L+1, n//2-L+2)
s -= 1
s = mx+1
while 1:
L = max(1, l+s)
R = min(n, r-s)
# print(s, L, R)
if L > R+1: break
ans += nCr(R-L+1, n//2-L+1)
if n & 1:
ans += nCr(R-L+1, n//2-L+2)
s += 1
ans %= md
print(ans)
for testcase in range(II()):
solve()
```
Yes
| 95,530 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Submitted Solution:
```
import sys
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()
import bisect,string,math,time,functools,random,fractions
from bisect import*
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def I():return int(input())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def AI():return map(int,open(0).read().split())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def NLI(n):return [[int(i) for i in input().split()] for i in range(n)]
def NLI_(n):return [[int(i)-1 for i in input().split()] for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def INP():
N=10
n=random.randint(1,N)
a=RLI(n,1,n)
return n,a
def Rtest(T):
case,err=0,0
for i in range(T):
inp=INP()
a1=naive(*inp)
a2=solve(*inp)
if a1!=a2:
print(inp)
print('naive',a1)
print('solve',a2)
err+=1
case+=1
print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
org_inp=[];g=[[] for i in range(V)]
FromStdin=True if ls==None else False
for i in range(E):
if FromStdin:
inp=LI()
org_inp.append(inp)
else:
inp=ls[i]
if len(inp)==2:a,b=inp;c=1
else:a,b,c=inp
if index==1:a-=1;b-=1
aa=(a,c);bb=(b,c);g[a].append(bb)
if not Directed:g[b].append(aa)
return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
mp=[boundary]*(w+2);found={}
for i in R(h):
s=input()
for char in search:
if char in s:
found[char]=((i+1)*(w+2)+s.index(char)+1)
mp_def[char]=mp_def[replacement_of_found]
mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
mp+=[boundary]*(w+2)
return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
rt=[0]
for i in ls:rt+=[rt[-1]+i]
return rt
def bit_combination(n,base=2):
rt=[]
for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
return rt
def gcd(x,y):
if y==0:return x
if x%y==0:return y
while x%y!=0:x,y=y,x%y
return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print('YNeos'[not x::2])
def show(*inp,end='\n'):
if show_flg:print(*inp,end=end)
def showf(inp,length=3,end='\n'):
if show_flg:print([' '*(length-len(str(i)))+str(i)for i in inp],end=end)
mo=10**9+7
#mo=998244353
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
alp=[chr(ord('a')+i)for i in range(26)]
#sys.setrecursionlimit(10**7)
def gcj(c,x):
print("Case #{0}:".format(c+1),x)
show_flg=False
show_flg=True
class Comb:
def __init__(self,n,mo=10**9+7):
self.fac=[0]*(n+1)
self.inv=[1]*(n+1)
self.fac[0]=1
self.fact(n)
for i in range(1,n+1):
self.fac[i]=i*self.fac[i-1]%mo
self.inv[n]*=i
self.inv[n]%=mo
self.inv[n]=pow(self.inv[n],mo-2,mo)
for i in range(1,n):
self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
return
def fact(self,n):
return self.fac[n]
def invf(self,n):
return self.inv[n]
def comb(self,x,y):
if y<0 or y>x:
return 0
return self.fac[x]*self.inv[x-y]*self.inv[y]%mo
def cat(self,x):
if x<0:
return 0
return self.fac[2*x]*self.inv[x]*self.inv[x+1]%mo
ans=0
for _ in range(I()):
n,l,r=LI()
cm=Comb(n+10)
#show(n,l,r)
if abs(l-n)<=abs(r-1):l,r=n+1-r,-l+n+1
#show(n,l,r)
m=n//2
a=0
for x in range(r-n,r-1+1):
if x==0:
continue
cr=r-x
cl=min(n,max(0,n-(l+x-1)))
if cl>=n and cr>=n and False:
a+=cm.comb(n,m)
#show((n,m),x,a)
if n%2==1:a+=cm.comb(n,m+1)
else:
s=n-cl
t=n-cr
a+=cm.comb(n-s-t,m-s)
#show((n-s-t,m-s),x,a,(cl,cr),(s,t))
if n%2==1:a+=cm.comb(n-s-t,m+1-s)
if r-n-1>0:
a+=cm.comb(n,m)*(r-n-1)
if n%2==1:a+=cm.comb(n,m+1)*(r-n-1)
#show(x,(cr,cl))
print(a%mo)
```
Yes
| 95,531 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
from bisect import bisect_left
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
import math
N = 200001
# array to store inverse of 1 to N
factorialNumInverse = [None] * (N + 1)
# array to precompute inverse of 1! to N!
naturalNumInverse = [None] * (N + 1)
# array to store factorial of
# first N numbers
fact = [None] * (N + 1)
# Function to precompute inverse of numbers
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
# Function to precompute inverse
# of factorials
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
# precompute inverse of natural numbers
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
# Function to calculate factorial of 1 to N
def factorial(p):
fact[0] = 1
# precompute factorials
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
# Function to return nCr % p in O(1) time
def Binomial(N, R, p):
# n C r = n!*inverse(r!)*inverse((n-r)!)
ans = ((fact[N] * factorialNumInverse[R]) % p *
factorialNumInverse[N - R]) % p
return ans
p=10**9+7
InverseofNumber(p)
InverseofFactorial(p)
factorial(p)
t=int(input())
for _ in range(t):
n,l,r=map(int,input().split())
mi=min(1-l,r-n)
ma=max(1-l,r-n)
ans=0
if (n%2==0):
cmi=n//2
cma=n//2
ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cmi]))%p
val=mi+1
while(cmi>0):
if val>mi:
cmi+=-1
if val>ma:
cma+=-1
ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p
val+=1
else:
cmi=(n-1)//2
cma=(n+1)//2
ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cma]))%p
val=mi+1
while(cmi>0):
if val>mi:
cmi+=-1
if val>ma:
cma+=-1
ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p
val+=1
cmi=(n+1)//2
cma=(n-1)//2
ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cma]))%p
val=mi+1
while(cmi>0):
if val>mi:
cmi+=-1
if val>ma:
cma+=-1
ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p
val+=1
print(ans%p)
#a=list(map(int,input().split()))
```
No
| 95,532 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Submitted Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
M = 10**9+7
MAX = 10**6+1
factor = [1]*MAX
for i in range(1,MAX):
factor[i] = (factor[i-1]*i)%M
def fastfrac(a,b,M):
numb = pow(b,M-2,M)
return ((a%M)*(numb%M))%M
def comb(m,n):
if n<0: return 0
num1 = factor[m]
num2 = factor[n]
num3 = factor[m-n]
num = fastfrac(num1,num2,M)
num = fastfrac(num,num3,M)
return num
def getnum(n,mustl,mustr):
if mustl>mustr: mustl,mustr = mustr,mustl
output = 0
freedom = n - mustl - mustr
if n%2==0:
pick = n//2 - mustr
output += comb(freedom,pick)
else:
pick1 = n//2 - mustr
pick2 = n//2 - mustr + 1
output += comb(freedom,pick1)
output += comb(freedom,pick2)
return output
T = int(input())
t = 1
while t<=T:
n,l,r = map(int,input().split())
lleft = l - 1
rleft = r - 1
lright = l - n
rright = r - n
ans = min(-lleft,rright) * getnum(n,0,0)
ans = ans%M
diff = abs(-lleft-rright)
mustl = 0
mustr = 0
while diff>0:
mustr += 1
ans += getnum(n,mustl,mustr)
ans = ans%M
diff -= 1
while mustr<n//2+2:
mustl += 1
mustr += 1
ans += getnum(n,mustl,mustr)
ans = ans%M
print(ans)
t += 1
```
No
| 95,533 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Submitted Solution:
```
import sys
input = sys.stdin.readline
mod=10**9+7
FACT=[1]
for i in range(1,4*10**5+1):
FACT.append(FACT[-1]*i%mod)
FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(4*10**5,0,-1):
FACT_INV.append(FACT_INV[-1]*i%mod)
FACT_INV.reverse()
def Combi(a,b):
if 0<=b<=a:
return FACT[a]*FACT_INV[b]%mod*FACT_INV[a-b]%mod
else:
return 0
"""
ANS=Combi(42,21)*13
for i in range(1,42):
ANS+=Combi(42-i,21-i)
ANS%=mod
print(ANS)
"""
t=int(input())
for tests in range(t):
n,l,r=map(int,input().split())
x,y,z,w=1-r,1-l,n-r,n-l
#print(x,y,z,w)
"""
if x>=0 or w<=0:
ANS=1
for i in range(1,n+1):
if l<=1<=r:
ANS=ANS*(r-l)%mod
else:
ANS=ANS*(r-l+1)%mod
print(ANS)
continue
"""
k=min(-x,-z,y,w)
if n%2==0:
ANS=k*Combi(n,n//2)
for i in range(1,n):
ANS+=Combi(n-i,n//2-i)
ANS%=mod
print(ANS)
else:
ANS=k*Combi(n,n//2)*2
for i in range(1,n):
ANS+=Combi(n-i,n//2+1-i)+Combi(n-i,n//2-i)
ANS%=mod
print(ANS)
```
No
| 95,534 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arrays of size n.
Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9).
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the number of excellent arrays modulo 10^9 + 7.
Example
Input
4
3 0 3
4 -3 5
42 -33 55
69 -42 146
Output
4
10
143922563
698570404
Note
In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are:
1. [2, 1, 2];
2. [0, 3, 2];
3. [2, 3, 2];
4. [3, 0, 1].
Submitted Solution:
```
#
# author: vongkh
# created: Mon Dec 28 2020
#
from sys import stdin, stdout # only need for big input
from math import factorial, sqrt
mxN = int(2e5+100)
fact = [0] * mxN
ifact = [0] * mxN
MOD = int(1e9 + 7)
def add(x, y):
ret = x + y
if ret >= MOD:
ret = ret % MOD
return ret
def mul(x, y):
ret = x * y
if ret >= MOD:
ret %= MOD
return ret
def pow_mod(a, p):
ret = 1
if p > 0:
ret = pow_mod(a, p//2)
ret = mul(ret, ret)
if p % 2:
ret = mul(ret, a)
return ret
def inv(a):
return pow_mod(a, MOD - 2)
def init_fact():
fact[0] = 1
ifact[0] = 1
for i in range(1, mxN):
fact[i] = mul(fact[i-1], i)
ifact[i] = inv(fact[i])
def nCr(n , r):
if n < r:
return 0
ret = mul(fact[n], ifact[r])
ret = mul(ret, ifact[n-r])
return ret
def choice(n, wants):
ret = 0
for w in wants:
ret = add(ret, nCr(n, w))
return ret
def solve():
n, l, r = list(map(int, input().split()))
wants = [n // 2]
right = r - 1
left = n - l
shortest = min(right, left)
# print("shortest", shortest)
if n % 2 :
wants.append((n+1)//2)
ans = 0
for i in range(1, n+1):
if shortest > 0:
ans = add(ans, choice(i, wants))
shortest -= 1
if shortest > 0:
additional = mul(shortest , choice(n, wants))
ans = add(ans, additional)
print(ans)
def main():
init_fact()
test = int(input())
for i in range(1, test + 1):
# print(f"Case #{i}: ", end="")
solve()
if __name__ == "__main__":
main()
```
No
| 95,535 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Tags: implementation
Correct Solution:
```
n = int(input())
mat = []
for i in range(n):
m_ = input()
m_ = m_.split(' ')
mat.append(m_)
i = 0
s=0
m = int((n-1)/2)
while i<n:
if i != m:
s += int(mat[i][i]) + int(mat[i][n-i-1]) + int(mat[i][m])
else:
pass
i += 1
i=0
while i<n:
s+= int(mat[m][i])
i+=1
print(s)
```
| 95,536 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Tags: implementation
Correct Solution:
```
import time
import collections
class Time_test:
def __enter__(self):
self.enter_time = time.time()
def __exit__(self, exc_type, exc_val, exc_tb):
print("Command was executed in", time.time()-self.enter_time)
n = int(input())
s = 0
for i in range(n):
ipt = [int(x) for x in input().split()]
if n//2 == i:
s += sum(ipt)
continue
s += ipt[n//2] + ipt[i] + ipt[n-i-1]
print(s)
```
| 95,537 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Tags: implementation
Correct Solution:
```
n=int(input())
k=[]
sum1=0
sum2=0
sum3=0
sum4=0
for i in range(n):
k.append(list(map(int,input().split())))
for i in range(len(k)):
sum1=sum1+k[i][i]
sum2=sum2+k[i][(len(k)-1)-i]
sum3=sum3+k[int(len(k)/2)][i]
sum4=sum4+k[i][int(len(k)/2)]
j=k[int(len(k)/2)][int(len(k)/2)]
x=sum1+sum2+sum3+sum4-3*j
print(x)
```
| 95,538 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Tags: implementation
Correct Solution:
```
import sys
def main():
inp = sys.stdin.read().strip().split('\n')
n = int(inp[0])
m = [[int(x) for x in s.split()] for s in inp[1:]]
s = sum(m[i][i] + m[i][-i-1] + m[i][n//2] + m[n//2][i] for i in range(n))
return s - 3*m[n//2][n//2]
print(main())
```
| 95,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Tags: implementation
Correct Solution:
```
N = int( input() )
mat = list( list( map( int, input().split() ) ) for i in range( N ) )
ans = 0
for i in range( N ):
ans += mat[ i ][ i ]
ans += mat[ N - 1 - i ][ i ]
ans += mat[ N >> 1 ][ i ]
ans += mat[ i ][ N >> 1 ]
print( ans - mat[ N >> 1 ][ N >> 1 ] * 3 )
```
| 95,540 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Tags: implementation
Correct Solution:
```
n = int(input())
grid = []
for i in range(n):
row = [int(i) for i in input().split()]
grid.append(row)
sum = 0
for i in range(n):
for j in range(n):
if i == j or i == n - 1 - j or i == (n - 1) / 2 or j == (n - 1) / 2:
sum += grid[i][j]
print(sum)
```
| 95,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Tags: implementation
Correct Solution:
```
row=int(input())
matrix=[]
for i in range(row):
r=list(map(int, input().split()))
matrix.append(r)
p=row-1
count=0
for i in range(row):
count += matrix[i][i]
count += matrix[p-i][i]
count += matrix[int(((p-1)/2)+1)][i]
count += matrix[i][int(((p - 1) / 2) + 1)]
count -= 3*matrix[int(((p-1)/2)+1)][int(((p-1)/2)+1)]
print(count)
```
| 95,542 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Tags: implementation
Correct Solution:
```
n = int(input())
matrix = [[int(j) for j in input().split()] for i in range(n)]
summ=0
k=n//2
for i in range(n):
for j in range(n):
if i==j:
summ = summ + matrix[i][j]
elif i+j+1 ==n:
summ = summ + matrix[i][j]
elif i==k:
summ = summ + matrix[i][j]
elif j==k:
summ = summ + matrix[i][j]
print(summ)
```
| 95,543 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Submitted Solution:
```
n = int(input()); V = 0
if n > 2:
for i in range(n):
L = [int(x) for x in input().split()]
if i == 0.5*(n-1):
V += sum(L)
else:
V += L[i] + L[int((n-1)/2)] + L[n-i-1]
print(V)
else:
print(int(input()))
```
Yes
| 95,544 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Submitted Solution:
```
x=int(input())
z=0;s=0;l=(x-1)
for i in range(x):
y=input().split()
if i<((x//2)-1) :
z+=int(y[s])+int(y[l])+int(y[x//2])
s+=1;l-=1
elif i==((x//2)-1) :
z += int(y[s]) + int(y[l]) + int(y[x // 2])
elif i ==(x//2):
for r in range(x):
z+=int(y[r])
else:
z+=int(y[x//2])+int(y[l])+int(y[s])
s-=1;l+=1
print(z)
```
Yes
| 95,545 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Submitted Solution:
```
n = int(input())
IL = lambda: list(map(int, input().split()))
M = [IL() for i in range(n)]
print(sum(M[n//2]) + sum([M[i][i] + M[i][n-i-1] + M[i][n//2] for i in range(n)]) - 3*M[n//2][n//2])
```
Yes
| 95,546 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Submitted Solution:
```
n = int(input())
a = []
for i in range(n):
a.append([int(i) for i in input().split()])
goodSum = 0
for i in range(n):
goodSum += a[i][i] + a[i][n-1-i] + a[n//2][i] + a[i][n//2]
print(goodSum - (3 * a[n//2][n//2]))
```
Yes
| 95,547 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Submitted Solution:
```
n = int(input())
m = [[int(i) for i in input().split()] for i in range(n)]
a = 0
b = 0
c = 0
d = 0
s = 0
if n==3:
for i in range(n):
s += sum(m[i])
else:
for i in range(n//3):
a += m[len(m)//2][i]
b += m[i][len(m)//2]
c += m[i][i]
for i in range(n-n//3, n):
a += m[len(m)//2][i]
b += m[i][len(m)//2]
c += m[i][i]
p = 0
for i in range(n-1,n-n//3-1,-1):
d += m[i][p]
p += 1
p = n-n//3
for i in range(n//3-1,-1,-1):
d += m[i][p]
p += 1
for h in range(n//3, n-n//3):
for w in range(n//3, n-n//3):
s += m[h][w]
s += a+b+c+d
print(s)
```
No
| 95,548 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Submitted Solution:
```
b=int(input())
a= [[int(j) for j in input().split()] for i in range(b)]
print(a)
sum=0
gum=0
rum=0
drum=0
d=int((b-1)/2)
for i in range(b):
sum=sum+a[d][i]
gum=gum+a[i][d]
for j in range(b):
if(i==j):
rum=rum+a[i][j]
if((i+j)==b-1):
drum=drum+a[i][j]
c=int(sum+gum+rum+drum-(3*a[d][d]))
print(c)
```
No
| 95,549 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Submitted Solution:
```
"""
Author : Indian Coder
Date : 29th May ,2021
"""
#Imports
import math
import time
import random
start=time.time()
n=int(input())
sample=0
sample1=[]
for i in range(0,n):
a1=list(map(int ,input().split()))
sample+=(sum(a1))
sample1.append(a1)
if(n<=3):
print(sample)
else:
back_val=n
back_value_list=[]
for i in range(0,len(sample1)):
back_value_list.append(sample1[i][back_val-1])
back_val-=1
#print(sample1)
#print(back_value_list)
front_valu=0
front_value_list=[]
for j in range(0,len(sample1)):
front_value_list.append(sample1[j][front_valu])
front_valu+=1
#print(front_value_list)
middle_col_value=0
pos_add=n//2+1
for k in range(0,len(sample1)):
middle_col_value+=sample1[k][pos_add-1]
#print(middle_col_value)
middle_row_sum=sum(sample1[pos_add-1])
print(sum(front_value_list)+sum(back_value_list)+middle_col_value+middle_row_sum-3*sample1[n//2+1][2])
end=time.time()
#print("Time Of Execution Is",end-start)
```
No
| 95,550 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Submitted Solution:
```
n = int(input())
arr = [[int(i) for i in input().split()] for j in range(n)]
ans = 0
for i in range(n):
ans += arr[i][i]
arr[i][i] = 0
ans += arr[n - 1 - i][i];
arr[n - i - 1][i] = 0
ans += arr[n-1][n//2];
arr[n-1][n//2] = 0
ans += arr[n//2][n-1];
arr[n//2][n-1] = 0
print(ans)
```
No
| 95,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.
The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions.
An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 ≤ i < j ≤ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element.
Help the Little Elephant and count the number of the described pairs.
Input
The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 1018) — the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of array a.
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
In a single line print a single number — the answer to the problem.
Examples
Input
3 1
1 3 2
Output
3
Input
5 2
1 3 2 1 7
Output
6
Tags: data structures, two pointers
Correct Solution:
```
# 220E
import sys
from collections import defaultdict
class BIT():
def __init__(self, n):
self.n = n
self.tree = [0] * n
def _F(self, i):
return i & (i + 1)
def _get_sum(self, r):
'''
sum on interval [0, r)
'''
result = 0
while r > 0:
result += self.tree[r-1]
r = self._F(r-1)
return result
def get_sum(self, l, r):
'''
sum on interval [l, r)
'''
return self._get_sum(r) - self._get_sum(l)
def _H(self, i):
return i | (i + 1)
def add(self, i, value=1):
while i < self.n:
self.tree[i] += value
i = self._H(i)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n, k = map(int, input().split())
a = list(map(int, input().split()))
pos = defaultdict(list)
for i, val in enumerate(a):
pos[val].append(i)
i = 0
prev = -1
for val in sorted(a):
if prev == val: continue
for j in pos[val]:
a[j] = i
i += 1
prev = val
left = BIT(n)
right = BIT(n)
total_inv = 0
left.add(a[0])
for t in range(1, n):
i = a[t]
total_inv += right.get_sum(i+1, n)
right.add(i)
if i < a[0]:
total_inv += 1
if total_inv <= k:
print((n*(n-1))>>1)
sys.exit()
l = 0
r = 1
while r < n and total_inv > k:
total_inv -= left.get_sum(a[r]+1, n) + right.get_sum(0, a[r])
right.add(a[r], -1)
r += 1
pairs = 0
while r < n:
while True:
add = left.get_sum(a[l+1]+1, n) + right.get_sum(0, a[l+1])
if total_inv + add > k:
pairs += l + 1
break
else:
l += 1
total_inv += add
left.add(a[l])
total_inv -= left.get_sum(a[r]+1, n) + right.get_sum(0, a[r])
right.add(a[r], -1)
r += 1
print(pairs)
```
| 95,552 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.
The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions.
An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 ≤ i < j ≤ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element.
Help the Little Elephant and count the number of the described pairs.
Input
The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 1018) — the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of array a.
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
In a single line print a single number — the answer to the problem.
Examples
Input
3 1
1 3 2
Output
3
Input
5 2
1 3 2 1 7
Output
6
Tags: data structures, two pointers
Correct Solution:
```
'''
Created on 19/07/2018
@author: ernesto
'''
# XXX: http://codeforces.com/problemset/problem/220/E
# XXX: https://practice.geeksforgeeks.org/problems/magic-triplets/0
# XXX: https://gist.github.com/robert-king/5660418
class RangeBit:
def __init__(self, n):
sz = 1
while n >= sz:
sz *= 2
self.size = sz
self.dataAdd = [0] * sz
self.dataMul = [0] * sz
def sum(self, i):
r = 0
if i > 0:
add = 0
mul = 0
start = i
while i > 0:
add += self.dataAdd[i]
mul += self.dataMul[i]
i -= i & -i
r = mul * start + add
return r
def add(self, left, right, by):
assert 0 < left <= right
self._add(left, by, -by * (left - 1))
self._add(right, -by, by * right)
def _add(self, i, mul, add):
assert i > 0
while i < self.size:
self.dataAdd[i] += add
self.dataMul[i] += mul
i += i & -i
def sum_range(self, i, j):
# print("j {} s {}".format(j, self.sum(j)))
# print("i {} s {}".format(i, self.sum(i)))
return self.sum(j) - self.sum(i - 1)
def sum_back(self, i):
return self.sum_range(i, self.size - 1)
def add_point(self, i, by):
self.add(i, i, by)
class numero():
def __init__(self, valor, posicion_inicial):
self.valor = valor
self.posicion_inicial = posicion_inicial
self.posicion_final = -1;
def __lt__(self, other):
if self.valor == other.valor:
r = self.posicion_inicial < other.posicion_inicial
else:
r = self.valor < other.valor
return r
def __repr__(self):
return "{}:{}:{}".format(self.valor, self.posicion_inicial, self.posicion_final)
def swap(a, i, j):
a[i], a[j] = a[j], a[i]
def crea_arreglo_enriquecido(nums):
numse = list(sorted(map(lambda t:numero(t[1], t[0]), enumerate(nums))))
r = [0] * len(nums)
# print("numse {}".format(numse))
for i, n in enumerate(numse):
r[n.posicion_inicial] = i + 1
return r
def fuerza_bruta(a):
a_len = len(a)
r = 0
for i in range(a_len):
for j in range(i):
if a[i] < a[j]:
r += 1
return r
def quita(bi, bd, a, i):
return modifica(bi, bd, a, i, False)
def anade(bi, bd, a, i):
return modifica(bi, bd, a, i, True)
def modifica(bi, bd, a, i, anade):
if anade:
bc = bi
fac = 1
else:
bc = bd
fac = -1
inv = bi.sum_back(a[i] + 1) + bd.sum(a[i] - 1)
# print("num {} parte de i {} de d {} fact {}".format(a[i], bi.sum(a[i] + 1), bd.sum(a[i] - 1), fac))
bc.add_point(a[i], fac)
return inv
def core(nums, nmi):
numse = crea_arreglo_enriquecido(nums)
# print("numse {}".format(numse))
a = numse
# print("a {}".format(list(map(lambda x:x - 1, a))))
i = 0
j = 0
ni = 0
r = 0
a_len = len(a)
bitch_izq = RangeBit(a_len + 2)
bitch_der = RangeBit(a_len + 2)
nif = 0
for i, x in enumerate(a):
nif += bitch_der.sum_range(x + 1, a_len)
bitch_der.add(x, x, 1)
# print("en x {} ({}) nif {}".format(x, numse[i].valor , nif))
j = 0
ni = nif
# print("ni ini {}".format(ni))
ni += anade(bitch_izq, bitch_der, a, 0)
for i in range(1, a_len):
while j < a_len and (j < i or ni > nmi):
ni -= quita(bitch_izq, bitch_der, a, j)
# print("en j {} se kito {} {}".format(j, nums[j], ni))
j += 1
r += a_len - j
# print("en i {} j {} anadido {} inv {}".format(i, j, a_len - j, ni))
ni += anade(bitch_izq, bitch_der, a, i)
# print("en i {} se puso {}".format(i, ni))
# print("r f aora {}".format(r))
return r
_, k = [int(x) for x in input().strip().split(" ")]
nums = [int(x) for x in input().strip().split(" ")]
# nums = [6, 8, 6, 7, 2, 4, 2, 1, 7, 6, 2, 1, 2, 3, 2, 5, 3, 7, 1, 7, 7]
# nums = [1, 3, 2, 1, 7]
# nums = [1, 3, 2]
# k = 0
print(core(nums, k))
```
| 95,553 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.
The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions.
An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 ≤ i < j ≤ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element.
Help the Little Elephant and count the number of the described pairs.
Input
The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 1018) — the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of array a.
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
In a single line print a single number — the answer to the problem.
Examples
Input
3 1
1 3 2
Output
3
Input
5 2
1 3 2 1 7
Output
6
Submitted Solution:
```
# 220E
import sys
class BIT():
def __init__(self, n):
self.n = n
self.tree = [0] * n
def _F(self, i):
return i & (i + 1)
def _get_sum(self, r):
'''
sum on interval [0, r)
'''
result = 0
while r > 0:
result += self.tree[r-1]
r = self._F(r-1)
return result
def get_sum(self, l, r):
'''
sum on interval [l, r)
'''
return self._get_sum(r) - self._get_sum(l)
def _H(self, i):
return i | (i + 1)
def add(self, i, value=1):
while i < self.n:
self.tree[i] += value
i = self._H(i)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n, k = map(int, input().split())
a = list(map(int, input().split()))
pos = {val:i for i, val in enumerate(a)}
for i, val in enumerate(sorted(a)):
a[pos[val]] = i
left = BIT(n)
right = BIT(n)
total_inv = 0
left.add(a[0])
for t in range(1, n):
i = a[t]
total_inv += right.get_sum(i, n)
right.add(i)
if i < a[0]:
total_inv += 1
# print(total_inv, k)
if total_inv <= k:
print((n*(n-1))>>1)
sys.exit()
l = 0
r = 1
while r < n and total_inv > k:
total_inv -= left.get_sum(a[r], n) + right.get_sum(0, a[r])
right.add(a[r], -1)
r += 1
pairs = 0
while r < n:
while True:
add = left.get_sum(a[l+1], n) + right.get_sum(0, a[l+1])
if total_inv + add > k:
pairs += l + 1
break
else:
l += 1
total_inv += add
left.add(a[l])
total_inv -= left.get_sum(a[r], n) + right.get_sum(0, a[r])
right.add(a[r], -1)
r += 1
print(pairs)
```
No
| 95,554 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.
The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions.
An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 ≤ i < j ≤ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element.
Help the Little Elephant and count the number of the described pairs.
Input
The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 1018) — the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of array a.
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
In a single line print a single number — the answer to the problem.
Examples
Input
3 1
1 3 2
Output
3
Input
5 2
1 3 2 1 7
Output
6
Submitted Solution:
```
'''
Created on 19/07/2018
@author: ernesto
'''
# XXX: http://codeforces.com/problemset/problem/220/E
# XXX: https://practice.geeksforgeeks.org/problems/magic-triplets/0
# XXX: https://gist.github.com/robert-king/5660418
class RangeBit:
def __init__(self, n):
sz = 1
while n >= sz:
sz *= 2
self.size = sz
self.dataAdd = [0] * sz
self.dataMul = [0] * sz
def sum(self, i):
r = 0
if i > 0:
add = 0
mul = 0
start = i
while i > 0:
add += self.dataAdd[i]
mul += self.dataMul[i]
i -= i & -i
r = mul * start + add
return r
def add(self, left, right, by):
assert 0 < left <= right
self._add(left, by, -by * (left - 1))
self._add(right, -by, by * right)
def _add(self, i, mul, add):
assert i > 0
while i < self.size:
self.dataAdd[i] += add
self.dataMul[i] += mul
i += i & -i
def sum_range(self, i, j):
# print("j {} s {}".format(j, self.sum(j)))
# print("i {} s {}".format(i, self.sum(i)))
return self.sum(j) - self.sum(i - 1)
def sum_back(self, i):
return self.sum_range(i, self.size - 1)
def add_point(self, i, by):
self.add(i, i, by)
class numero():
def __init__(self, valor, posicion_inicial):
self.valor = valor
self.posicion_inicial = posicion_inicial
self.posicion_final = -1;
def __lt__(self, other):
if self.valor == other.valor:
r = self.posicion_inicial < other.posicion_inicial
else:
r = self.valor < other.valor
return r
def __repr__(self):
return "{}:{}:{}".format(self.valor, self.posicion_inicial, self.posicion_final)
def swap(a, i, j):
a[i], a[j] = a[j], a[i]
def crea_arreglo_enriquecido(nums):
numso = list(sorted(nums))
numse = list(map(lambda t:numero(t[1], t[0]), enumerate(nums)))
numseo = []
for i in range(len(nums)):
if nums[i] != numso[i]:
numseo.append(numse[i])
numseo = list(sorted(numseo))
j = 0
for i in range(len(nums)):
if nums[i] != numso[i]:
numse[i] = numseo[j]
j += 1
numse[i].posicion_final = i
for i in range(len(nums)):
while i != numse[i].posicion_inicial:
swap(numse, i, numse[i].posicion_inicial)
return numse
def fuerza_bruta(a):
a_len = len(a)
r = 0
for i in range(a_len):
for j in range(i):
if a[i] < a[j]:
r += 1
return r
def quita(bi, bd, a, i):
return modifica(bi, bd, a, i, False)
def anade(bi, bd, a, i):
return modifica(bi, bd, a, i, True)
def modifica(bi, bd, a, i, anade):
if anade:
bc = bi
fac = 1
else:
bc = bd
fac = -1
inv = bi.sum(a[i] + 1) + bd.sum(a[i] - 1)
bc.add_point(a[i], fac)
return inv
def core(nums, nmi):
numse = crea_arreglo_enriquecido(nums)
a = list(map(lambda x:x.posicion_final + 1, numse))
i = 0
j = 0
ni = 0
r = 0
a_len = len(a)
bitch_izq = RangeBit(a_len + 2)
bitch_der = RangeBit(a_len + 2)
nif = 0
for x in a:
nif += bitch_der.sum_range(x + 1, a_len)
bitch_der.add(x, x, 1)
j = 0
ni = nif
# print("ni ini {}".format(ni))
for i in range(1, a_len):
while j < a_len and (j < i or ni > nmi):
ni -= quita(bitch_izq, bitch_der, a, j)
# print("en j {} se kito {}".format(j, ni))
j += 1
r += a_len - j
ni += anade(bitch_izq, bitch_der, a, i)
# print("en i {} se puso {}".format(i, ni))
# print("r f aora {}".format(r))
return r
_, k = [int(x) for x in input().strip().split(" ")]
nums = [int(x) for x in input().strip().split(" ")]
# nums = [6, 8, 6, 7, 2, 4, 2, 1, 7, 6, 2, 1, 2, 3, 2, 5, 3, 7, 1, 7, 7]
# nums = [1, 3, 2, 1, 7]
# nums = [1, 3, 2]
# k = 0
print(core(nums, k))
```
No
| 95,555 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.
The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions.
An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 ≤ i < j ≤ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element.
Help the Little Elephant and count the number of the described pairs.
Input
The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 1018) — the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of array a.
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
In a single line print a single number — the answer to the problem.
Examples
Input
3 1
1 3 2
Output
3
Input
5 2
1 3 2 1 7
Output
6
Submitted Solution:
```
'''
Created on 19/07/2018
@author: ernesto
'''
# XXX: http://codeforces.com/problemset/problem/220/E
# XXX: https://gist.github.com/robert-king/5660418
class RangeBit:
def __init__(self, n):
sz = 1
while n >= sz:
sz *= 2
self.size = sz
self.dataAdd = [0] * sz
self.dataMul = [0] * sz
def sum(self, i):
assert i > 0
add = 0
mul = 0
start = i
while i > 0:
add += self.dataAdd[i]
mul += self.dataMul[i]
i -= i & -i
return mul * start + add
def add(self, left, right, by):
assert 0 < left <= right
self._add(left, by, -by * (left - 1))
self._add(right, -by, by * right)
def _add(self, i, mul, add):
assert i > 0
while i < self.size:
self.dataAdd[i] += add
self.dataMul[i] += mul
i += i & -i
def sum_range(self, i, j):
# print("j {} s {}".format(j, self.sum(j)))
# print("i {} s {}".format(i, self.sum(i)))
return self.sum(j) - self.sum(i - 1)
class numero():
def __init__(self, valor, posicion_inicial):
self.valor = valor
self.posicion_inicial = posicion_inicial
self.posicion_final = -1;
def __lt__(self, other):
if self.valor == other.valor:
r = self.posicion_inicial < other.posicion_inicial
else:
r = self.valor < other.valor
return r
def __repr__(self):
return "{}:{}:{}".format(self.valor, self.posicion_inicial, self.posicion_final)
def swap(a, i, j):
a[i], a[j] = a[j], a[i]
def crea_arreglo_enriquecido(nums):
numso = list(sorted(nums))
numse = list(map(lambda t:numero(t[1], t[0]), enumerate(nums)))
numseo = []
for i in range(len(nums)):
if nums[i] != numso[i]:
numseo.append(numse[i])
numseo = list(sorted(numseo))
j = 0
for i in range(len(nums)):
if nums[i] != numso[i]:
numse[i] = numseo[j]
j += 1
numse[i].posicion_final = i
for i in range(len(nums)):
while i != numse[i].posicion_inicial:
swap(numse, i, numse[i].posicion_inicial)
return numse
def fuerza_bruta(a):
a_len = len(a)
r = 0
for i in range(a_len):
for j in range(i):
if a[i] < a[j]:
r += 1
return r
def core(nums, nmi):
numse = crea_arreglo_enriquecido(nums)
a = (list(map(lambda x:x.posicion_final + 1, numse)))
i = 0
j = 0
ni = 0
r = 0
lmin = False
a_len = len(a)
bitch = RangeBit(a_len + 2)
bitch.add(a[0], a[0], 1)
while True:
if ni <= nmi:
j += 1
if j == a_len:
break
bitch.add(a[j], a[j], 1)
ni += bitch.sum_range(a[j] + 1, a_len)
# print("anadido {} aora {}".format(a[j], ni))
lmin = True
else:
bitch.add(a[i], a[i], -1)
if a[i] - 1:
ni -= bitch.sum(a[i] - 1)
# print("kitado {} aora {}".format(a[i], ni))
if lmin and ni > nmi:
n = j - i - 1
# print("la ventana es i {} j {} n {}".format(i, j, n))
r += (n * (n + 1)) >> 1
# print("r aora {}".format(r))
lmin = False
i += 1
caca = fuerza_bruta(a[i:j + 1])
assert caca == ni, "caca {} ni {} en nums {}".format(caca, ni, a[i:j + 1])
j -= 1
while ni > nmi :
assert i < j
bitch.add(a[i], a[i], -1)
if a[i] - 1:
ni -= bitch.sum(a[i] - 1)
i += 1
caca = fuerza_bruta(a[i:j + 1])
assert caca == ni, "caca f {} ni {} en nums {}".format(caca, ni, a[i:j + 1])
if i < j:
assert ni <= nmi
n = j - i
# print("la ventana f es i {} j {} n {}".format(i, j, n))
r += (n * (n + 1)) >> 1
# print("r f aora {}".format(r))
return r
_, k = [int(x) for x in input().strip().split(" ")]
nums = [int(x) for x in input().strip().split(" ")]
# nums = [6, 8, 6, 7, 2, 4, 2, 1, 7, 6, 2, 1, 2, 3, 2, 5, 3, 7, 1, 7, 7]
# nums = [1, 3, 2, 1, 7]
# nums = [1, 3, 2]
# k = 0
print(core(nums, k))
```
No
| 95,556 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Tags: implementation
Correct Solution:
```
n=int(input())
a=[[0, 0], [0, 0]]
b=[]
for i in range(n):
b=input().split()
a[int(b[0])-1][0]+=int(b[1])
a[int(b[0])-1][1]+=int(b[2])
if a[0][0]>=a[0][1]:
print("LIVE")
else:
print("DEAD")
if a[1][0]>=a[1][1]:
print("LIVE")
else:
print("DEAD")
```
| 95,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Tags: implementation
Correct Solution:
```
n=int(input())
a=[0]*n
for i in range(n):
a[i] = [0]*3
a[i]=input().split()
a1 = a2 = b1 = b2 = 0
for i in range(n):
if (a[i][0]=='1'):
a1+=int(a[i][1])
a2+=int(a[i][2])
if (a[i][0]=='2'):
b1+=int(a[i][1])
b2+=int(a[i][2])
if (a1>=a2):
print("LIVE")
else:
print("DEAD")
if (b1>=b2):
print("LIVE")
else:
print("DEAD")
```
| 95,558 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Tags: implementation
Correct Solution:
```
n=int(input())
pinga=pingb=sum1=sum2=0
for i in range(n):
t,x,y=map(int,input().split())
if t==1:
pinga+=1
sum1+=x
elif t==2:
pingb+=1
sum2+=x
if sum1>=(pinga*10)//2:
print("LIVE")
else:
print("DEAD")
if sum2>=(pingb*10)//2:
print("LIVE")
else:
print("DEAD")
```
| 95,559 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Tags: implementation
Correct Solution:
```
T = int(input())
a_x,b_y = 0,0
A_x,B_y = 0,0
for i in range(T):
t,x,y = map(int,input().split())
if t == 1:
a_x += x
b_y += y
else:
A_x += x
B_y += y
if a_x >= b_y:
print('LIVE')
else:
print('DEAD')
if A_x > B_y:
print('LIVE')
else:
print('DEAD')
```
| 95,560 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Tags: implementation
Correct Solution:
```
n=int(input())
a=0
a1=0
b=0
b1=0
for i in range(n):
t,x,y=map(int,input().split())
if t==1:
a+=x
a1+=y
else:
b+=x
b1+=y
if a>=a1:
print('LIVE')
else:
print('DEAD')
if b>=b1:
print('LIVE')
else:
print('DEAD')
```
| 95,561 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Tags: implementation
Correct Solution:
```
n = int(input())
x1, y1, x2, y2 = 0, 0, 0, 0
for _ in range(n):
a = list(map(int, input().split()))
if a[0] == 1:
x1 = x1+a[1]
y1 = y1+a[2]
else:
x2 = x2+a[1]
y2 = y2+a[2]
if x1>=y1:
print("LIVE")
else:
print("DEAD")
if x2>=y2:
print("LIVE")
else:
print("DEAD")
```
| 95,562 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Tags: implementation
Correct Solution:
```
n=int(input())
sum1=0
sum2=0
z=0
c=0
for i in range(n):
t,x,y=map(int,input().split())
if t==1:
sum1+=x
z+=1
if t==2:
sum2+=x
c+=1
if sum1>=int(5*z):
print("LIVE")
else:
print("DEAD")
if sum2>=int(5*c):
print("LIVE")
else:
print("DEAD")
```
| 95,563 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Tags: implementation
Correct Solution:
```
x=int(input())
a,b,c,d=0,0,0,0
for i in range(x):
t,x,y=map(int,input().split())
if t==1:
a+=1
b+=x
if t==2:
c+=1
d+=x
if b>=a*5:
print('LIVE')
else:
print('DEAD')
if d>=c*5:
print('LIVE')
else:
print('DEAD')
```
| 95,564 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Submitted Solution:
```
n = int(input())
s = [[0, 0], [0, 0]]
for i in range(n):
x = [int(s) for s in input().split(' ')]
s[x[0] - 1][0] += x[1]
s[x[0] - 1][1] += x[2]
for server in s:
if server[0] >= server[1]:
print('LIVE')
else:
print('DEAD')
```
Yes
| 95,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Submitted Solution:
```
n = int(input())
live_a = 0
dead_a = 0
live_b = 0
dead_b = 0
status_a = False
status_b = False
for i in range(n):
x = list(map(int, input().split()))
if x[0] == 1:
live_a += x[1]
dead_a += x[2]
else:
live_b += x[1]
dead_b += x[2]
if live_a >= dead_a:
status_a = True
if live_b >= dead_b:
status_b = True
print("LIVE" if status_a == True else "DEAD")
print("LIVE" if status_b == True else "DEAD")
```
Yes
| 95,566 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Submitted Solution:
```
import math
t = int(input())
sum1 = 0
sum2 = 0
s1 = 0
s2 = 0
for i in range(t):
s, x, y = input().split()
if int(s) == 1:
sum1 += int(x)
s1 += 1
else:
sum2 += int(x)
s2 += 1
if sum1 >= s1*5:
print("LIVE")
else:
print("DEAD")
if sum2 >= s2*5:
print("LIVE")
else:
print("DEAD")
```
Yes
| 95,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Submitted Solution:
```
x = int(input())
y = []
k = 0
l = 0
s = 0
s1 = 0
for i in range(x):
y.append(list(map(int,input().split())))
for i in range(x):
if y[i][0] == 1:
t = y[i][1]
s = s + t
k = k + 1
if y[i][0] == 2:
g = y[i][1]
s1 = s1 + g
l = l + 1
if s>=5*k:
print("LIVE")
if s<5*k:
print("DEAD")
if s1>=5*l:
print("LIVE")
if s1<5*l:
print("DEAD")
```
Yes
| 95,568 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Submitted Solution:
```
n = int(input())
at, bt, al, bl = 0, 0, 0, 0
for _ in range(n):
t, x, y = map(int,input().split())
if t == 1:
at += x
al += y
if t == 2:
bt += x
bl += y
if at>=int((al+at)/2):
print("LIVE")
else:
print("DEAD")
if bt >= int((al+at)/2):
print("LIVE")
else:
print("DEAD")
```
No
| 95,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Submitted Solution:
```
n = int(input())
at, bt, al, bl = 0, 0, 0, 0
for _ in range(n):
t, x, y = map(int,input().split())
if t == 1:
at += x
al += y
if t == 2:
bt += x
bl += y
if at>=int(al/2):
print("LIVE")
else:
print("DEAD")
if bt >= int(bl/2):
print("LIVE")
else:
print("DEAD")
```
No
| 95,570 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Submitted Solution:
```
n=int(input())
l=[]
m=[]
count=0
add=0
for i in range(n):
li=list(map(int,input().split()))
if li[0]==1:
l.append(li)
count+=1
else:
m.append(li)
add+=1
sum1=0
sum2=0
for row in range(count):
sum1+=l[row][1]
for col in range(add):
sum2+=m[col][1]
if sum1>=int(count)*5:
print("live")
else:
print("dead")
if sum2>=int(add)*5:
print("live")
else:
print("dead")
```
No
| 95,571 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.
Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.
Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.
It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
Output
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).
In the second line print the state of server b in the similar format.
Examples
Input
2
1 5 5
2 6 4
Output
LIVE
LIVE
Input
3
1 0 10
2 0 10
1 10 0
Output
LIVE
DEAD
Note
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.
Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Submitted Solution:
```
x = int(input())
i1 = 0
i2 = 0
check = 0
for i in range(x):
l1 = [int(n) for n in input().split()]
check += l1[2]
if l1[0] == 1:
i1 += l1[1]
else:
i2 += l1[1]
if(i1 >= (check // 2)):
print("LIVE")
else:
print("DEAD")
if (i2 >= (check // 2)):
print("LIVE")
else:
print("DEAD")
```
No
| 95,572 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Tags: combinatorics, math, probabilities
Correct Solution:
```
# METO Bot 0.9.9
n,m,k=map(int,input().split())
if k<m<=k+n:
t=1
for i in range(k+1):
t*=(m-i)/(n+k-(i-1))
print(1-t)
else:
print(0 if m>n+k else 1)
# Made By Mostafa_Khaled
```
| 95,573 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Tags: combinatorics, math, probabilities
Correct Solution:
```
n,m,k = map(int,input().split())
if m >k and m <= n+k:
res= 1
for x in range(k+1):
res*=(m-x)/(n+k-(x-1))
print(1-res)
else:
print(0 if m > n+k else 1)
```
| 95,574 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Tags: combinatorics, math, probabilities
Correct Solution:
```
import sys
from array import array # noqa: F401
from math import log, e
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, m, k = map(int, input().split())
if m <= k:
print(1)
exit()
if n + k < m:
print(0)
exit()
prob1 = 0.0
for i in range(m + n, m, -1):
prob1 += log(i)
for i in range(2, n + 1):
prob1 -= log(i)
prob2 = 0.0
for i in range(m + n, m - k - 1, -1):
prob2 += log(i)
for i in range(2, n + k + 2):
prob2 -= log(i)
print(1 - pow(e, prob2 - prob1))
```
| 95,575 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Tags: combinatorics, math, probabilities
Correct Solution:
```
def find(A):
n,m,k=A
if m<k:
return 1
temp1=1
temp2=1
for i in range(k+1):
temp1*=(m-i)
temp2*=(n+i+1)
return max(1-temp1/temp2,0)
print(find(list(map(int,input().strip().split(' ')))))
```
| 95,576 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Tags: combinatorics, math, probabilities
Correct Solution:
```
#!/usr/bin/python3.5
# -*- coding: utf-8 -*-
import json
import sys
def main():
n, m, k = map(int, input().strip().split())
if n + k < m:
print(0)
return
ans = 1.0
for i in range(k+1):
ans *= (m - i) * 1.0 / (n + i + 1)
print(1.0 - ans)
if __name__ == '__main__':
main()
```
| 95,577 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Tags: combinatorics, math, probabilities
Correct Solution:
```
n,m,k=map(int,input().split())
if k<m<=k+n:
t=1
for i in range(k+1):
t*=(m-i)/(n+k-(i-1))
print(1-t)
else:
print(0 if m>n+k else 1)
```
| 95,578 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Tags: combinatorics, math, probabilities
Correct Solution:
```
def main():
inp = input().split(" ")
n = (int)(inp[0])
m = (int)(inp[1])
k = (int)(inp[2])
if (m - n > k):
print(0)
elif (m <= k):
print(1)
else:
det = 1
num = 1
for i in range(m, m - k - 1, -1):
num *= i
for i in range(n + 1, n + k + 2, 1):
det *= i
print(1 - num / det)
main()
```
| 95,579 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Tags: combinatorics, math, probabilities
Correct Solution:
```
'''
Calculate the probability of m / (n + k) for each m and n
Print the 1 - the probability
'''
num10NotePeople, num20NotePeople, num10Notes = input().split()
num10NotePeople, num20NotePeople, num10Notes = int(num10NotePeople), int(num20NotePeople), int(num10Notes)
if num10Notes >= num20NotePeople:
print(1)
elif num20NotePeople > (num10NotePeople + num10Notes):
print(0)
else:
num = 1
den = 1
for i in range(num10Notes + 1):
num *= num20NotePeople - i
den *= num10NotePeople + i + 1
prob = 1 - num / den;
print(prob)
```
| 95,580 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Submitted Solution:
```
# METO Bot 0.9.9
n,m,k=map(int,input().split())
if k<m<=k+n:
t=1
for i in range(k+1):
t*=(m-i)/(n+k-(i-1))
print(1-t)
else:
print(0 if m>n+k else 1)
```
Yes
| 95,581 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Submitted Solution:
```
n, m, k=map(int, input().split())
if k >= m:
print(1)
elif k < m <= k + n:
ans = 1
for i in range(k + 1):
ans *= (m - i) / (n + 1 + i)
print(1 - ans)
else:
print(0)
```
Yes
| 95,582 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Submitted Solution:
```
def find(A):
n,m,k=A
if m<k:
return 1
temp1=1
temp2=1
for i in range(k+1):
temp1*=(m-i)
temp2*=(n+i+1)
return 1-temp1/temp2
print(find(list(map(int,input().strip().split(' ')))))
```
No
| 95,583 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Submitted Solution:
```
n, m, k=map(int, input().split())
if k >= m:
print(1)
elif k < m <= k + n:
ans = 1
for i in range(k + 1):
ans *= (m - i) / (n + 1 + i)
print(1 - ans)
else:
print(1)
```
No
| 95,584 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Submitted Solution:
```
num10NotePeople, num20NotePeople, num10Notes = input().split()
num10NotePeople, num20NotePeople, num10Notes = int(num10NotePeople), int(num20NotePeople), int(num10Notes)
num = 1
den = 1
for i in range(num10Notes + 1):
num *= num20NotePeople - i
den *= num10NotePeople + i + 1
prob = 1 - num / den;
print(prob)
```
No
| 95,585 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input
The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).
Output
Output on a single line the desired probability with at least 4 digits after the decimal point.
Examples
Input
5 3 1
Output
0.857143
Input
0 5 5
Output
1
Input
0 1 0
Output
0
Submitted Solution:
```
n,m,k = map(int,input().split())
if m >k and m < n+k:
res= 1
for x in range(k+1):
res*=(m-x)/(n+k-(x-1))
print(1-res)
else:
print(0 if m > n+k else 1)
```
No
| 95,586 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Tags: games, greedy
Correct Solution:
```
"""
Author - Satwik Tiwari .
24th NOV , 2020 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
for pp in range(t):
solve(pp)
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))
def solve(case):
n = int(inp())
a = inp()
b = inp()
chck = [0]*4
for i in range(2*n):
chck[int(a[i]) + 2*int(b[i])] +=1
f = 0
s = 0
for i in range(n):
if(chck[3] > 0):
f+=1;chck[3]-=1
elif(chck[1]>0):
f+=1;chck[1]-=1
elif(chck[2]>0):
chck[2]-=1
else: chck[0]-=1
if(chck[3] > 0):
s+=1;chck[3]-=1
elif(chck[2]>0):
s+=1;chck[2]-=1
elif(chck[1]>0):
chck[1]-=1
else: chck[0]-=1
print('Draw' if f==s else ('First' if f>s else 'Second'))
testcase(1)
# testcase(int(inp()))
```
| 95,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Tags: games, greedy
Correct Solution:
```
n = int(input())
a, b = input(), input()
t = {i + j: 0 for i in '01' for j in '01'}
for i in range(2 * n): t[a[i] + b[i]] += 1
d = t['11'] & 1
d += (t['10'] - t['01'] + 1 - d) // 2
if d > 0: d = 1
elif d < 0: d = 2
print(['Draw', 'First', 'Second'][d])
```
| 95,588 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Tags: games, greedy
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
##########################################################
from collections import Counter
# c=sorted((i,int(val))for i,val in enumerate(input().split()))
import heapq
# c=sorted((i,int(val))for i,val in enumerate(input().split()))
# n = int(input())
# ls = list(map(int, input().split()))
# n, k = map(int, input().split())
# n =int(input())
# e=list(map(int, input().split()))
from collections import Counter
#print("\n".join(ls))
#print(os.path.commonprefix(ls[0:2]))
#for _ in range(int(input())):
#for _ in range(int(input())):
n=int(input())
s=input()
t=input()
both=0
only_a=0
only_b=0
for i in range(2*n):
if s[i]=="1" and t[i]=="1":
both+=1
else:
if s[i]=="1":
only_a+=1
if t[i]=="1":
only_b+=1
a=0
b=0
for i in range(n):
if both:
a+=1
both-=1
elif only_a:
only_a-=1
a+=1
elif only_b:
only_b-=1
if both:
both-=1
b+=1
elif only_b:
b+=1
only_b-=1
elif only_a:
only_a-=1
if a>b:
print("First")
elif a==b:
print("Draw")
else:
print("Second")
```
| 95,589 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Tags: games, greedy
Correct Solution:
```
from sys import stdin
#def read(): return map(int, stdin.readline().split())
n = int(stdin.readline())
a = stdin.readline()
b = stdin.readline()
cnt0 = 0
cnt1 = 0
cnt2 = 0
for i in range(n*2):
if a[i] == '0':
if b[i] == '0': cnt0 += 1
else: cnt1 += 1
elif b[i] == '0': cnt2 += 1
cnt = [ cnt0, cnt1, cnt2, 2*n - cnt0 - cnt1 - cnt2 ]
dif = 0
iter1 = iter ( ( 0b11, 0b10, 0b01, 0b00 ) )
iter2 = iter ( ( 0b11, 0b01, 0b10, 0b00 ) )
cur1 = next(iter1)
cur2 = next(iter2)
left = n
while left > 0:
while cnt[cur1] == 0:
cur1 = next(iter1)
dif += (cur1>>1)
cnt[cur1] -= 1
while cnt[cur2] == 0:
cur2 = next(iter2)
dif -= (cur2&1)
cnt[cur2] -= 1
jump = min ( cnt[cur1], cnt[cur2] ) if cur1 != cur2 else cnt[cur1]//2
dif += ( (cur1>>1) - (cur2&1) )*jump
cnt[cur1] -= jump
cnt[cur2] -= jump
left -= jump+1
if dif > 0: print( "First" )
elif dif < 0: print ( "Second" )
else: print ( "Draw" )
```
| 95,590 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Tags: games, greedy
Correct Solution:
```
ii=lambda:int(input())
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
n,a1,a2=ii(),input(),input()
locs = [0]*4
for i in range(2*n):
locs[int(a1[i])+2*int(a2[i])]+=1
rm = min(locs[1],locs[2])
locs[1]-=rm
locs[2]-=rm
locs[3]=locs[3]&1
if locs[1]:
print("First")
else:
if locs[3]:
if locs[2]==0:
print("First")
elif locs[2]<3:
print("Draw")
else:
print("Second")
else:
if locs[2]<2:
print("Draw")
else:
print("Second")
```
| 95,591 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Tags: games, greedy
Correct Solution:
```
import io, os
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline
ii=lambda:int(input())
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
n,a1,a2=ii(),input(),input()
locs = [0]*4
for i in range(2*n):
locs[int(a1[i])+2*int(a2[i])]+=1
rm = min(locs[1],locs[2])
locs[1]-=rm
locs[2]-=rm
locs[3]=locs[3]&1
if locs[1]:
print("First")
else:
if locs[3]:
if locs[2]==0:
print("First")
elif locs[2]<3:
print("Draw")
else:
print("Second")
else:
if locs[2]<2:
print("Draw")
else:
print("Second")
```
| 95,592 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Tags: games, greedy
Correct Solution:
```
import sys
import math
n = int(input())
st1 = input()
st2 = input()
k = 0
res = 0
for i in range(2 * n):
if(st1[i] == '1' and st2[i] == '1'):
k += 1
elif(st1[i] == '1'):
res -= 1
elif(st2[i] == '1'):
res += 1
res1 = int(k / 2) + k % 2
res2 = k - res1
v = 0
if(k % 2 == 0):
v = -1
if(res < 0):
b = math.fabs(res)
res1 += int(b / 2) + res % 2
elif(res > 0):
res += v
res2 += int(res / 2) + res % 2
if(res1 > res2):
print("First")
elif(res1 < res2):
print("Second")
else:
print("Draw")
```
| 95,593 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Tags: games, greedy
Correct Solution:
```
from sys import stdin
from math import ceil, floor
n = int(input())
s = stdin.readline()
t = stdin.readline()
first = 0
second = 0
draw = 0
for i in range(2*n):
if( s[i] == '1' and t[i] == '1' ): draw += 1
elif( s[i] == '1' ): first += 1
elif( t[i] == '1' ): second += 1
#print( first, second, draw )
if( first > second ):
if( draw%2 == 1 ): first -= ceil( (first-second)/2 )
else: first -= (first-second) - ceil( (first-second)/2 )
elif( second > first ):
if( draw%2 == 1 ): second -= (second-first) - ceil( (second-first)/2 )
else: second -= ceil( (second-first)/2 )
#print( first, second, draw )
first += ceil(draw/2.0)
second += (draw - ceil(draw/2.0))
#print( first, second, draw )
if( first > second ): print( "First" )
elif( second > first ): print( "Second" )
else: print("Draw")
```
| 95,594 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Submitted Solution:
```
import sys
import bisect
try:
fin = open('in')
except:
fin = sys.stdin
input = lambda: fin.readline().strip()
n=int(input())
a=list(map(int,input()))
b=list(map(int,input()))
r=[[0,0],[0,0]]
for i in range(2*n):
r[a[i]][b[i]] += 1
t=[0]*2
for i in range(2*n):
j=i%2
if r[1][1]>0:
r[1][1]-=1
t[j]+=[1,1][j]
elif r[0][1]>0:
r[0][1]-=1
t[j]+=[0,1][j]
elif r[1][0]>0:
r[1][0]-=1
t[j]+=[1,0][j]
else:
r[0][0]-=1
t[j]+=[0,0][j]
x,y=t
if x>y:print("First")
elif x<y:print("Second")
else:print("Draw")
```
Yes
| 95,595 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Submitted Solution:
```
n = input()
s = input()
t = input()
fir = 0
sec = 0
same = 0
for (l, r) in zip(s, t):
if l == '1':
fir += 1
if r == '1':
same += 1
sec += 1
elif r == '1':
sec += 1
if same % 2 != 0:
fir += 1
if fir > sec: #or (sec - fir <= 1 and same % 2 != 0):
print("First")
elif sec > fir + 1: # or (sec - fir <= 1 and same % 2 == 0):
print("Second")
else:
print("Draw")
```
Yes
| 95,596 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Submitted Solution:
```
import sys
import math
n = int(input())
st1 = input()
st2 = input()
k = 0
res = 0
for i in range(2 * n):
if(st1[i] == '1' and st2[i] == '1'):
k += 1
elif(st1[i] == '1'):
res -= 1
elif(st2[i] == '1'):
res += 1
res1 = int(k / 2) + k % 2
res2 = k - res1
if(res < 0):
b = math.fabs(res)
res1 += int(b / 2) + res % 2
elif(res > 0):
res += (k % 2) - 1
res2 += int(res / 2) + res % 2
if(res1 > res2):
print("First")
elif(res1 < res2):
print("Second")
else:
print("Draw")
```
Yes
| 95,597 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Submitted Solution:
```
n = int(input())
s=input()
t=input()
s_1 = 0
t_1 = 0
for i in range(2*n):
if s[i]=='1':
s_1+=1
if t[i]=='1':
t_1+=1
first = 0
second = 0
r = 0
for i in range(2*n):
if s[i]=='1' and t[i]=='0':
first+=1
elif s[i]=='0' and t[i]=='1':
second+=1
elif s[i]=='1' and t[i]=='1':
r+=1
if r%2==1:
first+=1
if s_1>t_1:
print('First')
elif first==second or first==second-1:
print('Draw')
elif first>second:
print('First')
elif first < second:
print('Second')
```
Yes
| 95,598 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.
Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.
The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.
You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.
It is guaranteed that both words consist of 2·n characters "0" and "1".
Output
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
Examples
Input
2
0111
0001
Output
First
Input
3
110110
001001
Output
First
Input
3
111000
000111
Output
Draw
Input
4
01010110
00101101
Output
First
Input
4
01100000
10010011
Output
Second
Submitted Solution:
```
import sys
import math
n = int(input())
st1 = input()
st2 = input()
k = 0
res = 0
for i in range(2 * n):
if(st1[i] == '1' and st2[i] == '1'):
k += 1
elif(st1[i] == '1'):
res -= 1
elif(st2[i] == '1'):
res += 1
res1 = int(k / 2) + k % 2
res2 = int(k / 2)
if(res < 0):
b = math.fabs(res)
res1 += int(b / 2) + b % 2
elif(res > 0):
res2 += int(res / 2) + res % 2
if(res1 > res2):
print("First")
elif(res1 < res2):
print("Second")
else:
print("Draw")
```
No
| 95,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.