message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
1. Each vertex should be labeled by exactly one number 1, 2 or 3;
2. The total number of vertices with label 1 should be equal to n_1;
3. The total number of vertices with label 2 should be equal to n_2;
4. The total number of vertices with label 3 should be equal to n_3;
5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x.
If there are multiple valid labelings, print any of them.
Input
The first line contains two integers n and m (1 β€ n β€ 5000; 0 β€ m β€ 10^5) β the number of vertices and edges in the graph.
The second line contains three integers n_1, n_2 and n_3 (0 β€ n_1, n_2, n_3 β€ n) β the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n.
Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 β€ u_i, v_i β€ n; u_i β v_i) β the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
Output
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex.
If there is no valid labeling, print "NO" (without quotes).
Examples
Input
6 3
2 2 2
3 1
5 4
2 5
Output
YES
112323
Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Output
NO | instruction | 0 | 40,582 | 13 | 81,164 |
Tags: dfs and similar, dp, graphs
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
N, M = map(int, input().split())
n1, n2, n3 = map(int, input().split())
def check():
graph = [[] for _ in range(N)]
for _ in range(M):
a, b = map(int, input().split())
graph[a-1].append(b-1)
graph[b-1].append(a-1)
Color = [-1]*N
P = []
ok = True
for n in range(N):
if Color[n] != -1:
continue
q = [n]
Color[n] = 0
Cs = [[n], []]
while q:
qq = []
for p in q:
for np in graph[p]:
if Color[np] == -1:
qq.append(np)
Color[np] = Color[p]^1
Cs[Color[np]].append(np)
elif Color[np] != Color[p]^1:
ok = False
break
q = qq
P.append(Cs)
return ok, P
def main():
ok, P = check()
dp = [[None]*(n2+1) for _ in range(len(P)+1)]
dp[0][0] = 0
for i in range(len(P)):
a = len(P[i][0]); b = len(P[i][1])
for n in range(n2+1):
if not dp[i][n] is None:
if n+a <= n2:
dp[i+1][n+a] = ~a
if n+b <= n2:
dp[i+1][n+b] = b
if not ok or dp[-1][n2] is None:
print("NO")
else:
print("YES")
tmp = n2
Use2 = [-1]*N
for i in reversed(range(len(P))):
leng = dp[i+1][tmp]
label = 1
if leng < 0:
label = 0
leng = ~leng
for n in P[i][label]:
Use2[n] = 1
for n in P[i][label^1]:
Use2[n] = 0
tmp -= leng
ans = []
num1 = 0
for n, use2 in enumerate(Use2):
if use2:
ans.append("2")
elif num1 < n1:
num1 += 1
ans.append("1")
else:
ans.append("3")
print("".join(ans))
if __name__ == "__main__":
main()
``` | output | 1 | 40,582 | 13 | 81,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
1. Each vertex should be labeled by exactly one number 1, 2 or 3;
2. The total number of vertices with label 1 should be equal to n_1;
3. The total number of vertices with label 2 should be equal to n_2;
4. The total number of vertices with label 3 should be equal to n_3;
5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x.
If there are multiple valid labelings, print any of them.
Input
The first line contains two integers n and m (1 β€ n β€ 5000; 0 β€ m β€ 10^5) β the number of vertices and edges in the graph.
The second line contains three integers n_1, n_2 and n_3 (0 β€ n_1, n_2, n_3 β€ n) β the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n.
Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 β€ u_i, v_i β€ n; u_i β v_i) β the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
Output
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex.
If there is no valid labeling, print "NO" (without quotes).
Examples
Input
6 3
2 2 2
3 1
5 4
2 5
Output
YES
112323
Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Output
NO
Submitted Solution:
```
import io
import os
from collections import Counter, defaultdict, deque
def bfs(source, graph):
q = deque([source])
dist = {source: 0}
while q:
node = q.popleft()
d = dist[node]
for nbr in graph[node]:
if nbr not in dist:
dist[nbr] = d + 1
q.append(nbr)
return dist
def solve(N, M, N1, N2, N3, edges):
g = [[] for i in range(N + 1)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
# The only valid edges are 1-2 and 2-3
# So any 2-coloring of the graph should split the actual colors into 2 and 1,3 (without knowing which is which)
# Since the graph isn't connected, for each component we have to try both as color 2
seen = set()
comps = []
for source in range(N):
if source not in seen:
# BFS to label every other layer
compDist = bfs(source, g)
# Check each layer doesn't have internal edges
layers = [[], []]
for u, d in compDist.items():
mod = d % 2
for v in g[u]:
if compDist[v] % 2 == mod:
# Not two colorable
return "NO"
layers[mod].append(u)
comps.append(layers)
seen.update(compDist.keys())
possible = [{0}]
for comp in comps:
nextPossible = set()
for x in possible[-1]:
for layer in comp:
if x + len(layer) <= N2:
nextPossible.add(x + len(layer))
possible.append(nextPossible)
if N2 not in possible[-1]:
return "NO"
two = set()
target = N2
for i in range(len(possible) - 1, -1, -1):
assert target in possible[i]
for layer in comps[i - 1]:
if target - len(layer) in possible[i - 1]:
target -= len(layer)
two.update(layer)
break
ans = []
count = 0
for u in range(N):
if u in two:
ans.append(2)
else:
if count < N1:
ans.append(1)
count += 1
else:
ans.append(3)
return "YES" + "\n" + "".join(map(str, ans))
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
N1, N2, N3 = [int(x) for x in input().split()]
edges = [[int(x) - 1 for x in input().split()] for i in range(M)]
ans = solve(N, M, N1, N2, N3, edges)
print(ans)
``` | instruction | 0 | 40,583 | 13 | 81,166 |
Yes | output | 1 | 40,583 | 13 | 81,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
1. Each vertex should be labeled by exactly one number 1, 2 or 3;
2. The total number of vertices with label 1 should be equal to n_1;
3. The total number of vertices with label 2 should be equal to n_2;
4. The total number of vertices with label 3 should be equal to n_3;
5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x.
If there are multiple valid labelings, print any of them.
Input
The first line contains two integers n and m (1 β€ n β€ 5000; 0 β€ m β€ 10^5) β the number of vertices and edges in the graph.
The second line contains three integers n_1, n_2 and n_3 (0 β€ n_1, n_2, n_3 β€ n) β the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n.
Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 β€ u_i, v_i β€ n; u_i β v_i) β the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
Output
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex.
If there is no valid labeling, print "NO" (without quotes).
Examples
Input
6 3
2 2 2
3 1
5 4
2 5
Output
YES
112323
Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Output
NO
Submitted Solution:
```
class UnionFind:
def __init__(self, n):
self.par = [i for i in range(n+1)]
self.rank = [0] * (n+1)
def find(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.rank[x] < self.rank[y]:
self.par[x] = y
else:
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def same_check(self, x, y):
return self.find(x) == self.find(y)
n, m = map(int, input().split())
n1, n2, n3 = map(int, input().split())
uf = UnionFind(n)
g = [[] for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
uf.unite(a - 1, b - 1)
g[a - 1].append(b - 1)
g[b - 1].append(a - 1)
d = dict()
ds = [-1] * n
idx = 0
c = []
c2 = []
l = []
for i in range(n):
p = uf.find(i)
if p in d:
continue
l.append(p)
d[p] = idx
idx += 1
s = [p]
ds[p] = 0
cnt = 0
cnt2 = 1
while s:
k = s.pop()
for node in g[k]:
if ds[node] == -1:
s.append(node)
ds[node] = ds[k] ^ 1
cnt += ds[node]
cnt2 += ds[node] ^ 1
elif ds[node] != ds[k] ^ 1:
print('NO')
exit(0)
c.append(cnt)
c2.append(cnt2)
dp = [[False] * (n + 1) for _ in range(len(c) + 1)]
dp[0][0] = True
prv = [[0] * (n + 1) for _ in range(len(c) + 1)]
for i in range(len(c)):
for j in range(n + 1):
if j >= c[i]:
dp[i + 1][j] |= dp[i][j - c[i]]
if dp[i][j - c[i]]:
prv[i + 1][j] = j - c[i]
if j >= c2[i]:
dp[i + 1][j] |= dp[i][j - c2[i]]
if dp[i][j - c2[i]]:
prv[i + 1][j] = j - c2[i]
if (dp[-1][n2]):
print('YES')
ans = [-1] * n
idx = n2
for i in range(1, len(c) + 1):
if idx - prv[-i][idx] == c[-i]:
s = [l[-i]]
while s:
p = s.pop()
ans[p] = ds[p] ^ 1
for node in g[p]:
if ans[node] == -1:
s.append(node)
else:
s = [l[-i]]
while s:
p = s.pop()
ans[p] = ds[p]
for node in g[p]:
if ans[node] == -1:
s.append(node)
idx = prv[-i][idx]
cnt = 0
for i in range(n):
if ans[i] == 0:
ans[i] = 2
else:
if cnt < n1:
ans[i] = 1
cnt += 1
else:
ans[i] = 3
print(''.join(map(str, ans)))
else:
print('NO')
``` | instruction | 0 | 40,584 | 13 | 81,168 |
Yes | output | 1 | 40,584 | 13 | 81,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
1. Each vertex should be labeled by exactly one number 1, 2 or 3;
2. The total number of vertices with label 1 should be equal to n_1;
3. The total number of vertices with label 2 should be equal to n_2;
4. The total number of vertices with label 3 should be equal to n_3;
5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x.
If there are multiple valid labelings, print any of them.
Input
The first line contains two integers n and m (1 β€ n β€ 5000; 0 β€ m β€ 10^5) β the number of vertices and edges in the graph.
The second line contains three integers n_1, n_2 and n_3 (0 β€ n_1, n_2, n_3 β€ n) β the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n.
Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 β€ u_i, v_i β€ n; u_i β v_i) β the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
Output
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex.
If there is no valid labeling, print "NO" (without quotes).
Examples
Input
6 3
2 2 2
3 1
5 4
2 5
Output
YES
112323
Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Output
NO
Submitted Solution:
```
n,m=map(int,input().split())
n1,n2,n3=map(int,input().split())
edge=[[] for i in range(n)]
for i in range(m):
u,v=map(int,input().split())
edge[u-1].append(v-1)
edge[v-1].append(u-1)
ans=[]
def is_bipartgraph():
color=[0]*n
used=[False]*n
for i in range(n):
if not used[i]:
stack=[(i,1)]
black=[]
white=[]
while stack:
v,c=stack.pop()
if not used[v]:
color[v]=c
if c==1:
black.append(v)
else:
white.append(v)
used[v]=True
for nv in edge[v]:
if color[nv]==color[v]:
return False
elif color[nv]==0:
stack.append((nv,-c))
ans.append([black,white])
return True
if is_bipartgraph():
dp=[[False for i in range(0,n2+1)] for j in range(len(ans))]
if n2>=len(ans[0][0]):
dp[0][len(ans[0][0])]=True
if n2>=len(ans[0][1]):
dp[0][len(ans[0][1])]=True
for i in range(1,len(ans)):
for j in range(n2+1):
test=False
if j>=len(ans[i][0]):
test=test|dp[i-1][j-len(ans[i][0])]
if j>=len(ans[i][1]):
test=test|dp[i-1][j-len(ans[i][1])]
dp[i][j]=test
if dp[-1][n2]:
even=[]
odd=[]
for i in range(len(ans)-1,0,-1):
if dp[i-1][n2-len(ans[i][0])] and n2>=len(ans[i][0]):
even+=ans[i][0]
odd+=ans[i][1]
n2-=len(ans[i][0])
else:
even+=ans[i][1]
odd+=ans[i][0]
n2-=len(ans[i][1])
if len(ans[0][0])==n2:
even+=ans[0][0]
odd+=ans[0][1]
else:
even+=ans[0][1]
odd+=ans[0][0]
ans=["" for i in range(n)]
for i in even:
ans[i]="2"
count=0
while odd:
i=odd.pop()
if n1>count:
ans[i]="1"
count+=1
else:
ans[i]="3"
print("YES")
print("".join(ans))
else:
print("NO")
else:
print("NO")
``` | instruction | 0 | 40,585 | 13 | 81,170 |
Yes | output | 1 | 40,585 | 13 | 81,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
1. Each vertex should be labeled by exactly one number 1, 2 or 3;
2. The total number of vertices with label 1 should be equal to n_1;
3. The total number of vertices with label 2 should be equal to n_2;
4. The total number of vertices with label 3 should be equal to n_3;
5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x.
If there are multiple valid labelings, print any of them.
Input
The first line contains two integers n and m (1 β€ n β€ 5000; 0 β€ m β€ 10^5) β the number of vertices and edges in the graph.
The second line contains three integers n_1, n_2 and n_3 (0 β€ n_1, n_2, n_3 β€ n) β the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n.
Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 β€ u_i, v_i β€ n; u_i β v_i) β the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
Output
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex.
If there is no valid labeling, print "NO" (without quotes).
Examples
Input
6 3
2 2 2
3 1
5 4
2 5
Output
YES
112323
Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Output
NO
Submitted Solution:
```
# ------------------- fast io --------------------
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")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
n, m = map(int, input().split())
n1, n2, n3 = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
graph = [[] for __ in range(n+1)]
for __ in range(m):
x, y = map(int, input().split())
graph[x] += [y]
graph[y] += [x]
def dfs(graph, alpha):
"""Depth First Search on a graph!"""
n = len(graph)
stack = [alpha]
colors[alpha] = 1
p1 = 1
comp = []
while stack:
v = stack[-1]
if not visited[v]:
visited[v] = True
for u in graph[v]:
if not visited[u]:
stack.append(u)
if colors[u] == -1:
colors[u] = 1 - colors[v]
if colors[u] == 1:p1+=1
if colors[u] != 1 - colors[v]:
return False, None
else:
comp += [stack.pop()]
return comp, p1
visited = [False] * (n+1)
pos = True
colors = [-1]*(n+1)
components = []
req, extra = 0, []
for i in range(1, n+1):
if not visited[i]:
x, p1 = dfs(graph, i)
if not x:
pos = False
break
components += [x]
p2 = len(x) - p1
req += min(p1, p2)
if p1 != p2:
extra += [abs(p1-p2)]
target = n2 - req
def check_subset_sum(a, n):
"""Checks if a subset of a exists with sum equal to n."""
dp = [[]] * (n + 1)
for i in range(len(a)):
for j in range(n, a[i] - 1, -1):
if j == a[i]:
dp[j] = [a[i]]
elif dp[j]:
continue
elif dp[j - a[i]]:
dp[j] = dp[j - a[i]] + [a[i]]
return dp[-1]
dp = []
if target >= 0:
dp = check_subset_sum(extra, target)
if pos and (sum(dp) == target):
print("YES")
ans = [1]*(n+1)
for comp in components:
odd = [i for i in comp if colors[i] == 1]
even = [i for i in comp if colors[i] == 0]
if len(odd) == len(even):
for k in odd:
ans[k] = 2
else:
if len(even) > len(odd):
odd, even = list(even), list(odd)
if (len(odd) - len(even)) in dp:
dp.remove(len(odd) - len(even))
for k in odd:
ans[k] = 2
else:
for k in even:
ans[k] = 2
if ans.count(2) != n2:
print(0/0)
for i in range(1, n+1):
if not n3:break
if ans[i] == 1:
n3 -= 1
ans[i] = 3
print(*ans[1:], sep='')
else:
print("NO")
``` | instruction | 0 | 40,586 | 13 | 81,172 |
Yes | output | 1 | 40,586 | 13 | 81,173 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
1. Each vertex should be labeled by exactly one number 1, 2 or 3;
2. The total number of vertices with label 1 should be equal to n_1;
3. The total number of vertices with label 2 should be equal to n_2;
4. The total number of vertices with label 3 should be equal to n_3;
5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x.
If there are multiple valid labelings, print any of them.
Input
The first line contains two integers n and m (1 β€ n β€ 5000; 0 β€ m β€ 10^5) β the number of vertices and edges in the graph.
The second line contains three integers n_1, n_2 and n_3 (0 β€ n_1, n_2, n_3 β€ n) β the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n.
Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 β€ u_i, v_i β€ n; u_i β v_i) β the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
Output
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex.
If there is no valid labeling, print "NO" (without quotes).
Examples
Input
6 3
2 2 2
3 1
5 4
2 5
Output
YES
112323
Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Output
NO
Submitted Solution:
```
from collections import defaultdict,deque
import sys
input=sys.stdin.readline
def bfs(root):
visited[root]=0
parity=[1,0]
store=[root]
queue=deque([root])
while queue:
vertex=queue.popleft()
for child in graph[vertex]:
if visited[child]==-1:
visited[child]=visited[vertex]^1
store.append(child)
queue.append(child)
parity[visited[child]]+=1
elif visited[child]==visited[vertex]:
return(False,(-1,-1),(-1,-1))
return(True,parity,store)
n,m=map(int,input().split())
n1,n2,n3=map(int,input().split())
graph=defaultdict(list)
for i in range(m):
u,v=map(int,input().split())
u-=1
v-=1
graph[u].append(v)
graph[v].append(u)
visited=[-1]*(n)
ans=[]
ind=[]
for i in range(1,len(visited)):
if visited[i]==-1:
ret,ret2,ret3=bfs(i)
if not ret:
print('NO')
exit()
ind.append(ret3)
ans.append(ret2)
#print(ind,ans,visited)
dp=[[False]*(n+1) for _ in range(len(ans)+1)]
dp[0][0]=True
for i in range(len(ans)):
#print(ans)
even,odd=ans[i][0],ans[i][1]
for j in range(len(dp[0])):
if even+j<(n+1):
dp[i+1][j+even]=(dp[i][j] or dp[i+1][j+even])
if odd+j<(n+1):
dp[i+1][j+odd]=(dp[i][j] or dp[i+1][j+odd])
#print(dp)
if dp[-1][n2]==False:
print("NO")
exit()
c = n2
which = []
for i in range(len(ans))[::-1]:
for j, val in enumerate(ans[i]):
if c - val >= 0:
if dp[i][c - val]:
c = c - val
which.append(j)
break
which = which[::-1]
res = [-1] * n
for i in range(len(which)):
whi = which[i]
for indu in ind[i]:
if visited[indu] == whi:
res[indu] = 2
for i in range(n):
if res[i] == -1:
if n1 > 0:
res[i] = 1
n1 -= 1
else:
res[i] = 3
print("YES")
print("".join(map(str, res)))
``` | instruction | 0 | 40,587 | 13 | 81,174 |
No | output | 1 | 40,587 | 13 | 81,175 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
1. Each vertex should be labeled by exactly one number 1, 2 or 3;
2. The total number of vertices with label 1 should be equal to n_1;
3. The total number of vertices with label 2 should be equal to n_2;
4. The total number of vertices with label 3 should be equal to n_3;
5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x.
If there are multiple valid labelings, print any of them.
Input
The first line contains two integers n and m (1 β€ n β€ 5000; 0 β€ m β€ 10^5) β the number of vertices and edges in the graph.
The second line contains three integers n_1, n_2 and n_3 (0 β€ n_1, n_2, n_3 β€ n) β the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n.
Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 β€ u_i, v_i β€ n; u_i β v_i) β the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
Output
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex.
If there is no valid labeling, print "NO" (without quotes).
Examples
Input
6 3
2 2 2
3 1
5 4
2 5
Output
YES
112323
Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Output
NO
Submitted Solution:
```
import sys
input = sys.stdin.readline
flush = sys.stdout.flush
n, m = map(int, input().split())
n1, n2, n3 = map(int, input().split())
nbhd = [[] for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
nbhd[u - 1].append(v - 1)
nbhd[v - 1].append(u - 1)
color = [None] * n
bipar = []
for v in range(n):
if color[v] is not None:
continue
cnt = [[], []]
i = 0
S = [v]
while S != []:
w = S.pop()
if color[w] == i ^ 1:
print("NO")
quit()
if color[w] == i:
continue
color[w] = i
cnt[i].append(w)
i ^= 1
S += nbhd[w]
bipar.append(cnt)
k = len(bipar)
ddp = [[False] * (n2 + 1) for _ in range(k + 1)]
ddp[0][0] = True
for i in range(1, k + 1):
for j in range(n2 + 1):
if j >= len(bipar[i - 1][0]) and ddp[i - 1][j - len(bipar[i - 1][0])]:
ddp[i][j] = True
if j >= len(bipar[i - 1][1]) and ddp[i - 1][j - len(bipar[i - 1][1])]:
ddp[i][j] = True
if not ddp[k][n2]:
print("NO")
quit()
idx = [None] * k
temp = n2
for i in reversed(range(k)):
if temp - len(bipar[i][0]) >= 0 and ddp[i][temp - len(bipar[i][0])]:
idx[i] = 0
temp -= len(bipar[i][0])
if temp - len(bipar[i][1]) >= 0 and ddp[i][temp - len(bipar[i][1])]:
idx[i] = 1
temp -= len(bipar[i][1])
color = [3] * n
for i, x in enumerate(bipar):
for y in x[idx[i]]:
color[y] = 2
for i in range(n):
if n1 == 0:
break
if color[i] == 3:
color[i] = 1
n1 -= 1
print("YES")
print(*color, sep = "")
``` | instruction | 0 | 40,588 | 13 | 81,176 |
No | output | 1 | 40,588 | 13 | 81,177 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
1. Each vertex should be labeled by exactly one number 1, 2 or 3;
2. The total number of vertices with label 1 should be equal to n_1;
3. The total number of vertices with label 2 should be equal to n_2;
4. The total number of vertices with label 3 should be equal to n_3;
5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x.
If there are multiple valid labelings, print any of them.
Input
The first line contains two integers n and m (1 β€ n β€ 5000; 0 β€ m β€ 10^5) β the number of vertices and edges in the graph.
The second line contains three integers n_1, n_2 and n_3 (0 β€ n_1, n_2, n_3 β€ n) β the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n.
Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 β€ u_i, v_i β€ n; u_i β v_i) β the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
Output
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex.
If there is no valid labeling, print "NO" (without quotes).
Examples
Input
6 3
2 2 2
3 1
5 4
2 5
Output
YES
112323
Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Output
NO
Submitted Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
from typing import List
"""
created by shhuan at 2020/6/13 13:25
"""
INF = 10**6 + 10
def solve(N, M, G, A, B, C):
if M == 0:
return ['YES', '1' * A + '2' * B + '3' * C]
# vis[i] is id of group
vis = [0 for _ in range(N + 1)]
# marks[0] means color 2, else color 1 or 3
marks = [0 for _ in range(N + 1)]
def bfs(u, mark, idx):
q = [(u, mark)]
vis[u] = idx
a, b = 0, 0
while q:
nq = []
for u, mark in q:
marks[u] = mark
a += mark ^ 1
b += 1
for v in G[u]:
if vis[v] == 0:
vis[v] = idx
nq.append((v, mark ^ 1))
else:
if marks[u] == marks[v]:
return INF, 2 * INF
q = nq
# count of color 2, count of nodes
return a, b
groupId = 1
colors = []
for i in range(1, N + 1):
if vis[i] > 0:
continue
a, b = bfs(i, 0, groupId)
if a >= INF:
return ['NO']
colors.append((a, b - a))
groupId += 1
minv, maxv = sum([min(a, b) for a, b in colors]), sum([max(a, b) for a, b in colors])
if B < minv or B > maxv:
return ['NO']
select = [0 if a <= b else 1 for a, b in colors]
diff = B - sum([v[select[i]] for i, v in enumerate(colors)])
if diff > 0:
D = [abs(a - b) for a, b in colors]
ND = len(D)
dp = [[False for _ in range(diff + 1)] for _ in range(ND + 1)]
pre = [[(0, 0, 0) for _ in range(diff + 1)] for _ in range(ND + 1)]
dp[0][0] = True
for i in range(1, ND + 1):
for j in range(diff + 1):
pd = j - D[i - 1]
if pd >= 0 and dp[i - 1][pd]:
dp[i][j] = True
pre[i][j] = (i - 1, pd, 1)
elif dp[i - 1][j]:
dp[i][j] = True
pre[i][j] = (i - 1, j, 0)
if dp[ND][diff]:
i, j = ND, diff
while i > 0:
i, j, s = pre[i][j]
if s:
select[i - 1] ^= 1
s = sum([v[select[i]] for i, v in enumerate(colors)])
if s != B:
return ['NO']
for i in range(1, N + 1):
if select[vis[i] - 1] == 1:
marks[i] ^= 1
# print(marks)
for i in range(1, N + 1):
if marks[i] == 0:
marks[i] = 2
else:
if A > 0:
marks[i] = 1
A -= 1
else:
marks[i] = 3
return ['YES', ''.join(map(str, marks[1:]))]
N, M = map(int, input().split())
A, B, C = map(int, input().split())
G = collections.defaultdict(list)
for i in range(M):
u, v = map(int, input().split())
G[u].append(v)
G[v].append(u)
print('\n'.join(solve(N, M, G, A, B, C)))
``` | instruction | 0 | 40,589 | 13 | 81,178 |
No | output | 1 | 40,589 | 13 | 81,179 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
1. Each vertex should be labeled by exactly one number 1, 2 or 3;
2. The total number of vertices with label 1 should be equal to n_1;
3. The total number of vertices with label 2 should be equal to n_2;
4. The total number of vertices with label 3 should be equal to n_3;
5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x.
If there are multiple valid labelings, print any of them.
Input
The first line contains two integers n and m (1 β€ n β€ 5000; 0 β€ m β€ 10^5) β the number of vertices and edges in the graph.
The second line contains three integers n_1, n_2 and n_3 (0 β€ n_1, n_2, n_3 β€ n) β the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n.
Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 β€ u_i, v_i β€ n; u_i β v_i) β the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
Output
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex.
If there is no valid labeling, print "NO" (without quotes).
Examples
Input
6 3
2 2 2
3 1
5 4
2 5
Output
YES
112323
Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Output
NO
Submitted Solution:
```
import sys
input = sys.stdin.readline
flush = sys.stdout.flush
n, m = map(int, input().split())
n1, n2, n3 = map(int, input().split())
nbhd = [[] for _ in range(n)]
for t in range(m):
u, v = map(int, input().split())
nbhd[u - 1].append(v - 1)
nbhd[v - 1].append(u - 1)
color = [None] * n
bipar = []
for v in range(n):
if color[v] is not None:
continue
cnt = [[], []]
i = 0
S = [v]
while S != []:
w = S.pop()
if color[w] == i ^ 1:
if t == 11:
print("NO2")
quit()
print("NO")
quit()
if color[w] == i:
continue
color[w] = i
cnt[i].append(w)
i ^= 1
S += nbhd[w]
bipar.append(cnt)
k = len(bipar)
ddp = [[False] * (n2 + 1) for _ in range(k + 1)]
ddp[0][0] = True
for i in range(1, k + 1):
for j in range(n2 + 1):
if j >= len(bipar[i - 1][0]) and ddp[i - 1][j - len(bipar[i - 1][0])]:
ddp[i][j] = True
if j >= len(bipar[i - 1][1]) and ddp[i - 1][j - len(bipar[i - 1][1])]:
ddp[i][j] = True
if not ddp[k][n2]:
if t == 11:
print("NO1")
quit()
print("NO")
quit()
idx = [None] * k
temp = n2
for i in reversed(range(k)):
if temp - len(bipar[i][0]) >= 0 and ddp[i][temp - len(bipar[i][0])]:
idx[i] = 0
temp -= len(bipar[i][0])
elif temp - len(bipar[i][1]) >= 0 and ddp[i][temp - len(bipar[i][1])]:
idx[i] = 1
temp -= len(bipar[i][1])
color = [3] * n
for i, x in enumerate(bipar):
for y in x[idx[i]]:
color[y] = 2
for i in range(n):
if n1 == 0:
break
if color[i] == 3:
color[i] = 1
n1 -= 1
print("YES")
print(*color, sep = "")
``` | instruction | 0 | 40,590 | 13 | 81,180 |
No | output | 1 | 40,590 | 13 | 81,181 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 40,675 | 13 | 81,350 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
def solve():
MOD = 10**9+7
inv2 = (MOD+1)//2
n = int(input())
#graph = [[] for i in range(n)]
dist = [[n]*n for i in range(n)]
for i in range(n):
dist[i][i] = 0
for i in range(n-1):
x, y = map(int, input().split())
x -= 1
y -= 1
dist[x][y] = dist[y][x] = 1
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k]+dist[k][j])
dp = [[0]*n for i in range(n)]
dp[0] = [1]*n
for i in range(1, n):
for j in range(1, n):
dp[i][j] = (dp[i-1][j]+dp[i][j-1])*inv2%MOD
ans = 0
for i in range(n):
for j in range(i):
for k in range(n):
di, dj, d = dist[i][k], dist[j][k], dist[i][j]
ans = (ans+dp[(di+d-dj)//2][(dj+d-di)//2]) % MOD
return ans * pow(n, MOD-2, MOD) % MOD
import sys
input = lambda: sys.stdin.readline().rstrip()
print(solve())
``` | output | 1 | 40,675 | 13 | 81,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 40,676 | 13 | 81,352 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
import sys, os
from collections import defaultdict
from queue import Queue
if os.environ['USERNAME']=='kissz':
inp=open('in.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
inp=sys.stdin.readline
def debug(*args):
pass
# SCRIPT STARTS HERE
def iterative_egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q,r = b//a,b%a; m,n = x-u*q,y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
return b, x, y
def modinv(a, m):
g, x, y = iterative_egcd(a, m)
if g != 1:
return None
else:
return x % m
M=1000000007
E=defaultdict(list)
n=int(inp())
for _ in range(n-1):
x,y=map(int,inp().split())
x-=1
y-=1
E[x]+=[y]
E[y]+=[x]
maxdepth=0
D=[[-1]*n for _ in range(n)]
for root in range(n):
Q=[(root,0)]
while Q:
q,d=Q.pop()
D[root][q]=d
maxdepth=max(maxdepth,d)
for j in E[q]:
if D[root][j]<0:
Q.append((j,d+1))
inv_mult=2**maxdepth
F=[[inv_mult]*maxdepth]+[[0]*maxdepth for _ in range(maxdepth-1)]
for i in range(1,maxdepth):
for j in range(1,maxdepth):
F[i][j]=(F[i][j-1]+F[i-1][j])//2
debug(F)
debug(maxdepth)
inversions=0
for root in range(n):
debug("root ",root)
layers=defaultdict(list)
layers[0]=[root]
Q=Queue()
Q.put((root,0,[root]))
while not Q.empty():
node,depth,ancestors=Q.get()
for j in E[node]:
if depth==0 or j!=ancestors[depth-1]:
layers[depth+1]+=[j]
Q.put((j,depth+1,ancestors+[j]))
Q=Queue()
Q.put((root,0,[root]))
while not Q.empty():
node,depth,ancestors=Q.get()
for l in range(depth+1):
for j in layers[l]:
if j==ancestors[l]:
inversions+=(j>node)*inv_mult
else:
d=D[j][node]
commond=(depth+l-d)//2
if j<node:
inversions+=F[depth-commond][l-commond] # - common root depth!
elif l!=depth:
inversions+=F[l-commond][depth-commond]
#debug(l,depth,d,j,inversions)
debug(node,depth,ancestors,inversions)
for j in E[node]:
if depth==0 or j!=ancestors[depth-1]:
Q.put((j,depth+1,ancestors+[j]))
inversions=inversions%M
debug(inversions)
debug(layers)
print(modinv(inv_mult*n,M)*inversions % M)
``` | output | 1 | 40,676 | 13 | 81,353 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 40,677 | 13 | 81,354 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
from collections import deque
mod = 10 ** 9 + 7
N = int(input())
E = []
for _ in range(N - 1):
x, y = map(int, input().split())
x, y = x-1, y-1
E.append((x, y))
pre = [1]
PA = [pre]
for i in range(N + 2):
ne = [0] * (i + 2)
for j, a in enumerate(pre):
ne[j] = (ne[j] + a) % mod
ne[j+1] = (ne[j+1] + a) % mod
PA.append(ne)
pre = ne
for pa in PA:
for i in range(len(pa) - 1):
pa[i+1] = (pa[i+1] + pa[i]) % mod
i2 = mod + 1 >> 1
poi2 = [1]
for _ in range(N + 5):
poi2.append(poi2[-1] * i2 % mod)
iN = pow(N, mod - 2, mod)
ans = 0
for i0 in range(N):
X = [[] for i in range(N)]
for x, y in E:
X[x].append(y)
X[y].append(x)
P = [-1] * N
Q = deque([i0])
R = []
D = [0] * N
while Q:
i = deque.popleft(Q)
R.append(i)
for a in X[i]:
if a != P[i]:
P[a] = i
X[a].remove(i)
deque.append(Q, a)
D[a] = D[i] + 1
size = [1] * N
for j in R[1:][::-1]:
size[P[j]] += size[j]
for j in R:
if j <= i0: continue
d = D[j]
ans = (ans + size[j] * iN)
k = j
while P[k] != i0:
p = P[k]
s = size[p] - size[k]
ans = (ans + s * PA[d-1][D[p]-1] % mod * iN % mod * poi2[d-1]) % mod
k = p
print(ans)
``` | output | 1 | 40,677 | 13 | 81,355 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 40,678 | 13 | 81,356 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
MOD = 10 ** 9 + 7
N = 1000
fact = [0 for _ in range(N)]
invfact = [0 for _ in range(N)]
fact[0] = 1
for i in range(1, N):
fact[i] = fact[i - 1] * i % MOD
invfact[N - 1] = pow(fact[N - 1], MOD - 2, MOD)
for i in range(N - 2, -1, -1):
invfact[i] = invfact[i + 1] * (i + 1) % MOD
def nCk(n, k):
if k < 0 or n < k:
return 0
else:
return (fact[n] * invfact[k] % MOD) * invfact[n - k] % MOD
def nHk(n, k):
return nCk(n + k - 1, k)
def main():
n = int(input())
edges = [[] for _ in range(n)]
for _ in range(n - 1):
x, y = map(int, input().split())
x -= 1
y -= 1
edges[x].append(y)
edges[y].append(x)
def cnt(i, j):
bef = [-1] * n
used = [False] * n
stack = [i]
while stack:
pos = stack.pop()
if pos == j:
break
for npos in edges[pos]:
if used[npos]:
continue
used[npos] = True
bef[npos] = pos
stack.append(npos)
c = 0
queue = deque()
queue.append((j, 0))
pos = j
used = [False] * n
used[pos] = True
while pos != i:
pos = bef[pos]
c += 1
queue.append((pos, c))
used[pos] = True
cnts = [1] * (c + 1)
C = c
while queue:
pos, c = queue.popleft()
for npos in edges[pos]:
if used[npos]: continue
used[npos] = True
cnts[c] += 1
queue.append((npos, c))
ret = 0
tot = 0
times = 1
inv = pow(pow(2, C - 1, MOD), MOD - 2, MOD)
for i, c in enumerate(cnts[:-1]):
ret += c * times
ret %= MOD
times -= nCk(C - 1, i) * inv
times %= MOD
return ret
ans = 0
for i in range(n):
for j in range(i + 1, n):
ans += cnt(i, j)
ans %= MOD
ans *= pow(n, MOD - 2, MOD)
print(ans % MOD)
for _ in range(1):
main()
``` | output | 1 | 40,678 | 13 | 81,357 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 40,679 | 13 | 81,358 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
mod = 10**9 + 7
def power(a, b):
if b == 0: return 1
s = power(a, b >> 1)
s = s * s % mod
if b&1: return (s * a % mod)
return s
n = int(input())
d = [[10**9 for i in range(n)] for i in range(n)]
for i in range(1, n):
x, y = map(int, input().split())
x -= 1
y -= 1
d[x][y] = 1
d[y][x] = 1
for i in range(n): d[i][i] = 0
for k in range(n):
for i in range(n):
for j in range(n):
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
dp = [[0 for i in range(n)] for i in range(n)]
inv2 = power(2, mod - 2)
for i in range(n):
for j in range(n):
if j == 0:
continue
if i == 0:
dp[i][j] = 1
continue
dp[i][j] = (dp[i-1][j] + dp[i][j-1]) * inv2 % mod
ans = 0
for r in range(n):
for i in range(n):
for j in range(i):
x, y = d[r][i], d[r][j]
dist = int((x + y - d[i][j]) / 2)
x -= dist
y -= dist
ans += dp[x][y]
print(ans * power(n, mod - 2) % mod)
``` | output | 1 | 40,679 | 13 | 81,359 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 40,680 | 13 | 81,360 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
n=int(input())
N=n
mod=10**9+7
E=[[] for i in range(n)]
for i in range(n-1):
x,y=map(int,input().split())
x-=1
y-=1
E[x].append(y)
E[y].append(x)
INV2=pow(2,mod-2,mod)
INV2LIST=[1]
for i in range(500):
INV2LIST.append(INV2LIST[-1]*INV2%mod)
FACT=[1]
for i in range(1,2*10**5+1):
FACT.append(FACT[-1]*i%mod)
FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(2*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
from functools import lru_cache
@lru_cache(maxsize=None)
def calc(i,j):
if i<=0 or j<=0:
return 0
ANS=0
for k in range(j):
ANS=(ANS+(Combi(i+k,i)-Combi(i+k-1,i))*INV2LIST[i+k])%mod
return ANS
ANS=0
for i in range(N):
for j in range(i+1,N):
Q=[j]
USE=[0]*N
DIS=[-1]*N
DIS[j]=0
FR=[-1]*N
while Q:
x=Q.pop()
for to in E[x]:
if DIS[to]==-1:
DIS[to]=DIS[x]+1
FR[to]=x
Q.append(to)
now=i
while now!=j:
USE[now]=1
now=FR[now]
USE[i]=1
USE[j]=1
ko=DIS[i]-1
INV=pow(INV2,ko,mod)
now=i
kei=0
while now!=j:
Q=[now]
USED=[0]*N
kos=1
USED[now]=1
while Q:
x=Q.pop()
for to in E[x]:
if USED[to]==0 and USE[to]==0:
USED[to]=1
kos+=1
Q.append(to)
#print("!",now,kei,kos)
#print(ko,DIS[now],ko+1-DIS[now])
ANS+=kos*calc(DIS[now],ko+1-DIS[now])
ANS%=mod
now=FR[now]
#print("?",ANS)
Q=[j]
USED=[0]*N
kos=1
USED[j]=1
while Q:
x=Q.pop()
for to in E[x]:
if USED[to]==0 and USE[to]==0:
USED[to]=1
kos+=1
Q.append(to)
ANS+=kos
ANS%=mod
#print("kos",kos)
#print(ANS)
print(ANS*pow(n,mod-2,mod)%mod)
``` | output | 1 | 40,680 | 13 | 81,361 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 40,681 | 13 | 81,362 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
import sys
from sys import stdin
from collections import deque
def NC_Dij(lis,start):
ret = [float("inf")] * len(lis)
ret[start] = 0
q = deque([start])
plis = [i for i in range(len(lis))]
while len(q) > 0:
now = q.popleft()
for nex in lis[now]:
if ret[nex] > ret[now] + 1:
ret[nex] = ret[now] + 1
plis[nex] = now
q.append(nex)
return ret,plis
def merge(x,y):
if len(x) > len(y):
x,y = y,x
for i in x:
y.append(i)
x = y
return x,y
def inverse(x,mod):
return pow(x,mod-2,mod)
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):
if r == 0:
return 1
return fac[n] * inv[n-r] * inv[r] % mod
mod = 10**9+7
fac,inv = modfac(500,mod)
half = inverse(2,mod)
dp = [ [0] * 300 for i in range(300) ]
for l in range(300):
for r in range(300):
if l == 0:
dp[l][r] = 1
elif r == 0:
dp[l][r] = 0
else:
dp[l][r] = (dp[l-1][r] + dp[l][r-1]) * half % mod
tt = 1
for loop in range(tt):
n = int(stdin.readline())
xy = []
lis = [ [] for i in range(n) ]
for i in range(n-1):
x,y = map(int,stdin.readline().split())
x -= 1
y -= 1
lis[x].append(y)
lis[y].append(x)
ans = 0
for z in range(n):
dlis,plis = NC_Dij(lis,z)
#print (z,dlis,plis)
nans = 0
LCA = [[None] * n for i in range(n)]
chlis = [ [i] for i in range(n) ]
d_v = [(dlis[i],i) for i in range(n)]
d_v.sort()
d_v.reverse()
#print (d_v)
for d,v in d_v:
for nex in lis[v]:
if nex != plis[v]:
for mv in chlis[v]:
for yv in chlis[nex]:
LCA[mv][yv] = LCA[yv][mv] = v
chlis[v],chlis[nex] = merge(chlis[v],chlis[nex])
#print (z,v,chlis[v],plis[v])
#for ch in chlis[v]:
# able[v][ch] = able[ch][v] = False
# #print (z,v,ch)
# if ch < v:
# nans += 1
#if plis[v] != v:
# chlis[v],chlis[plis[v]] = merge(chlis[v],chlis[plis[v]])
#print (z,nans)
for r in range(n):
for l in range(r):
lcav = LCA[l][r]
ld,rd = dlis[l] - dlis[lcav] , dlis[r] - dlis[lcav]
if min(ld,rd) > 0:
#print (z,l,r,LCA[l][r],dp[ld][rd])
nans += dp[rd][ld] #modnCr(ld+rd-1,ld-1) * inverse( modnCr(ld+rd,ld) , mod )
elif dlis[r] < dlis[l]:
#print (z,l,r,LCA[l][r],file=sys.stderr)
nans += 1
nans %= mod
ans += nans
ans %= mod
print (ans * inverse(n,mod) % mod)
``` | output | 1 | 40,681 | 13 | 81,363 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 40,682 | 13 | 81,364 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
from sys import stdin, stdout
# 1 -> 2 -> 3 -> 4 -> 5 -> 6
# 2^4 = (2^3) + (2^3)
def dfs(cur, pre, d, dic, dep_a, jmp_a):
dep_a[cur] = d
jmp_a[cur][0] = pre
for i in range(1, 10):
jmp_a[cur][i] = jmp_a[jmp_a[cur][i-1]][i-1]
for next in dic[cur]:
if next == pre:
continue
dfs(next, cur, d+1, dic, dep_a, jmp_a)
def lca(a, b, dep_a, jmp_a):
da = dep_a[a]
db = dep_a[b]
if da > db:
return lca(b, a, dep_a, jmp_a)
df = db - da
for i in range(10):
if ((1 << i) & df) != 0:
b = jmp_a[b][i]
while a != b:
jmp = -1
for i in range(9, -1, -1):
if jmp_a[a][i] != jmp_a[b][i]:
jmp = i
break
if jmp != -1:
a = jmp_a[a][jmp]
b = jmp_a[b][jmp]
else:
a = jmp_a[a][0]
b = jmp_a[b][0]
return a
# left stacks before right stacks consumed possibility
# dp[i,j] = (dp[i-1,j] + dp[i,j-1]) / 2
def get_percentage(n):
per_a = [[0 for _ in range(n)] for _ in range(n)]
for j in range(1, n):
per_a[0][j] = 1
for i in range(1, n):
for j in range(1, n):
per_a[i][j] = (per_a[i-1][j] + per_a[i][j-1]) * bpow(2, MOD-2)
#per_a[i][j] = (float(per_a[i - 1][j]) + float(per_a[i][j - 1])) / 2
per_a[i][j] %= MOD
return per_a
def bpow(a, b):
if b == 0:
return 1
c = b // 2
r = bpow(a, c)
r *= r
r %= MOD
if b % 2 == 1:
r *= a
r %= MOD
return r
MOD = 1000000007
dic = {}
n = int(stdin.readline())
for _ in range(n-1):
x, y = map(int, stdin.readline().split())
if x not in dic:
dic[x] = []
if y not in dic:
dic[y] = []
dic[x].append(y)
dic[y].append(x)
per_a = get_percentage(n)
res = 0
for i in range(1, n+1):
dep_a = [0] * (n + 1)
jmp_a = [[j for _ in range(10)] for j in range(n+1)]
# cal dep_a and jmp_a
dfs(i, i, 0, dic, dep_a, jmp_a)
# cal possibility
for l in range(2, n+1):
for r in range(l-1, 0, -1):
node = lca(l, r, dep_a, jmp_a)
res += per_a[dep_a[l] - dep_a[node]][dep_a[r] - dep_a[node]]
res %= MOD
res *= bpow(n, MOD-2)
res %= MOD
stdout.write(str(res) + '\n')
``` | output | 1 | 40,682 | 13 | 81,365 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted 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
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 = 1000
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
dp = [[0 for L in range(201)] for R in range(201)]
for L in range(1,201):
dp[L][0] = 1
for R in range(1,201):
for L in range(1,201):
dp[L][R] = dp[L-1][R] + dp[L][R-1]
dp[L][R] *= inverse[2]
dp[L][R] %= mod
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
n = int(input())
edge = [[] for v in range(n)]
for _ in range(n-1):
u,v = mi()
edge[u-1].append(v-1)
edge[v-1].append(u-1)
def solve(root):
res = 0
parent = [-1 for v in range(n)]
depth = [0 for v in range(n)]
deq = deque([root])
topo = []
while deq:
v = deq.popleft()
topo.append(v)
for nv in edge[v]:
if nv!=parent[v]:
parent[nv] = v
depth[nv] = depth[v] + 1
deq.append(nv)
#print(topo)
size = [1 for v in range(n)]
for v in topo[::-1]:
for nv in edge[v]:
if nv==parent[v]:
continue
size[v] += size[nv]
upper_size = [0 for v in range(n)]
for v in topo:
if v==root:
for nv in edge[v]:
upper_size[nv] = n - size[nv]
else:
for nv in edge[v]:
if nv==parent[v]:
continue
upper_size[nv] = upper_size[v]
if v < root:
pos = v
d = 0
while parent[pos]!=-1:
L,R = d+1,depth[v]-d-1
tmp = (size[parent[pos]]-size[pos]) * dp[L][R] % mod
res += tmp
res %= mod
pos = parent[pos]
d += 1
return res
res = 0
for r in range(n):
res += solve(r)
res %= mod
#2.1
print(res*inverse[n] % mod)
``` | instruction | 0 | 40,683 | 13 | 81,366 |
Yes | output | 1 | 40,683 | 13 | 81,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
maxn = 300
mod = 10**9 + 7
fac = [0]*(maxn+1)
inv_fac = [0]*(maxn+1)
fac[0] = 1
for i in range(1,maxn+1):
fac[i] = fac[i-1] * i % mod
inv_fac[maxn] = pow(fac[maxn],mod-2,mod)
for i in range(maxn-1,-1,-1):
inv_fac[i] = inv_fac[i+1] * (i+1) % mod
def choose(n,k):
if k > n:
return 0
return fac[n] * inv_fac[k] * inv_fac[n-k] % mod
inv_p = [0]*(300)
inv_p[1] = inv_fac[2]
for i in range(2,300):
inv_p[i] = inv_p[1]*inv_p[i-1]%mod
n = int(input())
adj = [[] for i in range(n+1)]
for i in range(n-1):
a,b = map(int,input().split())
adj[a].append(b)
adj[b].append(a)
ans = 0
line_prob = [[0]*(n+1) for i in range(n+1)] # i from smaller j from larger
for j in range(1,n+1):
tot = 0
for i in range(n+1-j):
tot += choose(j-1+i,i)*inv_p[j-1+i+1]%mod
line_prob[i+1][j] = tot
'''
for i in range(1,n+1):
for j in range(1,n+1):
line_prob[i][j] = choose(j+i-1,i-1)*inv_fac[2]%mod
print(line_prob[i][j],i,j)
'''
for root in range(1,n+1):
size_of_sub = [0]*(n+1)
# compute size of sub
s = [root]
vis = [0]*(n+1)
par = [0]*(n+1)
while s:
c = s[-1]
if not vis[c]:
vis[c] = 1
for ne in adj[c]:
if not vis[ne]:
par[ne] = c
s.append(ne)
else:
size_of_sub[c] += 1
size_of_sub[par[c]] += size_of_sub[c]
s.pop()
# compute answer
s = [root]
vis = [0] * (n + 1)
path = [] # num of nodes at each depth on the path where ancestor
# = node at this depth but no nodes deeper on path
while s:
c = s[-1]
if not vis[c]:
vis[c] = 1
if len(path):
path[-1] -= size_of_sub[c]
path.append(size_of_sub[c])
# compute ans
if c > root:
#print(root,c,path)
ln = len(path)-1
for depth in range(1,ln):
#print(depth,ln-depth,line_prob[depth][ln-depth])
ans = (ans + path[depth]*line_prob[depth][ln-depth]%mod)
ans = (ans + size_of_sub[c]) % mod
for ne in adj[c]:
if not vis[ne]:
s.append(ne)
else:
if len(path) >= 2:
path[-2] += path[-1]
path.pop()
s.pop()
print(ans*pow(n,mod-2,mod)%mod)
``` | instruction | 0 | 40,684 | 13 | 81,368 |
Yes | output | 1 | 40,684 | 13 | 81,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
mod = 10 ** 9 + 7
n = int(input())
dist = [[float("inf")] * n for _ in range(n)]
for _ in range(n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
dist[a][b] = dist[b][a] = 1
for i in range(n): dist[i][i] = 0
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
dp = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(1, n + 1): dp[i][0] = 1
for i in range(1, n + 1):
for j in range(1, n + 1):
dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) * pow(2, mod - 2, mod) % mod
ans = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(n):
x, y = dist[i][k], dist[j][k]
d = (x + y - dist[i][j]) // 2
x -= d
y -= d
ans += dp[x][y]
ans %= mod
print(ans * pow(n, mod - 2, mod) % mod)
``` | instruction | 0 | 40,685 | 13 | 81,370 |
Yes | output | 1 | 40,685 | 13 | 81,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
n=int(input())
N=n
mod=10**9+7
E=[[] for i in range(n)]
for i in range(n-1):
x,y=map(int,input().split())
x-=1
y-=1
E[x].append(y)
E[y].append(x)
ROOT=0
QUE=[ROOT]
Parent=[-1]*(N+1)
Parent[ROOT]=N
TOP_SORT=[]
while QUE:
x=QUE.pop()
TOP_SORT.append(x)
for to in E[x]:
if Parent[to]==-1:
Parent[to]=x
QUE.append(to)
Children=[1]*(N+1)
for x in TOP_SORT[::-1]:
Children[Parent[x]]+=Children[x]
USE=[0]*N
Group=[i for i in range(N)]
for x in TOP_SORT: # HLεθ§£γ«γγγ°γ«γΌγεγ
USE[x]=1
MAX_children=0
select_node=0
for to in E[x]:
if USE[to]==0 and Children[to]>MAX_children:
select_node=to
MAX_children=Children[to]
for to in E[x]:
if USE[to]==0 and to==select_node:
Group[to]=Group[x]
def LCA(a,b): # HLεθ§£γε©η¨γγ¦LCAγζ±γγ
while Group[a]!=Group[b]:
if Children[Parent[Group[a]]]<Children[Parent[Group[b]]]:
a=Parent[Group[a]]
else:
b=Parent[Group[b]]
if Children[a]>Children[b]:
return a
else:
return b
ANS=0
INV2=pow(2,mod-2,mod)
for i in range(N):
for j in range(i+1,N):
Q=[j]
USE=[0]*N
DIS=[-1]*N
DIS[j]=0
FR=[-1]*N
while Q:
x=Q.pop()
for to in E[x]:
if DIS[to]==-1:
DIS[to]=DIS[x]+1
FR[to]=x
Q.append(to)
now=i
while now!=j:
USE[now]=1
now=FR[now]
USE[i]=1
USE[j]=1
ko=DIS[i]-1
INV=pow(INV2,ko,mod)
now=i
kei=0
while now!=j:
Q=[now]
USED=[0]*N
kos=1
USED[now]=1
while Q:
x=Q.pop()
for to in E[x]:
if USED[to]==0 and USE[to]==0:
USED[to]=1
kos+=1
Q.append(to)
#print("!",now,kei,kos)
ANS+=kei*kos*INV
ANS%=mod
kei=kei*2+1
now=FR[now]
#print("?",ANS)
Q=[j]
USED=[0]*N
kos=1
USED[j]=1
while Q:
x=Q.pop()
for to in E[x]:
if USED[to]==0 and USE[to]==0:
USED[to]=1
kos+=1
Q.append(to)
ANS+=kos
ANS%=mod
#print("kos",kos)
#print(ANS)
print(ANS*pow(n,mod-2,mod)%mod)
``` | instruction | 0 | 40,686 | 13 | 81,372 |
No | output | 1 | 40,686 | 13 | 81,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
# region fastio # from https://codeforces.com/contest/1333/submission/75948789
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.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(io.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()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#endregion
class Combination:
def __init__(self, n_max, mod=10**9+7):
# O(n_max + log(mod))
self.mod = mod
f = 1
self.fac = fac = [f]
for i in range(1, n_max+1):
f = f * i % mod
fac.append(f)
f = pow(f, mod-2, mod)
self.facinv = facinv = [f]
for i in range(n_max, 0, -1):
f = f * i % mod
facinv.append(f)
facinv.reverse()
def __call__(self, n, r):
return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod
def C(self, n, r):
if not 0 <= r <= n: return 0
return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod
class HLD:
def __init__(self, E, root=1):
self.E = E
self.root = root
self.N = N = len(E)
self.Parent = [-1]*N
self.Size = [-1]*N
self.dfs1()
self.Mapping = [-1]*N
self.Head = list(range(N))
self.Depth = [0]*N
self.dfs2()
def dfs1(self):
E = self.E
Parent, Size = self.Parent, self.Size
Path = [self.root]
Idx_edge = [0]
while Path:
v = Path[-1]
idx_edge = Idx_edge[-1]
Ev = E[v]
if idx_edge != len(Ev):
u = Ev[idx_edge]
Idx_edge[-1] += 1
E[u].remove(v)
Parent[u] = v
Path.append(u)
Idx_edge.append(0)
else:
if len(Ev) >= 2:
ma = -1
argmax = None
for i, u in enumerate(Ev):
if Size[u] > ma:
ma = Size[u]
argmax = i
u0, um = Ev[0], Ev[argmax]
Size[u0], Size[um] = Size[um], Size[u0]
Ev[0], Ev[argmax] = Ev[argmax], Ev[0]
Size[v] = sum(Size[u] for u in Ev)+1
Path.pop()
Idx_edge.pop()
def dfs2(self):
E = self.E
Mapping = self.Mapping
Head = self.Head
Depth = self.Depth
k = 0
St = [self.root]
while St:
v = St.pop()
Mapping[v] = k
k += 1
Ev = E[v]
if Ev:
Head[Ev[0]] = Head[v]
St += Ev[::-1]
for u in Ev:
Depth[u] = Depth[v] + 1
def lca(self, v, u):
# O(logN)
Parent = self.Parent
Mapping = self.Mapping
Head = self.Head
while True:
if Mapping[v] > Mapping[u]:
v, u = u, v
if Head[v] == Head[u]:
return v
u = Parent[Head[u]]
N = int(input())
G = [[] for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
G[a].append(b)
G[b].append(a)
hld = HLD(G)
ans = 0
comb = Combination(202)
mod = 10**9 + 7
inv2 = pow(2, mod-2, mod)
Table = [[0] * 202 for _ in range(202)]
for d in range(202):
for x in range(1, d):
y = d - x
s = 0
p = 1
for l in range(y):
s += p * comb(x-1+l, x-1) % mod
p = p * inv2 % mod
s %= mod
Table[d][x] = pow(inv2, x, mod) * s % mod
cnt = 0
for a in range(1, N):
for b in range(a+1, N+1):
# a > b
lca = hld.lca(a, b)
da = hld.Depth[a] - hld.Depth[lca]
db = hld.Depth[b] - hld.Depth[lca]
distance = da + db
tans = ans
ignore = hld.Size[a]
v = a
x = 0
while v != lca:
v = hld.Parent[v]
x += 1
if v == lca:
break
siz = hld.Size[v]
ans += (siz - ignore) * Table[distance][x] % mod
assert x != distance and x != 0, (x, distance)
ignore = siz
ignore_a = ignore
ignore = hld.Size[b]
v = b
x = distance
while v != lca:
v = hld.Parent[v]
x -= 1
if v == lca:
break
siz = hld.Size[v]
ans += (siz - ignore) * Table[distance][x] % mod
assert x != distance and x != 0, (x, distance)
ignore = siz
ignore_b = ignore
if a != lca and b != lca:
ans += (N - ignore_a - ignore_b) * Table[distance][da] % mod
ans += hld.Size[a]
elif a == lca:
ans += N - ignore_b
else:
ans += hld.Size[a]
#print(a, b, (ans - tans) % mod)
ans = ans * pow(N, mod-2, mod) % mod
ans = (N * (N-1) // 2 - ans) % mod
print(ans)
``` | instruction | 0 | 40,687 | 13 | 81,374 |
No | output | 1 | 40,687 | 13 | 81,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
# region fastio # from https://codeforces.com/contest/1333/submission/75948789
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.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(io.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()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#endregion
class Combination:
def __init__(self, n_max, mod=10**9+7):
# O(n_max + log(mod))
self.mod = mod
f = 1
self.fac = fac = [f]
for i in range(1, n_max+1):
f = f * i % mod
fac.append(f)
f = pow(f, mod-2, mod)
self.facinv = facinv = [f]
for i in range(n_max, 0, -1):
f = f * i % mod
facinv.append(f)
facinv.reverse()
def __call__(self, n, r):
return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod
def C(self, n, r):
if not 0 <= r <= n: return 0
return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod
class HLD:
def __init__(self, E, root=1):
self.E = E
self.root = root
self.N = N = len(E)
self.Parent = [-1]*N
self.Size = [-1]*N
self.dfs1()
self.Mapping = [-1]*N
self.Head = list(range(N))
self.Depth = [0]*N
self.dfs2()
def dfs1(self):
E = self.E
Parent, Size = self.Parent, self.Size
Path = [self.root]
Idx_edge = [0]
while Path:
v = Path[-1]
idx_edge = Idx_edge[-1]
Ev = E[v]
if idx_edge != len(Ev):
u = Ev[idx_edge]
Idx_edge[-1] += 1
E[u].remove(v)
Parent[u] = v
Path.append(u)
Idx_edge.append(0)
else:
if len(Ev) >= 2:
ma = -1
argmax = None
for i, u in enumerate(Ev):
if Size[u] > ma:
ma = Size[u]
argmax = i
u0, um = Ev[0], Ev[argmax]
Size[u0], Size[um] = Size[um], Size[u0]
Ev[0], Ev[argmax] = Ev[argmax], Ev[0]
Size[v] = sum(Size[u] for u in Ev)+1
Path.pop()
Idx_edge.pop()
def dfs2(self):
E = self.E
Mapping = self.Mapping
Head = self.Head
Depth = self.Depth
k = 0
St = [self.root]
while St:
v = St.pop()
Mapping[v] = k
k += 1
Ev = E[v]
if Ev:
Head[Ev[0]] = Head[v]
St += Ev[::-1]
for u in Ev:
Depth[u] = Depth[v] + 1
def lca(self, v, u):
# O(logN)
Parent = self.Parent
Mapping = self.Mapping
Head = self.Head
while True:
if Mapping[v] > Mapping[u]:
v, u = u, v
if Head[v] == Head[u]:
return v
u = Parent[Head[u]]
N = int(input())
G = [[] for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
G[a].append(b)
G[b].append(a)
hld = HLD(G)
ans = 0
comb = Combination(202)
mod = 10**9 + 7
inv2 = pow(2, mod-2, mod)
Table = [[0] * 202 for _ in range(202)]
for d in range(202):
for x in range(1, d):
y = d - x
s = 0
p = 1
for l in range(y):
s += p * comb(x-1+l, x-1) % mod
p = p * inv2 % mod
s %= mod
Table[d][x] = pow(inv2, x, mod) * s % mod
for b in range(1, N):
for a in range(b+1, N+1):
# a > b
lca = hld.lca(a, b)
da = hld.Depth[a] - hld.Depth[lca]
db = hld.Depth[b] - hld.Depth[lca]
distance = da + db
tans = ans
ignore = hld.Size[a]
v = a
x = 0
while v != lca:
v = hld.Parent[v]
x += 1
if v == lca:
break
siz = hld.Size[v]
ans += (siz - ignore) * Table[distance][x] % mod
assert x != distance and x != 0, (x, distance)
ignore = siz
ignore_a = ignore
ignore = hld.Size[b]
v = b
x = distance
while v != lca:
v = hld.Parent[v]
x -= 1
if v == lca:
break
siz = hld.Size[v]
ans += (siz - ignore) * Table[distance][x] % mod
assert x != distance and x != 0, (x, distance)
ignore = siz
ignore_b = ignore
if a != lca and b != lca:
ans += (N - ignore_a - ignore_b) * Table[distance][da] % mod
ans += hld.Size[a]
elif a == lca:
ans += N - ignore_b
else:
ans += hld.Size[a]
#print(a, b, (ans - tans) % mod)
ans = ans * pow(N, mod-2, mod) % mod
print(ans)
``` | instruction | 0 | 40,688 | 13 | 81,376 |
No | output | 1 | 40,688 | 13 | 81,377 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
n=int(input())
N=n
mod=10**9+7
E=[[] for i in range(n)]
for i in range(n-1):
x,y=map(int,input().split())
x-=1
y-=1
E[x].append(y)
E[y].append(x)
ROOT=0
QUE=[ROOT]
Parent=[-1]*(N+1)
Parent[ROOT]=N
TOP_SORT=[]
while QUE:
x=QUE.pop()
TOP_SORT.append(x)
for to in E[x]:
if Parent[to]==-1:
Parent[to]=x
QUE.append(to)
Children=[1]*(N+1)
for x in TOP_SORT[::-1]:
Children[Parent[x]]+=Children[x]
USE=[0]*N
Group=[i for i in range(N)]
for x in TOP_SORT: # HLεθ§£γ«γγγ°γ«γΌγεγ
USE[x]=1
MAX_children=0
select_node=0
for to in E[x]:
if USE[to]==0 and Children[to]>MAX_children:
select_node=to
MAX_children=Children[to]
for to in E[x]:
if USE[to]==0 and to==select_node:
Group[to]=Group[x]
def LCA(a,b): # HLεθ§£γε©η¨γγ¦LCAγζ±γγ
while Group[a]!=Group[b]:
if Children[Parent[Group[a]]]<Children[Parent[Group[b]]]:
a=Parent[Group[a]]
else:
b=Parent[Group[b]]
if Children[a]>Children[b]:
return a
else:
return b
ANS=0
INV2=pow(2,mod-2,mod)
for i in range(N):
for j in range(i+1,N):
Q=[j]
USE=[0]*N
DIS=[-1]*N
DIS[j]=0
FR=[-1]*N
while Q:
x=Q.pop()
for to in E[x]:
if DIS[to]==-1:
DIS[to]=DIS[x]+1
FR[to]=x
Q.append(to)
now=i
while now!=j:
USE[now]=1
now=FR[now]
ko=DIS[i]-1
INV=pow(INV2,ko,mod)
now=i
kei=0
while now!=j:
Q=[now]
USED=[0]*N
kos=1
USED[now]=1
while Q:
x=Q.pop()
for to in E[x]:
if USED[to]==0 and USE[to]==0:
USED[to]=1
kos+=1
Q.append(to)
#print("!",now,kei,kos)
ANS+=kei*kos*INV
ANS%=mod
kei=kei*2+1
now=FR[now]
#print("?",ANS)
Q=[j]
USED=[0]*N
kos=1
USED[j]=1
while Q:
x=Q.pop()
for to in E[x]:
if USED[to]==0 and USE[to]==0:
USED[to]=1
kos+=1
Q.append(to)
ANS+=kos*INV
ANS%=mod
#print(ANS)
print(ANS*pow(n,mod-2,mod)%mod)
``` | instruction | 0 | 40,689 | 13 | 81,378 |
No | output | 1 | 40,689 | 13 | 81,379 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO | instruction | 0 | 40,959 | 13 | 81,918 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n, a, b = map(int, input().split())
if min(a, b) > 1 or 1 < n < 4 and max(a, b) == 1:
print('NO')
exit()
print('YES')
f = int(a == 1)
g = [a, b][f]
r = [[f] * n for i in range(n)]
for i in range(n):
r[i][i] = 0
for i in range(n - g):
r[i][i + 1] ^= 1
r[i + 1][i] ^= 1
for x in r:
print(*x, sep='')
johnny=0
``` | output | 1 | 40,959 | 13 | 81,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO | instruction | 0 | 40,960 | 13 | 81,920 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
str=input().split()
n,a,b=[int(str[x]) for x in range(0,3)]
inv=0
if (b!=1):
t=a
a=b
b=t
inv=1
if (b!=1 or n>1 and n<4 and a==1 and b==1):
print ('NO')
exit()
print ('YES')
f=[[0]*n for i in range(0,n)]
#print (f)
for i in range(0,n-a):
f[i][i+1]=f[i+1][i]=1
#f[0][1]=1
#print (f[0][1],f[1][1],f[2][1])
for i in range(0,n):
cur=[chr(((f[i][j]^inv)&(i!=j))+48) for j in range(0,n)]
print (''.join(cur))
``` | output | 1 | 40,960 | 13 | 81,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO | instruction | 0 | 40,961 | 13 | 81,922 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
def generate_matrix(n):
result = [[0 for c in range(n)] for y in range(n)]
return result
def generate_m_component_matrix(n, comp):
result = generate_matrix(n)
for i in range(0, n - comp + 1):
for j in range(0, n - comp + 1):
result[i][j] = 0 if i == j else 1
return result
def invert_matrix(n, result):
for i in range(0, n):
for j in range(0, n):
result[i][j] = 1 if result[i][j] == 0 and i != j else 0
return result
def generate_one_component_graph(n):
result = generate_matrix(n)
for i in range(1, n):
result[i][i - 1] = result[i - 1][i] = 1
return result
def print_matrix(n, matrix):
for i in range(0, n):
s = ''.join(str(e) for e in matrix[i])
print(s)
n, a, b = map(int, input().split())
if a > 1 and b > 1:
print('NO')
elif a > 1:
# generate matrix
matrix = generate_m_component_matrix(n, a)
print('YES')
print_matrix(n, matrix)
elif b > 1:
# generate matrix and invert it
matrix = generate_m_component_matrix(n, b)
matrix = invert_matrix(n, matrix)
print('YES')
print_matrix(n, matrix)
else:
if n > 3 or n == 1:
# generate matrix with broken loop
matrix = generate_one_component_graph(n)
print('YES')
print_matrix(n, matrix)
else:
print('NO')
``` | output | 1 | 40,961 | 13 | 81,923 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO | instruction | 0 | 40,962 | 13 | 81,924 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
# Educational Codeforces Round 45 (Rated for Div. 2)
import collections
from functools import cmp_to_key
#key=cmp_to_key(lambda x,y: 1 if x not in y else -1 )
import sys
def getIntList():
return list(map(int, input().split()))
n,a,b = getIntList()
a0 = a
b0 = b
if a0>b0:
a0,b0 = b,a
if n==2 and (a0,b0) == (1,1):
print('NO')
sys.exit()
if n==3 and (a0,b0) == (1,1):
print('NO')
sys.exit()
if a>1 and b>1:
print('NO')
sys.exit()
mat = [['0' for y in range(n)]for x in range(n)]
mat1 = [['1' for y in range(n)]for x in range(n)]
if b==1:
for x in range(n-a):
mat[x][x+1] = '1'
mat[x+1][x] = '1'
else:
mat = mat1
for x in range(n):
mat[x][x] = '0'
for x in range(n-b):
mat[x][x+1] = '0'
mat[x+1][x] = '0'
print('YES')
for x in range(n):
print(''.join(mat[x]))
``` | output | 1 | 40,962 | 13 | 81,925 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO | instruction | 0 | 40,963 | 13 | 81,926 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n, a, b = map(int, input().split())
if min(a, b) > 1 or 1 < n < 4 and max(a, b) == 1:
print('NO')
exit()
print('YES')
f = int(a == 1)
g = [a, b][f]
r = [[f] * n for i in range(n)]
for i in range(n):
r[i][i] = 0
for i in range(n - g):
r[i][i + 1] ^= 1
r[i + 1][i] ^= 1
print('\n'.join(map(lambda x: ''.join(map(str, x)), r)))
``` | output | 1 | 40,963 | 13 | 81,927 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO | instruction | 0 | 40,964 | 13 | 81,928 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
def generate_matrix(n):
result = [[0 for x in range(n)] for y in range(n)]
return result
def generate_m_component_matrix(n, comp):
result = generate_matrix(n)
for i in range(0, n - comp + 1):
for j in range(0, n - comp + 1):
result[i][j] = 0 if i == j else 1
return result
def invert_matrix(n, result):
for i in range(0, n):
for j in range(0, n):
result[i][j] = 1 if result[i][j] == 0 and i != j else 0
return result
def generate_one_component_graph(n):
result = generate_matrix(n)
for i in range(1, n):
result[i][i - 1] = result[i - 1][i] = 1
return result
def print_matrix(n, matrix):
for i in range(0, n):
s = ''.join(str(e) for e in matrix[i])
print(s)
n, a, b = map(int, input().split())
if a > 1 and b > 1:
print('NO')
elif a > 1:
# generate matrix
matrix = generate_m_component_matrix(n, a)
print('YES')
print_matrix(n, matrix)
elif b > 1:
# generate matrix and invert it
matrix = generate_m_component_matrix(n, b)
matrix = invert_matrix(n, matrix)
print('YES')
print_matrix(n, matrix)
else:
if n > 3 or n == 1:
# generate matrix with broken loop
matrix = generate_one_component_graph(n)
print('YES')
print_matrix(n, matrix)
else:
print('NO')
``` | output | 1 | 40,964 | 13 | 81,929 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO | instruction | 0 | 40,965 | 13 | 81,930 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
def ii():
return int(input())
def mi():
return map(int, input().split())
def li():
return list(mi())
n, a, b = mi()
c = max(a, b)
if a != 1 and b != 1:
print('NO')
elif n == 2 and c == 1:
print('NO')
elif n == 3 and c == 1:
print('NO')
else:
if a == 1:
g = [[1] * n for i in range(n)]
for i in range(n):
g[i][i] = 0
for i in range(c - 1, n - 1):
g[i][i + 1] = g[i + 1][i] = 0
else:
g = [[0] * n for i in range(n)]
for i in range(c - 1, n - 1):
g[i][i + 1] = g[i + 1][i] = 1
print('YES')
for r in g:
print(''.join(str(x) for x in r))
``` | output | 1 | 40,965 | 13 | 81,931 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO | instruction | 0 | 40,966 | 13 | 81,932 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
def read():
return int(input())
def readlist():
return list(map(int, input().split()))
def readmap():
return map(int, input().split())
N, A, B = readmap()
if N == 1:
print("YES")
print(0)
elif N == 2:
if A == 1 and B == 2:
print("YES")
print("01")
print("10")
elif A == 2 and B == 1:
print("YES")
print("00")
print("00")
else:
print("NO")
elif N == 3:
if A == 1 and B == 2:
print("YES")
print("011")
print("100")
print("100")
elif A == 2 and B == 1:
print("YES")
print("001")
print("000")
print("100")
elif A == 1 and B == 3:
print("YES")
print("011")
print("101")
print("110")
elif A == 3 and B == 1:
print("YES")
print("000")
print("000")
print("000")
else:
print("NO")
else:
if A != 1 and B != 1:
print("NO")
else:
print("YES")
if B == 1 and A != 1:
mat = []
for i in range(N):
vec = []
if i == 0:
for j in range(N):
if j >= A:
vec.append(1)
else:
vec.append(0)
mat.append(vec)
else:
vec = [0] * N
if i >= A:
vec[0] = 1
mat.append(vec)
for n in range(N):
print("".join(list(map(str, mat[n]))))
elif A == 1 and B != 1:
mat = []
for i in range(N):
vec = []
if i == 0:
for j in range(N):
if j >= B:
vec.append(0)
else:
vec.append(1)
vec[i] = 0
mat.append(vec)
else:
vec = [1] * N
if i >= B:
vec[0] = 0
vec[i] = 0
mat.append(vec)
for n in range(N):
print("".join(list(map(str, mat[n]))))
else: # A == 1 and B == 1
mat = []
for i in range(N):
vec = []
if i == 0:
for j in range(N):
if j >= 2:
vec.append(1)
else:
vec.append(0)
mat.append(vec)
else:
vec = [0] * N
if i >= 2:
vec[0] = 1
mat.append(vec)
mat[1][2] = 1
mat[2][1] = 1
for n in range(N):
print("".join(list(map(str, mat[n]))))
``` | output | 1 | 40,966 | 13 | 81,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO
Submitted Solution:
```
n, a, b = map(int, input().split())
if (n == 3 or n == 2) and (a == 1 and b == 1):
print("NO")
exit(0)
g = [[0 for i in range(n)] for j in range(n)]
if a > 1 and b == 1:
for i in range(n - a - 1, -1, -1):
g[i][i + 1] = g[i + 1][i] = 1
elif b > 1 and a == 1:
a, b = b, a
for i in range(n - a - 1, -1, -1):
g[i][i + 1] = g[i + 1][i] = 1
for i in range(n):
for j in range(n):
if g[i][j] == 0:
g[i][j] = 1
elif g[i][j] == 1:
g[i][j] = 0
for i in range(n):
g[i][i] = 0
elif a == 1 and b == 1:
for i in range(n - 1):
g[i][i + 1] = g[i + 1][i] = 1
elif a > 1 and b > 1:
print("NO")
exit(0)
print("YES")
for i in range(n):
for j in range(n):
print(g[i][j], end='')
print()
``` | instruction | 0 | 40,967 | 13 | 81,934 |
Yes | output | 1 | 40,967 | 13 | 81,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO
Submitted Solution:
```
n, a, b = map(int, input().strip().split())
if min(a, b) > 1:
print('NO')
exit(0)
M = [[0] * n for _ in range(n)]
if a == 1 and b == 1:
if n == 1:
print('YES')
print('0')
exit(0)
if n == 2 or n == 3:
print('NO')
exit(0)
for i in range(1, n):
M[i - 1][i] = 1
M[i][i - 1] = 1
else:
# assume b == 1
s = n - max(a, b) + 1
for i in range(s):
for j in range(s):
if i != j:
M[i][j] = 1
if a == 1:
for i in range(n):
for j in range(n):
if i != j:
M[i][j] = 1 - M[i][j]
print('YES')
for i in range(n):
print(''.join(map(str, M[i])))
``` | instruction | 0 | 40,968 | 13 | 81,936 |
Yes | output | 1 | 40,968 | 13 | 81,937 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO
Submitted Solution:
```
n,a,b=map(int,input().split())
if a>n:
print('NO')
exit()
if b>n:
print("NO")
exit()
if a==1 and b==1:
if n==2 or n==3:
print('NO')
exit()
if n==1 and a>1 or n==1 and b>1:
print('NO')
exit()
if min(a,b)>1:
print('NO')
exit()
def check(mat):
vis=[0]*n
cnt=0
for i in range(n):
if vis[i]==0:
q=[i]
cnt+=1
vis[i]=1
while q:
t=q.pop(0)
for j in range(n):
if mat[t][j]==1 and vis[j]==0:
vis[j]=1
q.append(j)
return cnt
mat=[[0 for i in range(n)] for j in range(n)]
m=max(a,b)
j=1
for i in range(n):
if j<n:
mat[i][j]=1
mat[j][i]=1
j+=1
for i in range(m-1):
curr=n-i-1
for j in range(n):
if mat[curr][j]==1:
mat[curr][j]=0
mat[j][curr]=0
if b==1:
print('YES')
for i in range(n):
print(*mat[i],sep='')
else:
print('YES')
for i in range(n):
for j in range(n):
mat[i][j]=1-mat[i][j]
for i in range(n):
mat[i][i]=0
for i in range(n):
print(*mat[i],sep='')
``` | instruction | 0 | 40,969 | 13 | 81,938 |
Yes | output | 1 | 40,969 | 13 | 81,939 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO
Submitted Solution:
```
import sys
from array import array
n, a, b = map(int, input().split())
if a != 1 and b != 1 or 2 <= n <= 3 and a == 1 and b == 1:
print('NO')
exit()
if a == 1:
matrix = [[1]*n for _ in range(n)]
for i in range(n):
matrix[i][i] = 0
x = n
for i in range(n):
if x == b:
break
x -= 1
matrix[i][i+1] = matrix[i+1][i] = 0
else:
matrix = [[0]*n for _ in range(n)]
x = n
for i in range(n):
if x == a:
break
x -= 1
matrix[i][i+1] = matrix[i+1][i] = 1
ans = 'YES\n' + '\n'.join(''.join(map(str, row)) for row in matrix)
sys.stdout.buffer.write(ans.encode('utf-8'))
``` | instruction | 0 | 40,970 | 13 | 81,940 |
Yes | output | 1 | 40,970 | 13 | 81,941 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO
Submitted Solution:
```
n,a,b = map(int, input().strip().split())
if (a > 1 and b > 1) or a > n or b > n:
print ("NO")
else:
c = 0
print ("YES")
if b > 1:
c = 1
k = n - max(a,b)
for i in range (n):
for j in range (n):
if i == 0 and j <= k and j != 0:
print ((1+c)%2, end = " " )
elif 0 < i <= k and j == 0:
print ((1 + c)%2,end = " ")
elif i == j:
print (0,end = " ")
else: print (c,end = " ")
print()
``` | instruction | 0 | 40,971 | 13 | 81,942 |
No | output | 1 | 40,971 | 13 | 81,943 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO
Submitted Solution:
```
def main():
n, a, b = map(int, input().split())
if min(a, b) > 1 or a + b == 2 and 1 < n < 4:
print('NO')
return
if a == 1 < b:
l = [['1'] * n for _ in range(n)]
for i in range(n):
l[i][i] = '0'
for i in range(n - b):
l[i][i + 1] = l[i + 1][i] = '0'
else:
l = [['0'] * n for _ in range(n)]
for i in range(n - b):
l[i][i + 1] = l[i + 1][i] = '1'
print('YES')
print('\n'.join(map(''.join, l)))
if __name__ == '__main__':
main()
``` | instruction | 0 | 40,972 | 13 | 81,944 |
No | output | 1 | 40,972 | 13 | 81,945 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO
Submitted Solution:
```
from array import array
from sys import stdin
import bisect
from bisect import *
import itertools
from itertools import *
def scan_gen():
for line in stdin: yield from iter(line.split())
scan = scan_gen()
def nint(): return int(next(scan))
def nintk(k): return tuple(nint() for _ in range(k))
def nfloat(): return float(next(scan))
def intar_init(size): return array('i',[0]) *size
def intar(size=None):
if size == None: size = nint()
arr = intar_init(size)
for x in range(size): arr[x]=nint()
return arr
def printM(M,rev):
print("YES")
if rev:
for i,j in product(range(len(M)),range(len(M))):
if i!=j: M[i][j]=1-M[i][j]
for s in M:
print("".join(str(x) for x in s))
def solve1(n,a,b):
if a < b:
a,b=b,a
rev=True
else: rev = False
if a== 1:
print("NO")
return
M = [[0]*n for _ in range(n)]
connect = n -a
for p in range(1,connect+1):
M[0][p]=1
M[p][0]=1
printM(M,rev)
def solve0(n,a,b):
if a < b:
a,b=b,a
rev=True
else: rev = False
if a != n:
print("NO")
return
M = [[0]*n for _ in range(n)]
connect = n -a
for p in range(n):
for q in range(p+1,n):
M[q][p]=1
M[p][q]=1
printM(M,rev)
def solve():
n,a,b = nintk(3)
if min(a,b) == 0:
solve0(n,a,b)
elif min(a,b) ==1:
solve1(n,a,b)
else:
print("NO")
solve()
``` | instruction | 0 | 40,973 | 13 | 81,946 |
No | output | 1 | 40,973 | 13 | 81,947 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.
In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.
The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.
A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.
The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.
Input
In a single line, three numbers are given n, a, b (1 β€ n β€ 1000, 1 β€ a, b β€ n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
Output
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).
Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.
If there are several matrices that satisfy the conditions β output any of them.
Examples
Input
3 1 2
Output
YES
001
001
110
Input
3 3 3
Output
NO
Submitted Solution:
```
import sys
n, a, b = map(int, input().split())
if n == 1:
if a == b == 1:
print('YES\n0')
else:
print('NO')
sys.exit(0)
if n == 2:
if set([a, b]) == set([1, 2]):
print('YES\n01\n10')
else:
print('NO')
sys.exit(0)
if n == 3:
if set([a, b]) == set([1, 3]):
print('YES\n011\n101\n110')
elif set([a, b]) == set([1, 2]):
print('YES\n001\n001\n110')
else:
print('NO')
sys.exit(0)
if a != 1 and b != 1:
print('NO')
sys.exit(0)
if a > n or b > n:
print('NO')
sys.exit(0)
##################
switched = False
if b != 1:
a, b = b, a
switched = True
# a = 1
print('YES')
matrix = [['0' for _ in range(n)] for _ in range(n)]
comp = n
i = 0
while comp > a:
matrix[i][i+1] = '1'
matrix[i+1][i] = '1'
i += 1
comp -= 1
if switched:
for i in range(n):
for j in range(n):
if i != j:
matrix[i][j] = '1' if matrix[i][j] == '0' else '0'
for row in matrix:
print(''.join(row))
``` | instruction | 0 | 40,974 | 13 | 81,948 |
No | output | 1 | 40,974 | 13 | 81,949 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n vertices and m edges.
The weight of the i-th vertex is a_i.
The weight of the i-th edge is w_i.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
The weight of a subgraph is the sum of the weights of its edges, minus the sum of the weights of its vertices. You need to find the maximum weight of subgraph of given graph. The given graph does not contain loops and multiple edges.
Input
The first line contains two numbers n and m (1 β€ n β€ 10^3, 0 β€ m β€ 10^3) - the number of vertices and edges in the graph, respectively.
The next line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) - the weights of the vertices of the graph.
The following m lines contain edges: the i-e edge is defined by a triple of integers v_i, u_i, w_i (1 β€ v_i, u_i β€ n, 1 β€ w_i β€ 10^9, v_i β u_i). This triple means that between the vertices v_i and u_i there is an edge of weight w_i. It is guaranteed that the graph does not contain loops and multiple edges.
Output
Print one integer β the maximum weight of the subgraph of the given graph.
Examples
Input
4 5
1 5 2 2
1 3 4
1 4 4
3 4 5
3 2 2
4 2 2
Output
8
Input
3 3
9 7 8
1 2 1
2 3 2
1 3 3
Output
0
Note
In the first test example, the optimal subgraph consists of the vertices {1, 3, 4} and has weight 4 + 4 + 5 - (1 + 2 + 2) = 8. In the second test case, the optimal subgraph is empty. | instruction | 0 | 41,245 | 13 | 82,490 |
Tags: flows, graphs
Correct Solution:
```
class edge(object):
def __init__(self,ne,to,fl):
self.ne=ne
self.to=to
self.fl=fl
def add(x,y,z):
global tot
tot+=1
e.append(edge(he[x],y,z))
he[x]=tot
def addedge(x,y,z):
add(x,y,z)
add(y,x,0)
def bfs():
global deep
deep=[0 for i in range(T+1)]
q=[]
q.append(S)
deep[S]=1
lp=0
while (len(q)>lp):
x=q[lp]
lp+=1
i=he[x]
while (i):
y=e[i].to
if ((deep[y]==0)and(e[i].fl!=0)):
deep[y]=deep[x]+1
q.append(y)
i=e[i].ne
return deep[T]!=0
def dfs(x,flow):
global deep
if ((x==T)or(flow==0)):
return flow
used=0
i=he[x]
while (i):
y=e[i].to
if ((deep[y]==deep[x]+1)and(e[i].fl!=0)):
now=dfs(y,min(flow-used,e[i].fl))
used+=now
e[i].fl-=now
e[i^1].fl+=now
if (flow==used):
break;
i=e[i].ne
if (used==0):
deep[x]=-1
return used
def dinic():
res=0
while (bfs()):
res+=dfs(S,INF)
return res
n,m=map(int,input().split())
ans=0
weight=[0]+list(map(int,input().split()))
e=[0,0]
tot=1
S=n+m+1
T=S+1
he=[0 for i in range(T+1)]
INF=1000000007#εͺθ¦>10^9ε°±θΆ³ε€δΊ
for i in range(1,n+1):
addedge(S,i,weight[i]);
for i in range(1,m+1):
x,y,w=map(int,input().split())
addedge(n+i,T,w)
addedge(x,n+i,INF)
addedge(y,n+i,INF)
ans+=w
ans-=dinic()
print(ans)
``` | output | 1 | 41,245 | 13 | 82,491 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n vertices and m edges.
The weight of the i-th vertex is a_i.
The weight of the i-th edge is w_i.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
The weight of a subgraph is the sum of the weights of its edges, minus the sum of the weights of its vertices. You need to find the maximum weight of subgraph of given graph. The given graph does not contain loops and multiple edges.
Input
The first line contains two numbers n and m (1 β€ n β€ 10^3, 0 β€ m β€ 10^3) - the number of vertices and edges in the graph, respectively.
The next line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) - the weights of the vertices of the graph.
The following m lines contain edges: the i-e edge is defined by a triple of integers v_i, u_i, w_i (1 β€ v_i, u_i β€ n, 1 β€ w_i β€ 10^9, v_i β u_i). This triple means that between the vertices v_i and u_i there is an edge of weight w_i. It is guaranteed that the graph does not contain loops and multiple edges.
Output
Print one integer β the maximum weight of the subgraph of the given graph.
Examples
Input
4 5
1 5 2 2
1 3 4
1 4 4
3 4 5
3 2 2
4 2 2
Output
8
Input
3 3
9 7 8
1 2 1
2 3 2
1 3 3
Output
0
Note
In the first test example, the optimal subgraph consists of the vertices {1, 3, 4} and has weight 4 + 4 + 5 - (1 + 2 + 2) = 8. In the second test case, the optimal subgraph is empty. | instruction | 0 | 41,246 | 13 | 82,492 |
Tags: flows, graphs
Correct Solution:
```
class edge(object):
def __init__(self,ne,to,fl):
self.ne=ne
self.to=to
self.fl=fl
def add(x,y,z):
global tot
tot+=1
e.append(edge(he[x],y,z))
he[x]=tot
def addedge(x,y,z):
add(x,y,z)
add(y,x,0)
def bfs():
global deep
deep=[0 for i in range(T+1)]
q=[]
q.append(S)
deep[S]=1
while (len(q)>0):
x=q[0]
del(q[0])
i=he[x]
while (i):
y=e[i].to
if ((deep[y]==0)and(e[i].fl!=0)):
deep[y]=deep[x]+1
q.append(y)
i=e[i].ne
return deep[T]!=0
def dfs(x,flow):
global deep
if ((x==T)or(flow==0)):
return flow
used=0
i=he[x]
while (i):
y=e[i].to
if ((deep[y]==deep[x]+1)and(e[i].fl!=0)):
now=dfs(y,min(flow-used,e[i].fl))
used+=now
e[i].fl-=now
e[i^1].fl+=now
if (flow==used):
break;
i=e[i].ne
if (used==0):
deep[x]=-1
return used
def dinic():
res=0
while (bfs()):
res+=dfs(S,INF)
return res
n,m=map(int,input().split())
ans=0
weight=[0]+list(map(int,input().split()))
e=[0,0]
tot=1
S=n+m+1
T=S+1
he=[0 for i in range(T+1)]
INF=1000000007
for i in range(1,n+1):
addedge(S,i,weight[i]);
for i in range(1,m+1):
x,y,w=map(int,input().split())
addedge(n+i,T,w)
addedge(x,n+i,INF)
addedge(y,n+i,INF)
ans+=w
ans-=dinic()
print(ans)
``` | output | 1 | 41,246 | 13 | 82,493 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n vertices and m edges.
The weight of the i-th vertex is a_i.
The weight of the i-th edge is w_i.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
The weight of a subgraph is the sum of the weights of its edges, minus the sum of the weights of its vertices. You need to find the maximum weight of subgraph of given graph. The given graph does not contain loops and multiple edges.
Input
The first line contains two numbers n and m (1 β€ n β€ 10^3, 0 β€ m β€ 10^3) - the number of vertices and edges in the graph, respectively.
The next line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) - the weights of the vertices of the graph.
The following m lines contain edges: the i-e edge is defined by a triple of integers v_i, u_i, w_i (1 β€ v_i, u_i β€ n, 1 β€ w_i β€ 10^9, v_i β u_i). This triple means that between the vertices v_i and u_i there is an edge of weight w_i. It is guaranteed that the graph does not contain loops and multiple edges.
Output
Print one integer β the maximum weight of the subgraph of the given graph.
Examples
Input
4 5
1 5 2 2
1 3 4
1 4 4
3 4 5
3 2 2
4 2 2
Output
8
Input
3 3
9 7 8
1 2 1
2 3 2
1 3 3
Output
0
Note
In the first test example, the optimal subgraph consists of the vertices {1, 3, 4} and has weight 4 + 4 + 5 - (1 + 2 + 2) = 8. In the second test case, the optimal subgraph is empty. | instruction | 0 | 41,247 | 13 | 82,494 |
Tags: flows, graphs
Correct Solution:
```
from collections import deque
def addedge(u, v, value):
global e
a = [v, value, None]
b = [u, 0, a]
a[2] = b
e[u].append(a)
e[v].append(b)
inf = 2 * (10 ** 12)
ans = 0
n, m = map(int, input().split())
e = [[] for i in range(n + m + 2)]
a = tuple(map(int, input().split()))
S, T = 0, m + n + 1
for i in range(1, m + 1):
u, v, w = map(int, input().split())
ans += w
addedge(i, u + m, inf)
addedge(i, v + m, inf)
addedge(S, i, w)
for i in range(m + 1, T):
addedge(i, T, a[i - m - 1])
# for i in range(n + m + 2):
# for edge in e[i]:
# print('%d to %d w %d' % (i, edge[0] if edge[0] <= m else edge[0] - m, edge[1]))
lvl = None
def bfs():
global e, lvl
lvl = [0] * (n + m + 2)
q = deque([0])
while q:
node = q.popleft()
# print('node = %d' % node)
for edge in e[node]:
if edge[0] != 0 and lvl[edge[0]] == 0 and edge[1]:
lvl[edge[0]] = lvl[node] + 1
q.append(edge[0])
# print(lvl)
def dfs(node, maxdelta):
global e, lvl
if node == T:
return maxdelta
delta = 0
for edge in e[node]:
if lvl[edge[0]] == lvl[node] + 1 and edge[1]:
tmp = dfs(edge[0], min(maxdelta, edge[1]))
if tmp > 0:
edge[1] -= tmp
edge[2][1] += tmp
maxdelta -= tmp
delta += tmp
if maxdelta == 0:
break
return delta
flow = 0
while 1:
bfs()
tmp = dfs(0, inf)
if tmp == 0:
break
flow += tmp
ans -= flow
print(ans)
``` | output | 1 | 41,247 | 13 | 82,495 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n vertices and m edges.
The weight of the i-th vertex is a_i.
The weight of the i-th edge is w_i.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
The weight of a subgraph is the sum of the weights of its edges, minus the sum of the weights of its vertices. You need to find the maximum weight of subgraph of given graph. The given graph does not contain loops and multiple edges.
Input
The first line contains two numbers n and m (1 β€ n β€ 10^3, 0 β€ m β€ 10^3) - the number of vertices and edges in the graph, respectively.
The next line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) - the weights of the vertices of the graph.
The following m lines contain edges: the i-e edge is defined by a triple of integers v_i, u_i, w_i (1 β€ v_i, u_i β€ n, 1 β€ w_i β€ 10^9, v_i β u_i). This triple means that between the vertices v_i and u_i there is an edge of weight w_i. It is guaranteed that the graph does not contain loops and multiple edges.
Output
Print one integer β the maximum weight of the subgraph of the given graph.
Examples
Input
4 5
1 5 2 2
1 3 4
1 4 4
3 4 5
3 2 2
4 2 2
Output
8
Input
3 3
9 7 8
1 2 1
2 3 2
1 3 3
Output
0
Note
In the first test example, the optimal subgraph consists of the vertices {1, 3, 4} and has weight 4 + 4 + 5 - (1 + 2 + 2) = 8. In the second test case, the optimal subgraph is empty. | instruction | 0 | 41,248 | 13 | 82,496 |
Tags: flows, graphs
Correct Solution:
```
import sys
class Graph:
verticies = {}
nodesCount = 0
class Vertex:
def __init__(self, label, endPoint=None):
self.label = label
self.edges = []
self.visitedToken = 0
self.endPoint = endPoint
class Edge:
residual = None
def __init__(self, from_, to_, isResidual, maxCapacity):
self.from_ = from_
self.to_ = to_
self.isResidual = isResidual
self.capacity = maxCapacity
self.flow = 0
def augment(self, bootleneck):
self.flow += bootleneck
self.residual.flow -= bootleneck
def remainingCapacity(self):
return self.capacity - self.flow
def addEdge(self, from_, to_, capacity):
from_ = self.verticies[from_]
to_ = self.verticies[to_]
if from_.endPoint and from_.endPoint != to_:
from_ = from_.endPoint
main = self.Edge(from_, to_, False, capacity)
residual = self.Edge(to_, from_, True, 0)
main.residual = residual
residual.residual = main
from_.edges.append(main)
to_.edges.append(residual)
def addVertex(self, label, *args):
self.nodesCount += 1
self.verticies[label] = self.Vertex(label)
def maxFlow(self, f, t):
f = self.verticies[f]
t = self.verticies[t]
visitedToken = 1
flow = 0
def dfs(node, bootleneck=sys.maxsize):
node.visitedToken = visitedToken
bootleneck_backup = bootleneck
if node == t:
return bootleneck
for edge in node.edges:
if edge.remainingCapacity() == 0 or edge.to_.visitedToken == visitedToken:
continue
bootleneck = dfs(edge.to_, min(
bootleneck, edge.remainingCapacity()))
if bootleneck:
edge.augment(bootleneck)
return bootleneck
else:
bootleneck = bootleneck_backup
return 0
while True:
bootleneck = dfs(f)
# print(bootleneck)
if not bootleneck:
break
flow += bootleneck
visitedToken += 1
return flow
g = Graph()
n, m = map(int, input().split())
vv = list(map(int, input().split()))
for i in range(n+m+2):
g.addVertex(i)
for i, v in enumerate(vv):
g.addEdge(m+i+1, n+m+1, v)
s = 0
for i in range(1, m+1):
a, b, c = map(int, input().split())
s += c
g.addEdge(0, i, c)
g.addEdge(i, a+m, c)
g.addEdge(i, b+m, c)
print(s-g.maxFlow(0, n+m+1))
``` | output | 1 | 41,248 | 13 | 82,497 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n vertices and m edges.
The weight of the i-th vertex is a_i.
The weight of the i-th edge is w_i.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
The weight of a subgraph is the sum of the weights of its edges, minus the sum of the weights of its vertices. You need to find the maximum weight of subgraph of given graph. The given graph does not contain loops and multiple edges.
Input
The first line contains two numbers n and m (1 β€ n β€ 10^3, 0 β€ m β€ 10^3) - the number of vertices and edges in the graph, respectively.
The next line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) - the weights of the vertices of the graph.
The following m lines contain edges: the i-e edge is defined by a triple of integers v_i, u_i, w_i (1 β€ v_i, u_i β€ n, 1 β€ w_i β€ 10^9, v_i β u_i). This triple means that between the vertices v_i and u_i there is an edge of weight w_i. It is guaranteed that the graph does not contain loops and multiple edges.
Output
Print one integer β the maximum weight of the subgraph of the given graph.
Examples
Input
4 5
1 5 2 2
1 3 4
1 4 4
3 4 5
3 2 2
4 2 2
Output
8
Input
3 3
9 7 8
1 2 1
2 3 2
1 3 3
Output
0
Note
In the first test example, the optimal subgraph consists of the vertices {1, 3, 4} and has weight 4 + 4 + 5 - (1 + 2 + 2) = 8. In the second test case, the optimal subgraph is empty.
Submitted Solution:
```
class SegmentTree(object):
def __init__(self, values, left=None, right=None):
if not left:
left = 0
if not right:
right = len(values)
self.values = values
self.left = left
self.right = right
if self.left + 1 == self.right:
self.value = self.values[self.left]
self.lnode = None
self.rnode = None
else:
self.lnode = SegmentTree(values, self.left, self.middle)
self.rnode = SegmentTree(values, self.middle, self.right)
self.value = self.cmp(self.lnode.value, self.rnode.value)
@property
def middle(self):
return (self.right - self.left) // 2 + self.left
def cmp(self, lvalue, rvalue):
if lvalue.cost is None:
return rvalue
elif rvalue.cost is None:
return lvalue
else:
return lvalue if lvalue.cost > rvalue.cost else rvalue
def update(self, index):
if index == self.left == self.right - 1:
return
if index < self.middle:
self.lnode.update(index)
else:
self.rnode.update(index)
self.value = self.cmp(self.lnode.value, self.rnode.value)
class Vertex(object):
def __init__(self, cost):
self.cost = cost
self.edges = []
class Edge(object):
def __init__(self, index, from_vertex, to_vertex, cost):
self.index = index
self.vertices = [from_vertex, to_vertex]
self._cost = cost
@property
def cost(self):
return self._cost - self.vertices[0].cost - self.vertices[1].cost if self._cost else None
n, m = map(int, input().split())
vertices = [
Vertex(int(cost))
for cost in input().split()
]
edges = []
for index in range(m):
from_vertex, to_vertex, cost = map(int, input().split())
from_vertex = vertices[from_vertex - 1]
to_vertex = vertices[to_vertex - 1]
from_vertex.edges.append(index)
to_vertex.edges.append(index)
edge = Edge(index, from_vertex, to_vertex, cost)
edges.append(edge)
tree = SegmentTree(edges)
best = 0
current = 0
while tree.value.cost is not None:
edge = tree.value
current += edge.cost
if current > best:
best = current
edge._cost = 0
tree.update(edge.index)
for vertex in edge.vertices:
vertex.cost = 0
for index in vertex.edges:
tree.update(index)
print(best)
``` | instruction | 0 | 41,249 | 13 | 82,498 |
No | output | 1 | 41,249 | 13 | 82,499 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n vertices and m edges.
The weight of the i-th vertex is a_i.
The weight of the i-th edge is w_i.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
The weight of a subgraph is the sum of the weights of its edges, minus the sum of the weights of its vertices. You need to find the maximum weight of subgraph of given graph. The given graph does not contain loops and multiple edges.
Input
The first line contains two numbers n and m (1 β€ n β€ 10^3, 0 β€ m β€ 10^3) - the number of vertices and edges in the graph, respectively.
The next line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) - the weights of the vertices of the graph.
The following m lines contain edges: the i-e edge is defined by a triple of integers v_i, u_i, w_i (1 β€ v_i, u_i β€ n, 1 β€ w_i β€ 10^9, v_i β u_i). This triple means that between the vertices v_i and u_i there is an edge of weight w_i. It is guaranteed that the graph does not contain loops and multiple edges.
Output
Print one integer β the maximum weight of the subgraph of the given graph.
Examples
Input
4 5
1 5 2 2
1 3 4
1 4 4
3 4 5
3 2 2
4 2 2
Output
8
Input
3 3
9 7 8
1 2 1
2 3 2
1 3 3
Output
0
Note
In the first test example, the optimal subgraph consists of the vertices {1, 3, 4} and has weight 4 + 4 + 5 - (1 + 2 + 2) = 8. In the second test case, the optimal subgraph is empty.
Submitted Solution:
```
print('8')
``` | instruction | 0 | 41,250 | 13 | 82,500 |
No | output | 1 | 41,250 | 13 | 82,501 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n vertices and m edges.
The weight of the i-th vertex is a_i.
The weight of the i-th edge is w_i.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
The weight of a subgraph is the sum of the weights of its edges, minus the sum of the weights of its vertices. You need to find the maximum weight of subgraph of given graph. The given graph does not contain loops and multiple edges.
Input
The first line contains two numbers n and m (1 β€ n β€ 10^3, 0 β€ m β€ 10^3) - the number of vertices and edges in the graph, respectively.
The next line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) - the weights of the vertices of the graph.
The following m lines contain edges: the i-e edge is defined by a triple of integers v_i, u_i, w_i (1 β€ v_i, u_i β€ n, 1 β€ w_i β€ 10^9, v_i β u_i). This triple means that between the vertices v_i and u_i there is an edge of weight w_i. It is guaranteed that the graph does not contain loops and multiple edges.
Output
Print one integer β the maximum weight of the subgraph of the given graph.
Examples
Input
4 5
1 5 2 2
1 3 4
1 4 4
3 4 5
3 2 2
4 2 2
Output
8
Input
3 3
9 7 8
1 2 1
2 3 2
1 3 3
Output
0
Note
In the first test example, the optimal subgraph consists of the vertices {1, 3, 4} and has weight 4 + 4 + 5 - (1 + 2 + 2) = 8. In the second test case, the optimal subgraph is empty.
Submitted Solution:
```
import sys
class Graph:
verticies = {}
nodesCount = 0
class Vertex:
def __init__(self, label, endPoint=None):
self.label = label
self.edges = []
self.visitedToken = 0
self.endPoint = endPoint
class Edge:
residual = None
def __init__(self, from_, to_, isResidual, maxCapacity):
self.from_ = from_
self.to_ = to_
self.isResidual = isResidual
self.capacity = maxCapacity
self.flow = 0
def augment(self, bootleneck):
self.flow += bootleneck
self.residual.flow -= bootleneck
def remainingCapacity(self):
return self.capacity - self.flow
def addEdge(self, from_, to_, capacity):
from_ = self.verticies[from_]
to_ = self.verticies[to_]
if from_.endPoint and from_.endPoint != to_:
from_ = from_.endPoint
main = self.Edge(from_, to_, False, capacity)
residual = self.Edge(to_, from_, True, 0)
main.residual = residual
residual.residual = main
from_.edges.append(main)
to_.edges.append(residual)
def addVertex(self, label, *args):
self.nodesCount += 1
self.verticies[label] = self.Vertex(label)
def maxFlow(self, f, t):
f = self.verticies[f]
t = self.verticies[t]
visitedToken = 1
flow = 0
def dfs(node, bootleneck=sys.maxsize):
node.visitedToken = visitedToken
bootleneck_backup = bootleneck
if node == t:
return bootleneck
for edge in node.edges:
if edge.remainingCapacity() == 0 or edge.to_.visitedToken == visitedToken:
continue
bootleneck = dfs(edge.to_, min(
bootleneck, edge.remainingCapacity()))
if bootleneck:
edge.augment(bootleneck)
return bootleneck
else:
bootleneck = bootleneck_backup
return 0
while True:
bootleneck = dfs(f)
# print(bootleneck)
if not bootleneck:
break
flow += bootleneck
visitedToken += 1
return flow
g = Graph()
n, m = map(int, input().split())
v = list(map(int, input().split()))
for i in range(0, n+m+2):
g.addVertex(i)
for i, vv in enumerate(v):
g.addEdge(n+i+1, n+m+1, vv)
s = 0
for i in range(1, m+1):
a, b, c = map(int, input().split())
s += c
g.addEdge(0, i, c)
g.addEdge(i, a+n, c)
g.addEdge(i, b+n, c)
print(s-g.maxFlow(0, n+m+1))
``` | instruction | 0 | 41,251 | 13 | 82,502 |
No | output | 1 | 41,251 | 13 | 82,503 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n vertices. Each vertex i has a value a_i associated with it.
Let us root the tree at some vertex v. The vertex v is called a distinctive root if the following holds: in all paths that start at v and end at some other node, all the values encountered are distinct. Two different paths may have values in common but a single path must have all distinct values.
Find the number of distinctive roots in the tree.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2β
10^5) β the number of vertices in the tree.
The next line contains n space-separated integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
The following n-1 lines each contain two space-separated integers u and v (1 β€ u, v β€ n), denoting an edge from u to v.
It is guaranteed that the edges form a tree.
Output
Print a single integer β the number of distinctive roots in the tree.
Examples
Input
5
2 5 1 1 4
1 2
1 3
2 4
2 5
Output
3
Input
5
2 1 1 1 4
1 2
1 3
2 4
2 5
Output
0
Note
In the first example, 1, 2 and 5 are distinctive roots. | instruction | 0 | 41,481 | 13 | 82,962 |
Tags: data structures, dfs and similar, dp, trees
Correct Solution:
```
import io, os
from collections import Counter, defaultdict, deque
class LazySegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the lazy segment tree with data"""
_default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self._lazy = [0] * (2 * _size)
self.data = [default] * (2 * _size)
self.data[_size : _size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __len__(self):
return self._len
def _push(self, idx):
"""push query on idx to its children"""
# Let the children know of the queries
q, self._lazy[idx] = self._lazy[idx], 0
self._lazy[2 * idx] += q
self._lazy[2 * idx + 1] += q
self.data[2 * idx] += q
self.data[2 * idx + 1] += q
def _update(self, idx):
"""updates the node idx to know of all queries applied to it via its ancestors"""
for i in reversed(range(1, idx.bit_length())):
self._push(idx >> i)
def _build(self, idx):
"""make the changes to idx be known to its ancestors"""
idx >>= 1
while idx:
self.data[idx] = (
self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
)
idx >>= 1
def add(self, start, stop, value):
"""lazily add value to [start, stop)"""
if start == stop:
return
start = start_copy = start + self._size
stop = stop_copy = stop + self._size
while start < stop:
if start & 1:
self._lazy[start] += value
self.data[start] += value
start += 1
if stop & 1:
stop -= 1
self._lazy[stop] += value
self.data[stop] += value
start >>= 1
stop >>= 1
self._build(start_copy)
self._build(stop_copy - 1)
def query(self, start, stop, default=0):
"""func of data[start, stop)"""
start += self._size
stop += self._size
self._update(start)
self._update(stop - 1)
res = default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "LazySegmentTree({0})".format(self.data)
def solve(N, A, edges):
graph = [[] for i in range(N)]
for u, indices in edges:
graph[u].append(indices)
graph[indices].append(u)
# Build euler tour
eulerTour = []
root = 0
stack = [root]
seen = [False] * len(graph)
while stack:
node = stack.pop()
eulerTour.append(node)
if not seen[node]:
seen[node] = True
for nbr in graph[node]:
if not seen[nbr]:
stack.append(node)
stack.append(nbr)
assert eulerTour[0] == eulerTour[-1]
eulerTour.pop()
tourByValues = defaultdict(list)
for i, x in enumerate(eulerTour):
tourByValues[A[x]].append(i)
segTree = LazySegmentTree([0] * len(eulerTour), 0, lambda x, y: x + y)
for k, indices in tourByValues.items():
nodes = set(eulerTour[i] for i in indices)
if len(nodes) >= 2:
for i in indices:
segTree.add(i, i + 1, 1)
subtour = []
for i, j in zip(indices, indices[1:]):
x = eulerTour[i]
y = eulerTour[j]
if x == y:
segTree.add(i, j + 1, 1)
else:
subtour.append(i)
i = indices[-1]
j = indices[0]
x = eulerTour[i]
y = eulerTour[j]
if x == y:
segTree.add(i, len(eulerTour), 1)
segTree.add(0, j + 1, 1)
else:
subtour.append(i)
if len(nodes) != len(subtour):
# Subtour has non leaves, impossible
return 0
if False:
print("label", k, "visits", indices, "nodes", nodes)
print(
"\t".join(
str(eulerTour[i]) + ":" + str(A[eulerTour[i]])
for i in range(len(eulerTour))
)
)
for i in range(len(eulerTour)):
if segTree.query(i, i + 1) != 0:
print("x", end="\t")
else:
print("o", end="\t")
print()
print()
ans = set()
for i in range(len(eulerTour)):
if segTree.query(i, i + 1) != 0:
ans.add(eulerTour[i])
return N - len(set(ans))
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = 1
for tc in range(1, TC + 1):
(N,) = [int(x) for x in input().split()]
A = [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, A, edges)
print(ans)
``` | output | 1 | 41,481 | 13 | 82,963 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n vertices. Each vertex i has a value a_i associated with it.
Let us root the tree at some vertex v. The vertex v is called a distinctive root if the following holds: in all paths that start at v and end at some other node, all the values encountered are distinct. Two different paths may have values in common but a single path must have all distinct values.
Find the number of distinctive roots in the tree.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2β
10^5) β the number of vertices in the tree.
The next line contains n space-separated integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
The following n-1 lines each contain two space-separated integers u and v (1 β€ u, v β€ n), denoting an edge from u to v.
It is guaranteed that the edges form a tree.
Output
Print a single integer β the number of distinctive roots in the tree.
Examples
Input
5
2 5 1 1 4
1 2
1 3
2 4
2 5
Output
3
Input
5
2 1 1 1 4
1 2
1 3
2 4
2 5
Output
0
Note
In the first example, 1, 2 and 5 are distinctive roots. | instruction | 0 | 41,482 | 13 | 82,964 |
Tags: data structures, dfs and similar, dp, trees
Correct Solution:
```
import io, os
from collections import Counter, defaultdict, deque
class LazySegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the lazy segment tree with data"""
_default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self._lazy = [0] * (2 * _size)
self.data = [default] * (2 * _size)
self.data[_size : _size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __len__(self):
return self._len
def _push(self, idx):
"""push query on idx to its children"""
# Let the children know of the queries
q, self._lazy[idx] = self._lazy[idx], 0
self._lazy[2 * idx] += q
self._lazy[2 * idx + 1] += q
self.data[2 * idx] += q
self.data[2 * idx + 1] += q
def _update(self, idx):
"""updates the node idx to know of all queries applied to it via its ancestors"""
for i in reversed(range(1, idx.bit_length())):
self._push(idx >> i)
def _build(self, idx):
"""make the changes to idx be known to its ancestors"""
idx >>= 1
while idx:
self.data[idx] = (
self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
)
idx >>= 1
def add(self, start, stop, value):
"""lazily add value to [start, stop)"""
if start == stop:
return
start = start_copy = start + self._size
stop = stop_copy = stop + self._size
while start < stop:
if start & 1:
self._lazy[start] += value
self.data[start] += value
start += 1
if stop & 1:
stop -= 1
self._lazy[stop] += value
self.data[stop] += value
start >>= 1
stop >>= 1
self._build(start_copy)
self._build(stop_copy - 1)
def query(self, start, stop, default=0):
"""func of data[start, stop)"""
start += self._size
stop += self._size
self._update(start)
self._update(stop - 1)
res = default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "LazySegmentTree({0})".format(self.data)
def solve(N, A, edges):
graph = [[] for i in range(N)]
for u, indices in edges:
graph[u].append(indices)
graph[indices].append(u)
# Build euler tour
eulerTour = []
root = 0
stack = [root]
seen = [False] * len(graph)
while stack:
node = stack.pop()
eulerTour.append(node)
if not seen[node]:
seen[node] = True
for nbr in graph[node]:
if not seen[nbr]:
stack.append(node)
stack.append(nbr)
assert eulerTour[0] == eulerTour[-1]
eulerTour.pop()
tourByValues = defaultdict(list)
for i, x in enumerate(eulerTour):
tourByValues[A[x]].append(i)
segTree = LazySegmentTree([0] * len(eulerTour), 0, lambda x, y: x + y)
for k, indices in tourByValues.items():
nodes = set(eulerTour[i] for i in indices)
if len(nodes) >= 2:
for i in indices:
segTree.add(i, i + 1, 1)
subtour = []
for i, j in zip(indices, indices[1:]):
x = eulerTour[i]
y = eulerTour[j]
if x == y:
segTree.add(i, j + 1, 1)
else:
subtour.append(i)
i = indices[-1]
j = indices[0]
x = eulerTour[i]
y = eulerTour[j]
if x == y:
segTree.add(i, len(eulerTour), 1)
segTree.add(0, j + 1, 1)
else:
subtour.append(i)
if len(nodes) != len(subtour):
# Subtour has non leaves, impossible
return 0
if False:
print("label", k, "visits", indices, "nodes", nodes)
print(
"\t".join(
str(eulerTour[i]) + ":" + str(A[eulerTour[i]])
for i in range(len(eulerTour))
)
)
for i in range(len(eulerTour)):
if segTree.query(i, i + 1) != 0:
print("x", end="\t")
else:
print("o", end="\t")
print()
print()
ans = set()
for i in range(len(eulerTour)):
if segTree.query(i, i + 1) != 0:
ans.add(eulerTour[i])
return N - len(set(ans))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N = int(input());A = [int(x) for x in input().split()];e = [[int(x) - 1 for x in input().split()] for i in range(N - 1)];print(solve(N, A, e))
``` | output | 1 | 41,482 | 13 | 82,965 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n vertices. Each vertex i has a value a_i associated with it.
Let us root the tree at some vertex v. The vertex v is called a distinctive root if the following holds: in all paths that start at v and end at some other node, all the values encountered are distinct. Two different paths may have values in common but a single path must have all distinct values.
Find the number of distinctive roots in the tree.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2β
10^5) β the number of vertices in the tree.
The next line contains n space-separated integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
The following n-1 lines each contain two space-separated integers u and v (1 β€ u, v β€ n), denoting an edge from u to v.
It is guaranteed that the edges form a tree.
Output
Print a single integer β the number of distinctive roots in the tree.
Examples
Input
5
2 5 1 1 4
1 2
1 3
2 4
2 5
Output
3
Input
5
2 1 1 1 4
1 2
1 3
2 4
2 5
Output
0
Note
In the first example, 1, 2 and 5 are distinctive roots. | instruction | 0 | 41,483 | 13 | 82,966 |
Tags: data structures, dfs and similar, dp, trees
Correct Solution:
```
import io, os;from collections import Counter, defaultdict, deque
class LazySegmentTree:
def __init__(self, data, default=0, func=max):
_default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self._lazy = [0] * (2 * _size)
self.data = [default] * (2 * _size)
self.data[_size : _size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __len__(self):
return self._len
def _push(self, idx):
q, self._lazy[idx] = self._lazy[idx], 0
self._lazy[2 * idx] += q
self._lazy[2 * idx + 1] += q
self.data[2 * idx] += q
self.data[2 * idx + 1] += q
def _update(self, idx):
for i in reversed(range(1, idx.bit_length())):
self._push(idx >> i)
def _build(self, idx):
idx >>= 1
while idx:
self.data[idx] = (
self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
)
idx >>= 1
def add(self, start, stop, value):
if start == stop:
return
start = start_copy = start + self._size
stop = stop_copy = stop + self._size
while start < stop:
if start & 1:
self._lazy[start] += value
self.data[start] += value
start += 1
if stop & 1:
stop -= 1
self._lazy[stop] += value
self.data[stop] += value
start >>= 1
stop >>= 1
self._build(start_copy)
self._build(stop_copy - 1)
def query(self, start, stop, default=0):
start += self._size
stop += self._size
self._update(start)
self._update(stop - 1)
res = default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "LazySegmentTree({0})".format(self.data)
def solve(N, A, edges):
graph = [[] for i in range(N)]
for u, indices in edges:graph[u].append(indices);graph[indices].append(u)
eulerTour = [];root = 0;stack = [root];seen = [False] * len(graph)
while stack:
node = stack.pop();eulerTour.append(node)
if not seen[node]:
seen[node] = True
for nbr in graph[node]:
if not seen[nbr]:stack.append(node);stack.append(nbr)
assert eulerTour[0] == eulerTour[-1];eulerTour.pop();tourByValues = defaultdict(list)
for i, x in enumerate(eulerTour):tourByValues[A[x]].append(i)
segTree = LazySegmentTree([0] * len(eulerTour), 0, lambda x, y: x + y)
for k, indices in tourByValues.items():
nodes = set(eulerTour[i] for i in indices)
if len(nodes) >= 2:
for i in indices:segTree.add(i, i + 1, 1)
subtour = []
for i, j in zip(indices, indices[1:]):
x = eulerTour[i];y = eulerTour[j]
if x == y:segTree.add(i, j + 1, 1)
else:subtour.append(i)
i = indices[-1];j = indices[0];x = eulerTour[i];y = eulerTour[j]
if x == y:segTree.add(i, len(eulerTour), 1);segTree.add(0, j + 1, 1)
else:subtour.append(i)
if len(nodes) != len(subtour):return 0
if False:
print("label", k, "visits", indices, "nodes", nodes);print("\t".join(str(eulerTour[i]) + ":" + str(A[eulerTour[i]]) for i in range(len(eulerTour))))
for i in range(len(eulerTour)):print("x", end="\t") if segTree.query(i, i + 1) != 0 else print("o", end="\t")
print();print()
return N - len(set([eulerTour[i] for i in range(len(eulerTour)) if segTree.query(i, i + 1) != 0]))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N = int(input());A = [int(x) for x in input().split()];e = [[int(x) - 1 for x in input().split()] for i in range(N - 1)];print(solve(N, A, e))
``` | output | 1 | 41,483 | 13 | 82,967 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.