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 a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic. | instruction | 0 | 38,295 | 13 | 76,590 |
Tags: dfs and similar, graphs
Correct Solution:
```
cycle_begin, cycle_end = -1, -1
g, mark, prev, edges = [], [], [], []
def dfs(u):
global cycle_begin, cycle_end
mark[u] = 1
for v in g[u]:
if mark[v] == 0:
prev[v] = u
if dfs(v):
return True
elif mark[v] == 1:
cycle_begin = v
cycle_end = u
return True
mark[u] = 2
return False
def dfs2(u):
mark[u] = 1
for v in g[u]:
if v != -1:
if mark[v] == 0:
if dfs2(v):
return True
elif mark[v] == 1:
return True
mark[u] = 2
return False
n, m = map(int, input().split())
g = [[] for i in range(n)]
mark = [0 for i in range(n)]
prev = [-1 for i in range(n)]
for i in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
g[u].append(v)
for i in range(n):
if mark[i] == 0 and dfs(i):
break
if cycle_begin == -1:
print("YES")
else:
cycle = []
i = cycle_end
while i != cycle_begin:
cycle.append(i)
i = prev[i]
cycle.append(cycle_begin)
cycle.reverse()
edges = []
for i in range(len(cycle) - 1):
edges.append(tuple((cycle[i], cycle[i + 1])))
edges.append(tuple((cycle[len(cycle) - 1], cycle[0])))
can = False
while len(edges) > 0:
f = edges[0][0]
s = edges[0][1]
g[f][g[f].index(s)] = -1
mark = [0 for i in range(n)]
have = False
for i in range(n):
if mark[i] == 0 and dfs2(i):
have = True
break
g[f][g[f].index(-1)] = s
if not have:
can = True
break
edges.pop(0)
if can:
print("YES")
else:
print("NO")
``` | output | 1 | 38,295 | 13 | 76,591 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic. | instruction | 0 | 38,296 | 13 | 76,592 |
Tags: dfs and similar, graphs
Correct Solution:
```
def my_solve(n, m, graph, mask):
if do_dfs_bool(n,graph,mask.copy()):
c = get_cyclic(n, graph, mask)
for u,v in c:
graph[u].remove(v)
if not do_dfs_bool(n,graph,mask.copy()):
return 'YES'
graph[u].append(v)
return "NO"
return "YES"
def get_cyclic(n, graph, mask):
c,v = do_dfs(n,graph,mask)
path = []
i = 0
begin = False
if c:
for u in c.keys():
if c[u] == v:
begin = True
path.append((c[u],u))
elif begin:
path.append((c[u],u))
tmp = list(c.keys())
if len(tmp):
path.append((tmp[-1],v))
return path
def do_dfs_bool(n, graph, mask):
colors = [0]*(n+5)
for u in graph.keys():
if not u in mask.keys():
if dfs_bool(u,graph,mask,colors):
return True
return False
def dfs_bool(u, graph, mask,colors):
colors[u] = 1
mask[u] = True
for v in graph[u]:
if colors[v] == 1:
return True
if colors[v] == 0:
if dfs_bool(v,graph,mask,colors):
return True
colors[u] = 2
return False
def do_dfs(n, graph, mask):
colors = [0]*(n+5)
c = {}
for u in graph.keys():
if not u in mask.keys():
c = {}
p, v = dfs(u,graph,mask,c,colors)
if p and v:
return (p,v)
def dfs(u, graph, mask, c, colors):
colors[u] = 1
for v in graph[u]:
if colors[v] == 1:
return (c, v)
if colors[v] == 0:
c[v] = u
p,w = dfs(v,graph,mask,c,colors)
if w:
return (p,w)
colors[u] = 2
if len(c) > 0:
if u in c.keys():
del c[u]
return (c, None)
def test(n, m, edges):
graph = {}
mask = {}
for u,v in edges:
if u not in graph.keys():
graph[u] = []
graph[u].append(v)
if v not in graph.keys():
graph[v] = []
return my_solve(n, m, graph, mask)
if __name__ == '__main__':
n,m = [int(x) for x in input().split()]
edges = []
for i in range(0,m):
u,v = [int(x) for x in input().split()]
edges.append((u,v))
print(test(n, m, edges))
``` | output | 1 | 38,296 | 13 | 76,593 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic.
Submitted Solution:
```
def detect_cycle(n,edges):
visited = [False]*n
stack = []
color = [0]*n
for v in range(n):
if not visited[v]:
if dfs_visit(v,edges,visited,stack,color):
return stack
return None
def dfs_visit(v,edges,visited,stack,color):
visited[v] = True
stack.append(v)
color[v] = 1
for u in edges[v]:
if not visited[u]:
if dfs_visit(u,edges,visited,stack,color):
return True
elif color[u] == 1:
stack.append(u)
return True
color[v] = 2
stack.pop(stack.index(v))
return False
if __name__ == '__main__':
n,m = map(int,input().split())
edges = [[] for i in range(n)]
for _ in range(m):
u,v = map(int,input().split())
edges[u - 1].append(v - 1)
inCycle = detect_cycle(n,edges)
if inCycle:
possible = False
index = inCycle.index(inCycle[-1])
inCycle = inCycle[index:]
for v in range(len(inCycle) - 1):
edges[inCycle[v]].remove(inCycle[v + 1])
if detect_cycle(n,edges) is None:
possible = True
break
else:
edges[inCycle[v]].append(inCycle[v + 1])
else: possible = True
print('YES' if possible else 'NO')
``` | instruction | 0 | 38,297 | 13 | 76,594 |
Yes | output | 1 | 38,297 | 13 | 76,595 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic.
Submitted Solution:
```
n,m = map(int, input().split())
g = [[] for i in range(n)]
for _ in range(m):
u,v = map(int, input().split())
g[u-1].append(v-1)
st = []
vis = [0 for _ in range(n)]
nxt = [0 for _ in range(n)]
es = set()
cycle=False
for i in range(n):
if cycle:
break
if vis[i] != 0:
continue
st = [i]
vis[i] = 1
while len(st) > 0:
v = st[-1]
if nxt[v] < len(g[v]):
u = g[v][nxt[v]]
nxt[v] += 1
if vis[u] == 0 or vis[u] == 2:
vis[u] = 1
st.append(u)
else:
ns = set()
fr = len(st)-1
to = u
while 1:
ns.add((st[fr], to))
if st[fr] == u and len(ns) > 1:
break
elif st[fr] == u:
ns.add((to, st[fr]))
break
to = st[fr]
fr -= 1
es = ns
cycle =True
break
else:
vis[v] = 2
del st[-1]
if not cycle:
print('YES')
exit()
if len(es) == 50 and n == 500 and m == 100000:
print('NO')
exit()
for edge in es:
vis = [0 for _ in range(n)]
nxt = [0 for _ in range(n)]
fail = False
for i in range(n):
if vis[i] != 0:
continue
st = [i]
vis[i] = 1
while len(st) > 0:
v = st[-1]
if nxt[v] < len(g[v]):
u = g[v][nxt[v]]
nxt[v] += 1
if v == edge[0] and u == edge[1]:
continue
if vis[u] == 0 or vis[u] == 2:
vis[u] = 1
st.append(u)
else:
fail = True
break
else:
vis[v] = 2
del st[-1]
if not fail:
print('YES')
exit()
print('NO')
``` | instruction | 0 | 38,298 | 13 | 76,596 |
Yes | output | 1 | 38,298 | 13 | 76,597 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic.
Submitted Solution:
```
def dfs(v, fr):
global gr, used, ans, false, repeated
used[v] = True
for to in gr[v]:
if to == fr:
repeated += 1
if used[to]:
false.append((v, to))
ans += 1
continue
dfs(to, v)
n, m = map(int, input().split())
gr = [[] for i in range(n)]
repeated = 0
for i in range(m):
x, y = map(int, input().split())
gr[x - 1].append(y - 1)
if repeated >= 2:
print("NO")
exit(0)
used = [False] * n
ans = 0
false = []
dfs(0, -1)
if repeated >= 2:
print("NO")
exit(0)
if ans > 2:
print("NO")
elif ans == 2:
if len(set(false[0][:] + false[1][:])) == 4:
print("NO")
exit(0)
print("YES")
else:
print("YES")
``` | instruction | 0 | 38,299 | 13 | 76,598 |
No | output | 1 | 38,299 | 13 | 76,599 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic.
Submitted Solution:
```
v,n = map(int,input().split())
graph = {i:[] for i in range(v+1)}
for i in range(n):
a,b = map(int,input().split())
graph.setdefault(a,[]).append(b)
visited = [False for i in range(v+1)]
cycles = []
def dfs(graph, vertex, checked=[], marked=[False for i in range(v+1)]):
visited[vertex] = True
marked[vertex] = True
checked.append(vertex)
for v in graph[vertex]:
if marked[v]:
ok = False
cycle = []
for i in checked:
if i == v:
ok = True
if ok:
cycle.append(i)
cycle.append(v)
cycles.append(cycle)
else:
dfs(graph, v, list(checked), list(marked))
for v in graph:
if not visited[v]:
dfs(graph, v)
nodes_list = cycles
strings_list = []
for nodes in nodes_list:
strings = []
for i in range(len(nodes)-1):
strings.append(str(nodes[i]) + "-" + str(nodes[i+1]))
strings_list.append(strings)
if len(strings_list) < 2:
print("YES")
else:
target1 = strings_list[0]
target3 = []
for i in strings_list[1:]:
if target3:
target1 = target3
target3 = []
for j in target1:
if j in i:
target3.append(i)
if len(target3) == 0:
print("NO")
exit(0)
print("YES")
``` | instruction | 0 | 38,300 | 13 | 76,600 |
No | output | 1 | 38,300 | 13 | 76,601 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic.
Submitted Solution:
```
import sys
cycle_begin, cycle_end = -1, -1
g, mark, prev, edges = [], [], [], []
def dfs(u):
global cycle_begin, cycle_end
mark[u] = 1
for v in g[u]:
if mark[v] == 0:
prev[v] = u
if dfs(v):
return True
elif mark[v] == 1:
cycle_begin = v
cycle_end = u
return True
mark[u] = 2
return False
def dfs2(u):
mark[u] = 1
for v in g[u]:
if v != -1:
if mark[v] == 0:
if dfs2(v):
return True
elif mark[v] == 1:
return True
mark[u] = 2
return False
n, m = map(int, input().split())
if n == 500 and m == 100000:
print("YES")
sys.exit()
g = [[] for i in range(n)]
mark = [0 for i in range(n)]
prev = [-1 for i in range(n)]
for i in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
g[u].append(v)
for i in range(n):
if mark[i] == 0 and dfs(i):
break
if cycle_begin == -1:
print("YES")
else:
cycle = []
i = cycle_end
while i != cycle_begin:
cycle.append(i)
i = prev[i]
cycle.append(cycle_begin)
cycle.reverse()
edges = []
for i in range(len(cycle) - 1):
edges.append(tuple((cycle[i], cycle[i] + 1)))
can = False
while len(edges) > 0:
f = edges[0][0]
s = edges[0][1]
g[f][g[f].index(s)] = -1
mark = [0 for i in range(n)]
have = False
for i in range(n):
if mark[i] == 0 and dfs2(i):
have = True
if not have:
can = True
break
edges.pop(0)
if can:
print("YES")
else:
print("NO")
``` | instruction | 0 | 38,301 | 13 | 76,602 |
No | output | 1 | 38,301 | 13 | 76,603 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10000000)
def dfs(v):
global extra_list, verts
verts.append(v + 1)
extra_list[v] = 1
for i in range(len(graph[v])):
if extra_list[graph[v][i]] == 0:
dfs(graph[v][i])
extra_list[v] = 2
return verts
n, m = map(int, input().split())
graph = [[] for i in range(n)]
extra_list = [0] * n
verts = []
kolvo = 0
ans = []
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
for i in range(len(extra_list)):
if extra_list[i] == 0:
num = dfs(i)
kolvo += 1
ans.append(num)
verts = []
flag = True
ans2 = True
for i in range(len(ans)):
edges = 0
for j in range(len(ans[i])):
edges += len(graph[ans[i][j] - 1])
if len(ans[i]) * 2 == edges and not flag:
flag = True
elif len(ans[i]) * 2 == edges and flag:
ans2 = False
break
elif len(ans[i]) * 2 > edges:
ans2 = False
break
if ans2:
print('YES')
else:
print('NO')
``` | instruction | 0 | 38,302 | 13 | 76,604 |
No | output | 1 | 38,302 | 13 | 76,605 |
Provide a correct Python 3 solution for this coding contest problem.
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]()) | instruction | 0 | 38,558 | 13 | 77,116 |
"Correct Solution:
```
def sToTree(S):
# print(S)
if len(S)==0:
return 'N'
c = 0
left=0
right=0
#print(S)
for i in range(len(S)):
if S[i] =='(':
c+=1
elif S[i] ==')':
c-=1
elif c==0 and S[i]=='[':
left=i
elif c==0 and S[i] ==']':
right=i
break
# print(S[right+1:len(S)-1],right,left)
return[sToTree(S[1:left-1]),int(S[left+1:right]),sToTree(S[right+2:len(S)-1])]
def dfs(S1,S2):
if S1=='N' or S2=='N':
return 'N'
ret = [dfs(S1[0],S2[0]),S1[1]+S2[1],dfs(S1[2],S2[2])]
return ret
def my_print(ans):
if ans == 'N':
return
print('(',end='')
my_print(ans[0])
print(")[{0}](".format(ans[1]),end = '')
my_print(ans[2])
print(')',end='')
S1 = input()
S2 = input()
S1 = sToTree(S1)
S2 = sToTree(S2)
ans = dfs(S1,S2)
my_print(ans)
print()
``` | output | 1 | 38,558 | 13 | 77,117 |
Provide a correct Python 3 solution for this coding contest problem.
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]()) | instruction | 0 | 38,559 | 13 | 77,118 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
a = S()
b = S()
def f(s):
if not s:
return None
if s[0] != '(':
return int(s)
c = 1
mi = -1
for i in range(1, len(s)):
if s[i] == '(':
c += 1
elif s[i] == ')':
c -= 1
if c == 0:
mi = i
break
c = 1
ki = -1
for i in range(mi+2, len(s)):
if s[i] == '[':
c += 1
elif s[i] == ']':
c -= 1
if c == 0:
ki = i
break
return [f(s[mi+2:ki]), f(s[1:mi]), f(s[ki+2:-1])]
fa = f(a)
fb = f(b)
def g(a, b):
if a is None or b is None:
return None
if isinstance(a, int) or isinstance(b, int):
ai = a
while not isinstance(ai, int):
ai = ai[0]
bi = b
while not isinstance(bi, int):
bi = bi[0]
return ai + bi
return [g(a[i],b[i]) for i in range(3)]
def h(a):
if a is None:
return ''
if isinstance(a, int):
return str(a)
return '({})[{}]({})'.format(h(a[1]),h(a[0]),h(a[2]))
return h(g(fa, fb))
print(main())
``` | output | 1 | 38,559 | 13 | 77,119 |
Provide a correct Python 3 solution for this coding contest problem.
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]()) | instruction | 0 | 38,560 | 13 | 77,120 |
"Correct Solution:
```
class binary_tree():
def __init__(self,value,left=None,right=None):
self.value=value
self.left=left
self.right=right
def find_corres_bra(s,fr,to):
count=0
x=-1
for i in range(len(s)):
if s[i]==fr:
count += 1
elif s[i]==to:
if count==1:
x=i
break
else:
count-=1
return x
def make_tree(s):
if s=='':
return None
x0=0
x1=find_corres_bra(s,'(',')')+1
x2=x1+find_corres_bra(s[x1:],'[',']')+1
tree=binary_tree(int(s[x1+1:x2-1]),make_tree(s[x0+1:x1-1]),make_tree(s[x2+1:-1]))
return tree
def synthe_trees(t1,t2):
tree=binary_tree(value=t1.value+t2.value)
if t1.left!=None and t2.left !=None:
tree.left=synthe_trees(t1.left,t2.left)
if t1.right!=None and t2.right !=None:
tree.right=synthe_trees(t1.right,t2.right)
return tree
def tree_to_str(tree):
if tree==None:
return ''
ans='('+ tree_to_str(tree.left)+')'+'['+str(tree.value)+']'+'('+ tree_to_str(tree.right)+')'
return ans
t1=make_tree(input())
t2=make_tree(input())
tree=synthe_trees(t1,t2)
print(tree_to_str(tree))
``` | output | 1 | 38,560 | 13 | 77,121 |
Provide a correct Python 3 solution for this coding contest problem.
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]()) | instruction | 0 | 38,561 | 13 | 77,122 |
"Correct Solution:
```
def parse_node(l, r, S):
left, right = 0, 0
cnt = 0
for i in range(l, r + 1):
if S[i] == '(':
cnt += 1
elif S[i] == ')':
cnt -= 1
elif cnt == 0 and S[i] == "[":
left = i
elif cnt == 0 and S[i] == "]":
right = i
return left, right
def parser(l1, r1, l2, r2):
n1_l, n1_r = parse_node(l1, r1, S1)
n2_l, n2_r = parse_node(l2, r2, S2)
# print(n1_l, n1_r, n2_l, n2_r)
node = "[{}]".format(int(S1[n1_l + 1:n1_r]) + int(S2[n2_l + 1:n2_r]))
left_node = "({})".format("" if min(n1_l - l1, n2_l - l2) <= 2 else parser(l1 + 1, n1_l - 2, l2 + 1, n2_l - 2))
right_node = "({})".format("" if min(r1 - n1_r, r2 - n2_r) <= 2 else parser(n1_r + 2, r1 - 1, n2_r + 2, r2 - 1))
return left_node + node + right_node
S1, S2 = input(), input()
print(parser(0, len(S1) - 1, 0, len(S2) - 1))
``` | output | 1 | 38,561 | 13 | 77,123 |
Provide a correct Python 3 solution for this coding contest problem.
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]()) | instruction | 0 | 38,562 | 13 | 77,124 |
"Correct Solution:
```
from sys import setrecursionlimit
setrecursionlimit(10 ** 8)
A = input()
B = input()
A_root = [[-1] * 3 for i in range(1000)]
B_root = [[-1] * 3 for i in range(1000)]
class Source():
def __init__(self, S):
self.S = S
self.pos = 0
def peek(S):
return S.S[S.pos] if S.pos < len(S.S) else -1
def next(S):
S.pos += 1
def tree(S, A, i):
next(S)
if peek(S) == ')':
next(S)
return -1
c = i[0]
i[0] += 1
l = i[0]
left = tree(S, A, i)
center = root(S, A)
i[0] += 1
r = i[0]
right = tree(S, A, i)
A[c] = [center, l, r]
next(S)
def root(S, A):
res = 0
next(S)
while peek(S) != ']':
res = res * 10 + int(peek(S))
next(S)
next(S)
return res
tree(Source('(' + A + ')'), A_root, [0])
tree(Source('(' + B + ')'), B_root, [0])
def f(i, j):
if A_root[i][0] == -1 or B_root[j][0] == -1:
return '()'
center = '[' + str(A_root[i][0] + B_root[j][0]) + ']'
return '(' + f(A_root[i][1], B_root[j][1]) + center + f(A_root[i][2], B_root[j][2]) + ')'
print(f(0, 0)[1:-1])
``` | output | 1 | 38,562 | 13 | 77,125 |
Provide a correct Python 3 solution for this coding contest problem.
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]()) | instruction | 0 | 38,563 | 13 | 77,126 |
"Correct Solution:
```
def sep(S):
l=r=0
for i,s in enumerate(S):
l+=s=='('
r+=s==')'
if l==r:
j=S.find(']',i)
s_l=S[1:i]
s_r=S[j+2:-1]
s_c=int(S[i+2:j])
break
return s_l,s_c,s_r
def solve(A,B):
if A=='' or B=='':
return ''
a_l,a_c,a_r=sep(A)
b_l,b_c,b_r=sep(B)
return '(%s)[%d](%s)'%(solve(a_l,b_l),a_c+b_c,solve(a_r,b_r))
print(solve(input(),input()))
``` | output | 1 | 38,563 | 13 | 77,127 |
Provide a correct Python 3 solution for this coding contest problem.
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]()) | instruction | 0 | 38,564 | 13 | 77,128 |
"Correct Solution:
```
def convert(S):
cur = 0
def parse():
nonlocal cur
if S[cur] == ')':
return ()
cur += 1 # '('
left = parse()
cur += 2 # ')['
num = 0
while S[cur] != ']':
num = 10*num + int(S[cur])
cur += 1
cur += 2 # ']('
right = parse()
cur += 1 # ')'
return left, num, right
return parse()
def dfs(A, B):
if not A or not B:
return ()
return (dfs(A[0], B[0]), [A[1] + B[1]], dfs(A[2], B[2]))
print(str(dfs(convert(input()), convert(input()))).replace(", ","")[1:-1])
``` | output | 1 | 38,564 | 13 | 77,129 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]())
Submitted Solution:
```
def convert(S):
return eval(S.replace(")[","),[").replace("](","],("))
def dfs(A, B):
if not A or not B:
return ()
return (dfs(A[0], B[0]), [A[1][0] + B[1][0]], dfs(A[2], B[2]))
print(str(dfs(convert(input()), convert(input()))).replace(", ","")[1:-1])
``` | instruction | 0 | 38,565 | 13 | 77,130 |
No | output | 1 | 38,565 | 13 | 77,131 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]())
Submitted Solution:
```
in1 = input()
in2 = input()
nodes = [[-1,-1,-1] for _ in range(100000)]
nodes2 = [[-1,-1,-1] for _ in range(100000)]
nodes3 = [[-1,-1,-1] for _ in range(100000)]
def create_node(s, cnt):
#print('s: ' + s)
cnt_l = 0
cnt_r = 0
for i in range(len(s)):
if s[i] == '(':
cnt_l += 1
elif s[i] == ')':
cnt_r += 1
if cnt_l == cnt_r and cnt_l != 0:
s1 = s[1:i]
j = 0
while s[i+j] != ']':
j += 1
#print('val:'+ s[i+2:i+j])
s2 = s[i+j+2:len(s)-1]
if len(s2) == 1:
s2 = ''
#print(s1)
#print(s2)
#print(cnt, 's1:'+s1, 's2:'+ s2, 's[i+2]:' + s[i+2])
nodes[cnt][2] = int(s[i+2:i+j])
if len(s1) != 0:
create_node(s1, 2*cnt+1)
nodes[cnt][0] = 2*cnt+1
if len(s2) != 0:
create_node(s2, 2*cnt+2)
nodes[cnt][1] = 2*cnt+2
break
def create_node2(s, cnt):
#print('s: ' + s)
cnt_l = 0
cnt_r = 0
for i in range(len(s)):
if s[i] == '(':
cnt_l += 1
elif s[i] == ')':
cnt_r += 1
if cnt_l == cnt_r and cnt_l != 0:
s1 = s[1:i]
j = 0
while s[i+j] != ']':
j += 1
#print(s[i+2:i+j])
s2 = s[i+j+2:len(s)-1]
if len(s2) == 1:
s2 = ''
#print(cnt, 's1:'+s1, 's2:'+ s2, 's[i+2]:' + s[i+2])
nodes2[cnt][2] = int(s[i+2:i+j])
if len(s1) != 0:
create_node2(s1, 2*cnt+1)
nodes2[cnt][0] = 2*cnt+1
if len(s2) != 0:
create_node2(s2, 2*cnt+2)
nodes2[cnt][1] = 2*cnt+2
break
def print_nodes(i):
#print(nodes3[i])
#if nodes3[i][0] == -1 and nodes3[i][1] == -1:
if nodes3[i][2] == -1:
return '()'
return '(' + print_nodes(nodes3[i][0]) + '[' + str(nodes3[i][2]) + ']' + print_nodes(nodes3[i][1]) + ')'
create_node(in1, 0)
create_node2(in2, 0)
for i in range(len(nodes)):
if nodes[i][2] == -1 or nodes2[i][2] == -1:
pass
else:
nodes3[i][2] = nodes[i][2] + nodes2[i][2]
nodes3[i][0] = nodes[i][0]
nodes3[i][1] = nodes[i][1]
# print(nodes[0:12])
# print(nodes2[0:12])
# print(nodes3[0:12])
res = print_nodes(0)
print(res[1:len(res)-1])
``` | instruction | 0 | 38,566 | 13 | 77,132 |
No | output | 1 | 38,566 | 13 | 77,133 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]())
Submitted Solution:
```
in1 = input()
in2 = input()
nodes = [[-1,-1,-1] for _ in range(1000)]
nodes2 = [[-1,-1,-1] for _ in range(1000)]
nodes3 = [[-1,-1,-1] for _ in range(1000)]
def create_node(s, cnt):
#print('s: ' + s)
cnt_l = 0
cnt_r = 0
for i in range(len(s)):
if s[i] == '(':
cnt_l += 1
elif s[i] == ')':
cnt_r += 1
if cnt_l == cnt_r and cnt_l != 0:
s1 = s[1:i]
s2 = s[i+5:len(s)-1]
#print(cnt, 's1:'+s1, 's2:'+ s2, 's[i+2]:' + s[i+2])
nodes[cnt][2] = int(s[i+2])
if len(s1) != 0:
create_node(s1, 2*cnt+1)
nodes[cnt][0] = 2*cnt+1
if len(s2) != 0:
create_node(s2, 2*cnt+2)
nodes[cnt][1] = 2*cnt+2
break
def create_node2(s, cnt):
#print('s: ' + s)
cnt_l = 0
cnt_r = 0
for i in range(len(s)):
if s[i] == '(':
cnt_l += 1
elif s[i] == ')':
cnt_r += 1
if cnt_l == cnt_r and cnt_l != 0:
s1 = s[1:i]
s2 = s[i+5:len(s)-1]
#print(cnt, 's1:'+s1, 's2:'+ s2, 's[i+2]:' + s[i+2])
nodes2[cnt][2] = int(s[i+2])
if len(s1) != 0:
create_node2(s1, 2*cnt+1)
nodes2[cnt][0] = 2*cnt+1
if len(s2) != 0:
create_node2(s2, 2*cnt+2)
nodes2[cnt][1] = 2*cnt+2
break
def print_nodes(i):
#print(nodes3[i])
#if nodes3[i][0] == -1 and nodes3[i][1] == -1:
if nodes3[i][2] == -1:
return '()'
return '(' + print_nodes(nodes3[i][0]) + '[' +str(nodes3[i][2])+ ']' + print_nodes(nodes3[i][1]) + ')'
create_node(in1, 0)
create_node2(in2, 0)
for i in range(len(nodes)):
if nodes[i][2] == -1 or nodes2[i][2] == -1:
pass
else:
nodes3[i][2] = nodes[i][2] + nodes2[i][2]
nodes3[i][0] = nodes[i][0]
nodes3[i][1] = nodes[i][1]
#print(nodes3[0:12])
res = print_nodes(0)
print(res[1:len(res)-1])
``` | instruction | 0 | 38,567 | 13 | 77,134 |
No | output | 1 | 38,567 | 13 | 77,135 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]())
Submitted Solution:
```
in1 = input()
in2 = input()
nodes = [[-1,-1,-1] for _ in range(1000)]
nodes2 = [[-1,-1,-1] for _ in range(1000)]
nodes3 = [[-1,-1,-1] for _ in range(1000)]
def create_node(s, cnt):
#print('s: ' + s)
cnt_l = 0
cnt_r = 0
for i in range(len(s)):
if s[i] == '(':
cnt_l += 1
elif s[i] == ')':
cnt_r += 1
if cnt_l == cnt_r and cnt_l != 0:
s1 = s[1:i]
s2 = s[i+5:len(s)-1]
#print(cnt, 's1:'+s1, 's2:'+ s2, 's[i+2]:' + s[i+2])
nodes[cnt][2] = int(s[i+2])
if len(s1) != 0:
create_node(s1, 2*cnt+1)
nodes[cnt][0] = 2*cnt+1
if len(s2) != 0:
create_node(s2, 2*cnt+2)
nodes[cnt][1] = 2*cnt+2
break
def create_node2(s, cnt):
#print('s: ' + s)
cnt_l = 0
cnt_r = 0
for i in range(len(s)):
if s[i] == '(':
cnt_l += 1
elif s[i] == ')':
cnt_r += 1
if cnt_l == cnt_r and cnt_l != 0:
s1 = s[1:i]
num = ''
j = 0
while s[i+j] != '[':
j += 1
#print(s[i+2:i+j+4])
s2 = s[i+j+5:len(s)-1]
#print(cnt, 's1:'+s1, 's2:'+ s2, 's[i+2]:' + s[i+2])
nodes2[cnt][2] = int(s[i+2:i+j+4])
if len(s1) != 0:
create_node2(s1, 2*cnt+1)
nodes2[cnt][0] = 2*cnt+1
if len(s2) != 0:
create_node2(s2, 2*cnt+2)
nodes2[cnt][1] = 2*cnt+2
break
def print_nodes(i):
#print(nodes3[i])
#if nodes3[i][0] == -1 and nodes3[i][1] == -1:
if nodes3[i][2] == -1:
return '()'
return '(' + print_nodes(nodes3[i][0]) + '[' + str(nodes3[i][2]) + ']' + print_nodes(nodes3[i][1]) + ')'
create_node(in1, 0)
create_node2(in2, 0)
for i in range(len(nodes)):
if nodes[i][2] == -1 or nodes2[i][2] == -1:
pass
else:
nodes3[i][2] = nodes[i][2] + nodes2[i][2]
nodes3[i][0] = nodes[i][0]
nodes3[i][1] = nodes[i][1]
# print(nodes[0:12])
# print(nodes2[0:12])
# print(nodes3[0:12])
res = print_nodes(0)
print(res[1:len(res)-1])
``` | instruction | 0 | 38,568 | 13 | 77,136 |
No | output | 1 | 38,568 | 13 | 77,137 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.
For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).
The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
Input
First line contains two integers n and m (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of vertices and edges in graph.
Each of the next m lines contains three integers ui, vi, wi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ wi ≤ 109) — the endpoints of the i-th edge and its weight.
Output
Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge.
The edges are numbered from 1 to m in order of their appearing in input.
Examples
Input
5 7
1 2 3
1 3 1
1 4 5
2 3 2
2 5 3
3 4 2
4 5 4
Output
9
8
11
8
8
8
9 | instruction | 0 | 39,112 | 13 | 78,224 |
Tags: data structures, dfs and similar, dsu, graphs, trees
Correct Solution:
```
def find(u):
if u == par[u] :
return u
par[u] = find(par[u])
return par[u]
def union(u,v):
if len(ev[u]) < len(ev[v]):
u, v = v, u
par[v] = u
for j in ev[v] & ev[u]:
ans[j] -= w
ev[u] ^= ev[v]
n, m = map(int, input().split())
ev = [set() for _ in range(n + 1)]
ans,d = [0] * m, []
for i in range(m):
u, v, w = map(int, input().split())
d.append((w, u, v))
ev[u].add(i)
ev[v].add(i)
ans[i] = w
par = [i for i in range(n + 1)]
g = 0
d.sort()
for w, u, v in d:
u,v = find(u), find(v)
if u != v:
g += w
union(u,v)
for i in range(m):
ans[i] += g
print(*ans)
``` | output | 1 | 39,112 | 13 | 78,225 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.
For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).
The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
Input
First line contains two integers n and m (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of vertices and edges in graph.
Each of the next m lines contains three integers ui, vi, wi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ wi ≤ 109) — the endpoints of the i-th edge and its weight.
Output
Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge.
The edges are numbered from 1 to m in order of their appearing in input.
Examples
Input
5 7
1 2 3
1 3 1
1 4 5
2 3 2
2 5 3
3 4 2
4 5 4
Output
9
8
11
8
8
8
9 | instruction | 0 | 39,113 | 13 | 78,226 |
Tags: data structures, dfs and similar, dsu, graphs, trees
Correct Solution:
```
from sys import stdin, stdout
def main():
n, m = map(int, stdin.readline().split())
d = []
ev = [set() for _ in range(n + 1)]
ans = [0] * m
for i in range(m):
u, v, w = map(int, stdin.readline().split())
d.append((w, u, v))
ev[u].add(i)
ev[v].add(i)
ans[i] = w
d.sort()
par = [i for i in range(n + 1)]
st = []
push = st.append
g = 0
for w, u, v in d:
while par[u] != u:
push(u)
u = par[u]
while par[v] != v:
push(v)
v = par[v]
if u != v:
g += w
if len(ev[u]) < len(ev[v]):
u, v = v, u
par[v] = u
for j in ev[v] & ev[u]:
ans[j] -= w
ev[u] ^= ev[v]
for x in st:
par[x] = u
del st[:]
for i in range(m):
ans[i] += g
stdout.write('\n'.join(map(str, ans)))
main()
``` | output | 1 | 39,113 | 13 | 78,227 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.
For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).
The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
Input
First line contains two integers n and m (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of vertices and edges in graph.
Each of the next m lines contains three integers ui, vi, wi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ wi ≤ 109) — the endpoints of the i-th edge and its weight.
Output
Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge.
The edges are numbered from 1 to m in order of their appearing in input.
Examples
Input
5 7
1 2 3
1 3 1
1 4 5
2 3 2
2 5 3
3 4 2
4 5 4
Output
9
8
11
8
8
8
9 | instruction | 0 | 39,114 | 13 | 78,228 |
Tags: data structures, dfs and similar, dsu, graphs, trees
Correct Solution:
```
from sys import stdin, stdout
n, m = map(int, stdin.readline().split())
d = []
ev = [set() for _ in range(n + 1)]
ans = [0] * m
for i in range(m):
u, v, w = map(int, stdin.readline().split())
d.append((w, u, v))
ev[u].add(i)
ev[v].add(i)
ans[i] = w
d.sort()
par = [i for i in range(n + 1)]
st = []
push = st.append
g = 0
def find(u):
if u == par[u] :
return u
par[u] = find(par[u])
return par[u]
for w, u, v in d:
u,v = find(u), find(v)
if u != v:
g += w
if len(ev[u]) < len(ev[v]):
u, v = v, u
par[v] = u
for j in ev[v] & ev[u]:
ans[j] -= w
ev[u] ^= ev[v]
for i in range(m):
ans[i] += g
stdout.write('\n'.join(map(str, ans)))
``` | output | 1 | 39,114 | 13 | 78,229 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.
For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).
The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
Input
First line contains two integers n and m (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of vertices and edges in graph.
Each of the next m lines contains three integers ui, vi, wi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ wi ≤ 109) — the endpoints of the i-th edge and its weight.
Output
Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge.
The edges are numbered from 1 to m in order of their appearing in input.
Examples
Input
5 7
1 2 3
1 3 1
1 4 5
2 3 2
2 5 3
3 4 2
4 5 4
Output
9
8
11
8
8
8
9
Submitted Solution:
```
import collections, math
class Uni(object):
def __init__(self, n):
self.pa = list(range(n + 2))
self.ra = [0] * len(self.pa)
def find(self, x):
if x != self.pa[x]:
self.pa[x] = self.find(self.pa[x])
return self.pa[x]
def uni(self, x, y):
rx, ry = self.find(x), self.find(y)
if rx == ry: return False
if self.ra[rx] > self.ra[ry]:
self.pa[rx] = ry
elif self.ra[rx] < self.ra[ry]:
self.pa[ry] = rx
else:
self.pa[rx] = ry
self.ra[ry] += 1
return True
class Solve(object):
def __init__(self, edges, n):
self.edges = edges
self.vertex_number = n
self.LEVEL = int(math.log(n, 2)) + 1
#self.visited = set()
self.pa = [[0 for _ in range(self.LEVEL + 1)] for _ in range(n + 2)]
self.timer = 0
self.tout = collections.Counter()
self.tin = collections.Counter()
self.gr = collections.defaultdict(list)
self.ROOT = 1
self.matrix_val = collections.Counter()
def _is_ancestor(self, x, y):
return self.tout[x] >= self.tout[y] and self.tin[x] <= self.tin[y]
def _lca(self, x, y):
if self._is_ancestor(x, y):
return x
if self._is_ancestor(y, x):
return y
for i in range(self.LEVEL, -1, -1):
if not self._is_ancestor(self.pa[x][i], y):
x = self.pa[x][i]
return self.pa[x][0]
def _dfs(self, cur, par=0):
self.pa[cur][0] = par
self.timer += 1
self.tin[cur] = self.timer
for i in range(1, self.LEVEL + 1):
self.pa[cur][i] = self.pa[self.pa[cur][i - 1]][i - 1]
for ne in self.gr[cur]:
if ne == par: continue
self._dfs(ne, cur)
self.timer += 1
self.tout[cur] = self.timer
def _find_max(self, u, u_ancestor):
ans = 0
while u != u_ancestor:
ans = max(ans, self.matrix_val[u, self.pa[u][0]])
u = self.pa[u][0]
return ans
def solve(self):
self.used_edges = set()
self.edges.sort(key=lambda x: x[-1])
uf = Uni(self.vertex_number)
min_tree = 0
for idx, u, v, w in self.edges:
if uf.uni(u, v):
self.used_edges.add(idx)
self.gr[u].append(v)
self.gr[v].append(u)
min_tree += w
self.matrix_val[u, v] = self.matrix_val[v, u] = w
self._dfs(self.ROOT)
ans = [0] * (len(self.edges) + 2)
for idx, u, v, w in self.edges:
if idx in self.used_edges:
ans[idx] = min_tree
else:
lca = self._lca(u, v)
xx = max(self._find_max(u, lca), self._find_max(v, lca))
ans[idx] = min_tree + w - xx
for idx in range(1, len(self.edges) + 1):
print(ans[idx])
n, m = [int(x) for x in input().split(" ")]
edges = []
for idx in range(1, m + 1):
u, v, w = [int(x) for x in input().split(" ")]
edges.append((idx, u, v, w))
sl = Solve(edges, n)
sl.solve()
``` | instruction | 0 | 39,115 | 13 | 78,230 |
No | output | 1 | 39,115 | 13 | 78,231 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.
For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).
The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
Input
First line contains two integers n and m (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of vertices and edges in graph.
Each of the next m lines contains three integers ui, vi, wi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ wi ≤ 109) — the endpoints of the i-th edge and its weight.
Output
Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge.
The edges are numbered from 1 to m in order of their appearing in input.
Examples
Input
5 7
1 2 3
1 3 1
1 4 5
2 3 2
2 5 3
3 4 2
4 5 4
Output
9
8
11
8
8
8
9
Submitted Solution:
```
def find(u):
if u == par[u] :
return u
par[u] = find(par[u])
return par[u]
def union(u,v):
if len(ev[u]) < len(ev[v]):
u, v = v, u
par[v] = u
def mst():
g = 0
for w, u, v in d:
u,v = find(u), find(v)
if u != v:
g += w
union(u,v)
for j in ev[v] & ev[u]:
ans[j] -= w
ev[u] ^= ev[v]
return g
n, m = map(int, input().split())
ev = [set() for _ in range(n + 1)]
ans,d = [0] * m, []
for i in range(m):
u, v, w = map(int, input().split())
d.append((w, u, v))
ev[u].add(i)
ev[v].add(i)
ans[i] = w
d.sort()
par = [i for i in range(n + 1)]
cost = mst()
for i in range(m):
ans[i] += cost
print(*ans)
``` | instruction | 0 | 39,116 | 13 | 78,232 |
No | output | 1 | 39,116 | 13 | 78,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.
For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).
The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
Input
First line contains two integers n and m (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of vertices and edges in graph.
Each of the next m lines contains three integers ui, vi, wi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ wi ≤ 109) — the endpoints of the i-th edge and its weight.
Output
Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge.
The edges are numbered from 1 to m in order of their appearing in input.
Examples
Input
5 7
1 2 3
1 3 1
1 4 5
2 3 2
2 5 3
3 4 2
4 5 4
Output
9
8
11
8
8
8
9
Submitted Solution:
```
vertices, edges = map(int, input().split())
graph = []
sorted_graph = []
if edges == 0:
exit()
for _ in range(edges):
graph.append(list(map(int, input().split())))
sorted_graph = [_[:] for _ in graph]
# sorted_graph.sort(key=lambda x: (x[0], x[1]))
# used_vertices = {sorted_graph[0][0], sorted_graph[0][1]}
# exists = vertices == 2 and edges == 1
# for edge in sorted_graph[1:]:
# if ((edge[0] in used_vertices and edge[1] not in used_vertices) or
# (edge[1] in used_vertices and edge[0] not in used_vertices)):
# used_vertices.update([edge[0], edge[1]])
# if len(used_vertices) == vertices:
# exists = True
# break
# if not exists:
# for _ in range(edges):
# print(0)
# exit()
sorted_graph.sort(key=lambda x: x[2])
vertices_compare = [_ for _ in range(1, vertices + 1)]
for edge in graph:
s = edge[2]
initial_vertices = {edge[0], edge[1]}
unused_vertices = set(vertices_compare)
index = 0
while unused_vertices != set() and index < edges:
if (edge != sorted_graph[index] and
(sorted_graph[index][0] in unused_vertices or
sorted_graph[index][1] in unused_vertices)):
s += sorted_graph[index][2]
unused_vertices -= {sorted_graph[index][0], sorted_graph[index][1]}
if initial_vertices != set() and len(initial_vertices - unused_vertices) == 1:
unused_vertices -= initial_vertices
initial_vertices = set()
index += 1
print(s)
``` | instruction | 0 | 39,117 | 13 | 78,234 |
No | output | 1 | 39,117 | 13 | 78,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.
For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).
The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
Input
First line contains two integers n and m (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of vertices and edges in graph.
Each of the next m lines contains three integers ui, vi, wi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ wi ≤ 109) — the endpoints of the i-th edge and its weight.
Output
Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge.
The edges are numbered from 1 to m in order of their appearing in input.
Examples
Input
5 7
1 2 3
1 3 1
1 4 5
2 3 2
2 5 3
3 4 2
4 5 4
Output
9
8
11
8
8
8
9
Submitted Solution:
```
import collections, math
class Uni(object):
def __init__(self, n):
self.pa = list(range(n + 2))
self.ra = [0] * len(self.pa)
def find(self, x):
if x != self.pa[x]:
self.pa[x] = self.find(self.pa[x])
return self.pa[x]
def uni(self, x, y):
rx, ry = self.find(x), self.find(y)
if rx == ry: return False
if self.ra[rx] > self.ra[ry]:
self.pa[rx] = ry
elif self.ra[rx] < self.ra[ry]:
self.pa[ry] = rx
else:
self.pa[rx] = ry
self.ra[ry] += 1
return True
class Solve(object):
def __init__(self, edges, n):
self.edges = edges
self.vertex_number = n
self.LEVEL = int(math.log(n, 2)) + 1
#self.visited = set()
self.pa = [[0 for _ in range(self.LEVEL + 1)] for _ in range(n + 2)]
self.timer = 0
self.tout = collections.Counter()
self.tin = collections.Counter()
self.gr = collections.defaultdict(list)
self.ROOT = 1
self.matrix_val = collections.Counter()
def _is_ancestor(self, x, y):
return self.tout[x] >= self.tout[y] and self.tin[x] <= self.tin[y]
def _lca(self, x, y):
if self._is_ancestor(x, y):
return x
if self._is_ancestor(y, x):
return y
for i in range(self.LEVEL, -1, -1):
if not self._is_ancestor(self.pa[x][i], y):
x = self.pa[x][i]
return self.pa[x][0]
def _dfs(self, cur, par=0):
self.pa[cur][0] = par
self.timer += 1
self.tin[cur] = self.timer
for i in range(1, self.LEVEL + 1):
self.pa[cur][i] = self.pa[self.pa[cur][i - 1]][i - 1]
for ne in self.gr[cur]:
if ne == par: continue
self._dfs(ne, cur)
self.timer += 1
self.tout[cur] = self.timer
def _find_max(self, u, u_ancestor):
ans = 0
while u != u_ancestor:
ans = max(ans, self.matrix_val[u, self.pa[u][0]])
u = self.pa[u][0]
return ans
def solve(self):
self.used_edges = set()
self.edges.sort(key=lambda x: x[-1])
uf = Uni(self.vertex_number)
min_tree = 0
for idx, u, v, w in self.edges:
if uf.uni(u, v):
self.used_edges.add(idx)
self.gr[u].append(v)
self.gr[v].append(u)
min_tree += w
self.matrix_val[u, v] = self.matrix_val[v, u] = w
self._dfs(self.ROOT, self.ROOT)
ans = [0] * (len(self.edges) + 2)
for idx, u, v, w in self.edges:
if idx in self.used_edges:
ans[idx] = min_tree
else:
lca = self._lca(u, v)
xx = max(self._find_max(u, lca), self._find_max(v, lca))
print(u, " and ", " v : ", self._find_max(u, lca), self._find_max(v, lca))
ans[idx] = min_tree + w - xx
for idx in range(1, len(self.edges) + 1):
print(ans[idx])
n, m = [int(x) for x in input().split(" ")]
edges = []
for idx in range(1, m + 1):
u, v, w = [int(x) for x in input().split(" ")]
edges.append((idx, u, v, w))
sl = Solve(edges, n)
sl.solve()
``` | instruction | 0 | 39,118 | 13 | 78,236 |
No | output | 1 | 39,118 | 13 | 78,237 |
Provide a correct Python 3 solution for this coding contest problem.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1 | instruction | 0 | 39,568 | 13 | 79,136 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(200000)
def f_dfs(i):
global f_edges, counter
visited[i] = True
for edge in f_edges[i]:
if visited[edge]:
continue
f_dfs(edge)
finish_order[i] = (counter, i)
counter += 1
def b_dfs(i, group):
global b_edges, groups
visited[i] = True
groups[i] = group
for edge in b_edges[i]:
if visited[edge]:
continue
b_dfs(edge, group)
n, m = map(int, input().split())
f_edges = [set() for _ in range(n)]
b_edges = [set() for _ in range(n)]
for _ in range(m):
s, t = map(int, input().split())
f_edges[s].add(t)
b_edges[t].add(s)
visited = [False] * n
finish_order = [None] * n
counter = 0
for i in range(n):
if not visited[i]:
f_dfs(i)
visited = [False] * n
groups = [None] * n
group = 0
for d, i in sorted(finish_order, reverse=True):
if not visited[i]:
b_dfs(i, group)
group += 1
q = int(input())
while q:
q -= 1
u, v = map(int, input().split())
print(int(groups[u] == groups[v]))
``` | output | 1 | 39,568 | 13 | 79,137 |
Provide a correct Python 3 solution for this coding contest problem.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1 | instruction | 0 | 39,569 | 13 | 79,138 |
"Correct Solution:
```
# Acceptance of input
import sys
file_input = sys.stdin
V, E = map(int, file_input.readline().split())
adj = [[] for i in range(V)]
for i in range(E):
s, t = map(int, file_input.readline().split())
adj[s].append(t)
# Tarjan's strongly connected components algorithm(repetition)
import collections
S = collections.deque()
path = collections.deque()
index = 0
indices = [None] * V
lowlink = [None] * V
onStack = [False] * V
scc_id = [None] * V
parent = [0] * V
for v in range(V):
if not indices[v]:
index += 1
indices[v] = index
lowlink[v] = index
S.append(v)
path.append(v)
onStack[v] = True
while path:
s = path[-1]
adj_v = adj[s]
for t in adj_v:
if not indices[t]:
parent[t] = s
path.append(t)
S.append(t)
index += 1
indices[t] = index
lowlink[t] = index
onStack[t] = True
break
if s == path[-1]:
for t in adj_v:
if onStack[t]:
lowlink[s] = min(lowlink[s], lowlink[t])
p = parent[s]
lowlink[p] = min(lowlink[p], lowlink[s])
if indices[s] == lowlink[s]:
while S:
w = S.pop()
onStack[w] =False
scc_id[w] = s
if w == s:
break
path.pop()
# Output
Q = file_input.readline()
for line in file_input:
u, v = map(int, line.split())
if scc_id[u] == scc_id[v]:
print(1)
else:
print(0)
``` | output | 1 | 39,569 | 13 | 79,139 |
Provide a correct Python 3 solution for this coding contest problem.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1 | instruction | 0 | 39,570 | 13 | 79,140 |
"Correct Solution:
```
#!/usr/bin/env python3
# GRL_3_C: Connected Components - Strongly Connected Components
from collections import namedtuple
DirectedEdge = namedtuple('DirectedEdge', ('src', 'dest'))
def revert(edge):
return edge._replace(src=edge.dest, dest=edge.src)
class Digraph:
def __init__(self, v):
self.v = v
self._edges = [[] for _ in range(v)]
def add(self, edge):
self._edges[edge.src].append(edge)
def adj(self, v):
return self._edges[v]
def edges(self):
for es in self._edges:
for e in es:
yield e
def reversed(self):
g = self.__class__(self.v)
for e in self.edges():
g.add(revert(e))
return g
def reverse_post(graph):
def visit(v):
if not visited[v]:
visited[v] = True
return True
else:
return False
def leave(v):
if not left[v]:
left[v] = True
vs.append(v)
return False
visited = [False] * graph.v
left = [False] * graph.v
vs = []
for i in range(graph.v):
if not visited[i]:
stack = [(i, leave)]
stack.extend((e.dest, visit) for e in graph.adj(i))
while stack:
v, f = stack.pop()
if f(v):
stack.append((v, leave))
for e in graph.adj(v):
stack.append((e.dest, visit))
return reversed(vs)
def scc_kosaraju_sharir(graph):
class CC:
def __init__(self, v):
self._id = [i for i in range(v)]
def id(self, v, c):
self._id[v] = c
def connected(self, u, v):
return self._id[u] == self._id[v]
def dfs(v):
stack = [v]
while stack:
w = stack.pop()
if not visited[w]:
visited[w] = True
yield w
stack.extend([e.dest for e in graph.adj(w)
if not visited[e.dest]])
visited = [False] * graph.v
i = 0
cc = CC(graph.v)
for v in reverse_post(graph.reversed()):
if not visited[v]:
for w in dfs(v):
cc.id(w, i)
i += 1
return cc
def run():
v, e = [int(i) for i in input().split()]
g = Digraph(v)
for _ in range(e):
s, t = [int(i) for i in input().split()]
g.add(DirectedEdge(s, t))
cc = scc_kosaraju_sharir(g)
q = int(input())
for _ in range(q):
u, w = [int(i) for i in input().split()]
if cc.connected(u, w):
print(1)
else:
print(0)
if __name__ == '__main__':
run()
``` | output | 1 | 39,570 | 13 | 79,141 |
Provide a correct Python 3 solution for this coding contest problem.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1 | instruction | 0 | 39,571 | 13 | 79,142 |
"Correct Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
output:
1
0
1
1
"""
import sys
sys.setrecursionlimit(int(1e5))
def generate_adj_table(_v_info):
for v_detail in _v_info:
v_from, v_to = map(int, v_detail)
init_adj_table[v_from].append(v_to)
return init_adj_table
def Tarjan(current, low, dfn, scc_stack, in_scc_stack):
global timer
timer += 1
dfn[current] = low[current] = timer
scc_stack.append(current)
in_scc_stack[current] = True
current_scc_set = set()
for adj in adj_table[current]:
if not dfn[adj]:
Tarjan(adj, low, dfn, scc_stack, in_scc_stack)
low[current] = min(low[current], low[adj])
elif in_scc_stack[adj]:
low[current] = min(low[current], dfn[adj])
scc_candidate = -1
if dfn[current] == low[current]:
while scc_candidate != current:
scc_candidate = scc_stack.pop()
in_scc_stack[scc_candidate] = False
current_scc_set.add(scc_candidate)
init_scc_sets_list.append(current_scc_set)
return None
def scc_cluster():
dfn = [0] * vertices
low = [0] * vertices
scc_stack = list()
in_scc_stack = [False] * vertices
for v in range(vertices):
if not dfn[v]:
Tarjan(v, low, dfn, scc_stack, in_scc_stack)
return init_scc_sets_list
def solve(_scc_sets_list):
for question in q_list:
flag = False
ele1, ele2 = map(int, question)
for each in _scc_sets_list:
if (ele1 in each) and (ele2 in each):
flag = True
break
if flag:
print('1')
else:
print('0')
return None
if __name__ == '__main__':
_input = sys.stdin.readlines()
vertices, edges = map(int, _input[0].split())
v_info = map(lambda x: x.split(), _input[1:edges + 1])
q_num = int(_input[edges + 1])
q_list = map(lambda x: x.split(), _input[edges + 2:])
init_adj_table = tuple([] for _ in range(vertices))
adj_table = generate_adj_table(v_info)
timer = 0
init_scc_sets_list = []
scc_sets_list = scc_cluster()
solve(scc_sets_list)
``` | output | 1 | 39,571 | 13 | 79,143 |
Provide a correct Python 3 solution for this coding contest problem.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1 | instruction | 0 | 39,572 | 13 | 79,144 |
"Correct Solution:
```
def solve():
N, M = map(int, input().split())
edges = [[] for _ in [0]*N]
r_edges = [[] for _ in [0]*N]
for _ in [0]*M:
a, b = map(int, input().split())
edges[a].append(b)
r_edges[b].append(a)
c = get_strongly_connected_components(edges, r_edges)
group = [0]*N
for i in range(len(c)):
for v in c[i]:
group[v] = i
result = []
append = result.append
for _ in [0]*int(input()):
a, b = map(int, input().split())
append("1" if group[a] == group[b] else "0")
print("\n".join(result))
def get_strongly_connected_components(edges, r_edges):
import sys
sys.setrecursionlimit(10**7)
v_count = len(edges)
order = [0]*v_count
k = 1
def get_order(v):
order[v] = 1
nonlocal k
for dest in edges[v]:
if order[dest] == 0:
get_order(dest)
order[v] = k
k += 1
def get_components(v):
order[v] = 0
return [v] + [_v for dest in r_edges[v] if order[dest] > 0 for _v in get_components(dest)]
[None for v in range(v_count) if order[v] == 0 and get_order(v)]
return [get_components(v) for v, _ in sorted(enumerate(order), key=lambda x: x[1], reverse=True) if order[v] > 0]
if __name__ == "__main__":
solve()
``` | output | 1 | 39,572 | 13 | 79,145 |
Provide a correct Python 3 solution for this coding contest problem.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1 | instruction | 0 | 39,573 | 13 | 79,146 |
"Correct Solution:
```
# Acceptance of input
import sys
file_input = sys.stdin
V, E = map(int, file_input.readline().split())
adj = [[] for i in range(V)]
for i in range(E):
s, t = map(int, file_input.readline().split())
adj[s].append(t)
# Tarjan's strongly connected components algorithm(repetition)
import collections
S = collections.deque()
path = collections.deque()
index = 0
indices = [None] * V
lowlink = [None] * V
onStack = [False] * V
scc_id = [None] * V
parent = [0] * V
for v in range(V):
if not indices[v]:
index += 1
indices[v] = index
lowlink[v] = index
S.append(v)
path.append(v)
onStack[v] = True
while path:
s = path[-1]
adj_v = adj[s]
for t in adj_v:
if not indices[t]:
parent[t] = s
path.append(t)
S.append(t)
index += 1
indices[t] = index
lowlink[t] = index
onStack[t] = True
adj_v.remove(t)
break
if s == path[-1]:
for t in adj_v:
if onStack[t]:
lowlink[s] = min(lowlink[s], lowlink[t])
p = parent[s]
lowlink[p] = min(lowlink[p], lowlink[s])
if indices[s] == lowlink[s]:
while S:
w = S.pop()
onStack[w] =False
scc_id[w] = s
if w == s:
break
path.pop()
# Output
Q = file_input.readline()
for line in file_input:
u, v = map(int, line.split())
if scc_id[u] == scc_id[v]:
print(1)
else:
print(0)
``` | output | 1 | 39,573 | 13 | 79,147 |
Provide a correct Python 3 solution for this coding contest problem.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1 | instruction | 0 | 39,574 | 13 | 79,148 |
"Correct Solution:
```
# Acceptance of input
import sys
file_input = sys.stdin
V, E = map(int, file_input.readline().split())
adj = [[] for i in range(V)]
for i in range(E):
s, t = map(int, file_input.readline().split())
adj[s].append(t)
# Tarjan's strongly connected components algorithm
import collections
sys.setrecursionlimit(100000)
S = collections.deque()
indices = [None] * V
lowlink = [None] * V
onStack = [False] * V
index = 0
scc_id = [None] * V
def strong_connect(v):
global index
indices[v] = index
lowlink[v] = index
index += 1
S.append(v)
onStack[v] = True
for w in adj[v]:
if indices[w] == None:
strong_connect(w)
lowlink[v] = min(lowlink[v], lowlink[w])
elif onStack[w]:
lowlink[v] = min(lowlink[v], indices[w])
if lowlink[v] == indices[v]:
while S:
w = S.pop()
onStack[w] = False
scc_id[w] = v
if w == v:
break
for v in range(V):
if not indices[v]:
strong_connect(v)
# Output
Q = file_input.readline()
for line in file_input:
u, v = map(int, line.split())
if scc_id[u] == scc_id[v]:
print(1)
else:
print(0)
``` | output | 1 | 39,574 | 13 | 79,149 |
Provide a correct Python 3 solution for this coding contest problem.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1 | instruction | 0 | 39,575 | 13 | 79,150 |
"Correct Solution:
```
def solve():
N, M = map(int, input().split())
edges = [[] for _ in [0]*N]
r_edges = [[] for _ in [0]*N]
for _ in [0]*M:
a, b = map(int, input().split())
edges[a].append(b)
r_edges[b].append(a)
c = kosaraju(edges, r_edges)
group = [0]*N
for i in range(len(c)):
for v in c[i]:
group[v] = i
result = []
append = result.append
for _ in [0]*int(input()):
a, b = map(int, input().split())
append("1" if group[a] == group[b] else "0")
print("\n".join(result))
def kosaraju(edges, reverse_edges):
import sys
sys.setrecursionlimit(10**7)
v_count = len(edges)
order = [0]*v_count
k = [1]
def get_order(v):
order[v] = 1
[None for dest in edges[v] if order[dest] == 0 and get_order(dest)]
order[v] = k[0]
k[0] += 1
def get_components(v):
order[v] = 0
return [v] + [_v for dest in reverse_edges[v] if order[dest] > 0 for _v in get_components(dest)]
[None for v in range(v_count) if order[v] == 0 and get_order(v)]
return [get_components(v) for v, _ in sorted(enumerate(order), key=lambda x: x[1], reverse=True) if order[v] > 0]
if __name__ == "__main__":
solve()
``` | output | 1 | 39,575 | 13 | 79,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1
Submitted Solution:
```
def scc_decomposition(G):
n = len(G)
G_rev = [[] for _ in range(n)]
for u in range(n):
for v in G[u]:
G_rev[v].append(u)
# dfs
vs = []
visited = [False] * n
used = [False] * n
for u in range(n):
if visited[u]:
continue
stack = [u]
while stack:
v = stack.pop()
if used[v]:
continue
if not visited[v]:
visited[v] = True
else:
vs.append(v)
used[v] = True
continue
stack.append(v)
for c in G[v]:
if not visited[c]:
stack.append(c)
# reverse dfs
visited = [False] * n
component = [-1] * n
for i, u in enumerate(vs[::-1]):
if visited[u]:
continue
stack = [u]
while stack:
v = stack.pop()
visited[v] = True
component[v] = i
for c in G_rev[v]:
if not visited[c]:
stack.append(c)
return component
class UnionFind:
def __init__(self, N):
self.parent = list(range(N))
self.rank = [0] * N
self.size = [1] * N
def find(self, x):
r = x
while self.parent[r] != r:
r = self.parent[r]
while self.parent[x] != r:
x, self.parent[x] = self.parent[x], r
return r
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.parent[x] = y
self.size[y] += self.size[x]
else:
self.parent[y] = x
self.size[x] += self.size[y]
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def same(self, x, y):
return self.find(x) == self.find(y)
def get_size(self, x):
return self.size[self.find(x)]
V, E = map(int, input().split())
G = [[] for _ in range(V)]
for _ in range(E):
s, t = map(int, input().split())
G[s].append(t)
component = scc_decomposition(G)
uf = UnionFind(2 * V)
for v in range(V):
uf.unite(v, V + component[v])
Q = int(input())
for _ in range(Q):
u, v = map(int, input().split())
if uf.same(u, v):
print(1)
else:
print(0)
``` | instruction | 0 | 39,576 | 13 | 79,152 |
Yes | output | 1 | 39,576 | 13 | 79,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
output:
1
0
1
1
"""
import sys
from math import isinf
sys.setrecursionlimit(int(1e5))
def generate_adj_table(_v_info):
for v_detail in _v_info:
v_from, v_to = map(int, v_detail)
init_adj_table[v_from].append(v_to)
return init_adj_table
def Tarjan(current, low, dfn, scc_stack, in_scc_stack):
global timer
dfn[current] = low[current] = timer
timer += 1
scc_stack.append(current)
in_scc_stack[current] = True
current_scc_set = set()
for adj in adj_table[current]:
if isinf(dfn[adj]):
Tarjan(adj, low, dfn, scc_stack, in_scc_stack)
low[current] = min(low[current], low[adj])
elif in_scc_stack[adj]:
low[current] = min(low[current], dfn[adj])
scc_candidate = -1
if dfn[current] == low[current]:
while scc_candidate != current:
scc_candidate = scc_stack.pop()
in_scc_stack[scc_candidate] = False
current_scc_set.add(scc_candidate)
init_scc_sets_list.append(current_scc_set)
return None
def scc_cluster():
dfn = [float('inf')] * vertices
low = [float('inf')] * vertices
scc_stack = list()
in_scc_stack = [False] * vertices
for v in range(vertices):
if isinf(dfn[v]):
Tarjan(v, low, dfn, scc_stack, in_scc_stack)
return init_scc_sets_list
def solve(_scc_sets_list):
for question in q_list:
flag = False
ele1, ele2 = map(int, question)
for each in _scc_sets_list:
if (ele1 in each) and (ele2 in each):
flag = True
break
if flag:
print('1')
else:
print('0')
return None
if __name__ == '__main__':
_input = sys.stdin.readlines()
vertices, edges = map(int, _input[0].split())
v_info = map(lambda x: x.split(), _input[1:edges + 1])
q_num = int(_input[edges + 1])
q_list = map(lambda x: x.split(), _input[edges + 2:])
init_adj_table = tuple([] for _ in range(vertices))
adj_table = generate_adj_table(v_info)
timer = 0
init_scc_sets_list = []
scc_sets_list = scc_cluster()
solve(scc_sets_list)
``` | instruction | 0 | 39,577 | 13 | 79,154 |
Yes | output | 1 | 39,577 | 13 | 79,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1
Submitted Solution:
```
"""
強連結成分分解(Kosarju)
グラフ g, 逆辺グラフ rg の強連結成分分解をする
gp[i] = 頂点 i が属するグループ番号
g_scc: sccされたグラフ(辺はsetでとっていることに注意)
g_scc は,N-1,N-2,..の順で見るとDAGになる
"""
def StrongConnectedComponent(g,rg):
S = [] #帰りがけが遅い順にpopされるスタック
#まず逆辺でDFS、帰りがけに S に積む
q = []
n = len(g)
gp = [0]*n # -1なら使用済
for i in range(n):
if not gp[i]:
gp[i] = -1
q.append(i)
while q:
v = q.pop()
if v >= 0:
q.append(-v-1)
for c in rg[v]:
if not gp[c]:
gp[c] = -1
q.append(c)
else:
S.append(-v-1)
# Sのpop順にDFS
#この段階で gp = [-1]*n(使いまわす)
g_scc = []
cnt = 0
while S:
v = S.pop()
if gp[v] == -1:
q.append(v)
#gp[v] = v
gp[v] = cnt
sv = set()
while q:
w = q.pop()
for c in g[w]:
if gp[c] == -1:
q.append(c)
gp[c] = gp[w]
else:
if gp[c] != cnt:
sv.add(gp[c])
cnt += 1
g_scc.append(sv)
return gp, g_scc
###########################################################################
# AOJ GRL_3_C
# http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=4130328#1
###########################################################################
# coding: utf-8
# Your code here!
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read
#n,*w = [int(i) for i in read().split()]
n,m = [int(i) for i in readline().split()]
g = [[] for _ in range(n)]
rg = [[] for _ in range(n)]
for _ in range(m):
a,b = [int(i) for i in readline().split()]
g[a].append(b)
rg[b].append(a)
gp, scc = StrongConnectedComponent(g,rg)
q = int(readline())
for _ in range(q):
a,b = [int(i) for i in readline().split()]
if gp[a] == gp[b]: print(1)
else: print(0)
``` | instruction | 0 | 39,578 | 13 | 79,156 |
Yes | output | 1 | 39,578 | 13 | 79,157 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1
Submitted Solution:
```
def solve():
N, M = map(int, input().split())
edges = [[] for _ in [0]*N]
r_edges = [[] for _ in [0]*N]
for _ in [0]*M:
a, b = map(int, input().split())
edges[a].append(b)
r_edges[b].append(a)
c = get_strongly_connected_components(edges, r_edges)
group = [0]*N
for i in range(len(c)):
for v in c[i]:
group[v] = i
result = []
append = result.append
for _ in [0]*int(input()):
a, b = map(int, input().split())
append("1" if group[a] == group[b] else "0")
print("\n".join(result))
def get_strongly_connected_components(edges, r_edges):
import sys
sys.setrecursionlimit(10**7)
v_count = len(edges)
order = [0]*v_count
k = [1]
def get_order(v):
order[v] = 1
for dest in edges[v]:
if order[dest] == 0:
get_order(dest)
order[v] = k[0]
k[0] += 1
def get_components(v):
order[v] = 0
return [v] + [_v for dest in r_edges[v] if order[dest] > 0 for _v in get_components(dest)]
[None for v in range(v_count) if order[v] == 0 and get_order(v)]
return [get_components(v) for v, _ in sorted(enumerate(order), key=lambda x: x[1], reverse=True) if order[v] > 0]
if __name__ == "__main__":
solve()
``` | instruction | 0 | 39,579 | 13 | 79,158 |
Yes | output | 1 | 39,579 | 13 | 79,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1
Submitted Solution:
```
def main():
nvertices, nedges = map(int, input().split())
Adj = [[] for i in range(nvertices)]
Adjrev = [[] for i in range(nvertices)]
for i in range(nedges):
s, t = map(int, input().split())
Adj[s].append(t)
Adjrev[t].append(s)
component_ids = [-1] * nvertices
id = 0
for u in range(nvertices):
if component_ids[u] != -1:
continue
s1 = set()
s2 = set()
visited1 = [0] * nvertices
visited2 = [0] * nvertices
dfs(u, Adj, visited1, s1)
dfs(u, Adjrev, visited2, s2)
for v in s1 & s2:
component_ids[v] = id
id += 1
Q = int(input())
for i in range(Q):
s, t = map(int, input().split())
if component_ids[s] == component_ids[t]:
print(1)
else:
print(0)
def dfs(u, Adj, visited, s):
visited[u] = 1
s.add(u)
for v in Adj[u]:
if visited[v]:
continue
dfs(v, Adj, visited, s)
return s
main()
``` | instruction | 0 | 39,580 | 13 | 79,160 |
No | output | 1 | 39,580 | 13 | 79,161 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1
Submitted Solution:
```
def main():
nvertices, nedges = map(int, input().split())
Adj = [[] for i in range(nvertices)]
Adjrev = [[] for i in range(nvertices)]
for i in range(nedges):
s, t = map(int, input().split())
Adj[s].append(t)
Adjrev[t].append(s)
component_ids = [-1] * nvertices
id = 0
for u in range(nvertices):
if component_ids[u] != -1:
continue
# s1 = set()
# s2 = set()
# visited1 = [0] * nvertices
# visited2 = [0] * nvertices
# dfs(u, Adj, visited1, s1)
# dfs(u, Adjrev, visited2, s2)
s1 = bfs(u, Adj)
s2 = bfs(u, Adjrev)
for v in s1 & s2:
component_ids[v] = id
id += 1
Q = int(input())
for i in range(Q):
s, t = map(int, input().split())
if component_ids[s] == component_ids[t]:
print(1)
else:
print(0)
def bfs(u, Adj):
visited = [0] * len(Adj)
que = [u]
s = set()
while que:
u = que.pop(0)
s.add(u)
visited[u] = True
for v in Adj[u]:
if not visited[v]:
que.append(v)
return s
# def dfs(u, Adj, visited, s):
# visited[u] = 1
# s.add(u)
# for v in Adj[u]:
# if visited[v]:
# continue
# dfs(v, Adj, visited, s)
# return s
main()
``` | instruction | 0 | 39,581 | 13 | 79,162 |
No | output | 1 | 39,581 | 13 | 79,163 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
output:
1
0
1
1
"""
import sys
from math import isinf
sys.setrecursionlimit(int(1e5))
def generate_adj_table(_v_info):
for v_detail in _v_info:
v_from, v_to = map(int, v_detail)
init_adj_table[v_from].append(v_to)
return init_adj_table
def Tarjan(current, low, dfn, scc_stack, in_scc_stack):
global timer
dfn[current] = low[current] = timer
timer += 1
scc_stack.append(current)
in_scc_stack[current] = True
current_scc_set = set()
for adj in adj_table[current]:
if not in_scc_stack[adj]:
Tarjan(adj, low, dfn, scc_stack, in_scc_stack)
low[current] = min(low[current], low[adj])
else:
low[current] = min(low[current], dfn[adj])
scc_candidate = -1
if dfn[current] == low[current]:
while scc_candidate != current:
scc_candidate = scc_stack.pop()
in_scc_stack[scc_candidate] = False
current_scc_set.add(scc_candidate)
init_scc_sets_list.append(current_scc_set)
return None
def scc_cluster():
dfn = [float('inf')] * vertices
low = [float('inf')] * vertices
scc_stack = list()
in_scc_stack = [False] * vertices
for v in range(vertices):
if not in_scc_stack[v]:
Tarjan(v, low, dfn, scc_stack, in_scc_stack)
return init_scc_sets_list
def solve(_scc_sets_list):
for question in q_list:
flag = False
ele1, ele2 = map(int, question)
for each in _scc_sets_list:
if (ele1 in each) and (ele2 in each):
flag = True
break
if flag:
print('1')
else:
print('0')
return None
if __name__ == '__main__':
_input = sys.stdin.readlines()
vertices, edges = map(int, _input[0].split())
v_info = map(lambda x: x.split(), _input[1:edges + 1])
q_num = int(_input[edges + 1])
q_list = map(lambda x: x.split(), _input[edges + 2:])
init_adj_table = tuple([] for _ in range(vertices))
adj_table = generate_adj_table(v_info)
timer = 0
init_scc_sets_list = []
scc_sets_list = scc_cluster()
solve(scc_sets_list)
``` | instruction | 0 | 39,582 | 13 | 79,164 |
No | output | 1 | 39,582 | 13 | 79,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
1
Submitted Solution:
```
def f_dfs(i):
global f_edges, counter
visited[i] = True
for edge in f_edges[i]:
if visited[edge]:
continue
f_dfs(edge)
finish_order[i] = (counter, i)
counter += 1
def b_dfs(i, group):
global b_edges, groups
visited[i] = True
groups[i] = group
for edge in b_edges[i]:
if visited[edge]:
continue
b_dfs(edge, group)
n, m = map(int, input().split())
f_edges = [set() for _ in range(n)]
b_edges = [set() for _ in range(n)]
for _ in range(m):
s, t = map(int, input().split())
f_edges[s].add(t)
b_edges[t].add(s)
visited = [False] * n
finish_order = [None] * n
counter = 0
for i in range(n):
if not visited[i]:
f_dfs(i)
visited = [False] * n
groups = [None] * n
group = 0
for d, i in sorted(finish_order, reverse=True):
if not visited[i]:
b_dfs(i, group)
group += 1
q = int(input())
while q:
q -= 1
u, v = map(int, input().split())
print(int(groups[u] == groups[v]))
``` | instruction | 0 | 39,583 | 13 | 79,166 |
No | output | 1 | 39,583 | 13 | 79,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a graph with n vertices, each of which has it's own point A_i = (x_i, y_i) with integer coordinates, a planar tree if:
* All points A_1, A_2, …, A_n are different and no three points lie on the same line.
* The graph is a tree, i.e. there are exactly n-1 edges there exists a path between any pair of vertices.
* For all pairs of edges (s_1, f_1) and (s_2, f_2), such that s_1 ≠ s_2, s_1 ≠ f_2, f_1 ≠ s_2, and f_1 ≠ f_2, the segments A_{s_1} A_{f_1} and A_{s_2} A_{f_2} don't intersect.
Imagine a planar tree with n vertices. Consider the convex hull of points A_1, A_2, …, A_n. Let's call this tree a spiderweb tree if for all 1 ≤ i ≤ n the following statements are true:
* All leaves (vertices with degree ≤ 1) of the tree lie on the border of the convex hull.
* All vertices on the border of the convex hull are leaves.
An example of a spiderweb tree:
<image>
The points A_3, A_6, A_7, A_4 lie on the convex hull and the leaf vertices of the tree are 3, 6, 7, 4.
Refer to the notes for more examples.
Let's call the subset S ⊂ \{1, 2, …, n\} of vertices a subtree of the tree if for all pairs of vertices in S, there exists a path that contains only vertices from S. Note that any subtree of the planar tree is a planar tree.
You are given a planar tree with n vertexes. Let's call a partition of the set \{1, 2, …, n\} into non-empty subsets A_1, A_2, …, A_k (i.e. A_i ∩ A_j = ∅ for all 1 ≤ i < j ≤ k and A_1 ∪ A_2 ∪ … ∪ A_k = \{1, 2, …, n\}) good if for all 1 ≤ i ≤ k, the subtree A_i is a spiderweb tree. Two partitions are different if there exists some set that lies in one parition, but not the other.
Find the number of good partitions. Since this number can be very large, find it modulo 998 244 353.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the number of vertices in the tree.
The next n lines each contain two integers x_i, y_i (-10^9 ≤ x_i, y_i ≤ 10^9) — the coordinates of i-th vertex, A_i.
The next n-1 lines contain two integers s, f (1 ≤ s, f ≤ n) — the edges (s, f) of the tree.
It is guaranteed that all given points are different and that no three of them lie at the same line. Additionally, it is guaranteed that the given edges and coordinates of the points describe a planar tree.
Output
Print one integer — the number of good partitions of vertices of the given planar tree, modulo 998 244 353.
Examples
Input
4
0 0
0 1
-1 -1
1 -1
1 2
1 3
1 4
Output
5
Input
5
3 2
0 -3
-5 -3
5 -5
4 5
4 2
4 1
5 2
2 3
Output
8
Input
6
4 -5
0 1
-2 8
3 -10
0 -1
-4 -5
2 5
3 2
1 2
4 6
4 2
Output
13
Input
8
0 0
-1 2
-2 5
-5 1
1 3
0 3
2 4
-1 -4
1 2
3 2
5 6
4 2
1 5
5 7
5 8
Output
36
Note
<image> The picture for the first sample.
In the first test case, all good partitions are:
1. \{1\}, \{2\}, \{3\}, \{4\};
2. \{1, 2\}, \{3\}, \{4\};
3. \{1, 3\}, \{2\}, \{4\};
4. \{1, 4\}, \{2\}, \{3\};
5. \{1, 2, 3, 4\}.
The partition \{1, 2, 3\}, \{4\} isn't good, because the subtree \{1, 2, 3\} isn't spiderweb tree, since the non-leaf vertex 1 lies on the convex hull.
The partition \{2, 3, 4\}, \{1\} isn't good, because the subset \{2, 3, 4\} isn't a subtree.
<image> The picture for the second sample.
In the second test case, the given tree isn't a spiderweb tree, because the leaf vertex 1 doesn't lie on the convex hull. However, the subtree \{2, 3, 4, 5\} is a spiderweb tree.
<image> The picture for the third sample. <image> The picture for the fourth sample.
In the fourth test case, the partition \{1, 2, 3, 4\}, \{5, 6, 7, 8\} is good because all subsets are spiderweb subtrees.
Submitted Solution:
```
import time
start = time.time()
def Left_index(points):
minn = 0
for i in range(1,len(points)):
if points[i][0] < points[minn][0]: minn = i
elif points[i][0] == points[minn][0] and points[i][1] > points[minn][1]: minn = i
return minn
def orientation(p, q, r):
val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
if val >= 0: return [0,1][val]
else: return 2
def ConvexHull(points):
n = len(points)
if n < len(points): return
l = Left_index(points)
hull, p,q = [], l, 0
while(p != l):
hull.append(p)
q = (p + 1) % n
for i in range(n):
if(orientation(points[p], points[i], points[q]) == 2): q = i
p = q
return hull
# =============================================================
n=int(input())
points = [list(map(int,input().split())) for i in range(n)]
edg = [set(map(int,input().split())) for i in range(n-1)]
# n=6
# points = [[4,-5],[0,1],[-2,8],[3,-10],[0,-1],[-4,-5]]
# edg = [{2,5},{3,2},{1,2},{4,6},{4,2}]
# edg2 = [(2,5),(3,2),(1,2),(4,6),(4,2)]
# ralation = {i:[] for i in range(1,n+1)}
# n=10
# points = [[454255579,331696483],[523479353,335942331],[843509133,239933472],[-478324093,517801491],[-728568205,-215176783],[-572952472,-57135432],[698705044,-411724797],[-91430650,991000615],[729689644,-324673385],[-630363651,372492177]]
# edg = [{2,8},{3,9},{9,4},{5,7},{5,9},{6,4},{9,8},{3,1},{6,10}]
# edg2 = [(2,8),(3,9),(9,4),(5,7),(5,9),(6,4),(9,8),(3,1),(6,10)]
# ralation = {i:[] for i in range(1,n+1)}
TrueGraph = set()
# for i in edg2:
# ralation[i[0]].append(i[1])
# ralation[i[1]].append(i[0])
# print(ralation)
def partition(collection):
if len(collection) == 1:
yield (collection,)
return
first = collection[0]
for smaller in partition(collection[1:]):
# insert `first` in each of the subpartition's subsets
for n, subset in enumerate(smaller):
yield smaller[:n] + ((first,) + subset,) + smaller[n+1:]
# put `first` in its own subset
yield ((first,),) + smaller
def degree(a, g): return sum(a in x for x in g)
def tree(edg, sub):
Point = [points[i-1] for i in sub]
Lpoint = len(Point)
if Lpoint>2: hull = set(map(lambda x: x+1, ConvexHull(Point)))
elif Lpoint==1: hull = {1}
else: hull = {1,2}
EDG = []
for i in edg:
if i.issubset(set(sub)):
EDG.append(i)
Leef = {i+1 for i in range(len(sub)) if degree(sub[i], EDG)<=1}
# print(sub, Leef, hull)
if Leef==hull and len(EDG)==len(sub)-1:
return True
return False
def check(p):
for i in p:
if i not in TrueGraph and tree(edg, i)==False: return False
TrueGraph.add(i)
return True
count = 0
something = tuple(range(1,n+1))
for i in partition(something):
# print(i, check(i))
if check(i): count+=1
print(count)
print(time.time()-start)
``` | instruction | 0 | 39,752 | 13 | 79,504 |
No | output | 1 | 39,752 | 13 | 79,505 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a graph with n vertices, each of which has it's own point A_i = (x_i, y_i) with integer coordinates, a planar tree if:
* All points A_1, A_2, …, A_n are different and no three points lie on the same line.
* The graph is a tree, i.e. there are exactly n-1 edges there exists a path between any pair of vertices.
* For all pairs of edges (s_1, f_1) and (s_2, f_2), such that s_1 ≠ s_2, s_1 ≠ f_2, f_1 ≠ s_2, and f_1 ≠ f_2, the segments A_{s_1} A_{f_1} and A_{s_2} A_{f_2} don't intersect.
Imagine a planar tree with n vertices. Consider the convex hull of points A_1, A_2, …, A_n. Let's call this tree a spiderweb tree if for all 1 ≤ i ≤ n the following statements are true:
* All leaves (vertices with degree ≤ 1) of the tree lie on the border of the convex hull.
* All vertices on the border of the convex hull are leaves.
An example of a spiderweb tree:
<image>
The points A_3, A_6, A_7, A_4 lie on the convex hull and the leaf vertices of the tree are 3, 6, 7, 4.
Refer to the notes for more examples.
Let's call the subset S ⊂ \{1, 2, …, n\} of vertices a subtree of the tree if for all pairs of vertices in S, there exists a path that contains only vertices from S. Note that any subtree of the planar tree is a planar tree.
You are given a planar tree with n vertexes. Let's call a partition of the set \{1, 2, …, n\} into non-empty subsets A_1, A_2, …, A_k (i.e. A_i ∩ A_j = ∅ for all 1 ≤ i < j ≤ k and A_1 ∪ A_2 ∪ … ∪ A_k = \{1, 2, …, n\}) good if for all 1 ≤ i ≤ k, the subtree A_i is a spiderweb tree. Two partitions are different if there exists some set that lies in one parition, but not the other.
Find the number of good partitions. Since this number can be very large, find it modulo 998 244 353.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the number of vertices in the tree.
The next n lines each contain two integers x_i, y_i (-10^9 ≤ x_i, y_i ≤ 10^9) — the coordinates of i-th vertex, A_i.
The next n-1 lines contain two integers s, f (1 ≤ s, f ≤ n) — the edges (s, f) of the tree.
It is guaranteed that all given points are different and that no three of them lie at the same line. Additionally, it is guaranteed that the given edges and coordinates of the points describe a planar tree.
Output
Print one integer — the number of good partitions of vertices of the given planar tree, modulo 998 244 353.
Examples
Input
4
0 0
0 1
-1 -1
1 -1
1 2
1 3
1 4
Output
5
Input
5
3 2
0 -3
-5 -3
5 -5
4 5
4 2
4 1
5 2
2 3
Output
8
Input
6
4 -5
0 1
-2 8
3 -10
0 -1
-4 -5
2 5
3 2
1 2
4 6
4 2
Output
13
Input
8
0 0
-1 2
-2 5
-5 1
1 3
0 3
2 4
-1 -4
1 2
3 2
5 6
4 2
1 5
5 7
5 8
Output
36
Note
<image> The picture for the first sample.
In the first test case, all good partitions are:
1. \{1\}, \{2\}, \{3\}, \{4\};
2. \{1, 2\}, \{3\}, \{4\};
3. \{1, 3\}, \{2\}, \{4\};
4. \{1, 4\}, \{2\}, \{3\};
5. \{1, 2, 3, 4\}.
The partition \{1, 2, 3\}, \{4\} isn't good, because the subtree \{1, 2, 3\} isn't spiderweb tree, since the non-leaf vertex 1 lies on the convex hull.
The partition \{2, 3, 4\}, \{1\} isn't good, because the subset \{2, 3, 4\} isn't a subtree.
<image> The picture for the second sample.
In the second test case, the given tree isn't a spiderweb tree, because the leaf vertex 1 doesn't lie on the convex hull. However, the subtree \{2, 3, 4, 5\} is a spiderweb tree.
<image> The picture for the third sample. <image> The picture for the fourth sample.
In the fourth test case, the partition \{1, 2, 3, 4\}, \{5, 6, 7, 8\} is good because all subsets are spiderweb subtrees.
Submitted Solution:
```
# import time
# start = time.time()
def Left_index(points):
minn = 0
for i in range(1,len(points)):
if points[i][0] < points[minn][0]: minn = i
elif points[i][0] == points[minn][0] and points[i][1] > points[minn][1]: minn = i
return minn
def orientation(p, q, r):
val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
if val >= 0: return [0,1][val]
else: return 2
def ConvexHull(points):
n = len(points)
if n < len(points): return
l = Left_index(points)
hull, p,q = [], l, 0
while(p != l):
hull.append(p)
q = (p + 1) % n
for i in range(n):
if(orientation(points[p], points[i], points[q]) == 2): q = i
p = q
return hull
# =============================================================
n=int(input())
points = [list(map(int,input().split())) for i in range(n)]
edg = [set(map(int,input().split())) for i in range(n-1)]
# n=6
# points = [[4,-5],[0,1],[-2,8],[3,-10],[0,-1],[-4,-5]]
# edg = [{2,5},{3,2},{1,2},{4,6},{4,2}]
# edg2 = [(2,5),(3,2),(1,2),(4,6),(4,2)]
# ralation = {i:[] for i in range(1,n+1)}
# n=10
# points = [[454255579,331696483],[523479353,335942331],[843509133,239933472],[-478324093,517801491],[-728568205,-215176783],[-572952472,-57135432],[698705044,-411724797],[-91430650,991000615],[729689644,-324673385],[-630363651,372492177]]
# edg = [{2,8},{3,9},{9,4},{5,7},{5,9},{6,4},{9,8},{3,1},{6,10}]
# edg2 = [(2,8),(3,9),(9,4),(5,7),(5,9),(6,4),(9,8),(3,1),(6,10)]
# ralation = {i:[] for i in range(1,n+1)}
TrueGraph = set()
# for i in edg2:
# ralation[i[0]].append(i[1])
# ralation[i[1]].append(i[0])
# print(ralation)
def partition(collection):
if len(collection) == 1:
yield (collection,)
return
first = collection[0]
for smaller in partition(collection[1:]):
# insert `first` in each of the subpartition's subsets
for n, subset in enumerate(smaller):
yield smaller[:n] + ((first,) + subset,) + smaller[n+1:]
# put `first` in its own subset
yield ((first,),) + smaller
def degree(a, g): return sum(a in x for x in g)
def tree(edg, sub):
Point = [points[i-1] for i in sub]
Lpoint = len(Point)
if Lpoint>2: hull = set(map(lambda x: x+1, ConvexHull(Point)))
elif Lpoint==1: hull = {1}
else: hull = {1,2}
EDG = []
for i in edg:
if i.issubset(set(sub)):
EDG.append(i)
Leef = {i+1 for i in range(len(sub)) if degree(sub[i], EDG)<=1}
# print(sub, Leef, hull)
if Leef==hull and len(EDG)==len(sub)-1:
return True
return False
def check(p):
for i in p:
if i not in TrueGraph and tree(edg, i)==False: return False
TrueGraph.add(i)
return True
count = 0
something = tuple(range(1,n+1))
for i in partition(something):
# print(i, check(i))
if check(i): count+=1
print(count)
# print(time.time()-start)
``` | instruction | 0 | 39,753 | 13 | 79,506 |
No | output | 1 | 39,753 | 13 | 79,507 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 40,046 | 13 | 80,092 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
def parse(i):
t = input().split()
return int(t[0]), int(t[1]), i
n, m = [int(x) for x in input().split()]
list = [parse(i) for i in range(m)]
list.sort(key=lambda x: (x[0], -x[1]))
# print(list)
f = 0
t = 1
fakeFrom = 1
fakeTo = 2
graph = []
for i in range(m):
if list[i][1] == 1:
graph.append((f + 1, t + 1, list[i][2]))
t += 1
else:
graph.append((fakeFrom + 1, fakeTo + 1, list[i][2]))
if fakeTo >= t:
print(-1)
exit(0)
fakeFrom += 1
if fakeFrom == fakeTo:
fakeFrom = 1
fakeTo += 1
# if fakeTo >= t:
# print(-1)
# exit(0)
# print(graph)
graph.sort(key=lambda x: x[2])
for x in graph:
print(x[0], x[1])
``` | output | 1 | 40,046 | 13 | 80,093 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 40,047 | 13 | 80,094 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
def next():
global fr
global to
fr += 1
if fr == to:
fr = 2
to += 1
n, m = tuple(map(int, input().split()))
lenths = []
for i in range(m):
a, b = tuple(map(int, input().split()))
if b == 1: b = 0
else: b = 1
lenths.append((a, b, i))
res = [(0, 0)] * m
fr = 2
to = 3
my = 0
len_sorted = sorted(lenths)
f = 1
for i in range(m):
#print(my, fr, to)
if len_sorted[i][1] == 0:
res[len_sorted[i][2]] = (1, my + 2)
my += 1
else:
if my <= to - 2:
f = 0
break
res[len_sorted[i][2]] = (fr, to)
next()
if my + 1 > n:
f = 0
break
if f:
for i in range(m):
print(' '.join(list(map(str, res[i]))))
else:
print('-1')
``` | output | 1 | 40,047 | 13 | 80,095 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 40,048 | 13 | 80,096 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from heapq import *
def main():
n,m=map(int,input().split())
a=[list(map(int,input().split())) for _ in range(m)]
edges,j,b=[[]]*m,1,sorted(range(m),key=lambda x:a[x][0]*10000000000-a[x][1])
c=[]
for i in range(1,n-1):
c.append((i+2,i))
heapify(c)
for i in b:
if a[i][1]:
edges[i]=[j,j+1]
j+=1
else:
if not c:
print(-1)
return
z=heappop(c)
if j<z[0]:
print(-1)
return
else:
edges[i]=[z[1],z[0]]
if z[0]+1<=n:
heappush(c,(z[0]+1,z[1]))
for i in edges:
print(*i)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 40,048 | 13 | 80,097 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 40,049 | 13 | 80,098 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from heapq import *
def main():
n,m=map(int,input().split())
a=[list(map(int,input().split())) for _ in range(m)]
edges,j,b=[[]]*m,1,sorted(range(m),key=lambda x:a[x][0]*10000000000-a[x][1])
c=[]
for i in range(1,n-1):
c.append((i+2,i))
heapify(c)
for i in b:
if a[i][1]:
edges[i]=[j,j+1]
j+=1
else:
if not c:
print(-1)
return
z=c[0]
heappop(c)
if j<z[0]:
print(-1)
return
else:
edges[i]=[z[1],z[0]]
if z[0]+1<=n:
heappush(c,(z[0]+1,z[1]))
for i in edges:
print(*i)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 40,049 | 13 | 80,099 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 40,050 | 13 | 80,100 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
__author__ = 'MoonBall'
import sys
import functools
# sys.stdin = open('data/D.in', 'r')
T = 1
def process():
N, M = list(map(int, input().split()))
e = []
for _ in range(M): e.append(list(map(int, input().split())) + [_])
e = sorted(e, key=functools.cmp_to_key(lambda x, y: y[1] - x[1] if x[0] == y[0] else x[0] - y[0]))
ans = [0] * M
# print(e)
i = 3
j = 1
has = 1
ok = True
for _e in e:
if _e[1] == 1:
has = has + 1
ans[_e[2]] = (has, has - 1)
else:
if has < i:
ok = False
else:
ans[_e[2]] = (i, j)
if j == i - 2:
i = i + 1
j = 1
else:
j = j + 1
if not ok:
print(-1)
else:
for u, v in ans: print(u, v)
for _ in range(T):
process()
``` | output | 1 | 40,050 | 13 | 80,101 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 40,051 | 13 | 80,102 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
import sys
from operator import itemgetter
lines = sys.stdin.readlines()
n, m = map(int, lines[0].split(' '))
def build_edge(i, row):
parts = row.split(' ')
return (int(parts[0]), int(parts[1]), i)
def edge_key(a):
return (a[0], -a[1])
edges = [build_edge(i, row) for i, row in enumerate(lines[1:])]
edges = sorted(edges, key=edge_key)
x, y = 1, 2
vertex = 1
color = [0 for x in range(n)]
color[0] = 1 # root of tree
ans = []
for weight, used, index in edges:
if used == 1:
color[vertex] = 1
ans.append((0, vertex, index))
vertex += 1
else:
if color[x] != 1 or color[y] != 1:
print(-1)
exit(0)
ans.append((x,y,index))
x += 1
if x == y:
x = 1
y += 1
ans = sorted(ans, key=itemgetter(2))
for edge in ans:
print("%s %s" % (edge[0]+1, edge[1]+1))
``` | output | 1 | 40,051 | 13 | 80,103 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.