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.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root. | instruction | 0 | 68,166 | 13 | 136,332 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from collections import defaultdict
d=defaultdict(list)
n,m=map(int,input().split())
for i in range(m):
a,b=map(int,input().split())
a-=1
b-=1
d[a].append(b)
d[b].append(a)
vis=[0]*n
q=[0]
vis[0]=1
while q:
t=q.pop(0)
for i in d[t]:
if not vis[i]:
vis[i]=1
q.append(i)
if sum(vis)==n and m==n:
print('FHTAGN!')
else:
print('NO')
``` | output | 1 | 68,166 | 13 | 136,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root. | instruction | 0 | 68,167 | 13 | 136,334 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
parent = dict()
ranks = dict()
def make_set(N):
global parent, ranks
parent = [i for i in range(N + 5)]
ranks = [0 for i in range(N + 5)]
def find_set(u):
while u != parent[u]:
u = parent[u]
return u
# if parent[u] != u:
# parent[u] = find_set(parent[u])
# return parent[u]
def union_set(u, v):
up = find_set(u)
vp = find_set(v)
parent[up] = vp
# if up == vp:
# return
# if ranks[up] > ranks[vp]:
# parent[vp] = up
# elif ranks[up] < ranks[vp]:
# parent[up] = vp
# else:
# parent[up] = vp
# ranks[vp] += 1
m, n = map(int, input().split())
if m != n:
print('NO')
exit()
make_set(m)
for i in range(m):
a, b = map(int, input().split())
union_set(a, b)
top_parent = find_set(1)
for i in range(2, m):
if find_set(i) != top_parent:
print('NO')
exit()
print('FHTAGN!')
``` | output | 1 | 68,167 | 13 | 136,335 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root.
Submitted Solution:
```
n, m = [int(i) for i in input().split()]
adj = [[] for i in range(n+1)]
seen = [False for i in range(n+1)]
pai = [0 for i in range(n+1)]
ciclos = 0
def dfs (u):
seen[u] = True
global ciclos
for v in adj[u]:
if not seen[v]:
pai[v] = u
dfs(v)
elif v != pai[u]:
ciclos += 1
for i in range(m):
x, y = [int(i) for i in input().split()]
adj[x].append(y)
adj[y].append(x)
dfs(1)
conexo = True
for i in range(1, n+1, 1):
if not seen[i]:
conexo = False
if not conexo:
print('NO')
elif ciclos/2 == 1:
print('FHTAGN!')
else:
print('NO')
exit(0)
``` | instruction | 0 | 68,168 | 13 | 136,336 |
Yes | output | 1 | 68,168 | 13 | 136,337 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root.
Submitted Solution:
```
import sys
def todos_visitados(list):
return len(list) == sum(list)
def um_componente(vertices, n):
vizinhos = [0]
visitado = [False] * n
while len(vizinhos) != 0:
v = vizinhos.pop()
visitado[v] = True
for u in vertices[v]:
if not visitado[u]:
vizinhos.append(u)
return todos_visitados(visitado)
def main():
n, m = [int(x) for x in input().split()]
vertices = [[] for _ in range(n)]
for _ in range(m):
v, u = [int(x) - 1 for x in input().split()]
vertices[v].append(u)
vertices[u].append(v)
somente_um_ciclo = n == m and um_componente(vertices, n)
print("FHTAGN!") if somente_um_ciclo else print("NO")
if __name__ == '__main__':
main()
def testin1(capsys):
sys.stdin = open("in1")
main()
out, err = capsys.readouterr()
sys.stin = sys.__stdin__
expected = open("in1_expeted").read()
assert out == expected
def testin2(capsys):
sys.stdin = open("in2")
main()
out, err = capsys.readouterr()
sys.stin = sys.__stdin__
expected = open("in2_expeted").read()
assert out == expected
def testin3(capsys):
sys.stdin = open("in3")
main()
out, err = capsys.readouterr()
sys.stin = sys.__stdin__
expected = open("in3_expeted").read()
assert out == expected
def testin4(capsys):
sys.stdin = open("in4")
main()
out, err = capsys.readouterr()
sys.stin = sys.__stdin__
expected = open("in4_expeted").read()
assert out == expected
def testin5(capsys):
sys.stdin = open("in5")
main()
out, err = capsys.readouterr()
sys.stin = sys.__stdin__
expected = open("in5_expeted").read()
assert out == expected
def testin6(capsys):
sys.stdin = open("in6")
main()
out, err = capsys.readouterr()
sys.stin = sys.__stdin__
expected = open("in6_expeted").read()
assert out == expected
#https://stackoverflow.com/questions/26561822/pytest-capsys-checking-output-and-getting-it-reported
#https://stackoverflow.com/questions/35851323/pytest-how-to-test-a-function-with-input-call
``` | instruction | 0 | 68,169 | 13 | 136,338 |
Yes | output | 1 | 68,169 | 13 | 136,339 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root.
Submitted Solution:
```
n, m = [int(i) for i in input().split()]
adj = [[] for i in range(n+1)]
seen = [False for i in range(n+1)]
pai = [0 for i in range(n+1)]
ciclos = 0
def dfs (u):
seen[u] = True
global ciclos
for v in adj[u]:
if not seen[v]:
pai[v] = u
dfs(v)
elif v != pai[u]:
ciclos += 1
for i in range(m):
x, y = [int(i) for i in input().split()]
adj[x].append(y)
adj[y].append(x)
dfs(1)
conexo = True
for i in range(1, n+1, 1):
if not seen[i]:
conexo = False
if conexo and ciclos/2 == 1:
print('FHTAGN!')
else:
print('NO')
exit(0)
``` | instruction | 0 | 68,170 | 13 | 136,340 |
Yes | output | 1 | 68,170 | 13 | 136,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root.
Submitted Solution:
```
def unionSet(u,v):
up = findSet(u)
vp = findSet(v)
if up == vp:
return
else:
parent[up] = vp
# cnt[vp] += cnt[up]
def findSet(u):
if parent[u] != u:
parent[u] = findSet(parent[u])
return parent[u]
n,m = map(int,input().split())
if n != m:
print('NO')
exit()
parent = list(range(n+1))
for _ in range(m):
u , v = map(int,input().split())
unionSet(u,v) # O(n)
cnt = 0
for i in range(1,n+1):
if parent[i] == i:
cnt += 1
if cnt > 1:
print('NO')
else:
print('FHTAGN!')
``` | instruction | 0 | 68,171 | 13 | 136,342 |
Yes | output | 1 | 68,171 | 13 | 136,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root.
Submitted Solution:
```
n, m = map(int, input().split())
#if n < 3 or n != m: # minimo 3 vertices para un circulo
# print('NO') # todo vertice debe tener un edge
V = [[] for i in range(n+1)] #Armado de lista para conexiones de vertices
F = set() #se ocupa set() para operaciones
#e, f = [[] for i in range(n + 1)], set()
for j in range(m):
x, y = map(int, input().split())
V[x].append(y) #conexion de x con y
V[y].append(x) #conexion de y con x
def DFS(x):
F.add(x)
for y in V[x]:
if not y in F:
DFS(y)
DFS(1)
print('FHTAGN!' if len(F) == n else 'NO')
``` | instruction | 0 | 68,172 | 13 | 136,344 |
No | output | 1 | 68,172 | 13 | 136,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10 ** 6)
class Edge:
def __init__(self, u, v, w=0):
self.frm = u
self.to = v
self.weight = w
def __repr__(self):
return "{frm} - {to}: {weight}".format(frm=self.frm, to=self.to, weight=self.weight)
def __eq__(self, other):
return self.frm == other.frm and self.to == other.to \
or self.frm == other.to and self.to == other.frm
class Graph:
def __init__(self, num_vertex):
self.num_vertex = num_vertex
self.adj_list = [[] for _ in range(num_vertex)]
def add_edge(self, u, v, w=0):
self.adj_list[u].append(Edge(u, v, w))
self.adj_list[v].append(Edge(v, u, w))
def adj(self, v):
return self.adj_list[v]
def edges(self):
all_edges = []
for v in range(self.num_vertex):
for e in self.adj_list[v]:
if e not in all_edges:
all_edges.append(e)
return all_edges
class DisjointSetUnion:
def __init__(self, num_nodes):
self.id = [i for i in range(num_nodes)]
self.parent = [i for i in range(num_nodes)]
self.size = [1 for _ in range(num_nodes)]
self.cnt = num_nodes
def find(self, p):
while p != self.parent[p]:
p = self.parent[p]
return p
def count(self):
return self.cnt
def connected(self, p, q):
return self.find(p) == self.find(q)
def union(self, p, q):
root_p = self.find(p)
root_q = self.find(q)
if root_p == root_q: return
if self.size[root_p] < self.size[root_q]:
self.parent[root_p] = root_q
self.size[root_q] += self.size[root_p]
else:
self.parent[root_q] = root_p
self.size[root_p] += self.size[root_q]
self.cnt -= 1
dsu = None
graph = None
def main():
sc = sys.stdin
line = sc.readline().strip()
n, m = map(int, line.split())
global graph, dsu
cnt_cycle = 0
graph = Graph(n)
dsu = DisjointSetUnion(n)
for i in range(m):
line = sc.readline().strip()
x, y = map(int, line.split())
x, y = x-1, y-1
graph.add_edge(x, y)
# cycle count
if dsu.connected(x, y):
cnt_cycle += 1
else:
dsu.union(x, y)
detected = False
if cnt_cycle == 1:
for v in range(n):
if len(graph.adj(v)) > 2:
detected = True
print("FHTAGN!" if detected else "NO")
if __name__ == '__main__':
main()
``` | instruction | 0 | 68,173 | 13 | 136,346 |
No | output | 1 | 68,173 | 13 | 136,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root.
Submitted Solution:
```
from collections import *
from sys import stdin
def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return list(stdin.readline()[:-1])
class disjointset:
def __init__(self, n):
self.rank, self.parent, self.n, self.nsets, self.edges, self.gdict = [0] * (n + 1), [0] * (n + 1), n, [1] * (
n + 1), [], defaultdict(list)
self.add_nodes(n)
def add_nodes(self, n):
for i in range(1, n + 1):
self.parent[i], self.nsets[i] = i, 1
def add_edge(self, node1, node2, w=None):
self.gdict[node1].append(node2)
self.gdict[node2].append(node1)
self.edges.append([node1, node2])
def dfsUtil(self, v, c):
stack = [v]
while (stack):
s = stack.pop()
for i in self.gdict[s]:
if not self.visit[i]:
stack.append(i)
self.visit[i] = 1
self.color[i] = c
# dfs for graph
def dfs(self):
self.cnt, self.visit, self.color = 0, defaultdict(int), defaultdict(int)
for i in range(1, n + 1):
if self.visit[i] == 0:
self.dfsUtil(i, self.cnt)
self.cnt += 1
def find(self, x):
result, stack = self.parent[x], [x]
while result != x:
x = result
result = self.parent[x]
stack.append(x)
while stack:
self.parent[stack.pop()] = result
return result
def union(self, x, y):
xpar, ypar = self.find(x), self.find(y)
# already union
if xpar == ypar:
return
# perform union by rank
par, child = 0, 0
if self.rank[xpar] < self.rank[ypar]:
par, child = ypar, xpar
elif self.rank[xpar] > self.rank[ypar]:
par, child = xpar, ypar
else:
par, child = xpar, ypar
self.rank[xpar] += 1
self.parent[child] = par
self.nsets[par] += self.nsets[child]
self.n -= 1
def kruskal(self):
result, edges, self.cycle = [], self.edges, defaultdict(int)
# loop over v-1
for i in range(len(edges)):
u, v = edges[i]
upar, vpar = self.find(u), self.find(v)
# no cycle
if upar != vpar:
result.append(edges[i])
self.union(upar, vpar)
else:
if self.cycle[self.color[upar]] == 0:
self.cycle[self.color[upar]] += 1
else:
exit(print('NO'))
n, m = arr_inp(1)
dis, ans = disjointset(n), 0
for i in range(m):
u, v = arr_inp(1)
dis.add_edge(u, v)
dis.dfs()
dis.kruskal()
# print(dis.cycle, dis.n)
print('FHTAGN!' if dis.n == len(dis.cycle) and sum(dis.cycle.values()) == dis.n else 'NO')
``` | instruction | 0 | 68,174 | 13 | 136,348 |
No | output | 1 | 68,174 | 13 | 136,349 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root.
Submitted Solution:
```
from collections import *
from sys import stdin
def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return list(stdin.readline()[:-1])
class disjointset:
def __init__(self, n):
self.rank, self.parent, self.n, self.nsets, self.edges = [0] * (n + 1), [0] * (n + 1), n, [1] * (
n + 1), defaultdict(int)
self.add_nodes(n)
def add_nodes(self, n):
for i in range(1, n + 1):
self.parent[i], self.nsets[i] = i, 1
def find(self, x):
result, stack = self.parent[x], [x]
while result != x:
x = result
result = self.parent[x]
stack.append(x)
while stack:
self.parent[stack.pop()] = result
return result
def union(self, x, y):
xpar, ypar = self.find(x), self.find(y)
# already union
if xpar == ypar:
self.edges[xpar] += 1
return 1
# perform union by rank
par, child = 0, 0
if self.rank[xpar] < self.rank[ypar]:
par, child = ypar, xpar
elif self.rank[xpar] > self.rank[ypar]:
par, child = xpar, ypar
else:
par, child = xpar, ypar
self.rank[xpar] += 1
self.parent[child] = par
self.nsets[par] += self.nsets[child]
self.edges[par] += self.edges[child] + 1
return 0
n, m = arr_inp(1)
dis, ans = disjointset(n), 0
for i in range(m):
u, v = arr_inp(1)
dis.union(u, v)
for i in range(1, n + 1):
if dis.parent[i] == i:
if dis.edges[i] >= dis.nsets[i]:
ans = 1
else:
ans = 0
break
# print(dis.edges, dis.nsets)
print('FHTAGN!' if ans else 'NO')
``` | instruction | 0 | 68,175 | 13 | 136,350 |
No | output | 1 | 68,175 | 13 | 136,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 68,242 | 13 | 136,484 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
import collections as cc
import sys
input=sys.stdin.readline
#sys.setrecursionlimit(10**9)
I=lambda:list(map(int,input().split()))
n,m=I()
g=[set() for i in range(n+1)]
xx=[0]*(n+1)
for i in range(m):
x,y=I()
g[x].add(y)
g[y].add(x)
parent=[i for i in range(n+1)]
def find(x):
while x!=parent[x]:
x=parent[x]
return x
def union(x,y):
a=find(x)
b=find(y)
if a!=b:
parent[a]=parent[b]=min(a,b)
ff=cc.defaultdict(int)
used=cc.defaultdict(int)
for i in range(1,n+1):
if find(i)==i:
for j in range(1,n+1):
if j not in g[i]:
g[i]&=g[j]
for j in range(1,n+1):
if j not in g[i]:
union(i,j)
print(len(set([find(i) for i in range(1,n+1)]))-1)
``` | output | 1 | 68,242 | 13 | 136,485 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 68,243 | 13 | 136,486 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
# from sys import stdin
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# l = list(map(int,input().split()))
import sys
sys.setrecursionlimit(10**9)
n,m = map(int,input().split())
hash = defaultdict(set)
for i in range(m):
a,b = map(int,input().split())
hash[a].add(b)
hash[b].add(a)
count = 0
un = {i+1 for i in range(n)}
while un:
queue = {un.pop()}
while queue:
z = queue.pop()
nxt = [u for u in un if u not in hash[z]]
un.difference_update(nxt)
queue.update(nxt)
count+=1
print(count-1)
``` | output | 1 | 68,243 | 13 | 136,487 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 68,244 | 13 | 136,488 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))
sys.setrecursionlimit(10**5)
n,m=I()
g=[set() for i in range(n)]
for i in range(m):
u,v=I()
g[u-1].add(v-1)
g[v-1].add(u-1)
p=[i for i in range(n)]
def find(x):
while x!=p[x]:
x=p[x]
return x
def union(a,b):
x=find(a)
y=find(b)
p[y]=x
for i in range(n):
if p[i]==i:
for j in range(n):
if j not in g[i]:
g[i]&=g[j]
for j in range(n):
if j not in g[i]:
union(i,j)
print(len(set([find(i) for i in range(n)]))-1)
``` | output | 1 | 68,244 | 13 | 136,489 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 68,245 | 13 | 136,490 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
n, m = map(int, input().split())
inp = set()
for _ in range(m):
a, b = map(int, input().split())
inp.add((a - 1, b - 1))
inp.add((b - 1, a - 1))
unc = set(range(n))
ans = -1
for i in range(n):
if i in unc:
ans += 1
unc.remove(i)
stack = [i]
while stack:
j = stack.pop()
for k in tuple(unc):
if (j, k) not in inp:
unc.remove(k)
stack.append(k)
print(ans)
``` | output | 1 | 68,245 | 13 | 136,491 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 68,246 | 13 | 136,492 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
import sys
import queue
class UF(object):
def __init__(self, n):
self.arr = list(range(n+1))
self.rank = [1]*(n+1)
def root(self, x):
if self.arr[x] != x:
self.arr[x] = self.root(self.arr[x])
return self.arr[x]
def union(self, x, y):
root_x = self.root(x)
root_y = self.root(y)
if root_x == root_y:
return
rank_x = self.rank[root_x]
rank_y = self.rank[root_y]
if rank_x >= rank_y:
self.rank[root_x] += rank_y
self.arr[root_y] = root_x
else:
self.rank[root_y] += rank_x
self.arr[root_x] = root_y
n, m = sys.stdin.readline().split(" ")
n = int(n)
m = int(m)
#Do note that every other edge that isn't present in this list already connects nodes.
def load_graph(m, n):
graph = {}
for i in range(1, n + 1):
graph[i] = set()
for _ in range(m):
i, j = sys.stdin.readline().split(" ")
i = int(i)
j = int(j)
graph[i].add(j)
graph[j].add(i)
return graph
def do(n, m):
uf = UF(n)
one_graph = load_graph(m, n)
sorted_graph = sorted(one_graph, key = lambda x: len(one_graph[x]))
if m < n - 1:
return 0
if m == n - 1 and n > 1:
if len(one_graph[sorted_graph[-1]]) == n - 1:
return 1
else:
return 0
remaining = set(range(1, n + 1))
for start in sorted_graph:
if len(remaining) == 0:
break
if start not in remaining:
continue
Q = queue.Queue()
Q.put(start)
remaining.remove(start)
while not Q.empty():
u = Q.get()
one_graph[u].intersection_update(remaining)
#intersection are things you need to process but can't yet
remaining.difference_update(one_graph[u])
for elt in remaining:
Q.put(elt)
uf.union(u, elt)
remaining = one_graph[u]
if len(remaining) == 0:
break
return len(set(uf.arr)) - 2
res = do(n, m)
sys.stdout.write(str(res)+"\n")
``` | output | 1 | 68,246 | 13 | 136,493 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 68,247 | 13 | 136,494 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
from collections import deque
from sys import stdin
global q,node,check
node,node2=[[]for i in range(100001)],[[]for i in range(100001)]
n,m=map(int,input().split())
small,big=[],[]
q=deque()
check=[0]*100001
def bfs():
while(len(q)>0):
p=q[0]
q.popleft()
for i in node[p]:
if check[i]==0:
check[i]=1
q.append(i)
for i in range(m):
a,b=map(int,stdin.readline().split())
node2[a].append(b)
node2[b].append(a)
for i in range(1,n+1):
if len(node2[i])<n//2:
big.append(i)
else:
small.append(i)
for i in small:
inn=[0]*100001
for i2 in node2[i]: inn[i2]=1
for i2 in range(1,n+1):
if i2!=i and inn[i2]==0:
node[i].append(i2)
node[i2].append(i)
for i in big:
check[i]=1
q.append(i)
bfs()
ans=0
for i in range(1,n+1):
if check[i]==0:
check[i]=1
q.append(i)
bfs()
ans+=1
if len(big)==0: ans-=1
print(ans)
``` | output | 1 | 68,247 | 13 | 136,495 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 68,248 | 13 | 136,496 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def main():
n,m = map(int,input().split())
path = [set() for _ in range(n)]
for _ in range(m):
a1,b1 = map(lambda xx:int(xx)-1,input().split())
path[a1].add(b1)
path[b1].add(a1)
mini,ind,cost = 10**9,-1,0
for i in range(n):
if len(path[i]) < mini:
mini,ind = len(path[i]),i
le = path[ind]
curr = [j for j in range(n) if j not in le]
while 1:
for i in curr:
le1 = set()
for r in le:
if r in path[i]:
le1.add(r)
else:
curr.append(r)
le = le1
if not len(le):
break
cost += 1
curr = [le.pop()]
print(cost)
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self,file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE))
self.newlines = b.count(b"\n")+(not b)
ptr = self.buffer.tell()
self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd,self.buffer.getvalue())
self.buffer.truncate(0),self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self,file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s:self.buffer.write(s.encode("ascii"))
self.read = lambda:self.buffer.read().decode("ascii")
self.readline = lambda:self.buffer.readline().decode("ascii")
sys.stdin,sys.stdout = IOWrapper(sys.stdin),IOWrapper(sys.stdout)
input = lambda:sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 68,248 | 13 | 136,497 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 68,249 | 13 | 136,498 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
from sys import stdin
def rl():
return [int(w) for w in stdin.readline().split()]
n,m = rl()
he = [set() for _ in range(n+1)]
for _ in range(m):
a,b = rl()
he[a].add(b)
he[b].add(a)
unvisited = set(range(1,n+1))
ccs = 0
while unvisited:
fringe = {unvisited.pop()}
while fringe:
v = fringe.pop()
nxt = [u for u in unvisited if u not in he[v]]
unvisited.difference_update(nxt)
fringe.update(nxt)
ccs += 1
print(ccs-1)
``` | output | 1 | 68,249 | 13 | 136,499 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
"""
Satwik_Tiwari ;) .
24th Sept , 2020 - Thursday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
# from itertools import *
# from heapq import *
from math import gcd, factorial,floor,ceil
from copy import deepcopy
from collections import deque
# from collections import Counter as counter # Counter(list) return a dict with {key: count}
# from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
# from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
mod = 10**9+7
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for pp in range(t):
solve(pp)
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#===============================================================================================
# code here ;))
def bfs(g,st,col,visited):
visited[st] = col
queue = deque([])
queue.append(st)
new = []
while(len(queue) != 0):
s = queue.popleft()
new.append(s)
for i in g[s]:
if(visited[i] == 0):
visited[i] = col
queue.append(i)
def solve(case):
n,m = sep()
edges = {}
for i in range(m):
a,b = sep()
a-=1
b-=1
# a,b = min(a,b),max(a,b)
edges[(a,b)] = True
edges[(b,a)] = True
# for i in range(n):
# print(g[i])
notvis = {i for i in range(n)}
vis = [0] * n
col = 1
for i in range(n):
if(vis[i] !=0):
continue
notvis.remove(i)
vis[i]= col
stack = [i]
while(len(stack)!=0):
ii = stack.pop()
done = set()
for j in notvis:
if((ii,j) not in edges):
vis[j] = col
stack.append(j)
done.add(j)
notvis-=done
col+=1
# print(vis)
print(col-2)
testcase(1)
# testcase(int(inp()))
``` | instruction | 0 | 68,250 | 13 | 136,500 |
Yes | output | 1 | 68,250 | 13 | 136,501 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n,m = inpl()
g = [set() for _ in range(n+1)]
for _ in range(m):
a,b = inpl()
a,b = a-1,b-1
g[a].add(b)
g[b].add(a)
seen = [False] * n
nd = set(x for x in range(n))
res = 0
def ch(i):
q = deque([i])
global nd
nd.remove(i)
while q:
nv = q.popleft()
now = g[nv]
for v in nd-now:
if seen[v]: continue
seen[v] = True
nd.remove(v)
q.append(v)
for i in range(n):
if seen[i]: continue
seen[i] = True
res += 1
ch(i)
print(res-1)
``` | instruction | 0 | 68,251 | 13 | 136,502 |
Yes | output | 1 | 68,251 | 13 | 136,503 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
n, m = map(int, input().split())
g = [list() for _ in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
vertex_to_cnt = [0, ] * n
cnt_to_vertices = {0: {v for v in range(0, n)}}
r = 0
weight = 0
size = 0
def add_to_tree(v):
global size
size += 1
cnt = vertex_to_cnt[v]
cnt_to_vertices[cnt].remove(v)
if len(cnt_to_vertices[cnt]) == 0:
cnt_to_vertices.pop(cnt)
vertex_to_cnt[v] = None
for c in g[v]:
assert isinstance(c, int)
if vertex_to_cnt[c] is not None:
cnt_to_vertices[vertex_to_cnt[c]].remove(c)
if len(cnt_to_vertices[vertex_to_cnt[c]]) == 0:
cnt_to_vertices.pop(vertex_to_cnt[c])
vertex_to_cnt[c] += 1
if vertex_to_cnt[c] not in cnt_to_vertices:
cnt_to_vertices[vertex_to_cnt[c]] = set()
cnt_to_vertices[vertex_to_cnt[c]].add(c)
add_to_tree(r)
for i in range(1, n):
v = None
for cnt, vertices in cnt_to_vertices.items():
if cnt < size:
for v in vertices:
break
break
if v is None:
cnt = size
vertices = cnt_to_vertices[cnt]
for v in vertices:
break
weight += 1
add_to_tree(v)
print(weight)
``` | instruction | 0 | 68,252 | 13 | 136,504 |
Yes | output | 1 | 68,252 | 13 | 136,505 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
n, m, *t = map(int, open(0).read().split())
from collections import defaultdict
mp = defaultdict(int)
s1 = []
s2 = []
s1.append(1)
for i in range(2, n + 1):
s2.append(i)
for a, b in zip(*[iter(t)] * 2):
mp[(a, b)] = 1
mp[(b, a)] = 1
ans = 0
while len(s2):
ns1 = []
ss1 = set()
for i in s1:
for j in s2:
if mp[(i, j)]:
continue
ns1.append(j)
ss1.add(j)
s2 = list(set(s2)-ss1)
if len(ss1) == 0:
ans += 1
s1 = [s2.pop()]
else:
s1 = ns1
if len(s2) == 0 and len(s1) and ans>0:
ans += 1
print(max(0,ans-1))
``` | instruction | 0 | 68,253 | 13 | 136,506 |
Yes | output | 1 | 68,253 | 13 | 136,507 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
from sys import stdin, exit
v,e = map(int,stdin.readline().split())
if e<v:
print(0)
exit()
m = v*(v+1)/2
if e == m:
print(v-1)
exit()
if e == m-1:
print(v-2)
exit()
if e == m-2:
print(v-3)
exit()
w1 = {tuple(map(int,stdin.readline().split())) for _ in range(e)}
w = 0
join = {1}
unj = {i for i in range(2,v+1)}
for _ in range(v-1):
done = False
for x in join:
for y in unj:
if x<y:
t = (x,y)
else:
t = (y,x)
if t not in w1:
join.add(y)
unj.remove(y)
done = True
break
if done:
break
if not done:
w+=1
join.add(unj.pop())
print(w)
``` | instruction | 0 | 68,254 | 13 | 136,508 |
No | output | 1 | 68,254 | 13 | 136,509 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
import sys
sys.setrecursionlimit(100001)
def dfs(v):
global used
used.discard(v)
add = []
while used and len(used) > len(add):
i = used.pop()
if i in g[v]:
add.append(i)
continue
dfs(i)
for el in add:
used.add(el)
n, m = map(int, input().split())
g = [{i} for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a].add(b)
g[b].add(a)
used = {i for i in range(n)}
ans = -1
while used:
dfs(used.pop())
ans += 1
print(ans)
``` | instruction | 0 | 68,255 | 13 | 136,510 |
No | output | 1 | 68,255 | 13 | 136,511 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
import sys
from sys import stdin,stdout
import itertools
# sys.setrecursionlimit(100001)
c = set()
def bfs(adj,n):
visit=[0]*n
queue=list(range(n))
ans=-1
while queue:
x= queue.pop(0)
c.discard(x)
count=0
for i in iter(c.copy()):
count+=1
if i not in adj[x]:
count=0
queue.insert(0,i)
if count==len(c):
ans+=1
return ans
n,m = stdin.readline().split()
n=int(n)
m=int(m)
adj = [set() for _ in range(n+1)]
for i in range(m):
x,y = stdin.readline().split()
x=int(x)
y=int(y)
adj[x-1].add(y-1)
adj[y-1].add(x-1)
visit=[0]*n
for i in range(n):
c.add(i)
ans = bfs(adj,n)
if ans==-1:
ans=0
stdout.write(str(ans)+'\n')
``` | instruction | 0 | 68,256 | 13 | 136,512 |
No | output | 1 | 68,256 | 13 | 136,513 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
from collections import deque
global q,node,check
node,node2=[[]for i in range(100001)],[[]for i in range(100001)]
n,m=map(int,input().split())
small,big=[],[]
q=deque()
check=[0]*100001
def bfs():
while(len(q)>0):
p=q[0]
q.popleft()
for i in node[p]:
if check[i]==0:
check[i]=1
q.append(i)
for i in range(m):
a,b=map(int,input().split())
node2[a].append(b)
node2[b].append(a)
for i in range(1,n+1):
if len(node2[i])<=n//2:
big.append(i)
else:
small.append(i)
for i in small:
for i2 in range(1,n+1):
if i2!=i and i2 not in node2[i]:
node[i].append(i2)
node[i2].append(i)
for i in big:
check[i]=1
q.append(i)
bfs()
ans=0
for i in range(1,n+1):
if check[i]==0:
check[i]=1
q.append(i)
bfs()
ans+=1
print(ans)
``` | instruction | 0 | 68,257 | 13 | 136,514 |
No | output | 1 | 68,257 | 13 | 136,515 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
""" Python 3 compatibility tools. """
from __future__ import division, print_function
import sys
import os
if 'XXYYZZ' in os.environ:
from typing import List, Set, Dict, Tuple, Text, Optional, Callable, Any, Union
from collections import deque
import collections
from types import GeneratorType
import itertools
import operator
import functools
import random
import copy
import heapq
import math
from atexit import register
from io import BytesIO, IOBase
import __pypy__ # type: ignore
EPS = 10**-12
#########
# INPUT #
#########
class Input(object):
def __init__(self):
if 'CPH' not in os.environ:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
def rawInput(self):
# type: () -> str
return sys.stdin.readline().rstrip('\r\n')
def readSplit(self, mapper):
return map(mapper, self.rawInput().split())
def readInt(self):
return int(self.rawInput())
##########
# OUTPUT #
##########
class Output(object):
def __init__(self):
self.out = __pypy__.builders.StringBuilder()
def write(self, text):
# type: (str) -> None
self.out.append(str(text))
def writeLine(self, text):
# type: (str) -> None
self.write(str(text) + '\n')
def finalize(self):
if sys.version_info[0] < 3:
os.write(1, self.out.build())
else:
os.write(1, self.out.build().encode())
###########
# LIBRARY #
###########
def bootstrap(f, stack=[]):
# Deep Recursion helper.
# From: https://github.com/cheran-senthil/PyRival/blob/c1972da95d102d95b9fea7c5c8e0474d61a54378/docs/bootstrap.rst
# Usage:
# @bootstrap
# def recur(n):
# if n == 0:
# yield 1
# yield (yield recur(n-1)) * n
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
int_add = __pypy__.intop.int_add
int_sub = __pypy__.intop.int_sub
int_mul = __pypy__.intop.int_mul
def make_mod_mul(mod):
fmod_inv = 1.0 / mod
def mod_mul(a, b, c=0):
res = int_sub(int_add(int_mul(a, b), c), int_mul(
mod, int(fmod_inv * a * b + fmod_inv * c)))
if res >= mod:
return res - mod
elif res < 0:
return res + mod
else:
return res
return mod_mul
class DisjointSetUnion(object):
'''
>>> dsu = DisjointSetUnion(10)
>>> dsu.get(5)
5
>>> dsu.get(3)
3
>>> dsu.join(3, 5)
>>> dsu.get(5) == dsu.get(3)
True
>>> dsu.get(5) != dsu.get(2)
True
>>> dsu.join(5, 3)
>>> dsu.get(5) == dsu.get(3)
True
>>> dsu.join(1, 2)
>>> dsu.join(2, 3)
>>> dsu.get(5) == dsu.get(1)
True
>>> dsu.get(4) == dsu.get(1)
False
>>> dsu.get(0) == dsu.get(1)
False
>>> dsu.get(0) == dsu.get(4)
False
Tested:
https://codeforces.com/contest/17/problem/B
'''
def __init__(self, n):
# Initialize with root and nil node
self.n = n
self.parent = range(n)
def get(self, node):
nodecopy = node
while self.parent[node] != node:
node = self.parent[node]
while nodecopy != node:
self.parent[nodecopy], nodecopy = node, self.parent[nodecopy]
return node
def join(self, node1, node2):
self.parent[self.get(node2)] = self.get(node1)
class LinkedList(object):
'''
>>> ll = LinkedList()
>>> ll.insert(ll.end(), 5) and None
>>> ll.insert(ll.end(), 6) and None
>>> ll.insert(ll.end(), 7) and None
>>> ll.insert(ll.end(), 8) and None
>>> ll.insert(ll.start(), 4) and None
>>> len(ll)
5
>>> ll.start().value
4
>>> ll.start().next.value
5
>>> ll.start().next.next.value
6
>>> ll.start().next.next.next.value
7
>>> ll.start().next.next.next.next.value
8
>>> ll.flatten()
[4, 5, 6, 7, 8]
>>> ll.start().next.next.next.next.next.next
>>> x = ll.start().next.next.next.next
>>> ll.insert(ll.end(), 9) and None
>>> x.next.value
9
>>> ll.insert(ll.start().next.next, 100) and None
>>> len(ll)
7
>>> ll.flatten()
[4, 5, 100, 6, 7, 8, 9]
>>> ll.pop(ll.start())
4
>>> len(ll)
6
>>> ll.start().value
5
>>> ll.pop(ll.start().next.next)
6
>>> len(ll)
5
>>> ll.flatten()
[5, 100, 7, 8, 9]
Tested on: https://codeforces.com/contest/45/submission/116633824
'''
class Node(object):
def __init__(self, value, prev, next):
# type: (Any, LinkedList.Node, LinkedList.Node) -> None
self.value = value
self.prev = prev
self.next = next
def __init__(self):
# Initialize with root and nil node
self.n = 0
self.start_pointer = LinkedList.Node(None, None, None)
self.end_pointer = self.start_pointer
def start(self):
# type: () -> LinkedList.Node
return self.start_pointer
def end(self):
# type: () -> LinkedList.Node
return self.end_pointer
def __len__(self):
return self.n
def insert(self, node, value):
# type: (LinkedList.Node, Any) -> LinkedList.Node
# insert value BEFORE node node
prev = node.prev
new_node = LinkedList.Node(value, prev, node)
if not prev:
self.start_pointer = new_node
else:
prev.next = new_node
node.prev = new_node
self.n += 1
return new_node
def pop(self, node):
# type: (LinkedList.Node) -> Any
assert node != self.end_pointer
prev = node.prev
next = node.next
next.prev = prev
if prev:
prev.next = next
else:
self.start_pointer = next
self.n -= 1
return node.value
def flatten(self):
node = self.start_pointer
result = []
while node != self.end_pointer:
result.append(node.value)
node = node.next
return result
#########
# LOGIC #
#########
def main(inp, out):
# type: (Input, Output) -> None
n, m = inp.readSplit(int)
edges = set()
for _ in range(m):
u, v = inp.readSplit(int)
u -= 1
v -= 1
edges.add((u, v))
dsu = DisjointSetUnion(n)
ll = LinkedList()
for i in range(n):
ll.insert(ll.end(), i)
for i in range(n):
llpt = ll.start()
while llpt != ll.end():
node = llpt.value
if node != i and (i, node) not in edges and (node, i) not in edges:
dsu.join(node, i)
ll.pop(llpt)
llpt = llpt.next
ans = -1
for i in range(n):
if dsu.get(i) == i:
ans += 1
out.writeLine(ans)
###############
# BOILERPLATE #
###############
output_obj = Output()
main(Input(), output_obj)
output_obj.finalize()
``` | instruction | 0 | 68,258 | 13 | 136,516 |
No | output | 1 | 68,258 | 13 | 136,517 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8 | instruction | 0 | 68,390 | 13 | 136,780 |
Tags: dfs and similar, divide and conquer, dp, greedy, trees
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def main():
T = int(input())
t = 1
while t<=T:
n = int(input())
neigh = [[] for i in range(n)]
smallest = [0]*n
largest = [0]*n
dp0 = [-1]*n
dp1 = [-1]*n
visited = [0]*n
dic = {}
for i in range(n):
s,l = map(int,input().split())
smallest[i] = s
largest[i] = l
for i in range(n-1):
u,v = map(int,input().split())
neigh[u-1].append(v-1)
neigh[v-1].append(u-1)
stack = []
stack.append(0)
visited[0] = 1
seq = [0]
while stack:
index = stack.pop()
for ele in neigh[index]:
if visited[ele]==1: continue
visited[ele] = 1
stack.append(ele)
seq.append(ele)
seq.reverse()
for index in seq:
dp0[index] = 0
dp1[index] = 0
inum0 = smallest[index]
inum1 = largest[index]
for e in neigh[index]:
if dp0[e]==-1 or dp1[e]==-1: continue
num00 = abs(inum0-smallest[e]) + dp0[e]
num01 = abs(inum0-largest[e]) + dp1[e]
num10 = abs(inum1-smallest[e]) + dp0[e]
num11 = abs(inum1-largest[e]) + dp1[e]
dp0[index] += max(num00,num01)
dp1[index] += max(num10,num11)
ans = max(dp0[0],dp1[0])
print(ans)
# if n>90000: return 0
t += 1
main()
``` | output | 1 | 68,390 | 13 | 136,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8 | instruction | 0 | 68,391 | 13 | 136,782 |
Tags: dfs and similar, divide and conquer, dp, greedy, trees
Correct Solution:
```
import sys
input=sys.stdin.buffer.readline
for t in range(int(input())):
N=int(input())
X=[list(map(int,input().split())) for i in range(N)]
G=[[] for i in range(N)]
for i in range(N-1):
a,b=map(int,input().split())
a-=1
b-=1
G[a].append(b)
G[b].append(a)
r=0
DP=[[0,0] for i in range(N)]
Q=[(r,0,-1)]
while len(Q):
w=Q[-1]
v=w[0]
del Q[-1]
if w[1]:
for t in range(2):
for i in range(len(G[v])):
if w[2]==G[v][i]:
continue
m=0
for j in range(2):
m=max(m,DP[G[v][i]][j]+abs(X[G[v][i]][j]-X[v][t]))
DP[v][t]+=m
continue
Q.append((v,1,w[2]))
for i in range(len(G[v])):
if w[2]!=G[v][i]:
Q.append((G[v][i],0,v))
print(max(DP[0]))
``` | output | 1 | 68,391 | 13 | 136,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8 | instruction | 0 | 68,392 | 13 | 136,784 |
Tags: dfs and similar, divide and conquer, dp, greedy, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
n = int(input())
a = [0] + [list(map(int,input().split())) for i in range(n)]
adj = [[] for i in range(n+1)]
for i in range(n-1):
u,v = map(int,input().split())
adj[u].append(v)
adj[v].append(u)
dp = [[0.0]*2 for i in range(n+1)]
s = [1]
vis = [0]*(n+1)
done = [0]*(n+1)
while s:
c = s[-1]
if not vis[c]:
vis[c] = 1
for ne in adj[c]:
if not vis[ne]:
s.append(ne)
else:
for ne in adj[c]:
if done[ne]:
dp[c][1] += max(dp[ne][0] + abs(a[c][1]-a[ne][0]), dp[ne][1] + abs(a[c][1]-a[ne][1]))
dp[c][0] += max(dp[ne][0] + abs(a[c][0]-a[ne][0]), dp[ne][1] + abs(a[c][0]-a[ne][1]))
done[c] = 1
s.pop()
print(int(max(dp[1])))
``` | output | 1 | 68,392 | 13 | 136,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8 | instruction | 0 | 68,393 | 13 | 136,786 |
Tags: dfs and similar, divide and conquer, dp, greedy, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
def main():
t = int(input()); INF = float("inf")
for _ in range(t):
n = int(input())
L = []; R = []
for i in range(n):
l,r = map(int,input().split())
L.append(l); R.append(r)
G = [[] for _ in range(n)]
for i in range(n-1):
a,b = map(int,input().split())
a-=1;b-=1 #0-index
G[a].append(b)
G[b].append(a)
root = 0
#depth = [-1]*n
#depth[0] = 0
par = [-1]*n
#depth_list = defaultdict(list)
#depth_list[0].append(root)
stack = []
stack.append(~0)
stack.append(0)
dp = [[0, 0] for _ in range(n)]
#cnt = 0
while stack:
#cnt += 1
v = stack.pop()
if v >= 0:
for u in G[v]:
if u == par[v]: continue
par[u] = v
stack.append(~u)
stack.append(u)
else:
u = ~v #child
v = par[u] #parent
if v == -1: continue
zero = max(dp[u][0] + abs(L[v] - L[u]), dp[u][1] + abs(L[v] - R[u]))
one = max(dp[u][0] + abs(R[v] - L[u]), dp[u][1] + abs(R[v] - R[u]))
dp[v][0] += zero
dp[v][1] += one
ans = max(dp[0])
#print("CNT",cnt)
#print(dp)
print(ans)
if __name__ == "__main__":
main()
``` | output | 1 | 68,393 | 13 | 136,787 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8 | instruction | 0 | 68,394 | 13 | 136,788 |
Tags: dfs and similar, divide and conquer, dp, greedy, trees
Correct Solution:
```
import io
import os
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop, heapify
from math import gcd, inf
from types import GeneratorType
# From https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def solve(N, LR, edges):
graph = [[] for i in range(N)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
dp = [-1] * (2 * N)
@bootstrap
def dfs(u, p, i):
if dp[2 * u + i] == -1:
# i is 0 or 1
a = LR[u][i]
best = 0.0
for v in graph[u]:
if v != p:
yield dfs(v, u, 0)
yield dfs(v, u, 1)
best += max(
abs(a - LR[v][0]) + dp[2 * v + 0],
abs(a - LR[v][1]) + dp[2 * v + 1],
)
dp[2 * u + i] = best
yield
root = 0
dfs(root, -1, 0)
dfs(root, -1, 1)
return int(max(dp[2 * root + 0], dp[2 * root + 1]))
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
(N,) = [int(x) for x in input().split()]
LR = [[int(x) for x in input().split()] for i in range(N)]
edges = [
[int(x) - 1 for x in input().split()] for i in range(N - 1)
] # 0 indexed
ans = solve(N, LR, edges)
print(ans)
``` | output | 1 | 68,394 | 13 | 136,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8 | instruction | 0 | 68,395 | 13 | 136,790 |
Tags: dfs and similar, divide and conquer, dp, greedy, trees
Correct Solution:
```
#start_time = time.time()
#def TIME_(): print(time.time()-start_time)
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
"""
"""
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
for _ in range(int(input())):
N = int(input())
A = [list(map(int,input().split())) for _ in range(N)]
G = [[] for _ in range(N)]
for i in range(N-1):
u, v = map(int,input().split())
u -= 1
v -= 1
G[u].append(v)
G[v].append(u)
ans = [-1]*(2*N)
@bootstrap
def dfs(u,p,i):
if ans[2*u+i] == -1:
a = A[u][i]
best = 0.0
for v in G[u]:
if v != p:
yield dfs(v,u,0)
yield dfs(v,u,1)
best += max(abs(a - A[v][0]) + ans[2*v], abs(a - A[v][1]) + ans[2*v+1])
ans[2*u+i] = best
yield
dfs(0,-1,0)
dfs(0,-1,1)
print(int(max(ans[0],ans[1])))
#solve()
#TIME_()
``` | output | 1 | 68,395 | 13 | 136,791 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8 | instruction | 0 | 68,396 | 13 | 136,792 |
Tags: dfs and similar, divide and conquer, dp, greedy, trees
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def main():
for _ in range(int(input())):
n = int(input())
l = [tuple(map(int,input().split())) for _ in range(n)]
path = [[] for _ in range(n)]
for _ in range(n-1):
u1,v1 = map(lambda xx:int(xx)-1,input().split())
path[u1].append(v1)
path[v1].append(u1)
st,poi,visi = [0],[0]*n,[1]+[0]*(n-1)
dp = [[0.0]*n for _ in range(2)]
while len(st):
x,y = st[-1],path[st[-1]]
if poi[x] != len(y) and visi[y[poi[x]]]:
poi[x] += 1
if poi[x] == len(y):
st.pop()
if len(st):
z = st[-1]
for rr in range(2):
dp[rr][z] += max(dp[0][x]+abs(l[x][0]-l[z][rr]),
dp[1][x]+abs(l[x][1]-l[z][rr]))
else:
i = y[poi[x]]
visi[i] = 1
st.append(i)
poi[x] += 1
print(int(max(dp[0][0],dp[1][0])))
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self,file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE))
self.newlines = b.count(b"\n")+(not b)
ptr = self.buffer.tell()
self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd,self.buffer.getvalue())
self.buffer.truncate(0),self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self,file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s:self.buffer.write(s.encode("ascii"))
self.read = lambda:self.buffer.read().decode("ascii")
self.readline = lambda:self.buffer.readline().decode("ascii")
sys.stdin,sys.stdout = IOWrapper(sys.stdin),IOWrapper(sys.stdout)
input = lambda:sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 68,396 | 13 | 136,793 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8 | instruction | 0 | 68,397 | 13 | 136,794 |
Tags: dfs and similar, divide and conquer, dp, greedy, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
n = int(input())
adj = [[] for i in range(0,n+1)]
points = [0]
dp = [[0.0 for i in range(2)]for i in range(n+1)]
points = [0] + [list(map(int,input().split())) for i in range(n)]
for i in range(0,n-1):
u,v = map(int,input().split())
adj[u].append(v)
adj[v].append(u)
vis = [0]*(n+1)
s = []
s.append(1)
done=[0]*(n+1)
while(len(s)):
u=s[-1]
if not vis[u]:
vis[u]=1
for v in adj[u]:
if(not vis[v]):
s.append(v)
else:
for v in adj[u]:
if(done[v]):
dp[u][0]+=max(abs(points[u][0]-points[v][0])+dp[v][0], abs(points[u][0]-points[v][1])+dp[v][1])
dp[u][1]+=max(abs(points[u][1]-points[v][0])+dp[v][0], abs(points[u][1]-points[v][1])+dp[v][1])
done[u]=1
s.pop()
print(int(max(dp[1][0],dp[1][1])))
``` | output | 1 | 68,397 | 13 | 136,795 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8
Submitted Solution:
```
#!/usr/bin/env python3
import sys
import getpass # not available on codechef
# import math, random
# import functools, itertools, collections, heapq, bisect
from collections import defaultdict
# input = sys.stdin.readline # to read input quickly
import os
import sys
from io import BytesIO, IOBase
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import scipy
BUFSIZE = 8192
M9 = 10**9 + 7 # 998244353
yes, no = "YES", "NO"
# d4 = [(1,0),(0,1),(-1,0),(0,-1)]
# d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
# d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout
MAXINT = sys.maxsize
# if testing locally, print to terminal with a different color
# OFFLINE_TEST = getpass.getuser() == "hkmac"
OFFLINE_TEST = False # codechef does not allow getpass
def log(*args):
if OFFLINE_TEST:
print('\033[36m', *args, '\033[0m', file=sys.stderr)
def solve(*args):
# screen input
if OFFLINE_TEST:
log("----- solving ------")
log(*args)
log("----- ------- ------")
return solve_(*args)
def read_matrix(rows):
return [list(map(int,input().split())) for _ in range(rows)]
def read_strings(rows):
return [input().strip() for _ in range(rows)]
def minus_one(arr):
return [x-1 for x in arr]
def minus_one_matrix(mrr):
return [[x-1 for x in row] for row in mrr]
# ---------------------------- template ends here ----------------------------
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")
# minmax
def solve_(minrr, maxrr, edges):
# print(minrr, maxrr, edges)
# your solution here
g = {i:[] for i in range(len(minrr))}
for a,b in edges:
g[a-1].append(b-1)
g[b-1].append(a-1)
# maxres = 0
# for boo in range(2):
# stack = [0]
# status = [-1]*len(mrr)
# status[0] = boo
# curres = 0
# while stack:
# cur = stack.pop()
# # log(cur)
# for nex in g[cur]:
# # log(nex)
# if status[nex] >= 0:
# continue
# status[nex] = 1-status[cur]
# stack.append(nex)
# val = abs(mrr[nex][status[nex]] - mrr[cur][status[cur]])
# # log(val)
# # log(nex)
# curres += val
# maxres = max(maxres, curres)
# return maxres
entered = set([0])
exiting = set()
prev = [-1]*len(minrr)
resmincur = [0]*len(minrr)
resmaxcur = [0]*len(minrr)
def operate(cur, nex):
if cur == -1:
return
resminnex = resmincur[nex]
resmaxnex = resmaxcur[nex]
resmax = max(resminnex + abs(minrr[nex] - maxrr[cur]), resmaxnex + abs(maxrr[nex] - maxrr[cur]))
resmin = max(resmaxnex + abs(maxrr[nex] - minrr[cur]), resminnex + abs(minrr[nex] - minrr[cur]))
resmincur[cur] += resmin
resmaxcur[cur] += resmax
stack = [0]
while stack:
cur = stack[-1]
if cur in exiting:
stack.pop()
operate(prev[cur], cur)
continue
for nex in g[cur]:
if nex in entered:
continue
entered.add(nex)
stack.append(nex)
prev[nex] = cur
exiting.add(cur)
return int(max(resmincur[0], resmaxcur[0]))
# for case_num in [0]: # no loop over test case
# for case_num in range(100): # if the number of test cases is specified
for case_num in range(int(input())):
# read line as an integer
k = int(input())
# read line as a string
# srr = input().strip()
# read one line and parse each word as a string
# lst = input().split()
# read one line and parse each word as an integer
# a,b,c = list(map(int,input().split()))
# lst = list(map(int,input().split()))
# lst = minus_one(lst)
# read multiple rows
# arr = read_strings(k) # and return as a list of str
# mrr = read_matrix(k) # and return as a list of list of int
arr = [0]*k
brr = [0]*k
for i in range(k):
arr[i], brr[i] = list(map(float,input().split()))
# del mrr
edges = read_matrix(k-1) # and return as a list of list of int
# edges = minus_one_matrix(edges)
res = solve(arr, brr, edges) # include input here
# print length if applicable
# print(len(res))
# parse result
# res = " ".join(str(x) for x in res)
# res = "\n".join(str(x) for x in res)
# res = "\n".join(" ".join(str(x) for x in row) for row in res)
# print result
# print("Case #{}: {}".format(case_num+1, res)) # Google and Facebook - case number required
print(res)
``` | instruction | 0 | 68,398 | 13 | 136,796 |
Yes | output | 1 | 68,398 | 13 | 136,797 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8
Submitted Solution:
```
import sys,io,os
try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
except:Z=lambda:sys.stdin.readline().encode()
Y=lambda:map(int,Z().split())
O=[]
for _ in range(int(Z())):
n=int(Z());w=[tuple(Y())for i in range(n)];g=[[]for i in range(n)]
for i in range(n-1):u,v=Y();u-=1;v-=1;g[u].append(v);g[v].append(u)
d=[[0,0]for i in range(n)];q=[(0,0,-1)]
while len(q):
t,v,p=q[-1];del q[-1]
if t:
for i in g[v]:
if i!=p:
for j in range(2):
m=0
for k in range(2):
m=max(m,abs(w[v][j]-w[i][k])+d[i][k])
d[v][j]+=m
continue
q.append((1,v,p))
for i in g[v]:
if i!=p:q.append((0,i,v))
O.append(str(max(d[0])))
print('\n'.join(O))
``` | instruction | 0 | 68,399 | 13 | 136,798 |
Yes | output | 1 | 68,399 | 13 | 136,799 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8
Submitted Solution:
```
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import deque
mm = (1 << 30) - 1
T = int(input())
for _ in range(T):
N = int(input())
LR = [0] * N
for i in range(N):
l, r = map(int, input().split())
LR[i] = (l << 30) + r
X = [[] for i in range(N)]
for i in range(N-1):
x, y = map(int, input().split())
x, y = x-1, y-1 # 1-indexed
X[x].append(y)
X[y].append(x)
P = [-1] * N
Q = deque([0])
R = []
while Q:
i = deque.popleft(Q)
R.append(i)
for a in X[i]:
if a != P[i]:
P[a] = i
X[a].remove(i)
deque.append(Q, a)
if 0:
print("X =", X) # �q���X�g
print("P =", P) # �e
print("R =", R) # �g�|���W�J���\�[�g
LL = [0] * N
RR = [0] * N
for i in R[1:][::-1]:
p = P[i]
lr = LR[i]
l, r = lr >> 30, lr & mm
lr = LR[p]
ll, rr = lr >> 30, lr & mm
LL[p] += max(abs(l - ll) + LL[i], abs(r - ll) + RR[i])
RR[p] += max(abs(l - rr) + LL[i], abs(r - rr) + RR[i])
print(max(LL[0], RR[0]))
``` | instruction | 0 | 68,400 | 13 | 136,800 |
Yes | output | 1 | 68,400 | 13 | 136,801 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8
Submitted Solution:
```
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import deque
mm = (1 << 30) - 1
T = int(input())
for _ in range(T):
N = int(input())
LR = [0] * N
for i in range(N):
l, r = map(int, input().split())
LR[i] = (l << 30) + r
X = [[] for i in range(N)]
for i in range(N-1):
x, y = map(int, input().split())
x, y = x-1, y-1 # 1-indexed
X[x].append(y)
X[y].append(x)
P = [-1] * N
Q = deque([0])
R = []
while Q:
i = deque.popleft(Q)
R.append(i)
for a in X[i]:
if a != P[i]:
P[a] = i
X[a].remove(i)
deque.append(Q, a)
LL = [0.0] * N
RR = [0.0] * N
for i in R[1:][::-1]:
p = P[i]
lr = LR[i]
l, r = lr >> 30, lr & mm
lr = LR[p]
ll, rr = lr >> 30, lr & mm
LL[p] += max(abs(l - ll) + LL[i], abs(r - ll) + RR[i])
RR[p] += max(abs(l - rr) + LL[i], abs(r - rr) + RR[i])
print(int(max(LL[0], RR[0]) + 0.5))
``` | instruction | 0 | 68,401 | 13 | 136,802 |
Yes | output | 1 | 68,401 | 13 | 136,803 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8
Submitted Solution:
```
from functools import lru_cache
import sys
from sys import stdin
sys.setrecursionlimit(2*10**5)
for k in range(int(input())):
from collections import defaultdict
g = defaultdict(list)
n = int(stdin.readline())
arr = []
for _ in range(n):
l,r = map(int,stdin.readline().split(' '))
arr.append([l,r])
for _ in range(n-1):
u,v = map(int,stdin.readline().split(' '))
g[u].append(v)
g[v].append(u)
if k==0:
print(7)
elif k==1:
print(8)
else:
print(62)
ans = 0
for _ in range(2*n):
ans = ans + 0
``` | instruction | 0 | 68,402 | 13 | 136,804 |
No | output | 1 | 68,402 | 13 | 136,805 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8
Submitted Solution:
```
import io
import os
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop, heapify
from math import gcd, inf
from types import GeneratorType
# From https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def solve(N, LR, edges):
graph = [[] for i in range(N)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
dp = [-1] * (2 * N)
@bootstrap
def dfs(u, p, i):
if dp[2 * u + i] == -1:
# i is 0 or 1
a = LR[u][i]
best = 0
for v in graph[u]:
if v != p:
yield dfs(v, u, 0)
yield dfs(v, u, 1)
best += max(
abs(a - LR[v][0]) + dp[2 * v + 0],
abs(a - LR[v][1]) + dp[2 * v + 1],
)
dp[2 * u + i] = best
yield
root = 0
dfs(root, -1, 0)
dfs(root, -1, 0)
return max(dp[2 * root + 0], dp[2 * root + 1])
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
(N,) = [int(x) for x in input().split()]
LR = [[int(x) for x in input().split()] for i in range(N)]
edges = [
[int(x) - 1 for x in input().split()] for i in range(N - 1)
] # 0 indexed
ans = solve(N, LR, edges)
print(ans)
``` | instruction | 0 | 68,403 | 13 | 136,806 |
No | output | 1 | 68,403 | 13 | 136,807 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8
Submitted Solution:
```
import sys,io,os
try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
except:Z=lambda:sys.stdin.readline().encode()
Y=lambda:map(int,Z().split())
O=[]
for _ in range(int(Z())):
n=int(Z());wl=[];wr=[];g=[[]for i in range(n)]
for i in range(n):x,y=Y();wl.append(x);wr.append(y)
for i in range(n-1):u,v=Y();u-=1;v-=1;g[u].append(v);g[v].append(u)
l=[0.0]*n;r=[0.0]*n;c=[-1]*n;p=[-1]*n;q=[0]
while q:
v=q.pop()
if c[v]==-1:
c[v]=0
for i in g[v]:
if i!=p[v]:p[i]=v;c[v]+=1;q.append(i)
if c[v]==0:
for i in g[v]:
if i!=p[v]:
l[v]+=max(abs(wl[v]-wl[i])+l[i],abs(wl[v]-wr[i])+r[i])
r[v]+=max(abs(wr[v]-wl[i])+l[i],abs(wr[v]-wr[i])+r[i])
c[p[v]]-=1
if v and c[p[v]]==0:q.append(p[v])
O.append(str(max(l[0],r[0])))
print('\n'.join(O))
``` | instruction | 0 | 68,404 | 13 | 136,808 |
No | output | 1 | 68,404 | 13 | 136,809 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
Input
The first line contains an integer t (1≤ t≤ 250) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2≤ n≤ 10^5) — the number of vertices in Parsa's tree.
The i-th of the following n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^9).
Each of the next n-1 lines contains two integers u and v (1 ≤ u , v ≤ n, u≠ v) meaning that there is an edge between the vertices u and v in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the maximum possible beauty for Parsa's tree.
Example
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
Note
The trees in the example:
<image>
In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.
In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8
Submitted Solution:
```
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import deque
mm = (1 << 30) - 1
T = int(input())
for _ in range(T):
N = int(input())
LR = [0] * N
for i in range(N):
l, r = map(int, input().split())
LR[i] = (l << 30) + r
X = [[] for i in range(N)]
for i in range(N-1):
x, y = map(int, input().split())
x, y = x-1, y-1 # 1-indexed
X[x].append(y)
X[y].append(x)
P = [-1] * N
Q = deque([0])
R = []
while Q:
i = deque.popleft(Q)
R.append(i)
for a in X[i]:
if a != P[i]:
P[a] = i
X[a].remove(i)
deque.append(Q, a)
if 0:
print("X =", X) # �q���X�g
print("P =", P) # �e
print("R =", R) # �g�|���W�J���\�[�g
LL = [0.0] * N
RR = [0.0] * N
for i in R[1:][::-1]:
p = P[i]
lr = LR[i]
l, r = lr >> 30, lr & mm
lr = LR[p]
ll, rr = lr >> 30, lr & mm
LL[p] += max(abs(l - ll) + LL[i], abs(r - ll) + RR[i])
RR[p] += max(abs(l - rr) + LL[i], abs(r - rr) + RR[i])
print(max(LL[0], RR[0]))
``` | instruction | 0 | 68,405 | 13 | 136,810 |
No | output | 1 | 68,405 | 13 | 136,811 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Programming teacher Dmitry Olegovich is going to propose the following task for one of his tests for students:
You are given a tree T with n vertices, specified by its adjacency matrix a[1... n, 1... n]. What is the output of the following pseudocode?
used[1 ... n] = {0, ..., 0};
procedure dfs(v):
print v;
used[v] = 1;
for i = 1, 2, ..., n:
if (a[v][i] == 1 and used[i] == 0):
dfs(i);
dfs(1);
In order to simplify the test results checking procedure, Dmitry Olegovich decided to create a tree T such that the result is his favorite sequence b. On the other hand, Dmitry Olegovich doesn't want to provide students with same trees as input, otherwise they might cheat. That's why Dmitry Olegovich is trying to find out the number of different trees T such that the result of running the above pseudocode with T as input is exactly the sequence b. Can you help him?
Two trees with n vertices are called different if their adjacency matrices a1 and a2 are different, i. e. there exists a pair (i, j), such that 1 ≤ i, j ≤ n and a1[i][j] ≠ a2[i][j].
Input
The first line contains the positive integer n (1 ≤ n ≤ 500) — the length of sequence b.
The second line contains n positive integers b1, b2, ..., bn (1 ≤ bi ≤ n). It is guaranteed that b is a permutation, or in other words, each of the numbers 1, 2, ..., n appears exactly once in the sequence b. Also it is guaranteed that b1 = 1.
Output
Output the number of trees satisfying the conditions above modulo 109 + 7.
Examples
Input
3
1 2 3
Output
2
Input
3
1 3 2
Output
1
Submitted Solution:
```
n=int(input())
s=0
b=list(map(int,input().split()))
c=[0 for i in range(n+1)]
c[n-1]=1
for i in range(n-1,-1,-1):
c[i]+=c[i+1]
#c[i]=c[i]%(10**9+7)
for j in range(1,i):
if b[i]>b[j]:
c[j-1]+=c[i]
print(c[0]%(10**9+7))
``` | instruction | 0 | 68,527 | 13 | 137,054 |
No | output | 1 | 68,527 | 13 | 137,055 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Programming teacher Dmitry Olegovich is going to propose the following task for one of his tests for students:
You are given a tree T with n vertices, specified by its adjacency matrix a[1... n, 1... n]. What is the output of the following pseudocode?
used[1 ... n] = {0, ..., 0};
procedure dfs(v):
print v;
used[v] = 1;
for i = 1, 2, ..., n:
if (a[v][i] == 1 and used[i] == 0):
dfs(i);
dfs(1);
In order to simplify the test results checking procedure, Dmitry Olegovich decided to create a tree T such that the result is his favorite sequence b. On the other hand, Dmitry Olegovich doesn't want to provide students with same trees as input, otherwise they might cheat. That's why Dmitry Olegovich is trying to find out the number of different trees T such that the result of running the above pseudocode with T as input is exactly the sequence b. Can you help him?
Two trees with n vertices are called different if their adjacency matrices a1 and a2 are different, i. e. there exists a pair (i, j), such that 1 ≤ i, j ≤ n and a1[i][j] ≠ a2[i][j].
Input
The first line contains the positive integer n (1 ≤ n ≤ 500) — the length of sequence b.
The second line contains n positive integers b1, b2, ..., bn (1 ≤ bi ≤ n). It is guaranteed that b is a permutation, or in other words, each of the numbers 1, 2, ..., n appears exactly once in the sequence b. Also it is guaranteed that b1 = 1.
Output
Output the number of trees satisfying the conditions above modulo 109 + 7.
Examples
Input
3
1 2 3
Output
2
Input
3
1 3 2
Output
1
Submitted Solution:
```
print("I cannot do it QAQ")
``` | instruction | 0 | 68,528 | 13 | 137,056 |
No | output | 1 | 68,528 | 13 | 137,057 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Programming teacher Dmitry Olegovich is going to propose the following task for one of his tests for students:
You are given a tree T with n vertices, specified by its adjacency matrix a[1... n, 1... n]. What is the output of the following pseudocode?
used[1 ... n] = {0, ..., 0};
procedure dfs(v):
print v;
used[v] = 1;
for i = 1, 2, ..., n:
if (a[v][i] == 1 and used[i] == 0):
dfs(i);
dfs(1);
In order to simplify the test results checking procedure, Dmitry Olegovich decided to create a tree T such that the result is his favorite sequence b. On the other hand, Dmitry Olegovich doesn't want to provide students with same trees as input, otherwise they might cheat. That's why Dmitry Olegovich is trying to find out the number of different trees T such that the result of running the above pseudocode with T as input is exactly the sequence b. Can you help him?
Two trees with n vertices are called different if their adjacency matrices a1 and a2 are different, i. e. there exists a pair (i, j), such that 1 ≤ i, j ≤ n and a1[i][j] ≠ a2[i][j].
Input
The first line contains the positive integer n (1 ≤ n ≤ 500) — the length of sequence b.
The second line contains n positive integers b1, b2, ..., bn (1 ≤ bi ≤ n). It is guaranteed that b is a permutation, or in other words, each of the numbers 1, 2, ..., n appears exactly once in the sequence b. Also it is guaranteed that b1 = 1.
Output
Output the number of trees satisfying the conditions above modulo 109 + 7.
Examples
Input
3
1 2 3
Output
2
Input
3
1 3 2
Output
1
Submitted Solution:
```
n=int(input())
s=0
b=list(map(int,input().split()))
for i in range(n):
for j in range(i,n):
if b[i]<b[j]:
s+=1
else:
s-=1
print(s-1)
``` | instruction | 0 | 68,529 | 13 | 137,058 |
No | output | 1 | 68,529 | 13 | 137,059 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Programming teacher Dmitry Olegovich is going to propose the following task for one of his tests for students:
You are given a tree T with n vertices, specified by its adjacency matrix a[1... n, 1... n]. What is the output of the following pseudocode?
used[1 ... n] = {0, ..., 0};
procedure dfs(v):
print v;
used[v] = 1;
for i = 1, 2, ..., n:
if (a[v][i] == 1 and used[i] == 0):
dfs(i);
dfs(1);
In order to simplify the test results checking procedure, Dmitry Olegovich decided to create a tree T such that the result is his favorite sequence b. On the other hand, Dmitry Olegovich doesn't want to provide students with same trees as input, otherwise they might cheat. That's why Dmitry Olegovich is trying to find out the number of different trees T such that the result of running the above pseudocode with T as input is exactly the sequence b. Can you help him?
Two trees with n vertices are called different if their adjacency matrices a1 and a2 are different, i. e. there exists a pair (i, j), such that 1 ≤ i, j ≤ n and a1[i][j] ≠ a2[i][j].
Input
The first line contains the positive integer n (1 ≤ n ≤ 500) — the length of sequence b.
The second line contains n positive integers b1, b2, ..., bn (1 ≤ bi ≤ n). It is guaranteed that b is a permutation, or in other words, each of the numbers 1, 2, ..., n appears exactly once in the sequence b. Also it is guaranteed that b1 = 1.
Output
Output the number of trees satisfying the conditions above modulo 109 + 7.
Examples
Input
3
1 2 3
Output
2
Input
3
1 3 2
Output
1
Submitted Solution:
```
n=int(input())
s=0
b=list(map(int,input().split()))
c=[0 for i in range(n+1)]
c[n-1]=1
for i in range(n-1,-1,-1):
c[i]+=c[i+1]
#c[i]=c[i]%(10**9+7)
for j in range(1,i):
if b[i]>b[j]:
c[j]+=c[i]
print(c[0]%(10**9+9))
``` | instruction | 0 | 68,530 | 13 | 137,060 |
No | output | 1 | 68,530 | 13 | 137,061 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N).
Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all the vertices painted black. (If no vertex is painted black, S is the empty graph.)
Let the holeyness of S be the number of white vertices contained in S. Find the expected holeyness of S.
Since the answer is a rational number, we ask you to print it \bmod 10^9+7, as described in Notes.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq A_i,B_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
A_1 B_1
:
A_{N-1} B_{N-1}
Output
Print the expected holeyness of S, \bmod 10^9+7.
Examples
Input
3
1 2
2 3
Output
125000001
Input
4
1 2
2 3
3 4
Output
375000003
Input
4
1 2
1 3
1 4
Output
250000002
Input
7
4 7
3 1
2 6
5 2
7 1
2 7
Output
570312505 | instruction | 0 | 68,713 | 13 | 137,426 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7
N, *AB = map(int, open(0).read().split())
E = [[] for _ in range(N + 1)]
for i, (a, b) in enumerate(zip(*[iter(AB)] * 2)):
E[a - 1].append((b - 1, i))
E[b - 1].append((a - 1, i))
X = [0] * N
def dfs(u, p):
res = 1
for v, c in E[u]:
if p != c:
res += dfs(v, c)
X[p] = res
return res
dfs(0, -1)
I = [1] * (N + 1)
inv = pow(2, mod - 2, mod)
for i in range(N):
I[i + 1] = I[i] * inv % mod
ans = - inv * N - I[N] + 1
for e in range(N - 1):
ans += (1 - I[X[e]]) * (1 - I[N - X[e]])
ans %= mod
print(ans)
``` | output | 1 | 68,713 | 13 | 137,427 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N).
Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all the vertices painted black. (If no vertex is painted black, S is the empty graph.)
Let the holeyness of S be the number of white vertices contained in S. Find the expected holeyness of S.
Since the answer is a rational number, we ask you to print it \bmod 10^9+7, as described in Notes.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq A_i,B_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
A_1 B_1
:
A_{N-1} B_{N-1}
Output
Print the expected holeyness of S, \bmod 10^9+7.
Examples
Input
3
1 2
2 3
Output
125000001
Input
4
1 2
2 3
3 4
Output
375000003
Input
4
1 2
1 3
1 4
Output
250000002
Input
7
4 7
3 1
2 6
5 2
7 1
2 7
Output
570312505 | instruction | 0 | 68,714 | 13 | 137,428 |
"Correct Solution:
```
n = int(input())
mod = 10**9 + 7
# 前準備
import sys
input = sys.stdin.readline
from collections import deque
graph = [[] for _ in range(n+1)]
for _ in range(n-1):
a,b = map(int,input().split())
graph[a].append(b)
graph[b].append(a)
ini = 0
# calcの定義 : 2辺を合わせる演算
def calc(a,b):
return a+b
# dp1の更新
def calc1(c,p):
p_num = ini
for i in graph[c]:
if i == p:
continue
p_num = calc(p_num, dp1[i])
dp1[c] = (p_num+1) % mod
# dp2の更新 累積和チックにすることでうに対策。
def calc2(p):
arr = [dp1[c] if c != parent[p] else dp2[p] for c in graph[p]]
left = [ini]
for i in arr[:-1]:
left.append( calc(left[-1], i ) )
right = [ini]
for i in arr[:0:-1]:
right.append( calc(right[-1], i) )
right = right[::-1]
prod = []
for a,b in zip(left,right):
prod.append( calc(a,b) )
for c,x in zip(graph[p], prod):
if(c != parent[p]):
dp2[c] = (x + 1) % mod
# 根から探索して親と探索順を記録
root = 1
order = []
parent = [0] * (n+1)
stack = deque()
stack.append(root)
while stack:
x = stack.pop()
order.append(x)
for y in graph[x]:
if y == parent[x]:
continue
stack.append(y)
parent[y] = x
# 親→子の値を算出
dp1 = [0] * (n+1)
for i in order[::-1]:
calc1(i, parent[i])
# 子→親の値を算出
dp2 = [0] * (n+1)
for i in order:
calc2(i)
ans = 0
for i in range(1,n+1):
gr = graph[i]
if(len(gr) == 1):
continue
tmp = pow(2,n-1,mod) - 1
for v in gr:
if(v == parent[i]):
exp_num = dp2[i]
else:
exp_num = dp1[v]
tmp = (tmp - (pow(2, exp_num, mod)-1)) % mod
ans = (ans + tmp) % mod
ans = ans * pow(pow(2,n,mod), mod-2, mod) % mod
print(ans)
``` | output | 1 | 68,714 | 13 | 137,429 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N).
Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all the vertices painted black. (If no vertex is painted black, S is the empty graph.)
Let the holeyness of S be the number of white vertices contained in S. Find the expected holeyness of S.
Since the answer is a rational number, we ask you to print it \bmod 10^9+7, as described in Notes.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq A_i,B_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
A_1 B_1
:
A_{N-1} B_{N-1}
Output
Print the expected holeyness of S, \bmod 10^9+7.
Examples
Input
3
1 2
2 3
Output
125000001
Input
4
1 2
2 3
3 4
Output
375000003
Input
4
1 2
1 3
1 4
Output
250000002
Input
7
4 7
3 1
2 6
5 2
7 1
2 7
Output
570312505 | instruction | 0 | 68,715 | 13 | 137,430 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
def r(a):
for i in range(1, 10001):
if i and a * i % mod <= 10000:
return str(a*i%mod) + "/" + str(i)
if i and -a * i % mod <= 10000:
return str(-(-a*i%mod)) + "/" + str(i)
return a
N = int(input())
X = [[] for i in range(N)]
for i in range(N-1):
x, y = map(int, input().split())
X[x-1].append(y-1)
X[y-1].append(x-1)
i0 = min([i for i in range(N) if len(X[i]) == 1])
P = [-1] * N
Q = deque([i0])
R = []
while Q:
i = deque.popleft(Q)
R.append(i)
for a in X[i]:
if a != P[i]:
P[a] = i
X[a].remove(i)
deque.append(Q, a)
mod = 10 ** 9 + 7
inv2 = (mod + 1) // 2
A = [1] * N # これ以下の部分木に黒を含まない確率
B = [1] * N # これより上の部分木に黒を含まない確率
for i in R[::-1]:
s = inv2
for j in X[i]:
s = (s * A[j]) % mod
A[i] = s
for i in R[1:]:
if P[i] == i0:
B[i] = A[i0] * pow(A[i], mod-2, mod) % mod
else:
B[i] = B[P[i]] * A[P[i]] * pow(A[i], mod-2, mod) % mod
ans = 0
for i in range(N):
s = B[i]
t = 1 + (1-B[i]) * pow(B[i], mod-2, mod)
for j in X[i]:
s = (s * A[j]) % mod
t = (t + (1-A[j]) * pow(A[j], mod-2, mod)) % mod
ans = (ans + 1 - s * t) % mod
print(ans * inv2 % mod)
``` | output | 1 | 68,715 | 13 | 137,431 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.