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
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` #!/usr/bin/env python3 # GRL_5_C: Tree - Lowest Common Ancestor class UnionFind: def __init__(self, n): self.nodes = [i for i in range(n)] self.sizes = [1 for _ in range(n)] def union(self, p, q): rp = self.root(p) rq = self.root(q) if self.sizes[rp] > self.sizes[rq]: self.nodes[rq] = rp self.sizes[rp] += self.sizes[rq] else: self.nodes[rp] = rq self.sizes[rq] += self.sizes[rp] def connected(self, p, q): return self.root(p) == self.root(q) def root(self, p): while p != self.nodes[p]: self.nodes[p] = self.nodes[self.nodes[p]] p = self.nodes[p] return p class Edge: __slots__ = ('v', 'w') def __init__(self, v, w): self.v = v self.w = w def either(self): return self.v def other(self, v): if v == self.v: return self.w else: return self.v class WeightedEdge(Edge): __slots__ = ('v', 'w', 'weight') def __init__(self, v, w, weight): super().__init__(v, w) self.weight = weight class Graph: def __init__(self, v): self.v = v self._edges = [[] for _ in range(v)] def add(self, e): self._edges[e.v].append(e) self._edges[e.w].append(e) def adj(self, v): return self._edges[v] def edges(self): for es in self._edges: for e in es: yield e def lca(graph, root, queries): index = [set() for _ in range(graph.v)] for v, w in queries: index[v].add((v, w)) visited = [False] * graph.v stored = [False] * graph.v parents = [None] * graph.v uf = UnionFind(graph.v) res = {} stack = [root] while stack: v = stack.pop() if not visited[v]: visited[v] = True stack.append(v) for e in graph.adj(v): w = e.other(v) if not visited[w]: stack.append(w) parents[w] = v else: stored[v] = True p = parents[v] rest = set() for i, j in index[v]: if stored[i] and stored[j]: if uf.connected(i, j) and (i, j) not in res: res[(i, j)] = v else: rest.add((i, j)) else: index[j].add((i, j)) index[v] = None if p is not None: uf.union(p, v) index[p].update(rest) return res def run(): n = int(input()) g = Graph(n) for i in range(n): k, *cs = [int(i) for i in input().split()] if k > 0: for j in cs: g.add(Edge(i, j)) q = int(input()) qs = [] for _ in range(q): v, w = [int(i) for i in input().split()] qs.append((v, w)) res = lca(g, 0, qs) for v, w in qs: print(res[(v, w)]) if __name__ == '__main__': run() ```
instruction
0
5,007
13
10,014
Yes
output
1
5,007
13
10,015
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` # 参考 https://tjkendev.github.io/procon-library/python/graph/lca-segment-tree.html # N: 頂点数 # G[v]: 頂点vの子頂点 (親頂点は含まない) import sys sys.setrecursionlimit(10**7) N = int(input()) G = [[] for _ in range(N)] for v in range(N): for j, nv in enumerate(map(int, input().split())): if j == 0: continue G[v].append(nv) # Euler Tour の構築 S = [] F = [0]*N depth = [0]*N def dfs(v, d): F[v] = len(S) depth[v] = d S.append(v) for w in G[v]: dfs(w, d+1) S.append(v) dfs(0, 0) # 存在しない範囲は深さが他よりも大きくなるようにする INF = (N, None) # LCAを計算するクエリの前計算 M = 2*N M0 = 2**(M-1).bit_length() data = [INF]*(2*M0) for i, v in enumerate(S): data[M0-1+i] = (depth[v], i) for i in range(M0-2, -1, -1): data[i] = min(data[2*i+1], data[2*i+2]) # LCAの計算 (generatorで最小値を求める) def _query(a, b): yield INF a += M0; b += M0 while a < b: if b & 1: b -= 1 yield data[b-1] if a & 1: yield data[a-1] a += 1 a >>= 1; b >>= 1 # LCAの計算 (外から呼び出す関数) def query(u, v): fu = F[u]; fv = F[v] if fu > fv: fu, fv = fv, fu return S[min(_query(fu, fv + 1))[1]] ans_list = [] q = int(input()) for _ in range(q): u, v = map(int, input().split()) ans = query(u, v) ans_list.append(ans) print(*ans_list, sep="\n") ```
instruction
0
5,008
13
10,016
Yes
output
1
5,008
13
10,017
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` import math from collections import defaultdict def dfs(here, p, d, parent, depth, connect): parent[0][here] = p depth[here] = d for next_v in connect[here]: dfs(next_v, here, d + 1, parent, depth, connect) def lca(v1, v2, parent): v1, v2 = max(v1, v2), min(v1, v2) for i in range(max_log): if depth[v1] - depth[v2] >> i & 1: v1 = parent[i][v1] if v1 == v2: return v2 for i in range(max_log - 1, -1, -1): if parent[i][v1] != parent[i][v2]: v1 = parent[i][v1] v2 = parent[i][v2] return parent[0][v2] connect = defaultdict(list) v_num = int(input()) root = 0 for i in range(v_num): edge = [int(n) for n in input().split(" ")] connect[i].extend(edge[1:]) depth = [-1 for n in range(v_num)] max_log = int(math.log(v_num, 2)) parent = [[-1 for n in range(v_num)] for m in range(max_log)] dfs(root, -1, 0, parent, depth, connect) for i in range(max_log - 1): for v in range(v_num): parent[i + 1][v] = -1 if parent[i][v] < 0 else parent[i][parent[i][v]] q_num = int(input()) for _ in range(q_num): v1, v2 = (int(n) for n in input().split(" ") ) print(lca(v1, v2, parent)) ```
instruction
0
5,009
13
10,018
No
output
1
5,009
13
10,019
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` #!/usr/bin/env python3 # GRL_5_C: Tree - Lowest Common Ancestor # Post Order順を使用して判定する # q = 100000では3分近くかかり、実用に耐えず class Edge: __slots__ = ('v', 'w') def __init__(self, v, w): self.v = v self.w = w def either(self): return self.v def other(self, v): if v == self.v: return self.w else: return self.v class Graph: def __init__(self, v): self.v = v self._edges = [[] for _ in range(v)] def add(self, e): self._edges[e.v].append(e) self._edges[e.w].append(e) def adj(self, v): return self._edges[v] def edges(self): for es in self._edges: for e in es: yield e class LowestCommonAncestor: def __init__(self, graph, root): self.graph = graph self.root = root self._cache = {} self._dfs() def _dfs(self): n = self.graph.v visited = [False] * n parent = [None] * n post_order = [0] * n stack = [self.root] i = 0 while stack: v = stack.pop() if not visited[v]: visited[v] = True stack.append(v) for e in self.graph.adj(v): w = e.other(v) if not visited[w]: parent[w] = v stack.append(w) else: post_order[v] = i i += 1 self.post_order = post_order self.parent = parent def find(self, v, w): pos = self.post_order i = pos[v] j = pos[w] if i > j: i, j = j, i v, w = w, v vv = v while i < j: if (vv, w) in self._cache: vv = self._cache[(vv, w)] break vv = self.parent[vv] i = pos[vv] self._cache[(v, w)] = vv return vv def run(): n = int(input()) g = Graph(n) for i in range(n): k, *cs = [int(i) for i in input().split()] if k > 0: for j in cs: g.add(Edge(i, j)) lca = LowestCommonAncestor(g, 0) q = int(input()) for _ in range(q): v, w = [int(i) for i in input().split()] print(lca.find(v, w)) if __name__ == '__main__': run() ```
instruction
0
5,010
13
10,020
No
output
1
5,010
13
10,021
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` from sys import stdin from collections import defaultdict readline = stdin.readline def main(): n = int(readline()) g = dict() for i in range(n): nodes = list(map(int, readline().split())) g[i] = nodes[1:] print(g) euler, height = euler_tour(g, n) index = defaultdict(list) for i in range(len(euler)): index[euler[i]].append(i) rmql = [(height[i], i) for i in euler] rmq = segment_tree(rmql,min,(float('inf'),)) q = int(readline()) for i in range(q): u, v = map(int, readline().split()) l, r = index[u][0], index[v][-1] if l > r: l, r = index[v][0], index[u][-1] print(rmq.find(l, r)[1]) def euler_tour(g, size): height = [None] * size euler = [] root = 0 dfs_stack = [(root, None, 0)] while dfs_stack: u, prev, h = dfs_stack.pop() height[u] = h euler.append(prev) if g[u]: dfs_stack.extend((v, u, h + 1) for v in g[u]) else: euler.append(u) return euler[1:], height import math class segment_tree: def __init__(self, dat, query, default=0): self.offset = 2 ** math.ceil(math.log(len(dat), 2)) self.table = [default] * self.offset + dat + [default] * (self.offset - len(dat)) self.query = query for i in reversed(range(1, self.offset)): self.table[i] = self.query(self.table[2 * i], self.table[2 * i + 1]) # [l, r] closed-interval def find(self, l, r): return self.query(self.__range(l,r)) def __range(self, l, r): l += self.offset r += self.offset while l <= r: if l & 1: yield self.table[l] l += 1 l >>= 1 if r & 1 == 0: yield self.table[r] r -= 1 r >>= 1 def update(self, i, x): i += self.offset self.table[i] = x while 1 < i: i >>= 1 self.table[i] = self.query(self.table[2 * i], self.table[2 * i + 1]) main() ```
instruction
0
5,011
13
10,022
No
output
1
5,011
13
10,023
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 16 3 1 2 3 3 4 5 6 0 2 7 8 0 2 9 10 2 14 15 0 0 0 3 11 12 13 0 0 0 0 0 10 1 3 4 5 4 9 4 10 4 13 9 13 9 14 9 8 13 14 13 7 output: 0 1 1 1 1 5 1 0 1 0 """ import sys import math sys.setrecursionlimit(int(1e5)) def dfs(v, v_parent, v_depth): # print(parent, v, v_parent) parent[0][v] = v_parent depth[v] = v_depth for adj in adj_table[v]: if adj != v_parent: dfs(adj, v, v_depth + 1) return None def dfs_init(): dfs(root, -1, 0) for k in range(v_log - 1): for v in range(v_num): if parent[k][v] < 0: parent[k + 1][v] = -1 else: parent[k + 1][v] = parent[k][parent[k][v]] return None def lca(u, v): if depth[u] > depth[v]: u, v = v, u for k in range(v_log): if ((depth[v] - depth[u]) >> k) & 1: v = parent[k][v] if u == v: return u for k in range(v_log - 1, -1, -1): if parent[k][u] != parent[k][v]: u = parent[k][u] v = parent[k][v] return parent[0][u] def cmd_exec(): for query in c_queries: q1, q2 = map(int, query) print(lca(q1, q2)) return None if __name__ == '__main__': # with open('test.txt', 'r') as f: # _input = f.readlines() _input = sys.stdin.readlines() v_num = int(_input[0]) c_edges = map(lambda x: x.split(), _input[1:v_num + 1]) q_num = int(_input[v_num + 1]) c_queries = map(lambda x: x.split(), _input[v_num + 2:]) v_log = math.floor(math.log2(v_num)) + 1 parent = [[-1] * v_num for _ in range(v_log)] depth = [-1] * v_num root = 0 adj_table = tuple([] for _ in range(v_num)) for idx, edge in enumerate(c_edges): c_num, *children = map(int, edge) assert len(children) == c_num adj_table[idx].extend(children) dfs_init() cmd_exec() ```
instruction
0
5,012
13
10,024
No
output
1
5,012
13
10,025
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
5,029
13
10,058
Tags: dfs and similar, dsu, graphs Correct Solution: ``` N, M = map(int, input().split()) g = [[] for i in range(N)] for i in range(M): a, b = map(int, input().split()) g[a-1].append(b-1) g[b-1].append(a-1) visited = [0] * N def dfs(n): global visn visited[n] = 1 for i in g[n]: if not visited[i]: dfs(i) if N != M: print("NO") exit() dfs(0) if 0 in visited: print("NO") else: print("FHTAGN!") ```
output
1
5,029
13
10,059
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
5,030
13
10,060
Tags: dfs and similar, dsu, graphs Correct Solution: ``` n, m = [int(i) for i in input().split()] c = [int(i) for i in range(n+1)] def find (u): if u == c[u]: return u c[u] = find(c[u]) return c[u] ciclos = 0 for i in range(m): x, y = [int(j) for j in input().split()] x = find(x) y = find(y) if find(x) != find(y): c[x] = c[y] = max(x, y) else: ciclos += 1 conexo = True componente = find(1) for i in range(2, n+1, 1): if find(i) != componente: conexo = False if conexo and ciclos == 1: print('FHTAGN!') else: print('NO') exit(0) ```
output
1
5,030
13
10,061
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
5,031
13
10,062
Tags: dfs and similar, dsu, graphs Correct Solution: ``` inp = input().split() n = int(inp[0]) m = int(inp[1]) def dfs(x): f.add(x) for y in e[x]: if not y in f: dfs(y) if n >= 3 and n == m: e, f = [[] for i in range(n + 1)], set() for j in range(m): x, y = map(int, input().split()) e[x].append(y) e[y].append(x) dfs(1) print('FHTAGN!' if len(f) == n else 'NO') else: print('NO') ```
output
1
5,031
13
10,063
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
5,032
13
10,064
Tags: dfs and similar, dsu, graphs Correct Solution: ``` class Graph(): def __init__(self, number_nodes): self.nodes = [0] * (number_nodes+1) for i in range(number_nodes): self.nodes[i+1] = Node(i+1) def connect(self, node_1, node_2): self.find(node_1).neighbors.append(self.find(node_2)) self.find(node_2).neighbors.append(self.find(node_1)) def find(self, i): return self.nodes[i] def bfs(self): stack = [] stack.append(self.nodes[1]) visited = {} fhtagn = False while(stack): current = stack.pop() if current.value in visited: continue visited[current.value] = 1 for neighbor in current.neighbors: if neighbor.value not in visited: neighbor.known_by = current stack.append(neighbor) else: if current.known_by != neighbor: if fhtagn==False: fhtagn = True else: return("NO") if fhtagn == True and len(visited)+1 == len(self.nodes): return("FHTAGN!") return("NO") class Node(): def __init__(self, value): self.value = value self.neighbors = [] self.known_by = self vertices, edges = [int(s) for s in input().split()] graph = Graph(vertices) for i in range(edges): node_1, node_2 = [int(s) for s in input().split()] graph.connect(node_1, node_2) print(graph.bfs()) ```
output
1
5,032
13
10,065
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
5,033
13
10,066
Tags: dfs and similar, dsu, graphs Correct Solution: ``` lectura=lambda:map(int, input().split()) nVertices, nEdges= lectura() array1= [[] for i in range(nVertices + 1)] array2=[] for i in range(0, nEdges): x, y= lectura() array1[x].append(y) array1[y].append(x) def DFS(x): array2.append(x) for y in array1[x]: if (y not in array2): DFS(y) DFS(1) if(nVertices!=nEdges): conclusion="NO" else: if(len(array2)==nVertices): conclusion="FHTAGN!" else: conclusion="NO" print(conclusion) ```
output
1
5,033
13
10,067
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
5,034
13
10,068
Tags: dfs and similar, dsu, graphs Correct Solution: ``` # Problem from Codeforces # http://codeforces.com/problemset/problem/103/B 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): 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) 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 def solution(): m, n = map(int, input().split()) if m != n: print('NO') return 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') return print('FHTAGN!') solution() ```
output
1
5,034
13
10,069
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
5,035
13
10,070
Tags: dfs and similar, dsu, graphs Correct 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 else: V = [] S = [] for i in range(n+1): #Armado de lista para conexiones de vertices V.append([]) 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(a): S.append(a) for v in V[a]: if not v in S: DFS(v) DFS(1) #hay que comenzar en algun punto if len(S) == n: print("FHTAGN!") else: print("NO") ```
output
1
5,035
13
10,071
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
5,036
13
10,072
Tags: dfs and similar, dsu, graphs Correct Solution: ``` def dfs(u): vis[u]=1 for v in adj[u]: if vis[v]==0: dfs(v) n,m=map(int,input().split()) vis=[0]*n adj=[[] for w in range(n)] for i in range (m): u,v = map(int,input().split()) u-=1 v-=1 adj[u].append(v) adj[v].append(u) cnt=0 for i in range(0,n-1): if vis[i]==0: dfs(i) cnt+=1 if cnt==1 and n==m: print('FHTAGN!') else: print('NO') ```
output
1
5,036
13
10,073
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") else: V = [] S = [] for i in range(n+1): #Armado de lista para conexiones de vertices V.append([]) 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(a): S.append(a) for v in V[a]: if not v in S: DFS(v) DFS(1) #hay que comenzar en algun punto if len(S) == n: print("FHTAGN!") else: print("NO") ```
instruction
0
5,037
13
10,074
Yes
output
1
5,037
13
10,075
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 dfs(graph, start): visited[start] = True for i in graph[start]: if not visited[i]: dfs(graph, i) a, b = list(map(int, input().split(' '))) g = {} for i in range(1, a+1): g[i] = [] for i in range(b): x, y = map(int, input().split(' ')) g[x].append(y) g[y].append(x) visited = [True] + [False] * a dfs(g, 1) if False in visited: print("NO") quit() if a != b: print("NO") quit() print("FHTAGN!") ```
instruction
0
5,038
13
10,076
Yes
output
1
5,038
13
10,077
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: ``` #Cthulhu n , m = map(int,input().split()) lst = [[] for i in range(n +1)] for i in range(m): x , y = map(int, input().split()) lst[x].append(y) lst[y].append(x) #print(lst) a = [0]*(n+1) b = [0]*(n+1) c = 0 def func(n): global a, b, c, lst a[n] = 1 for j in lst[n]: if a[j] == 1 and b[n] != j: c += 1 if(not a[j]): b[j] = n func(j) a[n] = 2 func(1) if c -1 or 0 in a[1: ]: print("NO") else: print("FHTAGN!") ```
instruction
0
5,039
13
10,078
Yes
output
1
5,039
13
10,079
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()] g = [[] for i in range(n)] mark = [False] * n if n is not m: print("NO") else: def dfs(node): mark[node] = True for u in g[node]: if mark[u] is False: dfs(u) for i in range(m): v, u = [int(x)-1 for x in input().split()] g[v].append(u) g[u].append(v) dfs(0) ans = True for i in range(1, n): if mark[i] is False: ans = False if ans is True: print("FHTAGN!") else: print("NO") ```
instruction
0
5,040
13
10,080
Yes
output
1
5,040
13
10,081
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 dfs(visited,adj,ind,parent): if(visited[ind]==1): return [-1,-1] visited[ind]=1 for i in adj[ind]: if(visited[i]==0): parent[i]=ind x=dfs(visited,adj,i,parent) if(x[0]!=-1): return x elif(visited[i]==1 and i!=parent[ind]): return [i,ind] return [-1,-1] def dfsx(visited,adj,ind,parent,part): if(visited[ind]==1): return 0 visited[ind]=1 for i in adj[ind]: if(part[i]==1): continue if(visited[i]==0): parent[i]=ind x=dfs(visited,adj,i,parent) if(x!=0): return 1 elif(visited[i]==1 and i!=parent[ind] and part[i]==0): return 1 return 0 n,m=[int(i) for i in input().split()] l=[] adj=[[] for i in range(n)] part_cycle=[0 for i in range(n)] for i in range(m): a,b=[int(x) for x in input().split()] adj[a-1].append(b-1) adj[b-1].append(a-1) parent=[-1 for i in range(n)] visited=[0 for i in range(n)] x=dfs(visited,adj,0,parent) if(x[0]==-1): print("NO") else: part_cycle[x[0]]=1; part_cycle[x[1]]= 1; cycle=[] ind=x[1] cycle.append(x[0]) while(ind!=x[0]): cycle.append(ind) part_cycle[ind]=1; part_cycle[parent[ind]]=1; ind=parent[ind] flag=0 for i in cycle: x=dfsx(visited, adj, i, parent,part_cycle) if(x==1): print("NO") flag=1 break if(flag==0): print("FHTAGN!") ```
instruction
0
5,041
13
10,082
No
output
1
5,041
13
10,083
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: ``` #!/usr/bin/python3 # B - Cthulhu import sys def dfs(curvertex): visited.add(curvertex) if curvertex in adjlist: for v in adjlist[curvertex]: if v not in visited: dfs(v) n, m = [int(x) for x in input().split()] if n != m: print("NO") sys.exit() adjlist = {} visited = set() for i in range(m): x, y = [int(x) for x in input().split()] if x not in adjlist: adjlist[x] = [y] else: adjlist[x].append(y) if y not in adjlist: adjlist[y] = [x] else: adjlist[y].append(x) dfs(next(iter(adjlist.keys()))) if visited == set(adjlist.keys()): print("FHTAGN!") else: print ("NO") ```
instruction
0
5,042
13
10,084
No
output
1
5,042
13
10,085
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: ``` read = lambda: map(int, input().split()) n, m = read() graph = [set() for _ in range(n + 1)] for __ in range(m): u, v = read() graph[u].add(v) graph[v].add(u) def find_cycle(start): parents, stack = [0] * (n + 1), [(start, +1)] while stack: vertex, parent = stack.pop() parents[vertex] = parent for neighbour in graph[vertex]: if neighbour != parent: if parents[neighbour]: cycle = set() cycle.add(neighbour) while vertex <= neighbour: cycle.add(vertex) vertex = parents[vertex] return cycle stack.append((neighbour, vertex)) return set() cyc = find_cycle(1) if not cyc: print('NO') exit() def dfs(): visited = set(cyc) for start in cyc: stack = [(v, start) for v in graph[start] if v not in cyc] while stack: vertex, parent = stack.pop() visited.add(vertex) for neighbour in graph[vertex]: if neighbour != parent: if neighbour in visited: return set() stack.append((neighbour, vertex)) return visited print('FHTAGN!' if len(dfs()) == n else 'NO') ```
instruction
0
5,043
13
10,086
No
output
1
5,043
13
10,087
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: ``` """ https://codeforces.com/problemset/problem/103/B """ parent = [] ranks = [] edge = [] isCthulhu = False def makeSet(n): global parent, ranks parent = [i for i in range(n)] ranks = [0 for _ in range(n)] def findSet(u): global parent if parent[u] != u: parent[u] = findSet(parent[u]) return parent[u] def unionSet(u, v): global parent, ranks, isCthulhu up = findSet(u) vp = findSet(v) if up == vp: isCthulhu = True if ranks[up] > ranks[vp]: parent[vp] = up elif ranks[up] < ranks[vp]: parent[up] = vp else: ranks[up] += 1 parent[vp] = up def Kruskal(): for i in range(len(edge)): u = edge[i][0] v = edge[i][1] if u != v: unionSet(u, v) def main(): n, m = map(int, input().split()) makeSet(n + 1) for _ in range(m): edge.append(list(map(int, input().split()))) Kruskal() if isCthulhu: print('FHTAGN!') else: print('NO') if __name__ == "__main__": main() ```
instruction
0
5,044
13
10,088
No
output
1
5,044
13
10,089
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly n - 1 edges. Petya wondered how many vertex triples (i, j, k) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1, 2, 3) is not equal to the triple (2, 1, 3) and is not equal to the triple (1, 3, 2). Find how many such triples of vertexes exist. Input The first line contains the single integer n (1 ≤ n ≤ 105) — the number of tree vertexes. Next n - 1 lines contain three integers each: ui vi wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — the pair of vertexes connected by the edge and the edge's weight. Output On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator. Examples Input 4 1 2 4 3 1 2 1 4 7 Output 16 Input 4 1 2 4 1 3 47 1 4 7447 Output 24 Note The 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2). In the second sample all the triples should be counted: 4·3·2 = 24.
instruction
0
5,825
13
11,650
Tags: dp, dsu, trees Correct Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(2*10**5) def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def dfs(u,p): for j in adj[u]: if j!=p: yield dfs(j, u) if d[j,u]!=0: ways[u]+=(ways[j]+1) yield @bootstrap def dfs2(u,p,v): for j in adj[u]: if j!=p: if d[u,j]==0: yield dfs2(j,u,0) else: yield dfs2(j,u,v+ways[u]-ways[j]) ans[u]= ways[u]*(ways[u]-1) + v*(v-1) + 2*(ways[u]*v+ (ways[u]+v)*(n-1-ways[u]-v)) yield def val(n): for j in str(n): if j=="4" or j=="7": pass else: return 1 return 0 n=int(input()) adj=[[] for i in range(n+1)] d=dict() for j in range(n-1): c=list(map(int,input().split())) adj[c[0]].append(c[1]) adj[c[1]].append(c[0]) c[2]=val(c[2]) d[c[0],c[1]]=c[2] d[c[1],c[0]]=c[2] ways=[0]*(n+1) dfs(1,0) ans=[0]*(n+1) dfs2(1,0,0) print(n*(n-1)*(n-2)-sum(ans)) ```
output
1
5,825
13
11,651
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly n - 1 edges. Petya wondered how many vertex triples (i, j, k) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1, 2, 3) is not equal to the triple (2, 1, 3) and is not equal to the triple (1, 3, 2). Find how many such triples of vertexes exist. Input The first line contains the single integer n (1 ≤ n ≤ 105) — the number of tree vertexes. Next n - 1 lines contain three integers each: ui vi wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — the pair of vertexes connected by the edge and the edge's weight. Output On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator. Examples Input 4 1 2 4 3 1 2 1 4 7 Output 16 Input 4 1 2 4 1 3 47 1 4 7447 Output 24 Note The 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2). In the second sample all the triples should be counted: 4·3·2 = 24. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(2*10**5) def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def dfs(u,p): for j in adj[u]: if j!=p: yield dfs(j, u) if d[j,u]!=0: ways[u]+=(ways[j]+1) yield @bootstrap def dfs2(u,p,v): for j in adj[u]: if j!=p: if d[u,j]==0: yield dfs2(j,u,0) else: yield dfs2(j,u,v+ways[u]-ways[j]) ans[u]=2*(ways[u]*(n-2)+v*(n-2)-(ways[u]*(ways[u]-1)+v*(v-1)+ways[u]*v)) yield def val(n): for j in str(n): if j=="4" or j=="7": pass else: return 1 return 0 n=int(input()) adj=[[] for i in range(n+1)] d=dict() for j in range(n-1): c=list(map(int,input().split())) adj[c[0]].append(c[1]) adj[c[1]].append(c[0]) c[2]=val(c[2]) d[c[0],c[1]]=c[2] d[c[1],c[0]]=c[2] ways=[0]*(n+1) dfs(1,0) ans=[0]*(n+1) dfs2(1,0,0) print(n*(n-1)*(n-2)-sum(ans)) ```
instruction
0
5,826
13
11,652
No
output
1
5,826
13
11,653
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
instruction
0
6,193
13
12,386
Tags: graphs, shortest paths Correct Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] edges = [] diameters = [] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 edges.append(v) graph[u].append(v) graph[v].append(u) distance = [maxValue]*n cc = [maxValue]*n for i in range(0, n): if distance[i] == maxValue: cc = bfs_2k(graph, i, distance) if(cc == None): print(-1) return diameters.append(distance[cc[-1]]) for v in range(1, len(cc)): newDistance = [maxValue]*n samecc = bfs_2k(graph, cc[v], newDistance) diameters[-1] = max(diameters[-1], newDistance[samecc[-1]]) print(sum(diameters)) def bfs_2k(graph, initVertex, dist): queue = [] qlen = 1 queue.append(initVertex) dist[initVertex] = 0 u = None i = 0 while qlen: u = queue[i] qlen-=1 for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue.append(v) qlen+=1 if (dist[u] - dist[v]) % 2 == 0: return None i+=1 return queue solve() ```
output
1
6,193
13
12,387
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
instruction
0
6,194
13
12,388
Tags: graphs, shortest paths Correct Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): global n, m n, m = map(lambda x: int(x), input().split()) global maxVal maxVal = n**2 graph = [[] for _ in range(0, n)] for _ in range(0, m): u, v = map(lambda x: int(x)-1, input().split()) graph[u].append(v) graph[v].append(u) ccNum = 0 cc = [0]*n # pueden ser a lo sumo vertices aislados innrCc = [0]*n dmtrs = [0]*n distance = [maxVal]*n for i in range(0, n): if distance[i] == maxVal: ccLen = bfs_2k(graph, i, distance, cc) if(ccLen is None): print(-1) return dmtrs[ccNum] = distance[cc[ccLen-1]] for v in range(0, ccLen): innrDst = [maxVal]*n bfs_2k(graph, cc[v], innrDst, innrCc) dmtrs[ccNum] = max(dmtrs[ccNum], innrDst[innrCc[ccLen-1]]) ccNum += 1 print(sum(dmtrs)) def bfs_2k(graph, s, dist, cc): queue = deque() queue.append(s) dist[s] = 0 ccLen = 0 while queue: u = queue.popleft() for v in graph[u]: if(dist[v] == maxVal): dist[v] = dist[u] + 1 queue.append(v) cc[ccLen] = v ccLen += 1 elif (dist[u] - dist[v]) % 2 == 0: return None return ccLen solve() ```
output
1
6,194
13
12,389
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
instruction
0
6,195
13
12,390
Tags: graphs, shortest paths Correct Solution: ``` def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] edges = [] diameters = [] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 edges.append(v) graph[u].append(v) graph[v].append(u) distance = [maxValue]*n queueCc = [0]*n queue = [0]*n for i in range(0, n): if distance[i] == maxValue: qlen = bfs_2k(graph, i, distance, queueCc) if(qlen == None): print(-1) return diameters.append(distance[queueCc[qlen-1]] if qlen > 0 else 0) for v in range(1, qlen): newDistance = [maxValue]*n bfs_2k(graph, queueCc[v], newDistance, queue) diameters[-1] = max(diameters[-1], newDistance[queue[qlen-1]]) print(sum(diameters)) def bfs_2k(graph, initVertex, dist, queue): dist[initVertex] = 0 queue[0] = initVertex qlen = qcount = 1 i = 0 while qcount: u = queue[i] qcount -= 1 i += 1 for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue[qlen] = v qlen += 1 qcount+=1 if (dist[u] - dist[v]) % 2 == 0: return None return qlen solve() ```
output
1
6,195
13
12,391
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
instruction
0
6,196
13
12,392
Tags: graphs, shortest paths Correct Solution: ``` n, m = map(int, input().split()) g = [[] for _ in range(n)] for i in range(m): p, q = map(int, input().split()) g[p - 1].append(q - 1) g[q - 1].append(p - 1) comp = [-1] * n def shortest(root): dist = [-1] * n q = [0] * n left, right = 0, 1 q[left] = root dist[root] = 0 good = True while left < right: x = q[left] left = left + 1 for i in g[x]: if dist[i] is -1: dist[i] = 1 + dist[x] q[right] = i right = right + 1 elif dist[i] == dist[x]: good = False far = 0 for i in dist: if far < i: far = i return good, far, dist arr = [0] * n good = True for i in range(n): _, opt, dist = shortest(i) if _ is False: good = False if comp[i] is -1: for j in range(n): if dist[j] is not -1: comp[j] = i if arr[comp[i]] < opt: arr[comp[i]] = opt if good is False: print('-1') else: print(sum(arr)) ```
output
1
6,196
13
12,393
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
instruction
0
6,197
13
12,394
Tags: graphs, shortest paths Correct Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 graph[u].append(v) graph[v].append(u) diameters = [0]*n ccNum =0 distance = [maxValue]*n cc = [0]*n # los a lo sumo n-1 vertices en la misma componente conexa de i # los a lo sumo n-1 vertices en la misma componente conexa de i en distinto orden innerCc = [0]*n for i in range(0, n): if distance[i] == maxValue: ccLen = bfs_2k(graph, i, distance, cc) if(ccLen == None): print(-1) return diameters[ccNum]=distance[cc[ccLen-1]] for v in range(0, ccLen): innerDist = [maxValue]*n bfs_2k(graph, cc[v], innerDist, innerCc) diameters[ccNum] = max(diameters[ccNum], innerDist[innerCc[ccLen-1]]) ccNum+=1 print(sum(diameters)) def bfs_2k(graph, initVertex, dist, cc): queue = deque() queue.append(initVertex) dist[initVertex] = 0 ccLen = 0 while queue: u = queue.popleft() for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue.append(v) cc[ccLen] = v ccLen += 1 if (dist[u] - dist[v]) % 2 == 0: return None return ccLen solve() ```
output
1
6,197
13
12,395
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
instruction
0
6,198
13
12,396
Tags: graphs, shortest paths Correct Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 graph[u].append(v) graph[v].append(u) diameters = [] distance = [maxValue]*n cc = [0]*n # los a lo sumo n-1 vertices en la misma componente conexa de i innerCc = [0]*n # los a lo sumo n-1 vertices en la misma componente conexa de i en distinto orden for i in range(0, n): if distance[i] == maxValue: ccLen = bfs_2k(graph, i, distance,cc) if(ccLen==None): print(-1) return diameters.append(distance[cc[ccLen-1]] if ccLen > 0 else 0) for v in range(0,ccLen): innerDist = [maxValue]*n bfs_2k(graph, cc[v], innerDist,innerCc) diameters[-1] = max(diameters[-1], innerDist[innerCc[ccLen-1]]) print(sum(diameters)) def bfs_2k(graph, initVertex, dist,cc): queue = deque() queue.append(initVertex) dist[initVertex] = 0 ccLen = 0 while queue: u = queue.popleft() for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue.append(v) cc[ccLen]=v ccLen+=1 if (dist[u] - dist[v]) % 2 == 0: return None return ccLen solve() ```
output
1
6,198
13
12,397
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
instruction
0
6,199
13
12,398
Tags: graphs, shortest paths Correct Solution: ``` from collections import deque def solve(): global n, m n, m = map(lambda x: int(x), input().split()) global maxVal maxVal = n**2 graph = [[] for _ in range(0, n)] for _ in range(0, m): u, v = map(lambda x: int(x)-1, input().split()) graph[u].append(v) graph[v].append(u) ccNum = 0 cc = [0]*n # pueden ser a lo sumo vertices aislados innrCc = [0]*n dmtrs = [0]*n distance = [maxVal]*n for i in range(0, n): if distance[i] == maxVal: ccLen = bfs_2k(graph, i, distance, cc) if(ccLen is None): print(-1) return dmtrs[ccNum] = distance[cc[ccLen-1]] for v in range(0, ccLen): innrDst = [maxVal]*n bfs_2k(graph, cc[v], innrDst, innrCc) dmtrs[ccNum] = max(dmtrs[ccNum], innrDst[innrCc[ccLen-1]]) ccNum += 1 print(sum(dmtrs)) def bfs_2k(graph, s, dist, cc): queue = deque() queue.append(s) dist[s] = 0 ccLen = 0 while queue: u = queue.popleft() for v in graph[u]: if(dist[v] == maxVal): dist[v] = dist[u] + 1 queue.append(v) cc[ccLen] = v ccLen += 1 elif (dist[u] - dist[v]) % 2 == 0: return None return ccLen solve() ```
output
1
6,199
13
12,399
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
instruction
0
6,200
13
12,400
Tags: graphs, shortest paths Correct Solution: ``` n, m = map(int, input().split()) g = [[] for _ in range(n)] for i in range(m): p, q = map(int, input().split()) g[p - 1].append(q - 1) g[q - 1].append(p - 1) comp = [-1] * n def shortest(root): dist = [-1] * n q = [0] * n left, right = 0, 1 q[left] = root dist[root] = 0 good = True while left < right: x = q[left] left = left + 1 for i in g[x]: if dist[i] is -1: dist[i] = 1 + dist[x] q[right] = i right = right + 1 elif dist[i] == dist[x]: good = False far = 0 for i in dist: if i > far: far = i return good, far, dist arr = [0] * n good = True for i in range(n): _, opt, dist = shortest(i) if _ is False: good = False if comp[i] is -1: for j in range(n): if dist[j] is not -1: comp[j] = i if arr[comp[i]] < opt: arr[comp[i]] = opt if good is False: print('-1') else: print(sum(arr)) ```
output
1
6,200
13
12,401
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Submitted Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] edges = [] diameters = [] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 edges.append(v) graph[u].append(v) graph[v].append(u) distance = [maxValue]*n cc = [maxValue]*n for i in range(0, n): if distance[i] == maxValue: cc = bfs_2k(graph, i, distance) if(cc == None): print(-1) return diameters.append(distance[cc[-1]]) for v in range(1, len(cc)): newDistance = [maxValue]*n samecc = bfs_2k(graph, cc[v], newDistance) diameters[-1] = max(diameters[-1], newDistance[samecc[-1]]) print(sum(diameters)) def bfs_2k(graph, initVertex, dist): queue = [] qlen = 1 queue.append(initVertex) dist[initVertex] = 0 u = None while qlen: u = queue[0] qlen-=1 for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue.append(v) qlen+=1 if (dist[u] - dist[v]) % 2 == 0: return None return queue solve() ```
instruction
0
6,201
13
12,402
No
output
1
6,201
13
12,403
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Submitted Solution: ``` n, m = map(int, input().split()) g = [[] for _ in range(n)] for i in range(m): p, q = map(int, input().split()) g[p - 1].append(q - 1) g[q - 1].append(p - 1) comp = [-1] * n def shortest(root): dist = [-1] * n q = [0] * n left, right = 0, 1 q[left] = root dist[root] = 0 good = True while left < right: x = q[left] left = left + 1 for i in g[x]: if dist[i] is -1: dist[i] = 1 + dist[x] q[right] = i right = right + 1 elif dist[i] == dist[x]: good = False far = 0 for i in dist: if i > far: far = i return good, far, dist arr = [0] * n good = True for i in range(n): _, opt, dist = shortest(i) if _ is False: good = False if arr[comp[i]] < opt: arr[comp[i]] = opt if good is False: print('-1') else: print(sum(arr)) ```
instruction
0
6,202
13
12,404
No
output
1
6,202
13
12,405
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Submitted Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 graph[u].append(v) graph[v].append(u) diameters = [] ccNum = 1 # los a lo sumo n vertices en la misma componente conexa de i cc = [maxValue]*n for v in range(0, n): if cc[v] == maxValue: distance = [maxValue]*n last = bfs_2k(graph, v, distance, cc, ccNum) cc[v] = -cc[v] if(last == None): print(-1) return diameters.append(distance[last]) ccNum += 1 for v in range(0, n): if cc[v] > 0: distance = [maxValue]*n last = bfs_2k(graph, v, distance, cc, cc[v]) diameters[cc[v]-1] = max(diameters[-1], distance[last]) print(sum(diameters)) def bfs_2k(graph, initVertex, dist, cc, ccNum): queue = deque() queue.append(initVertex) dist[initVertex] = 0 cc[initVertex] = ccNum u = None while queue: u = queue.popleft() for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue.append(v) cc[v] = ccNum if (dist[u] - dist[v]) % 2 == 0: return None return u solve() ```
instruction
0
6,203
13
12,406
No
output
1
6,203
13
12,407
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Submitted Solution: ``` n, m = map(int, input().split()) g = [[] for _ in range(n)] for i in range(m): p, q = map(int, input().split()) g[p - 1].append(q - 1) g[q - 1].append(p - 1) def shortest(root): dist = [-1] * n q = [0] * n left, right = 0, 1 q[left] = root dist[root] = 0 good = True while left < right: x = q[left] left = left + 1 for i in g[x]: if dist[i] is -1: dist[i] = 1 + dist[x] q[right] = i right = right + 1 elif dist[i] == dist[x]: good = False return good, dist def getDiameter(root): good, dist = shortest(root) far = root for i in range(n): if far < dist[i]: far = i dia = 0 _, dist = shortest(far) for i in range(n): if dia < dist[i]: dia = dist[i] return good, dia, dist vis = [False] * n good = True ans = 0 for i in range(n): if vis[i] is False: _, add, dist = getDiameter(i) if _ is False: good = False ans = ans + add for j in range(n): if dist[j] is not -1: vis[j] = True if good is False: print('-1') else: print(ans) ```
instruction
0
6,204
13
12,408
No
output
1
6,204
13
12,409
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences.
instruction
0
6,612
13
13,224
Tags: dfs and similar, dsu, graphs, math, trees Correct Solution: ``` # -*- coding: utf-8 -*- # @Date : 2019-03-22 08:08:26 # @Author : raj lath (oorja.halt@gmail.com) # @Link : link # @Version : 1.0.0 import sys sys.setrecursionlimit(10**5+1) inf = int(10 ** 20) max_val = inf min_val = -inf RW = lambda : sys.stdin.readline().strip() RI = lambda : int(RW()) RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()] RWI = lambda : [x for x in sys.stdin.readline().strip().split()] vertices, limit = RMI() graph = [[] for _ in range(vertices)] for i in range(vertices - 1): u, v, x = RMI() graph[u - 1].append((v - 1, x)) graph[v - 1].append((u - 1, x)) done = [0 for _ in range(vertices)] comps = [] for i in range(vertices): if done[i]:continue done[i] = 1 comps.append([i]) qu = [i] while qu: curr_u = qu[0] qu = qu[1:] for u, x in graph[curr_u]: if x == 0 and done[u] == 0: qu.append(u) done[u] = 1 comps[-1].append(u) answer = vertices ** limit for comp in comps: answer -= len(comp) ** limit print( answer % (10 ** 9 + 7)) ```
output
1
6,612
13
13,225
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences.
instruction
0
6,613
13
13,226
Tags: dfs and similar, dsu, graphs, math, trees Correct Solution: ``` def factorial(n): if n == 0: return 1 else: return (n * factorial(n-1))%(10**9+7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n-1): a,b,c = [int(i) for i in input().split()] if c == 0: s[a-1].append(b-1) s[b - 1].append(a - 1) used = [False]*n ans = pow(n, k, 10**9+7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c=0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c+=1 ans = (ans-pow(len(comp), k, 10**9+7))%(10**9+7) print(ans) ```
output
1
6,613
13
13,227
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences.
instruction
0
6,614
13
13,228
Tags: dfs and similar, dsu, graphs, math, trees Correct Solution: ``` from collections import Counter modulo = 10**9 + 7 def pow(a, n): res = 1 while n: #print('pow:', a, res, n) if n & 1: res *= a res %= modulo a *= a a %= modulo n //= 2 return res n, k = map(int, input().split()) links = [[i] for i in range(n)] def mark(a): res = links[a-1] while type(res[0]) == list: res = res[0] if type(links[a-1][0]) == list: links[a-1][:] = [res] return res for _ in range(n - 1): a, b, t = map(int, input().split()) if not t: ma = mark(a) mb = mark(b) #print(ma, mb, "->", *links) if ma != mb: mb[:] = [ma] #print(ma, mb, "->", *links) res = pow(n, k) for v in Counter(mark(x)[0] for x in range(1, n+1)).values(): #print(v, pow(v,k), res) res -= pow(v, k) res %= modulo print(res) ```
output
1
6,614
13
13,229
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences.
instruction
0
6,615
13
13,230
Tags: dfs and similar, dsu, graphs, math, trees Correct Solution: ``` # 1-indexed verticies import sys sys.setrecursionlimit(10 ** 5 + 10) n, k = map(int, input().split()) parents = [i for i in range(n + 1)] size = [1 for i in range(n + 1)] def find(a): if a == parents[a]: return a parents[a] = find(parents[a]) return parents[a] def union(a, b): a = find(a) b = find(b) if a != b: if size[a] < size[b]: a, b = b, a parents[b] = a size[a] += size[b] def same(a, b): return find(a) == find(b) for _ in range(n - 1): a, b, c = map(int, input().split()) if c == 0: union(a, b) dictionary = {} for i in range(1, n + 1): f = find(i) if f not in dictionary: dictionary[f] = 0 dictionary[f] += 1 s = pow(n, k, 10 ** 9 + 7) for key in dictionary: s -= pow(dictionary[key], k, 10 ** 9 + 7) print ((s % (10 ** 9 + 7) + (10 ** 9 + 7)) % (10 ** 9 + 7)) ```
output
1
6,615
13
13,231
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences.
instruction
0
6,616
13
13,232
Tags: dfs and similar, dsu, graphs, math, trees Correct Solution: ``` from collections import defaultdict as dd def dfs(s, tree, visited): stack = [] if s not in visited: stack.append(s) ccsize = 0 while stack: v = stack.pop() ccsize+=1 if v not in visited: visited.add(v) for n in tree[v]: if n not in visited: stack.append(n) return ccsize def read_input(): return [int(i) for i in input().split()] if __name__ == '__main__': n, k = read_input() total = n**k final = 10**9+7 tree = dd(list) for i in range(n-1): u, v, c = read_input() if c == 0: tree[u].append(v) tree[v].append(u) count_bad = 0 visited = set() for i in range(1,n+1): count_bad= (count_bad % final + dfs(i,tree, visited)**k % final) print(((total % final) - (count_bad % final) + final) % final) ```
output
1
6,616
13
13,233
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences.
instruction
0
6,617
13
13,234
Tags: dfs and similar, dsu, graphs, math, trees Correct Solution: ``` from collections import deque mod = 10**9 + 7 class TreeNode: def __init__(self, val): self.val = val self.edges = {} def add_edge(self, node, color): self.edges[node] = color n, k = map(int, input().split()) tree = [] for i in range(1, n+1): tree.append(TreeNode(i)) for _ in range(n-1): u, v, x = map(int, input().split()) tree[u-1].add_edge(v, x) tree[v-1].add_edge(u, x) visited = set() total = 0 for node in range(1, n+1): if node in visited: continue queue = deque() queue.append(node) visited.add(node) red_vertexes = 1 while queue: vertex = queue.popleft() for (e, c) in tree[vertex-1].edges.items(): if c == 0 and e not in visited: queue.append(e) red_vertexes = red_vertexes + 1 visited.add(e) total = (total + pow(red_vertexes, k, mod)) % mod total = (pow(n, k, mod) - total) % mod print(total) ```
output
1
6,617
13
13,235
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences.
instruction
0
6,618
13
13,236
Tags: dfs and similar, dsu, graphs, math, trees Correct Solution: ``` def dfs(x, p): vertex = 1 vis[x] = True for i in graph[x].keys(): if not vis[i]: vertex += dfs(i, x) return vertex n, k = map(int, input().split()) answer = pow(n, k) vis = [False for _ in range(n+1)] graph = [{} for _ in range(n+1)] dark_edges = 0 for _ in range(1, n): u, v, x = map(int, input().split()) if not x: graph[u][v] = x graph[v][u] = x else: dark_edges += 1 temp = 0 if dark_edges: for i in range(1, n+1): if not vis[i]: temp += pow(dfs(i, -1), k) print((pow(n, k) - temp) % (pow(10, 9) + 7)) else: print(0) ```
output
1
6,618
13
13,237
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences.
instruction
0
6,619
13
13,238
Tags: dfs and similar, dsu, graphs, math, trees Correct Solution: ``` import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') import math,datetime,functools,itertools,operator,bisect,fractions,statistics from collections import deque,defaultdict,OrderedDict,Counter from fractions import Fraction from decimal import Decimal from sys import stdout from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest sys.setrecursionlimit(111111) INF=99999999999999999999999999999999 class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def main(): mod=1000000007 # InverseofNumber(mod) # InverseofFactorial(mod) # factorial(mod) starttime=datetime.datetime.now() if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") ###CODE tc = 1 for _ in range(tc): n,k=ria() graph=[[] for i in range(n+1)] visited=[False]*(n+1) for i in range(n-1): a,b,type=ria() if type==0: graph[a].append(b) graph[b].append(a) def dfs(start): stack = [start] cs=0 while stack: start = stack[-1] # push unvisited children into stack if not visited[start]: cs+=1 visited[start] = True for child in graph[start]: if not visited[child]: stack.append(child) else: stack.pop() return cs nk=1 for i in range(k): nk=(n*nk)%mod for i in range(1,n+1): if not visited[i]: cs=dfs(i) rem=1 for i in range(k): rem=(cs*rem)%mod nk-=rem print(nk%mod) #<--Solving Area Ends endtime=datetime.datetime.now() time=(endtime-starttime).total_seconds()*1000 if(os.path.exists('input.txt')): print("Time:",time,"ms") class FastReader(io.IOBase): newlines = 0 def __init__(self, fd, chunk_size=1024 * 8): self._fd = fd self._chunk_size = chunk_size self.buffer = io.BytesIO() def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size)) 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, size=-1): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size)) 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() class FastWriter(io.IOBase): def __init__(self, fd): self._fd = fd self.buffer = io.BytesIO() self.write = self.buffer.write def flush(self): os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class FastStdin(io.IOBase): def __init__(self, fd=0): self.buffer = FastReader(fd) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class FastStdout(io.IOBase): def __init__(self, fd=1): self.buffer = FastWriter(fd) self.write = lambda s: self.buffer.write(s.encode("ascii")) self.flush = self.buffer.flush if __name__ == '__main__': sys.stdin = FastStdin() sys.stdout = FastStdout() main() ```
output
1
6,619
13
13,239
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences. Submitted Solution: ``` def dfs(s): stk,cnt=[],[] stk.append(s) cnt.append(0) while (len(stk)>0): s=stk[-1] ll=cnt[-1] visit[s]=1 # print(s) flag=1 for j in range(ll,len(adj[s]),1): if visit[adj[s][j]]==0: ct[0]+=1 cnt[-1]=j+1 stk.append(adj[s][j]) cnt.append(0) flag=0 break if flag: stk.pop() cnt.pop() def power(a,b,mod): res=1 while(b>0): if b&1: res=(res*a)%mod a=(a*a)%mod b>>=1 return res n,k=map(int,input().split()) adj=[0]*(n+1) for i in range(n+1): adj[i]=[] for i in range(n-1): x,y,f=map(int,input().split()) if f==0: adj[x].append(y) adj[y].append(x) visit=[0]*(n+1) mp={} # print(adj) for i in range(1,n+1): if visit[i]==0: ct=[1]*1 dfs(i) mp[i]=ct[0] ans=power(n,k,1000000007) for i in mp: ans=(ans-power(mp[i],k,1000000007)+1000000007)%1000000007 print(ans) ```
instruction
0
6,620
13
13,240
Yes
output
1
6,620
13
13,241
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences. Submitted Solution: ``` import sys import os.path Base = 1000000007 class Dsu: par = [] cnt = [] def __init__(self,size): self.par = [x for x in range(size + 2)] self.cnt = [1] * (size + 2) def findp(self,u): if self.par[u] == u: return u else : self.par[u] = self.findp(self.par[u]) return self.par[u] def join(self,u,v): u,v = self.findp(u),self.findp(v) if u == v : return if self.cnt[u] < self.cnt[v] : u,v = v,u self.cnt[u] += self.cnt[v] self.par[v] = u def getSize(self,u): return self.cnt[self.findp(u)] def mulmod(u,v): return ((u % Base) * (v % Base)) % Base def submod(u,v): return ((u % Base) - (v % Base) + Base) % Base def fastExp(x,h): ret = 1 while h > 0: if h & 1 == 1 : ret = mulmod(ret,x) x = mulmod(x,x) h = h // 2 return ret def solve(): # code goes here!! n,k = map(int,input().split()) dsu = Dsu(n) for i in range(1,n): u,v,x = map(int,input().split()) if x == 0: dsu.join(u,v) ans = fastExp(n,k) for u in range(1,n + 1): if dsu.findp(u) == u : ans = submod(ans,fastExp(dsu.getSize(u),k)) print(ans) def main(): # comment when submit. if os.path.exists('test.inp') : sys.stdin = open("test.inp","r") solve() if __name__ == '__main__': main() ```
instruction
0
6,621
13
13,242
Yes
output
1
6,621
13
13,243
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences. Submitted Solution: ``` import collections from collections import defaultdict as dd n,k = input().split() n,k=[int(n),int(k)] graph1=dd(list) power=(n**k)%(10**9+7) for x in range(n-1): u,v,x= input().split() u,v,x=[int(u),int(v),int(x)] if x==0: graph1[u].append(v) graph1[v].append(u) def bfs(graph, root): count=1 queue = collections.deque([root]) visited.add(root) while queue: vertex = queue.popleft() for neighbour in graph[vertex]: if neighbour not in visited: visited.add(neighbour) queue.append(neighbour) count+=1 return count visited=set() for i in range(1,n+1): if i not in visited: xy=bfs(graph1,i) power=(power-(xy**k)%(10**9+7))%(10**9+7) print(power%(10**9+7)) ```
instruction
0
6,622
13
13,244
Yes
output
1
6,622
13
13,245
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences. Submitted Solution: ``` import sys from sys import stdin,stdout sys.setrecursionlimit(2*10**5) n,k=stdin.readline().strip().split(' ');n,k=int(n),int(k) adj=[[] for i in range(n)] visited=[0 for i in range(n)] ver_col=[[] for i in range(n)] for i in range(n-1): u,v,x=stdin.readline().strip().split(' ');u,v,x=int(u),int(v),int(x) if x==0: adj[u-1].append(v-1) adj[v-1].append(u-1) count=[] def dfs(current_vertex,parent_vertex,idd): count[idd]+=1 visited[current_vertex]=1; arr=adj[current_vertex] while len(arr)>0: cv=arr.pop(0); if visited[cv]==0: count[idd]+=1; visited[cv]=1; arr+=adj[cv]; ctr=0 for i in range(n): if visited[i]==0: count.append(0) dfs(i,-1,len(count)-1) ctr+=count[-1] if ctr==n: break mo=10**9 + 7 ans=pow(n,k,mo) for i in count: ans=(ans-pow(i,k,mo))%mo stdout.write(str(ans)+"\n") #[[][][][][]] ```
instruction
0
6,623
13
13,246
Yes
output
1
6,623
13
13,247
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences. Submitted Solution: ``` import sys def dfs(start): global array,size used[start] = 1 for i in range(len(array[start])): if not used[array[start][i]]: size += 1 dfs(array[start][i]) sys.setrecursionlimit(5 * 10 ** 3) try: n, k = [int(s) for s in input().split()] array = [[] for i in range(n)] used = [0] * n for i in range(n - 1): u, v, num = [int(s) for s in input().split()] if num == 1: continue u -= 1 v -= 1 if not u in array[v]: array[v].append(u) if not v in array[u]: array[u].append(v) ans = (n ** k) for i in range(n): if not used[i]: size = 1 dfs(i) ans -= size ** k print(ans % (10 ** 9 + 7)) except Exception as e: print(e) ```
instruction
0
6,624
13
13,248
No
output
1
6,624
13
13,249
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≤ u_i, v_i ≤ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences. Submitted Solution: ``` # from debug import debug import sys;input = sys.stdin.readline from collections import deque mod = int(1e9)+7 n, k = map(int, input().split()) graph = [[] for _ in range(n)] for i in range(n-1): a, b, c = map(int, input().split()) if c: continue graph[a-1].append(b-1) graph[b-1].append(a-1) v = [False]*n ans = 0 for i in range(n): if not v[i]: q = deque([i]) v[i] = True s = 0 while q: node = q.popleft() s+=1 for j in graph[node]: if not v[j]: v[j] = True; q.append(j) ans = (ans%mod + pow(s, k, mod))%mod print(pow(n, k, mod) - ans) ```
instruction
0
6,625
13
13,250
No
output
1
6,625
13
13,251