message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide a correct Python 3 solution for this coding contest problem. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7
instruction
0
87,496
13
174,992
"Correct Solution: ``` import sys f_i = sys.stdin V, E = map(int, f_i.readline().split()) # adjacency matrix no_edge = float("inf") adj = [[no_edge] * V for i in range(V)] for i in range(V): adj[i][i] = 0 odd_b = 0 # bit DP to record odd vertex ans = 0 # acceptance of input for l_i in f_i: s, t, d = map(int, l_i.split()) t_d = min(d, adj[s][t]) adj[s][t] = t_d adj[t][s] = t_d odd_b ^= 1 << s odd_b ^= 1 << t ans += d if odd_b: # Warshall???Floyd Algorithm for k in range(V): for i in range(V): for j in range(V): adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]) # Minimum weighted matching mw = [no_edge] * (odd_b + 1) mw[0] = 0 digits = len(bin(odd_b)) - 2 for b in range(odd_b): for i in range(0, digits): if not (b & (1 << i)) and odd_b & (1 << i): for j in range(i + 1, digits): if not (b & (1 << j)) and odd_b & (1 << j): t_b = b + (1 << i) + (1 << j) if t_b == t_b & odd_b: t_w = mw[t_b] mw[t_b] = min(t_w, mw[b] + adj[i][j]) # Output ans += mw[odd_b] print(ans) else: print(ans) ```
output
1
87,496
13
174,993
Provide a correct Python 3 solution for this coding contest problem. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7
instruction
0
87,497
13
174,994
"Correct Solution: ``` def warshall_floyd(n, dists): prev = [t.copy() for t in dists] for k in range(n): current = [[0] * n for _ in range(n)] prev_k = prev[k] for i in range(n): prev_i, current_i = prev[i], current[i] prev_i_k = prev_i[k] for j in range(n): current_i[j] = min(prev_i[j], prev_i_k + prev_k[j]) prev = current return prev def solve(n, links, total_d, odd_vertices): if not odd_vertices: return total_d d_table = warshall_floyd(n, links) d_table = [[d for oj, d in enumerate(d_table[oi]) if oj in odd_vertices] for ni, oi in enumerate(odd_vertices)] ndt = len(d_table) bit_dict = {1 << i: i for i in range(ndt)} def minimum_pair(remains): if not remains: return 0 b = remains & -remains remains ^= b i = bit_dict[b] return min(minimum_pair(remains ^ (1 << j)) + d_table[i][j] for j in range(ndt) if remains & (1 << j)) return total_d + minimum_pair((1 << ndt) - 1) v, e = map(int, input().split()) dists = [[float('inf')] * v for _ in range(v)] for i in range(v): dists[i][i] = 0 odd_vertices = [0] * v total_d = 0 for _ in range(e): s, t, d = map(int, input().split()) dists[s][t] = min(dists[s][t], d) dists[t][s] = min(dists[t][s], d) odd_vertices[s] ^= 1 odd_vertices[t] ^= 1 total_d += d print(solve(v, dists, total_d, [i for i, v in enumerate(odd_vertices) if v])) ```
output
1
87,497
13
174,995
Provide a correct Python 3 solution for this coding contest problem. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7
instruction
0
87,498
13
174,996
"Correct Solution: ``` import math import sys from typing import List def warshall_floyd(table: List[List[int]], vertex_num: int) -> None: for k in range(vertex_num): for i in range(vertex_num): for j in range(vertex_num): table[i][j] = min(table[i][j], table[i][k] + table[k][j]) if __name__ == "__main__": V, E = map(lambda x: int(x), input().split()) adj = [[sys.maxsize] * V for i in range(V)] for i in range(V): adj[i][i] = 0 odd_b = 0 # bit DP to record odd vertex ans = 0 for _ in range(E): s, t, d = map(lambda x: int(x), input().split()) min_d = min(d, adj[s][t]) adj[s][t] = min_d adj[t][s] = min_d odd_b ^= 1 << s odd_b ^= 1 << t ans += d if odd_b: warshall_floyd(adj, V) # Minimum weighted matching mw = [sys.maxsize] * (odd_b + 1) mw[0] = 0 digits = int(math.log2(odd_b)) + 1 for b, mw_b in enumerate(mw): if 1 == b % 2: continue for i in range(0, digits): if b & (1 << i): continue for j in range(i + 1, digits): if b & (1 << j): continue t_b = b + (1 << i) + (1 << j) if t_b == t_b & odd_b: t_w = mw[t_b] mw[t_b] = min(t_w, mw_b + adj[i][j]) ans += mw[odd_b] print(ans) else: print(ans) ```
output
1
87,498
13
174,997
Provide a correct Python 3 solution for this coding contest problem. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7
instruction
0
87,499
13
174,998
"Correct Solution: ``` #!python3 iim = lambda: map(int, input().rstrip().split()) from heapq import heappush, heappop def resolve(): V, E = iim() inf = float("inf") ad = [[inf]*V for i in range(V)] bi = [1<<i for i in range(V)] ans = 0 odd = 0 for i in range(E): s, t, d = iim() ad[s][t] = ad[t][s] = min(d, ad[s][t]) odd ^= bi[s] odd ^= bi[t] ans += d if odd == 0: print(ans) return for _ in range(V): nochage = True for i in range(V): for j in range(i+1, V): for k in range(V): d1 = ad[i][j] d2 = ad[i][k] + ad[k][j] if d1 > d2: nochage = False ad[i][j] = d2 ad[j][i] = d2 if nochage: break v2 = [i for i in range(V) if odd & bi[i]] n2 = len(v2) dp = {0: 0} dk = [0] for i in range(n2): ii = bi[i] vi = v2[i] for j in range(i + 1, n2): jj = bi[j] vj = v2[j] for state in dk: ij = ii | jj if state & ij: continue st2 = state | ij co2 = dp[state] + ad[vi][vj] if st2 in dp: if co2 < dp[st2]: dp[st2] = co2 else: dp[st2] = co2 dk.append(st2) ans += dp[(1<<n2)-1] print(ans) if __name__ == "__main__": resolve() ```
output
1
87,499
13
174,999
Provide a correct Python 3 solution for this coding contest problem. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7
instruction
0
87,500
13
175,000
"Correct Solution: ``` import sys f_i = sys.stdin V, E = map(int, f_i.readline().split()) # adjacency matrix no_edge = 14001 adj = [[no_edge] * V for i in range(V)] for i in range(V): adj[i][i] = 0 odd_b = 0 # bit DP to record odd vertex ans = 0 # acceptance of input for l_i in f_i: s, t, d = map(int, l_i.split()) t_d = min(d, adj[s][t]) adj[s][t] = t_d adj[t][s] = t_d odd_b ^= 1 << s odd_b ^= 1 << t ans += d import math if odd_b: # Warshall???Floyd Algorithm for k in range(V): for i in range(V): for j in range(V): adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]) # Minimum weighted matching mw = [no_edge] * (odd_b + 1) mw[0] = 0 digits = int(math.log2(odd_b)) + 1 for b in range(odd_b): for i in range(0, digits): if not (b & (1 << i)): for j in range(i + 1, digits): if not (b & (1 << j)): t_b = b + (1 << i) + (1 << j) if t_b == t_b & odd_b: t_w = mw[t_b] mw[t_b] = min(t_w, mw[b] + adj[i][j]) # Output ans += mw[odd_b] print(ans) else: print(ans) ```
output
1
87,500
13
175,001
Provide a correct Python 3 solution for this coding contest problem. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7
instruction
0
87,501
13
175,002
"Correct Solution: ``` def warshall_floyd(n, dists): prev = [t.copy() for t in dists] for k in range(n): current = [t.copy() for t in prev] prev_k = prev[k] for i in range(n): prev_i, current_i = prev[i], current[i] prev_i_k = prev_i[k] for j in range(n): current_i[j] = min(prev_i[j], prev_i_k + prev_k[j]) prev = current return prev def solve(n, links, total_d, odd_vertices): if not odd_vertices: return total_d d_table = warshall_floyd(n, links) d_table = [[d for oj, d in enumerate(d_table[oi]) if oj in odd_vertices] for ni, oi in enumerate(odd_vertices)] ndt = len(d_table) bit_dict = {1 << i: i for i in range(ndt)} def minimum_pair(remains): if not remains: return 0 b = remains & -remains remains ^= b i = bit_dict[b] return min(minimum_pair(remains ^ (1 << j)) + d_table[i][j] for j in range(ndt) if remains & (1 << j)) return total_d + minimum_pair((1 << ndt) - 1) v, e = map(int, input().split()) dists = [[float('inf')] * v for _ in range(v)] for i in range(v): dists[i][i] = 0 odd_vertices = [0] * v total_d = 0 for _ in range(e): s, t, d = map(int, input().split()) dists[s][t] = min(dists[s][t], d) dists[t][s] = min(dists[t][s], d) odd_vertices[s] ^= 1 odd_vertices[t] ^= 1 total_d += d print(solve(v, dists, total_d, [i for i, v in enumerate(odd_vertices) if v])) ```
output
1
87,501
13
175,003
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7 Submitted Solution: ``` #! /usr/bin/python # -*- coding: utf-8 -*- """Chinese Postman Problem.""" import sys f_i = sys.stdin V, E = map(int, f_i.readline().split()) # adjacency matrix no_edge = 14001 adj = [[no_edge] * V for i in range(V)] for i in range(V): adj[i][i] = 0 odd_b = 0 # bit DP to record odd vertex ans = 0 # acceptance of input for l_i in f_i: s, t, d = map(int, l_i.split()) t_d = min(d, adj[s][t]) adj[s][t] = t_d adj[t][s] = t_d odd_b ^= 1 << s odd_b ^= 1 << t ans += d # A function to check if the number of 1 is odd in binary notation def odd_one(n): ans = 0 while n: ans ^= (n & 1) n >>= 1 return ans import math if odd_b: # Warshall???Floyd Algorithm for k in range(V): for i in range(V): for j in range(V): adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]) # Minimum weighted matching mw = [no_edge] * (odd_b + 1) mw[0] = 0 digits = int(math.log2(odd_b)) + 1 for b in range(odd_b): if odd_one(b): continue for i in range(0, digits): if not (b & (1 << i)): for j in range(i + 1, digits): if not (b & (1 << j)): t_b = b + (1 << i) + (1 << j) if t_b == t_b & odd_b: t_w = mw[t_b] mw[t_b] = min(t_w, mw[b] + adj[i][j]) # Output ans += mw[odd_b] print(ans) else: print(ans) ```
instruction
0
87,502
13
175,004
Yes
output
1
87,502
13
175,005
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7 Submitted Solution: ``` def warshall_floyd(n, dists): prev = [t.copy() for t in dists] for k in range(n): current = [t.copy() for t in prev] prev_k = prev[k] for i in range(n): prev_i, current_i = prev[i], current[i] prev_i_k = prev_i[k] for j in range(n): current_i[j] = min(prev_i[j], prev_i_k + prev_k[j]) prev = current return prev def solve(n, links, total_d, odd_vertices): if not odd_vertices: return total_d d_table = warshall_floyd(n, links) d_table = [[d for oj, d in enumerate(d_table[oi]) if oj in odd_vertices] for ni, oi in enumerate(odd_vertices)] ## odd_verticesのみ抽出したwarshall_floydテーブルになおす ndt = len(d_table) bit_dict = {1 << i: i for i in range(ndt)} def minimum_pair(remains): if not remains: return 0 b = remains & -remains ## 1であるbitのうち一番下のbit 1桁をとってくる remains ^= b ## bで選んだbitを反転 こいつは1確定なので、それが0になるってこと i = bit_dict[b] ## i=2**b return min(minimum_pair(remains ^ (1 << j)) + d_table[i][j] for j in range(ndt) if remains & (1 << j)) ## remainsは訪れてないとこのbit管理、iが現在地点、jが次の奇点、これで末尾の1から各odd_verticesに再帰で訪れていく odd_vertices個分の辺を足す return total_d + minimum_pair((1 << ndt) - 1) v, e = map(int, input().split()) dists = [[float('inf')] * v for _ in range(v)] for i in range(v): dists[i][i] = 0 odd_vertices = [0] * v total_d = 0 for _ in range(e): s, t, d = map(int, input().split()) dists[s][t] = min(dists[s][t], d) dists[t][s] = min(dists[t][s], d) odd_vertices[s] ^= 1 odd_vertices[t] ^= 1 total_d += d print(solve(v, dists, total_d, [i for i, v in enumerate(odd_vertices) if v])) ```
instruction
0
87,503
13
175,006
Yes
output
1
87,503
13
175,007
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7 Submitted Solution: ``` import sys f_i = sys.stdin V, E = map(int, f_i.readline().split()) # adjacency matrix no_edge = 14001 adj = [[no_edge] * V for i in range(V)] for i in range(V): adj[i][i] = 0 odd_b = 0 # bit DP to record odd vertex ans = 0 # acceptance of input for l_i in f_i: s, t, d = map(int, l_i.split()) t_d = min(d, adj[s][t]) adj[s][t] = t_d adj[t][s] = t_d odd_b ^= 1 << s odd_b ^= 1 << t ans += d # A function to check if the number of 1 in binary notation is odd def odd_one(n): ans = 0 while n: ans ^= (n & 1) n >>= 1 return ans import math if odd_b: # Warshall???Floyd Algorithm for k in range(V): for i in range(V): for j in range(V): adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]) # Minimum weighted matching mw = [no_edge] * (odd_b + 1) mw[0] = 0 digits = int(math.log2(odd_b)) + 1 for b, mw_b in enumerate(mw): if odd_one(b): continue for i in range(0, digits): if b & (1 << i): continue for j in range(i + 1, digits): if b & (1 << j): continue t_b = b + (1 << i) + (1 << j) if t_b == t_b & odd_b: t_w = mw[t_b] mw[t_b] = min(t_w, mw_b + adj[i][j]) # Output ans += mw[odd_b] print(ans) else: print(ans) ```
instruction
0
87,504
13
175,008
Yes
output
1
87,504
13
175,009
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7 Submitted Solution: ``` def warshall_floyd(distance_table, point_size): for k in range(point_size): for i in range(point_size): for j in range(point_size): if distance_table[i][j] > distance_table[i][k] + distance_table[k][j]: distance_table[i][j] = distance_table[i][k] + distance_table[k][j] class bit: __hash = 0x03F566ED27179461 __mask64 = (1 << 64) - 1 __table = bit.__createtable() def __createtable(): table = [None] * 64 hash = bit.__hash for i in range(64): table[hash >> 58] = i hash = (hash << 1) & bit.__mask64 return table def number_of_trailing_zeros(x): if x == 0:return 64 return bit.__table[((bit.lowest_one(x) * bit.__hash) & bit.__mask64) >> 58] def lowest_one(i): return i & -i def ccp(distance_table, point_size, v): if v: i = bit.number_of_trailing_zeros(v) v ^= (1 << i) return min(ccp(distance_table, point_size, v ^ (1 << j)) + distance_table[i][j] for j in range(point_size) if v & 1 << j) else: return 0 point_size, e = map(int, readline().split()) distance_table = [[float('inf')] * point_size for _ in range(point_size)] cost = 0 v = 0 for _ in range(e): s, t, d = map(int, readline().split()) distance_table[s][t] = min(distance_table[s][t], d) distance_table[t][s] = min(distance_table[t][s], d) v ^= 1 << s ^ 1 << t cost += d warshall_floyd(distance_table, point_size) print(cost + ccp(distance_table, point_size, v)) ```
instruction
0
87,505
13
175,010
No
output
1
87,505
13
175,011
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7 Submitted Solution: ``` def warshall_floyd(n, links): prev = [t.copy() for t in links] for i in range(n): prev[i][i] = 0 for k in range(n - 1): current = [t.copy() for t in prev] prev_k = prev[k] for i in range(n): prev_i, current_i = prev[i], current[i] prev_i_k = prev_i[k] for j in range(n): current_i[j] = min(prev_i[j], prev_i_k + prev_k[j]) prev = current return prev def solve(n, links, total_d, odd_vertices): if not odd_vertices: return total_d d_table = warshall_floyd(n, links) d_table = [[d for oj, d in enumerate(d_table[oi]) if oj in odd_vertices] for ni, oi in enumerate(odd_vertices)] ndt = len(d_table) bit_dict = {1 << i: i for i in range(ndt)} def minimum_pair(remains): if not remains: return 0 b = remains & -remains remains ^= b i = bit_dict[b] return min(minimum_pair(remains ^ (1 << j)) + d_table[i][j] for j in range(ndt) if remains & (1 << j)) return total_d + minimum_pair((1 << ndt) - 1) v, e = map(int, input().split()) links = [[float('inf')] * v for _ in range(v)] odd_vertices = [0] * v total_d = 0 for _ in range(e): s, t, d = map(int, input().split()) links[s][t] = min(links[s][t], d) links[t][s] = min(links[t][s], d) odd_vertices[s] ^= 1 odd_vertices[t] ^= 1 total_d += d print(solve(v, links, total_d, [i for i, v in enumerate(odd_vertices) if v])) ```
instruction
0
87,506
13
175,012
No
output
1
87,506
13
175,013
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7 Submitted Solution: ``` from collections import defaultdict v, e = map(int, input().split()) links = [defaultdict(int) for _ in range(v)] bests = [None] * (1 << v) for _ in range(e): s, t, d = map(int, input().split()) links[s][t] = max(links[s][t], d) bests[0] = {0: 0} for visited, best in enumerate(bests): if best is None: continue for last, cost in best.items(): for t, d in links[last].items(): new_visited = visited | (1 << t) if visited == new_visited: continue new_best = bests[new_visited] if new_best is None: bests[new_visited] = defaultdict(lambda: 15001, [(t, cost + d)]) else: new_best[t] = min(new_best[t], cost + d) print(bests[-1][0]) ```
instruction
0
87,507
13
175,014
No
output
1
87,507
13
175,015
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7 Submitted Solution: ``` from collections import defaultdict v, e = map(int, input().split()) links = [defaultdict(int) for _ in range(v)] bests = [None] * (1 << v) for _ in range(e): s, t, d = map(int, input().split()) links[s][t] = max(links[s][t], d) links[t][s] = max(links[t][s], d) bests[0] = {0: 0} for visited, best in enumerate(bests): if best is None: continue for last, cost in best.items(): for t, d in links[last].items(): new_visited = visited | (1 << t) if visited == new_visited: continue new_best = bests[new_visited] if new_best is None: bests[new_visited] = defaultdict(lambda: 15001, {t: cost + d}) else: new_best[t] = min(new_best[t], cost + d) print(bests[-1][0]) ```
instruction
0
87,508
13
175,016
No
output
1
87,508
13
175,017
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help. You are given a sequence a, consisting of n distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process. 1. First element a_1 becomes the root of the tree. 2. Elements a_2, a_3, …, a_n are added one by one. To add element a_i one needs to traverse the tree starting from the root and using the following rules: 1. The pointer to the current node is set to the root. 2. If a_i is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node. 3. If at some point there is no required child, the new node is created, it is assigned value a_i and becomes the corresponding child of the current node. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the length of the sequence a. The second line contains n distinct integers a_i (1 ≤ a_i ≤ 10^9) — the sequence a itself. Output Output n - 1 integers. For all i > 1 print the value written in the node that is the parent of the node with value a_i in it. Examples Input 3 1 2 3 Output 1 2 Input 5 4 2 3 1 6 Output 4 2 2 4 Submitted Solution: ``` n = int(input()) array = [int(x) for x in input().split()] tree = [] ans = '' for i in range(n): item = array[i] if i == 0: tree.append((item, 0)) else: if item < tree[0][0]: father = tree[0][0] tree.insert(0, (item, father)) elif item > tree[i - 1][0]: father = tree[i - 1][0] tree.append((item, father)) else: beg = 0 end = i - 1 while True: if tree[end][0] < item: break mid = (beg + end + 1) // 2 if tree[mid][0] < item: beg = mid else: end = mid - 1 if tree[end][1] == tree[end + 1][0]: father = tree[end][0] else: father = tree[end + 1][0] tree.insert(end + 1, (item, father)) ans += '%d ' % father print(ans) ```
instruction
0
88,888
13
177,776
No
output
1
88,888
13
177,777
Provide a correct Python 3 solution for this coding contest problem. You are given a tree T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4
instruction
0
89,197
13
178,394
"Correct Solution: ``` def solve(): import sys file_input = sys.stdin while True: N, Q = map(int, file_input.readline().split()) if N == 0: break parent = [None, None] parent += [int(file_input.readline()) for _ in range(N - 1)] unmarked = [True] * (N + 1) unmarked[1] = False ans = 0 for _ in range(Q): line = file_input.readline() v = int(line[2:]) if line[0] == 'M': unmarked[v] = False else: while unmarked[v]: v = parent[v] ans += v print(ans) solve() ```
output
1
89,197
13
178,395
Provide a correct Python 3 solution for this coding contest problem. You are given a tree T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4
instruction
0
89,198
13
178,396
"Correct Solution: ``` import sys sys.setrecursionlimit(10000000) MOD = 10 ** 9 + 7 INF = 10 ** 15 class UnionFind(): def __init__(self,n): self.n = n self.parents = [-1]*n def find(self,x): #根を見つける、繋ぎ直す if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def unite(self,x,y): y = self.find(y) x = self.find(x) self.parents[y] += self.parents[x] self.parents[x] = y def same(self,x,y):#xとyが同じグループにいるか判定 return self.find(x) == self.find(y) def solve(N,Q): parents = [-1] * N for i in range(1,N): p = int(input()) - 1 parents[i] = p query = [] mark = [0] * N mark[0] = 1 for _ in range(Q): q = input().split() v = int(q[1]) - 1 if q[0] == 'M': mark[v] += 1 query.append((0,v)) else: query.append((1,v)) uf = UnionFind(N) for i in range(N): if mark[i] == 0: uf.unite(i,parents[i]) ans = 0 for ty,v in query[::-1]: if ty == 0: mark[v] -= 1 if mark[v] == 0: uf.unite(v,parents[v]) else: ans += uf.find(v) + 1 print(ans) def main(): while True: N,M = map(int,input().split()) if N == 0: return solve(N,M) if __name__ == '__main__': main() ```
output
1
89,198
13
178,397
Provide a correct Python 3 solution for this coding contest problem. You are given a tree T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4
instruction
0
89,199
13
178,398
"Correct Solution: ``` def root(x): while P[x-1]!=x: x = P[x-1] return x def mark(x): P[x-1] = x while True: n,q = map(int,input().split()) res = 0 if n==0: break P = [1] for _ in range(n-1): P.append(int(input())) for _ in range(q): com,num=map(str,input().split()) if com == "Q": res += root(int(num)) else: mark(int(num)) print(res) ```
output
1
89,199
13
178,399
Provide a correct Python 3 solution for this coding contest problem. You are given a tree T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4
instruction
0
89,200
13
178,400
"Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) class UnionFind: def __init__(self, size): self.table = [-1 for _ in range(size)] def find(self, x): if self.table[x] < 0: return x else: self.table[x] = self.find(self.table[x]) return self.table[x] def union(self, x, y): s1 = self.find(x) s2 = self.find(y) if s1 != s2: self.table[s2] += self.table[s1] self.table[s1] = s2 return True return False def subsetall(self): a = [] for i in range(len(self.table)): if self.table[i] < 0: a.append((i, -self.table[i])) return a def main(): rr = [] def f(n,q): ps = [0, 1] + [I() for _ in range(n-1)] qs = [] ms = set() for i in range(q): s,t = LS() t = int(t) if s == 'M': if t in ms: continue ms.add(t) qs.append((s,t)) uf = UnionFind(n+1) for i in range(2,n+1): if i in ms: continue uf.union(i, ps[i]) r = 0 for s,t in qs[::-1]: if s == 'Q': r += uf.find(t) else: uf.union(t, ps[t]) return r while 1: n,q = LI() if n == 0 and q == 0: break rr.append(f(n,q)) return '\n'.join(map(str,rr)) print(main()) ```
output
1
89,200
13
178,401
Provide a correct Python 3 solution for this coding contest problem. You are given a tree T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4
instruction
0
89,201
13
178,402
"Correct Solution: ``` class UnionFind: def __init__(self, size): self.parent = list(range(size)) def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def unite(self, x, y): x = self.find(x) y = self.find(y) if x == y: return self.parent[x] = y def same(self, x, y): return self.find(x) == self.find(y) while True: N, Q = map(int, input().split()) if N == Q == 0: break parent = [0, 1] + [int(input()) for i in range(2, N+1)] queries = [] marked = set([1]) for i in range(Q): o, v = input().split() v = int(v) if o == 'M': if v in marked: continue marked.add(v) queries.append((o, v)) uf = UnionFind(N+1) for i in range(1, N+1): if i not in marked: uf.unite(i, parent[i]) ans = 0 for o, v in reversed(queries): if o == 'M': uf.unite(v, parent[v]) else: ans += uf.find(v) print(ans) ```
output
1
89,201
13
178,403
Provide a correct Python 3 solution for this coding contest problem. You are given a tree T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4
instruction
0
89,202
13
178,404
"Correct Solution: ``` import sys sys.setrecursionlimit(10 ** 6) class UnionFindTree: """Disjoint-Set Data Structure Union-Find Tree complexity: init: O(n) find, unite, same: O(alpha(n)) used in SRM505 div.2 900, ATC001 A, DSL1A(AOJ) """ def __init__(self, n): self.par = list(range(n)) # parent self.rank = [0] * n # depth of tree def find(self, x): if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] def unite(self, x, y): x, y = self.find(x), self.find(y) if x == y: return if self.rank[x] < self.rank[y]: self.par[x] = y else: self.par[y] = x if self.rank[x] == self.rank[y]: self.rank[x] += 1 def same(self, x, y): return self.find(x) == self.find(y) while True: N, Q = map(int, input().split()) if N == Q == 0: break parents = [0] + [int(input()) - 1 for _ in range(N - 1)] queries = [] marked = set() for _ in range(Q): k, v = input().split() v = int(v) - 1 if k == "Q": queries.append((k, v)) elif k == "M" and v not in marked: marked.add(v) queries.append((k, v)) uf = UnionFindTree(N) for i in range(1, N): if i not in marked: p_root = uf.find(parents[i]) uf.par[i] = p_root uf.rank[p_root] = max(uf.rank[p_root], uf.par[i] + 1) ans = 0 for k, v in reversed(queries): if k == "Q": ans += uf.find(v) + 1 elif not uf.same(v, parents[v]): p_root = uf.find(parents[v]) uf.par[v] = p_root uf.rank[p_root] = max(uf.rank[p_root], uf.par[v] + 1) print(ans) ```
output
1
89,202
13
178,405
Provide a correct Python 3 solution for this coding contest problem. You are given a tree T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4
instruction
0
89,203
13
178,406
"Correct Solution: ``` def root(x): while P[x] != x: x = P[x] return x def mark(x): P[x-1] = x-1 def query(x): v = root(x-1) +1 return v while True: N,Q = map(int,input().strip().split(" ")) if N == Q == 0: break P = [] P.append(0) for i in range(N-1): p_i = int(input().strip()) -1 P.append(p_i) s = 0 for j in range(Q): op = input().strip().split(" ") if op[0] == "M": mark(int(op[1])) else: s += query(int(op[1])) print(s) ```
output
1
89,203
13
178,407
Provide a correct Python 3 solution for this coding contest problem. You are given a tree T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4
instruction
0
89,204
13
178,408
"Correct Solution: ``` class UnionFind: def __init__(self, size): self.table = [None] * size def find(self, x): if self.table[x] == None: return x else: # compression of the path self.table[x] = self.find(self.table[x]) return self.table[x] def union(self, parent, child): p_root = self.find(parent) c_root = self.find(child) if p_root != c_root: self.table[c_root] = p_root def solve(): import sys input_lines = sys.stdin.readlines() while True: N, Q = map(int, input_lines[0].split()) if N == 0: break parent = [0, 1] + list(map(int, input_lines[1:N])) unmarked = [True] * (N + 1) unmarked[1] = False operation = [] for o in input_lines[N:N+Q]: mq, v = o.split() v = int(v) if mq == 'M': if unmarked[v]: unmarked[v] = False operation.append((mq, v)) else: operation.append((mq, v)) uf = UnionFind(N + 1) for v, p in enumerate(parent[2:], start=2): if unmarked[v]: uf.union(p, v) ans = 0 for mq, v in reversed(operation): if mq == 'M': uf.union(parent[v], v) else: ans += uf.find(v) print(ans) del input_lines[:N+Q] solve() ```
output
1
89,204
13
178,409
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 T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4 Submitted Solution: ``` class UnionFind: def __init__(self, size): self.table = [None] * size def find(self, x): if self.table[x] == None: return x else: # compression of the path self.table[x] = self.find(self.table[x]) return self.table[x] def union(self, parent, child): p_root = self.find(parent) c_root = self.find(child) if p_root != c_root: self.table[c_root] = p_root def solve(): import sys input_lines = sys.stdin.readlines() while True: N, Q = map(int, input_lines[0].split()) if N == 0: break unmarked = [True] * (N + 1) unmarked[1] = False operation = [] for o in input_lines[N:N+Q]: mq, v = o.split() v = int(v) if mq == 'M': if unmarked[v]: unmarked[v] = False operation.append((mq, v)) else: operation.append((mq, v)) uf = UnionFind(N + 1) parent = [None, 1] + list(map(int, input_lines[1:N])) for v, p in enumerate(parent[2:], start=2): if unmarked[v]: uf.union(p, v) ans = 0 for o, v in reversed(operation): if o == 'M': uf.union(parent[v], v) else: ans += uf.find(v) print(ans) del input_lines[:N+Q] solve() ```
instruction
0
89,205
13
178,410
Yes
output
1
89,205
13
178,411
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 T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4 Submitted Solution: ``` marked = [] par = [] rank = [] def find(x): if par[x] == x: return x else: if marked[x]: return x return find(par[x]) def main(): global marked, par, rank n,q = [int(i) for i in input().split()] marked = [False for i in range(n+1)] par = [ i for i in range(n+1)] rank = [ 0 for i in range(n+1)] ans = 0 for i in range(2,n+1): par[i] = int(input()) for i in range(q): s = input().split() if s[0] == 'Q': ans += find(int(s[1])) else: marked[int(s[1])]=True print(ans) input() if __name__ == '__main__': main() ```
instruction
0
89,206
13
178,412
No
output
1
89,206
13
178,413
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 T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4 Submitted Solution: ``` marked = [] par = [] rank = [] def find(x): if par[x] == x: return x else: if marked[x]: return x return find(par[x]) def main(): global marked, par, rank n,q = [int(i) for i in input().split()] marked = [False for i in range(n+1)] par = [ i for i in range(n+1)] rank = [ 0 for i in range(n+1)] ans = 0 for i in range(2,n+1): par[i] = int(input()) for i in range(q): s = input().split() if s[0] == 'Q': ans += find(int(s[1])) else: marked[int(s[1])]=True input() print(ans) if __name__ == '__main__': main() ```
instruction
0
89,207
13
178,414
No
output
1
89,207
13
178,415
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 T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4 Submitted Solution: ``` import sys sys.setrecursionlimit(1000000) marked = [] par = [] rank = [] def find(x): if par[x] == x: return x else: if marked[x]: return x return find(par[x]) def main(): global marked, par, rank n,q = [int(i) for i in input().split()] marked = [False for i in range(n+1)] par = [ i for i in range(n+1)] rank = [ 0 for i in range(n+1)] ans = 0 for i in range(2,n+1): par[i] = int(input()) for i in range(q): s = input().split() if s[0] == 'Q': print(find(int(s[1]))) else: marked[int(s[1])]=True input() if __name__ == '__main__': main() ```
instruction
0
89,208
13
178,416
No
output
1
89,208
13
178,417
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 T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root node is marked. Note that a node is an ancestor of itself. Your job is to write a program that performs a sequence of these operations on a given tree and calculates the value that each Q operation will print. To avoid too large output file, your program is requested to print the sum of the outputs of all query operations. Note that the judges confirmed that it is possible to calculate every output of query operations in a given sequence. Input The input consists of multiple datasets. Each dataset has the following format: The first line of the input contains two integers N and Q, which denotes the number of nodes in the tree T and the number of operations, respectively. These numbers meet the following conditions: 1 ≤ N ≤ 100000 and 1 ≤ Q ≤ 100000. The following N - 1 lines describe the configuration of the tree T. Each line contains a single integer pi (i = 2, ... , N), which represents the index of the parent of i-th node. The next Q lines contain operations in order. Each operation is formatted as "M v" or "Q v", where v is the index of a node. The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed. Output For each dataset, print the sum of the outputs of all query operations in one line. Example Input 6 3 1 1 2 3 3 Q 5 M 3 Q 5 0 0 Output 4 Submitted Solution: ``` import sys sys.setrecursionlimit(10 ** 6) class UnionFindTree: """Disjoint-Set Data Structure Union-Find Tree complexity: init: O(n) find, unite, same: O(alpha(n)) used in SRM505 div.2 900, ATC001 A, DSL1A(AOJ) """ def __init__(self, n): self.par = list(range(n)) # parent self.rank = [0] * n # depth of tree def find(self, x): if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] def unite(self, x, y): x, y = self.find(x), self.find(y) if x == y: return if self.rank[x] < self.rank[y]: self.par[x] = y else: self.par[y] = x if self.rank[x] == self.rank[y]: self.rank[x] += 1 def same(self, x, y): return self.find(x) == self.find(y) while True: N, Q = map(int, input().split()) if N == Q == 0: break parents = [0] + [int(input()) - 1 for _ in range(N - 1)] queries = [] marked = set() for _ in range(Q): k, v = input().split() v = int(v) - 1 queries.append((k, v)) if k == "M": marked.add(v) uf = UnionFindTree(N) for i in range(1, N): if i not in marked: p_root = uf.find(parents[i]) uf.par[i] = p_root uf.rank[p_root] = max(uf.rank[p_root], uf.par[i] + 1) ans = 0 for k, v in reversed(queries): if k == "Q": ans += uf.find(v) + 1 elif not uf.same(v, parents[v]): p_root = uf.find(parents[v]) uf.par[v] = p_root uf.rank[p_root] = max(uf.rank[p_root], uf.par[v] + 1) print(ans) ```
instruction
0
89,209
13
178,418
No
output
1
89,209
13
178,419
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph with n vertices and m edges. Also, you are given an integer k. Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it. A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them. Input The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers n, m, k (1 ≤ n, m, k ≤ 10^5, k ≤ n). Each of the next m lines contains two integers u, v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge between vertices u and v. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 ⋅ 10^5. Output For each test case: If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print -1. If there exists multiple possible answers you can print any of them. Example Input 3 5 9 4 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 10 15 3 1 2 2 3 3 4 4 5 5 1 1 7 2 8 3 9 4 10 5 6 7 10 10 8 8 6 6 9 9 7 4 5 4 1 2 2 3 3 4 4 1 1 3 Output 2 4 1 2 3 1 10 1 2 3 4 5 6 7 8 9 10 -1 Note In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4. In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer. In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1.
instruction
0
89,503
13
179,006
Tags: constructive algorithms, data structures, graphs Correct Solution: ``` import sys input = sys.stdin.readline testcase = int(input()) for _ in range(testcase): n,m,k = map(int,input().split()) ab = [list(map(int,input().split())) for i in range(m)] if k == 1: print(2) print(1) continue if k*(k-1) > 2*m: print(-1) continue graph = [set() for i in range(n+1)] for a,b in ab: graph[a].add(b) graph[b].add(a) trash = set() stack = [] for i in range(1,n+1): if len(graph[i]) < k-1: trash.add(i) stack.append(i) while stack: x = stack.pop() for y in graph[x]: if x in graph[y]: graph[y].remove(x) if len(graph[y]) < k-1: stack.append(y) trash.add(y) graph[x] = set() if n-len(trash) < k: print(-1) continue ansflg = 0 ccand = [] for i in range(1,n+1): if len(graph[i]) == k-1: ccand.append(i) while ccand: x = ccand.pop() if len(graph[x]) < k-1: trash.add(x) for y in graph[x]: if x in graph[y]: graph[y].remove(x) if len(graph[y]) == k-1: ccand.append(y) graph[x] = set() continue lsg = list(graph[x]) for i in range(len(lsg)-1): for j in range(i+1,len(lsg)): if lsg[j] not in graph[lsg[i]]: trash.add(x) for y in graph[x]: if x in graph[y]: graph[y].remove(x) if len(graph[y]) == k-1: ccand.append(y) graph[x] = set() break else: continue break else: ansflg = 1 break if ansflg: print(2) graph[x].add(x) print(*graph[x]) elif n-len(trash) >= k+1: ansls = [] for i in range(1,n+1): if i not in trash: ansls.append(i) print(1,len(ansls)) print(*ansls) else: print(-1) ```
output
1
89,503
13
179,007
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph with n vertices and m edges. Also, you are given an integer k. Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it. A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them. Input The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers n, m, k (1 ≤ n, m, k ≤ 10^5, k ≤ n). Each of the next m lines contains two integers u, v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge between vertices u and v. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 ⋅ 10^5. Output For each test case: If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print -1. If there exists multiple possible answers you can print any of them. Example Input 3 5 9 4 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 10 15 3 1 2 2 3 3 4 4 5 5 1 1 7 2 8 3 9 4 10 5 6 7 10 10 8 8 6 6 9 9 7 4 5 4 1 2 2 3 3 4 4 1 1 3 Output 2 4 1 2 3 1 10 1 2 3 4 5 6 7 8 9 10 -1 Note In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4. In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer. In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1.
instruction
0
89,504
13
179,008
Tags: constructive algorithms, data structures, graphs Correct Solution: ``` from __future__ import division,print_function from heapq import* import sys le = sys.__stdin__.read().split("\n")[::-1] af = [] for ezo in range(int(le.pop())): n,m,k = list(map(int, le.pop().split())) ar = [set() for _ in range(n)] for i in range(m): a,b = list(map(int, le.pop().split())) ar[a - 1].add(b - 1) ar[b - 1].add(a - 1) if k * (k - 1) > 2 * m: af.append(-1) else: pi = [i for i in range(n) if len(ar[i]) < k] re = set(i for i in range(n) if len(ar[i]) >= k) # print(re,pi,n,m) while pi: a = pi.pop() if len(ar[a]) == k - 1: clique = True for j in ar[a]: if clique: for h in ar[a]: if not (h in ar[j]) and h != j: # print(a,j,h) clique = False break if clique: af.append(2) af.append(" ".join(map(str, [i + 1 for i in ar[a]] + [a + 1]))) pi = [] re = {-1} for j in ar[a]: ar[j].remove(a) if len(ar[j]) < k: if j in re: pi.append(j) re.discard(j) if re and re != {-1}: af.append("1" + " " + str(len(re))) af.append(" ".join(map(str, [i + 1 for i in re]))) elif re != {-1}: af.append(-1) print("\n".join(map(str, af))) ```
output
1
89,504
13
179,009
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph with n vertices and m edges. Also, you are given an integer k. Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it. A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them. Input The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers n, m, k (1 ≤ n, m, k ≤ 10^5, k ≤ n). Each of the next m lines contains two integers u, v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge between vertices u and v. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 ⋅ 10^5. Output For each test case: If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print -1. If there exists multiple possible answers you can print any of them. Example Input 3 5 9 4 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 10 15 3 1 2 2 3 3 4 4 5 5 1 1 7 2 8 3 9 4 10 5 6 7 10 10 8 8 6 6 9 9 7 4 5 4 1 2 2 3 3 4 4 1 1 3 Output 2 4 1 2 3 1 10 1 2 3 4 5 6 7 8 9 10 -1 Note In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4. In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer. In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1.
instruction
0
89,505
13
179,010
Tags: constructive algorithms, data structures, graphs Correct Solution: ``` from collections import deque import sys input = sys.stdin.readline for _ in range(int(input())): n, m, k = map(int, input().split()) G = [set() for _ in range(n + 1)] deg = [0] * (n + 1) for _ in range(m): i, j = map(int, input().split()) G[i].add(j) G[j].add(i) deg[i] += 1 deg[j] += 1 if k * (k - 1) > 2 * m: print(-1) continue q = deque() seen = [0] * (n + 1) for i in range(1, n + 1): if deg[i] < k: seen[i] = 1 q.append(i) clique = [] end = 0 while q and not end: i = q.popleft() seen[i] = 2 if deg[i] == k - 1 and not clique and k * (k - 1) // 2 <= m: clique = [i] for j in G[i]: if seen[j] <= 1: clique.append(j) ok = 1 for x in clique: for y in clique: if x == y: break if y not in G[x]: ok = 0 break if not ok: break if not ok: clique = [] else: print(2) print(*clique) end = 1 break for j in G[i]: deg[j] -= 1 if deg[j] < k and not seen[j]: seen[j] = 1 q.append(j) if not end: subset = [i for i in range(1, n + 1) if not seen[i]] if subset: print("1 {}".format(len(subset))) print(*subset) else: print(-1) ```
output
1
89,505
13
179,011
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph with n vertices and m edges. Also, you are given an integer k. Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it. A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them. Input The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers n, m, k (1 ≤ n, m, k ≤ 10^5, k ≤ n). Each of the next m lines contains two integers u, v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge between vertices u and v. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 ⋅ 10^5. Output For each test case: If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print -1. If there exists multiple possible answers you can print any of them. Example Input 3 5 9 4 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 10 15 3 1 2 2 3 3 4 4 5 5 1 1 7 2 8 3 9 4 10 5 6 7 10 10 8 8 6 6 9 9 7 4 5 4 1 2 2 3 3 4 4 1 1 3 Output 2 4 1 2 3 1 10 1 2 3 4 5 6 7 8 9 10 -1 Note In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4. In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer. In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1.
instruction
0
89,506
13
179,012
Tags: constructive algorithms, data structures, graphs Correct Solution: ``` from __future__ import division,print_function from heapq import* import sys t = list(map(int, sys.stdin.readline().strip().split()))[0] af = [] for _ in range(t): n,m,k = list(map(int, sys.stdin.readline().strip().split())) ar = [set() for _ in range(n)] for i in range(m): a,b = list(map(int, sys.stdin.readline().strip().split())) ar[a - 1].add(b - 1) ar[b - 1].add(a - 1) if k * (k - 1) > 2 * m: af.append(-1) else: pi = [i for i in range(n) if len(ar[i]) < k] re = set(i for i in range(n) if len(ar[i]) >= k) # print(re,pi,n,m) while pi: a = pi.pop() if len(ar[a]) == k - 1: clique = True for j in ar[a]: if clique: for h in ar[a]: if not (h in ar[j]) and h != j: # print(a,j,h) clique = False break if clique: af.append(2) af.append(" ".join(map(str, [i + 1 for i in ar[a]] + [a + 1]))) pi = [] re = {-1} for j in ar[a]: ar[j].remove(a) if len(ar[j]) < k: if j in re: pi.append(j) re.discard(j) if re and re != {-1}: af.append("1" + " " + str(len(re))) af.append(" ".join(map(str, [i + 1 for i in re]))) elif re != {-1}: af.append(-1) print("\n".join(map(str, af))) ```
output
1
89,506
13
179,013
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph with n vertices and m edges. Also, you are given an integer k. Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it. A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them. Input The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers n, m, k (1 ≤ n, m, k ≤ 10^5, k ≤ n). Each of the next m lines contains two integers u, v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge between vertices u and v. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 ⋅ 10^5. Output For each test case: If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print -1. If there exists multiple possible answers you can print any of them. Example Input 3 5 9 4 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 10 15 3 1 2 2 3 3 4 4 5 5 1 1 7 2 8 3 9 4 10 5 6 7 10 10 8 8 6 6 9 9 7 4 5 4 1 2 2 3 3 4 4 1 1 3 Output 2 4 1 2 3 1 10 1 2 3 4 5 6 7 8 9 10 -1 Note In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4. In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer. In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1.
instruction
0
89,507
13
179,014
Tags: constructive algorithms, data structures, graphs Correct Solution: ``` from __future__ import division, print_function from heapq import * import sys le = sys.__stdin__.read().split("\n")[::-1] af = [] for ezo in range(int(le.pop())): n, m, k = list(map(int, le.pop().split())) ar = [set() for i in range(n)] for i in range(m): a, b = map(int, le.pop().split()) ar[a - 1].add(b - 1) ar[b - 1].add(a - 1) if k * (k - 1) > 2 * m: af.append(-1) else: pi = [i for i in range(n) if len(ar[i]) < k] re = set(i for i in range(n) if len(ar[i]) >= k) while pi: a = pi.pop() if len(ar[a]) == k - 1: clique = True for j in ar[a]: if clique: for h in ar[a]: if not (h in ar[j]) and h != j: clique = False break if clique: af.append(2) af.append(" ".join(map(str, [i + 1 for i in ar[a]] + [a + 1]))) pi = [] re = {-1} for j in ar[a]: ar[j].remove(a) if len(ar[j]) < k: if j in re: pi.append(j) re.discard(j) if re and re != {-1}: af.append("1" + " " + str(len(re))) af.append(" ".join(map(str, [i + 1 for i in re]))) elif re != {-1}: af.append(-1) print("\n".join(map(str, af))) ```
output
1
89,507
13
179,015
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with n vertices and m edges. Also, you are given an integer k. Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it. A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them. Input The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers n, m, k (1 ≤ n, m, k ≤ 10^5, k ≤ n). Each of the next m lines contains two integers u, v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge between vertices u and v. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 ⋅ 10^5. Output For each test case: If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print -1. If there exists multiple possible answers you can print any of them. Example Input 3 5 9 4 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 10 15 3 1 2 2 3 3 4 4 5 5 1 1 7 2 8 3 9 4 10 5 6 7 10 10 8 8 6 6 9 9 7 4 5 4 1 2 2 3 3 4 4 1 1 3 Output 2 4 1 2 3 1 10 1 2 3 4 5 6 7 8 9 10 -1 Note In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4. In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer. In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1. Submitted Solution: ``` import io,os import copy from math import * J=input;input=lambda:J().encode() input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def thin(G, n, k): good = list(range(n)) changed = True while changed: next = [] changed = False for i in good: if len(G[i]) >= k: next.append(i) continue changed = True for v in G[i]: G[v].discard(i) good = next return good, G for _ in range(int(input())): n,m,k=map(int,input().split()) G = [set() for _ in range(n)] for _ in range(m): u,v=map(int,input().split()) G[u-1].add(v-1) G[v-1].add(u-1) poss = list(range(n)) first, _ = thin(copy.deepcopy(G), n, k) if first: print(1, len(first)) print(*[x+1 for x in first]) continue second, _ = thin(copy.deepcopy(G), n, k-1) starts = [x for x in second if len(G[x]) == k-1] for s in starts: clique = set([s]) | G[s] if all(clique.issubset(set([v]) | G[v]) for v in G[s]): print(2) print(*[x+1 for x in clique]) break else: print(-1) ```
instruction
0
89,508
13
179,016
No
output
1
89,508
13
179,017
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with n vertices and m edges. Also, you are given an integer k. Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it. A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them. Input The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers n, m, k (1 ≤ n, m, k ≤ 10^5, k ≤ n). Each of the next m lines contains two integers u, v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge between vertices u and v. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 ⋅ 10^5. Output For each test case: If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print -1. If there exists multiple possible answers you can print any of them. Example Input 3 5 9 4 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 10 15 3 1 2 2 3 3 4 4 5 5 1 1 7 2 8 3 9 4 10 5 6 7 10 10 8 8 6 6 9 9 7 4 5 4 1 2 2 3 3 4 4 1 1 3 Output 2 4 1 2 3 1 10 1 2 3 4 5 6 7 8 9 10 -1 Note In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4. In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer. In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1. Submitted Solution: ``` import io,os import copy from math import * J=input;input=lambda:J().encode() input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline for _ in range(int(input())): n,m,k=map(int,input().split()) G = [set() for _ in range(n)] for _ in range(m): u,v=map(int,input().split()) G[u-1].add(v-1) G[v-1].add(u-1) poss = list(range(n)) H = copy.deepcopy(G) changed = True while changed and len(poss): changed = False next = [] for i in poss: if len(G[i]) >= k: next.append(i) continue changed = True for v in G[i]: G[v].discard(i) poss = next if len(poss): print(1, len(poss)) print(*[x+1 for x in poss]) continue G = H poss = list(range(n)) changed = True while changed and len(poss): changed = False next = [] for i in poss: if len(G[i]) >= k-1: next.append(i) continue changed = True for v in G[i]: G[v].discard(i) poss = next starters = set([x for x in poss if len(G[x]) == k-1]) poss = [] #print(starters) while starters: o = starters.pop() l = G[o] res = set([o]) | l good = True #print(o, res) for v in l: if not res.issubset(set([v]) | G[v]): good = False break if good: poss = res break if len(poss): print(2) print(*[x+1 for x in poss]) continue else: print(-1) continue ```
instruction
0
89,509
13
179,018
No
output
1
89,509
13
179,019
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with n vertices and m edges. Also, you are given an integer k. Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it. A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them. Input The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers n, m, k (1 ≤ n, m, k ≤ 10^5, k ≤ n). Each of the next m lines contains two integers u, v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge between vertices u and v. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 ⋅ 10^5. Output For each test case: If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print -1. If there exists multiple possible answers you can print any of them. Example Input 3 5 9 4 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 10 15 3 1 2 2 3 3 4 4 5 5 1 1 7 2 8 3 9 4 10 5 6 7 10 10 8 8 6 6 9 9 7 4 5 4 1 2 2 3 3 4 4 1 1 3 Output 2 4 1 2 3 1 10 1 2 3 4 5 6 7 8 9 10 -1 Note In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4. In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer. In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1. Submitted Solution: ``` import heapq import io import os import sys input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline print = sys.stdout.write def check(u, neighbors, edges): for v in neighbors: for w in neighbors: if v == w: continue if (v, w) not in edges: return False return True def solve(n, m, k, graph, edges): heap = [] for u in range(1, n + 1): heapq.heappush(heap, (len(graph[u]), u)) in_heap = set(range(1, n + 1)) clique = [] while len(in_heap) >= k: _, u = heapq.heappop(heap) if u not in in_heap: continue if len(graph[u]) >= k: ans = [str(u)] in_heap.remove(u) while len(heap) > 0: _, v = heapq.heappop(heap) if v in in_heap: ans.append(str(v)) in_heap.remove(v) print('1 ' + str(len(ans)) + '\n') print(' '.join(ans) + '\n') return if len(graph[u]) == k - 1: clique.append((u, graph[u].copy())) for v in graph[u]: graph[v].remove(u) heapq.heappush(heap, (len(graph[v]), v)) in_heap.remove(u) for u, neighbors in clique: if check(u, neighbors, edges): print('2\n') sys.stdout.write(str(n)) ans = [str(u)] for v in neighbors: ans.append(str(v)) print(' '.join(ans) + '\n') return print('-1\n') def main(): t = int(input().decode()) for _ in range(t): n, m, k = [int(word) for word in input().decode().rstrip().split()] graph = [set() for i in range(n + 1)] edges = set() for i in range(m): u, v = [int(word) for word in input().decode().rstrip().split()] graph[u].add(v) graph[v].add(u) edges.add((u, v)) edges.add((v, u)) solve(n, m, k, graph, edges) if __name__ == "__main__": main() ```
instruction
0
89,510
13
179,020
No
output
1
89,510
13
179,021
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with n vertices and m edges. Also, you are given an integer k. Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it. A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them. Input The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers n, m, k (1 ≤ n, m, k ≤ 10^5, k ≤ n). Each of the next m lines contains two integers u, v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge between vertices u and v. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 ⋅ 10^5. Output For each test case: If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print -1. If there exists multiple possible answers you can print any of them. Example Input 3 5 9 4 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 10 15 3 1 2 2 3 3 4 4 5 5 1 1 7 2 8 3 9 4 10 5 6 7 10 10 8 8 6 6 9 9 7 4 5 4 1 2 2 3 3 4 4 1 1 3 Output 2 4 1 2 3 1 10 1 2 3 4 5 6 7 8 9 10 -1 Note In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4. In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer. In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1. Submitted Solution: ``` import heapq def check(u, graph): for v in graph[u]: for w in graph[u]: if v == w: continue if v not in graph[w]: return False return True def solve(n, m, k, graph): heap = [] for u in range(1, n + 1): heapq.heappush(heap, (len(graph[u]), u)) in_heap = set(range(1, n + 1)) while len(in_heap) >= k: _, u = heapq.heappop(heap) if u not in in_heap: continue if len(graph[u]) >= k: print(1) ans = [str(u)] in_heap.remove(u) while len(heap) > 0: _, v = heapq.heappop(heap) if v in in_heap: ans.append(str(v)) in_heap.remove(v) print(' '.join(ans)) return if len(graph[u]) == k - 1 and check(u, graph): print(2) ans = [str(u)] for v in graph[u]: ans.append(str(v)) print(' '.join(ans)) for v in graph[u]: graph[v].remove(u) heapq.heappush(heap, (len(graph[v]), v)) in_heap.remove(u) print(-1) def main(): t = int(input()) for _ in range(t): n, m, k = [int(word) for word in input().rstrip().split()] graph = [set() for i in range(n + 1)] for i in range(m): u, v = [int(word) for word in input().rstrip().split()] graph[u].add(v) graph[v].add(u) solve(n, m, k, graph) if __name__ == "__main__": main() ```
instruction
0
89,511
13
179,022
No
output
1
89,511
13
179,023
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red. Find the minimum possible number of moves required to make the colors of all edges equal. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of vertices and edges, respectively. The following m lines provide the description of the edges, as the i-th of them contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the indices of the vertices connected by the i-th edge, and a character ci (<image>) providing the initial color of this edge. If ci equals 'R', then this edge is initially colored red. Otherwise, ci is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges. Output If there is no way to make the colors of all edges equal output - 1 in the only line of the output. Otherwise first output k — the minimum number of moves required to achieve the goal, then output k integers a1, a2, ..., ak, where ai is equal to the index of the vertex that should be used at the i-th move. If there are multiple optimal sequences of moves, output any of them. Examples Input 3 3 1 2 B 3 1 R 3 2 B Output 1 2 Input 6 5 1 3 R 2 3 R 3 4 B 4 5 R 4 6 R Output 2 3 4 Input 4 5 1 2 R 1 3 R 2 3 B 3 4 B 1 4 B Output -1
instruction
0
89,739
13
179,478
Tags: dfs and similar, graphs Correct Solution: ``` from collections import deque n, m = map(int, input().split()) adj = [[] for i in range(n)] for i in range(m): u, v, c = input().split() u, v = int(u)-1, int(v)-1 adj[u].append((v, c)) adj[v].append((u, c)) visited = S = T = None def bfs(i, k): q = deque([(i, 0)]) while q: u, p = q.pop() if visited[u] >= 0: if visited[u] == p: continue else: return False visited[u] = p if p: S.append(u) else: T.append(u) for v, c in adj[u]: nxt = p if c == k else p^1 q.appendleft((v, nxt)) return True def solve(k): global visited, S, T visited = [-1]*n res = [] for i in range(n): if visited[i] < 0: S, T = [], [] if not bfs(i, k): return [0]*(n+1) else: res.extend(S if len(S) < len(T) else T) return res res1 = solve("R") res2 = solve("B") if min(len(res1), len(res2)) > n: print (-1) else: print (min(len(res1), len(res2))) print (" ".join(map(lambda x: str(x+1), res1 if len(res1) < len(res2) else res2))) ```
output
1
89,739
13
179,479
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red. Find the minimum possible number of moves required to make the colors of all edges equal. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of vertices and edges, respectively. The following m lines provide the description of the edges, as the i-th of them contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the indices of the vertices connected by the i-th edge, and a character ci (<image>) providing the initial color of this edge. If ci equals 'R', then this edge is initially colored red. Otherwise, ci is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges. Output If there is no way to make the colors of all edges equal output - 1 in the only line of the output. Otherwise first output k — the minimum number of moves required to achieve the goal, then output k integers a1, a2, ..., ak, where ai is equal to the index of the vertex that should be used at the i-th move. If there are multiple optimal sequences of moves, output any of them. Examples Input 3 3 1 2 B 3 1 R 3 2 B Output 1 2 Input 6 5 1 3 R 2 3 R 3 4 B 4 5 R 4 6 R Output 2 3 4 Input 4 5 1 2 R 1 3 R 2 3 B 3 4 B 1 4 B Output -1 Submitted Solution: ``` node_count, vertex_count = map(int, input().split(' ')) nodes = [set() for i in range(node_count)] for i in range(vertex_count): f, t, c = input().split(' ') f, t, c = int(f) - 1, int(t) - 1, (1 if c == 'R' else 2) nodes[f].add((t, c)) nodes[t].add((f, c)) colors = [] # 0 = not visited, 1=not switching, 2=switching def dfs(graph, wanted_color): global colors colors = [0 for i in range(node_count)] can_be_done = True for index, node in enumerate(graph): if colors[index] == 0: try: can_be_done = can_be_done and dastan(graph, index, wanted_color) except: pass return can_be_done def dastan(graph, node_index, global_color, should_switch=None): if colors[node_index] > 0: # check if node is already in the state required (e.g. is switching) return (colors[node_index] == 2) == should_switch else: # check color if should_switch is None: colors[node_index] = 0 should_switch = False elif should_switch: colors[node_index] = 2 else: colors[node_index] = 1 for neighbour in nodes[node_index]: # graph, node_index, global (wanted color) , xor of if we are changing this node and if we should change next node if not dastan(graph, neighbour[0], global_color, ((global_color == neighbour[1]) == should_switch)): return False return True ans = [] if dfs(nodes, 1): ACount, BCount = colors.count(1), colors.count(2) ANodes, BNodes = [i for i, x in enumerate(colors) if x == 1], [i for i, x in enumerate(colors) if x == 2] ans.append((ACount, ANodes)) ans.append((BCount, BNodes)) a = 2 + 2 if dfs(nodes, 2): ACount, BCount = colors.count(1), colors.count(2) ANodes, BNodes = [i for i, x in enumerate(colors) if x == 1], [i for i, x in enumerate(colors) if x == 2] ans.append((ACount, ANodes)) ans.append((BCount, BNodes)) if len(ans) == 0: print(-1) else: shortest = sorted(ans, key=lambda x: x[0])[0] print(shortest[0]) print(' '.join(map(lambda x: str(x + 1), shortest[1]))) ```
instruction
0
89,740
13
179,480
No
output
1
89,740
13
179,481
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (a connected acyclic undirected graph) of n vertices. Vertices are numbered from 1 to n and each vertex is assigned a character from a to t. A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome. For each vertex, output the number of palindromic paths passing through it. Note: The path from vertex u to vertex v is considered to be the same as the path from vertex v to vertex u, and this path will be counted only once for each of the vertices it passes through. Input The first line contains an integer n (2 ≤ n ≤ 2·105) — the number of vertices in the tree. The next n - 1 lines each contain two integers u and v (1 ≤ u, v ≤ n, u ≠ v) denoting an edge connecting vertex u and vertex v. It is guaranteed that the given graph is a tree. The next line contains a string consisting of n lowercase characters from a to t where the i-th (1 ≤ i ≤ n) character is the label of vertex i in the tree. Output Print n integers in a single line, the i-th of which is the number of palindromic paths passing through vertex i in the tree. Examples Input 5 1 2 2 3 3 4 3 5 abcbb Output 1 3 4 3 3 Input 7 6 2 4 3 3 7 5 2 7 2 1 4 afefdfs Output 1 4 1 1 2 4 2 Note In the first sample case, the following paths are palindromic: 2 - 3 - 4 2 - 3 - 5 4 - 3 - 5 Additionally, all paths containing only one vertex are palindromic. Listed below are a few paths in the first sample that are not palindromic: 1 - 2 - 3 1 - 2 - 3 - 4 1 - 2 - 3 - 5
instruction
0
89,834
13
179,668
Tags: bitmasks, data structures, divide and conquer, trees Correct Solution: ``` import sys, os def centroid_decomp(coupl): n = len(coupl) bfs = [n - 1] for node in bfs: bfs += coupl[node] for nei in coupl[node]: coupl[nei].remove(node) size = [0] * n for node in reversed(bfs): size[node] = 1 + sum(size[child] for child in coupl[node]) def centroid_reroot(root): while coupl[root]: child = max(coupl[root], key = size.__getitem__) if size[child] <= size[root] // 2: break size[root] -= size[child] size[child] += size[root] coupl[root].remove(child) coupl[child].append(root) root = child return root bfs = [n - 1] for node in bfs: centroid = centroid_reroot(node) bfs += coupl[centroid] yield centroid inp = sys.stdin.buffer.read().split(); ii = 0 n = int(inp[ii]); ii += 1 coupl = [[] for _ in range(n)] for _ in range(n - 1): u = int(inp[ii]) - 1; ii += 1 v = int(inp[ii]) - 1; ii += 1 coupl[u].append(v) coupl[v].append(u) A = [1 << c - b'a'[0] for c in inp[ii]]; ii += 1 palistates = [0] + [1 << i for i in range(20)] ans = [0.0] * n dp = [0.0] * n val = [0] * n counter = [0] * (1 << 20) for centroid in centroid_decomp(coupl): bfss = [] for root in coupl[centroid]: bfs = [root] for node in bfs: bfs += coupl[node] bfss.append(bfs) for node in bfs: val[node] ^= A[node] for child in coupl[node]: val[child] = val[node] entire_bfs = [centroid] for bfs in bfss: entire_bfs += bfs for node in entire_bfs: val[node] ^= A[centroid] counter[val[node]] += 1 for bfs in bfss: for node in bfs: counter[val[node]] -= 1 for node in bfs: v = val[node] ^ A[centroid] for p in palistates: dp[node] += counter[v ^ p] for node in bfs: counter[val[node]] += 1 for node in reversed(entire_bfs): dp[node] += sum(dp[child] for child in coupl[node]) dp[centroid] += 1 for p in palistates: dp[centroid] += counter[p] dp[centroid] //= 2 for node in entire_bfs: ans[node] += dp[node] counter[val[node]] = val[node] = 0 dp[node] = 0.0 os.write(1, b' '.join(str(int(x)).encode('ascii') for x in ans)) ```
output
1
89,834
13
179,669
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. C: AA グラフ (AA Graph) Problem Given a graph as an ASCII Art (AA), please print the length of shortest paths from the vertex s to the vertex t. The AA of the graph satisfies the following constraints. A vertex is represented by an uppercase alphabet and symbols `o` in 8 neighbors as follows. ooo oAo ooo Horizontal edges and vertical edges are represented by symbols `-` and `|`, respectively. Lengths of all edges are 1, that is, it do not depends on the number of continuous symbols `-` or `|`. All edges do not cross each other, and all vertices do not overlap and touch each other. For each vertex, outgoing edges are at most 1 for each directions top, bottom, left, and right. Each edge is connected to a symbol `o` that is adjacent to an uppercase alphabet in 4 neighbors as follows. ..|.. .ooo. -oAo- .ooo. ..|.. Therefore, for example, following inputs are not given. .......... .ooo..ooo. .oAo..oBo. .ooo--ooo. .......... (Edges do not satisfies the constraint about their position.) oooooo oAooBo oooooo (Two vertices are adjacent each other.) Input Format H W s t a_1 $\vdots$ a_H * In line 1, two integers H and W, and two characters s and t are given. H and W is the width and height of the AA, respectively. s and t is the start and end vertices, respectively. They are given in separating by en spaces. * In line 1 + i where 1 \leq i \leq H, the string representing line i of the AA is given. Constraints * 3 \leq H, W \leq 50 * s and t are selected by uppercase alphabets from `A` to `Z`, and s \neq t. * a_i (1 \leq i \leq H) consists of uppercase alphabets and symbols `o`, `-`, `|`, and `.`. * Each uppercase alphabet occurs at most once in the AA. * It is guaranteed that there are two vertices representing s and t. * The AA represents a connected graph. Output Format Print the length of the shortest paths from s to t in one line. Example 1 14 16 A L ooo.....ooo..... oAo-----oHo..... ooo.....ooo..ooo .|.......|...oLo ooo..ooo.|...ooo oKo--oYo.|....|. ooo..ooo.|....|. .|....|.ooo...|. .|....|.oGo...|. .|....|.ooo...|. .|....|.......|. ooo..ooo.....ooo oFo--oXo-----oEo ooo..ooo.....ooo Output 1 5 Exapmple 2 21 17 F L ................. .....ooo.....ooo. .....oAo-----oBo. .....ooo.....ooo. ......|.......|.. .ooo..|..ooo..|.. .oCo..|..oDo.ooo. .ooo.ooo.ooo.oEo. ..|..oFo..|..ooo. ..|..ooo..|...|.. ..|...|...|...|.. ..|...|...|...|.. ..|...|...|...|.. .ooo.ooo.ooo..|.. .oGo-oHo-oIo..|.. .ooo.ooo.ooo..|.. ..|...........|.. .ooo...ooo...ooo. .oJo---oKo---oLo. .ooo...ooo...ooo. ................. Output 2 4 Example Input Output Submitted Solution: ``` #include <bits/stdc++.h> int alf_to_num(char c) { return (int)c - (int)'A'; } int main() { int H, W, i, j, k, nowv; char s, t; scanf("%d %d %c %c", &H, &W, &s, &t); char **a = (char **)malloc(sizeof(char *) * (H + 2)); for (i = 0; i <= H + 1; i++) { a[i] = (char *)malloc(sizeof(char) * (W + 2)); if (i == 0 || i == H + 1) { for (j = 0; j <= W + 1; j++) { a[i][j] = '.'; } } else { a[i][0] = '.'; scanf("%s", &a[i][1]); a[i][W + 1] = '.'; } } int **dis = (int **)malloc(sizeof(int *) * 26); for (i = 0; i < 26; i++) { dis[i] = (int *)malloc(sizeof(int) * 26); for (j = 0; j < 26; j++) { dis[i][j] = (int)(1e8); } } for (i = 0; i <= H + 1; i++) { for (j = 0; j <= W + 1; j++) { nowv = alf_to_num(a[i][j]); if (0 <= nowv && nowv < 26) { if (a[i - 2][j] == '|') { for (k = 2;; k++) { if (a[i - k][j] == 'o') { dis[nowv][alf_to_num(a[i - k - 1][j])] = 1; dis[alf_to_num(a[i - k - 1][j])][nowv] = 1; break; } else { a[i - k][j] = '.'; } } } if (a[i + 2][j] == '|') { for (k = 2;; k++) { if (a[i + k][j] == 'o') { dis[nowv][alf_to_num(a[i + k + 1][j])] = 1; dis[alf_to_num(a[i + k + 1][j])][nowv] = 1; break; } else { a[i + k][j] = '.'; } } } if (a[i][j - 2] == '-') { for (k = 2;; k++) { if (a[i][j - k] == 'o') { dis[nowv][alf_to_num(a[i][j - k - 1])] = 1; dis[alf_to_num(a[i][j - k - 1])][nowv] = 1; break; } else { a[i][j - k] = '.'; } } } if (a[i][j + 2] == '-') { for (k = 2;; k++) { if (a[i][j + k] == 'o') { dis[nowv][alf_to_num(a[i][j + k + 1])] = 1; dis[alf_to_num(a[i][j + k + 1])][nowv] = 1; break; } else { a[i][j + k] = '.'; } } } } } } for (k = 0; k < 26; k++) { for (i = 0; i < 26; i++) { for (j = 0; j < 26; j++) { if (dis[i][j] > dis[i][k] + dis[k][j]) { dis[i][j] = dis[i][k] + dis[k][j]; } } } } printf("%d\n", dis[alf_to_num(s)][alf_to_num(t)]); return 0; } ```
instruction
0
90,061
13
180,122
No
output
1
90,061
13
180,123
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3.
instruction
0
90,122
13
180,244
Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import defaultdict n, k = map(int, input().split()) connections = defaultdict(set) for _ in range(n-1): u, v = map(int, input().split()) connections[u].add(v) connections[v].add(u) leafs = set() for node in connections: if len(connections[node])==1: leafs.add(node) steps = 0 is_correct = True while is_correct and steps<=k: new_leafs = set() for x in leafs: if len(connections[x])>1: is_correct = False #print("Len of %d more than one"%x) break root = list(connections[x])[0] if len(connections[root])<4 and len(leafs)!=3: is_correct = False #print("x: %d Len of root %d less than three"%(x,root)) #print(connections[root]) break if not is_correct: break for x in leafs: root = list(connections[x])[0] new_leafs.add(root) connections[root].remove(x) leafs = new_leafs steps += 1 if len(leafs)==1 and len(connections[list(leafs)[0]])==0: break #print("steps is %d"%steps) if is_correct and steps==k: print("Yes") else: print('No') ```
output
1
90,122
13
180,245
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3.
instruction
0
90,123
13
180,246
Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import deque n, k = list(map(int, input().split())) G = [set() for _ in range(n + 1)] q, nq = deque(), deque() for _ in range(n - 1): u, v = list(map(int, input().split())) G[u].add(v) G[v].add(u) for u in range(1, n + 1): if len(G[u]) == 1: q.append(u) step = 0 removed = 0 ok = True while removed < n - 1: each = {} for u in q: nxt = G[u].pop() G[nxt].remove(u) each[nxt] = each.get(nxt, 0) + 1 removed += 1 if len(G[nxt]) == 0: break if len(G[nxt]) == 1: nq.append(nxt) if any(v < 3 for k,v in each.items()): ok = False break q, nq = nq, deque() step += 1 if ok and step == k and removed == n - 1: print('Yes') else: print('No') #print the result ```
output
1
90,123
13
180,247
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3.
instruction
0
90,124
13
180,248
Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import deque n, k = list(map(int, input().split())) G = [set() for _ in range(n + 1)] q, nq = deque(), deque() for _ in range(n - 1): u, v = list(map(int, input().split())) G[u].add(v) G[v].add(u) for u in range(1, n + 1): if len(G[u]) == 1: q.append(u) step = 0 removed = 0 ok = True while removed < n - 1: each = {} for u in q: nxt = G[u].pop() G[nxt].remove(u) each[nxt] = each.get(nxt, 0) + 1 removed += 1 if len(G[nxt]) == 0: break if len(G[nxt]) == 1: nq.append(nxt) if any(v < 3 for k,v in each.items()): ok = False break q, nq = nq, deque() step += 1 if ok and step == k and removed == n - 1: print('Yes') else: print('No') #JSR ```
output
1
90,124
13
180,249
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3.
instruction
0
90,125
13
180,250
Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import deque n,k = map(int,input().split()) d = {} for i in range(n): d[i+1] = set() for i in range(n-1): u,v = map(int,input().split()) d[u].add(v) d[v].add(u) dist = {} prev = {} dist[1] = 0 q = deque() q.append(1) while len(q) >0: cur = q.popleft() for x in d[cur]: if x not in dist: prev[x] = cur dist[x] = dist[cur]+1 q.append(x) answer = True if k > dist[cur]: answer = False else: for i in range(k): cur = prev[cur] dist2 = {} dist2[cur] = 0 q = deque() q.append(cur) while len(q) >0: cur2 = q.popleft() if cur2 == cur and len(d[cur]) < 3: answer = False break if len(d[cur2]) == 1: if dist2[cur2] != k: answer = False break elif len(d[cur2]) < 4 and cur2 != cur: answer = False break for x in d[cur2]: if x not in dist2: dist2[x] = dist2[cur2]+1 q.append(x) if answer: print("Yes") else: print("No") ```
output
1
90,125
13
180,251
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3.
instruction
0
90,126
13
180,252
Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` # https://codeforces.com/problemset/problem/1067/B def push(d, u, v): if u not in d: d[u] = [] if v not in d: d[v] = [] d[u].append(v) d[v].append(u) def push_v(d, u, val): if u not in d: d[u] = 0 d[u] += val n, k = map(int, input().split()) g = {} for _ in range(n-1): u, v = map(int, input().split()) push(g, u, v) deg1 = [] used = [0] * (n+1) for u in g: if len(g[u]) == 1: used[u] = 1 deg1.append(u) flg = True while k > 0: if k >= 1 and len(deg1) < 3: flg=False break cnt = {} for u in deg1: for v in g[u]: if used[v] == 0: push_v(cnt, v, 1) for v in deg1: used[v] = 1 deg1 = [] for v, val in cnt.items(): if val < 3: flg=False break deg1.append(v) if flg==False: break k-=1 if flg==True and len(deg1) > 1: flg=False if flg==False: print('NO') else: print('YES') ```
output
1
90,126
13
180,253
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3.
instruction
0
90,127
13
180,254
Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import deque n, k = list(map(int, input().split())) Gg = [set() for _ in range(n + 1)] q, nq = deque(), deque() for _ in range(n - 1): u, v = list(map(int, input().split())) Gg[u].add(v) Gg[v].add(u) for u in range(1, n + 1): if len(Gg[u]) == 1: q.append(u) step = 0 removed = 0 ok = True while removed < n - 1: each = {} for u in q: nxt = Gg[u].pop() Gg[nxt].remove(u) each[nxt] = each.get(nxt, 0) + 1 removed += 1 if len(Gg[nxt]) == 0: break if len(Gg[nxt]) == 1: nq.append(nxt) if any(v < 3 for k,v in each.items()): ok = False break q, nq = nq, deque() step += 1 if ok and step == k and removed == n - 1: print('Yes') else: print('No') #JSR ```
output
1
90,127
13
180,255
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3.
instruction
0
90,128
13
180,256
Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from sys import stdin from collections import deque n, k = map(int, stdin.readline().split()) graph = [[] for _ in range(n)] leaf = -1 for _ in range(n-1): a,b = map(int,stdin.readline().split()) graph[a - 1].append(b - 1) graph[b - 1].append(a - 1) def bfs(G, s): # la cola comienza con el vertice desde el cual hacemos bfs Q = deque() Q.append(s) # al inicio todas las distancias comienzan en infinito, por las # restricciones del problema ningun camino va a ser de ese tamanno infinite = 10 ** 6 d = [infinite]*n parent = [-1]*n valid = True # la distancia del vertice raiz es 0 d[s] = 0 while Q: # visitamos u u = Q.popleft() not_visited_count = 0 # visitamos cada adyacente de u for v in G[u]: # si no lo hemos visitado, le ponemos distancia y # lo agregamos a la cola para visitar sus adyacentes if d[v] == infinite: d[v] = d[u] + 1 parent[v] = u Q.append(v) not_visited_count += 1 if not_visited_count < 3 and d[u] != k: valid = False # retornamos el array d, que es el de las distancias del # nodo s al resto de los nodos del grafo return d, parent, valid leaf = -1 for i,v in enumerate(graph): if len(v) == 1: leaf = i break d, parent, _ = bfs(graph,leaf) center = -1 farthest_leaf = -1 path = 2*k for i,level in enumerate(d): if level == path: farthest_leaf = i break if len(graph[farthest_leaf]) != 1 or farthest_leaf == -1: print("NO") exit() for _ in range(k): center = parent[farthest_leaf] farthest_leaf = center _, _, valid = bfs(graph,center) if valid: print("YES") else: print("NO") ```
output
1
90,128
13
180,257
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3.
instruction
0
90,129
13
180,258
Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` import math n,k=map(int,input().split()) edges=[] for i in range(n-1): edges.append(tuple(map(int,input().split()))) degreelist=[] for i in range(min(k+1,math.floor(math.log2(n))+10)): degreelist.append({}) degrees=degreelist[0] for i in range(1,n+1): degrees[i]=0 for guy in edges: degrees[guy[0]]+=1 degrees[guy[1]]+=1 small=[] center=None done=False for i in range(k): if not done: small=[] for guy in degrees: if degrees[guy]==2: print("No") done=True break if degrees[guy]==3: small.append(guy) if center==None: center=guy elif center!=guy: print("No") done=True break elif degrees[guy]>1: small.append(guy) degrees=degreelist[i+1] if center!=None and center not in small: if not done: print("No") done=True break elif len(small)==0: if not done: print("No") done=True break for guy in small: degrees[guy]=0 for guy in edges: if guy[0] in degrees and guy[1] in degrees: degrees[guy[0]]+=1 degrees[guy[1]]+=1 for guy in degrees: if degrees[guy]>1 and degreelist[i][guy]!=degrees[guy]: if not done: print("No") done=True break else: break if not done: if len(degreelist[-1])==1: print("Yes") else: print("No") ```
output
1
90,129
13
180,259
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Submitted Solution: ``` from collections import deque n, h = list(map(int, input().split())) G = [set() for _ in range(n + 1)] q, nq = deque(), deque() for _ in range(n - 1): u, v = list(map(int, input().split())) G[u].add(v) G[v].add(u) for u in range(1, n + 1): if len(G[u]) == 1: q.append(u) step = 0 removed = 0 ok = True while removed < n - 1: each = {} for u in q: nxt = G[u].pop() G[nxt].remove(u) each[nxt] = each.get(nxt, 0) + 1 removed += 1 if len(G[nxt]) == 0: break if len(G[nxt]) == 1: nq.append(nxt) if any(v < 3 for h,v in each.items()): ok = False break q, nq = nq, deque() step += 1 if ok and step == h and removed == n - 1: print('Yes') else: print('No') ```
instruction
0
90,130
13
180,260
Yes
output
1
90,130
13
180,261
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Submitted Solution: ``` n,k = map(int,input().split(" ")) degrees = [0] * n neighbors = [list() for x in range(n)] for i in range(n-1): first,second = map(int,input().split(" ")) degrees[first-1] += 1 degrees[second-1] += 1 neighbors[first-1] += [second] neighbors[second-1] += [first] # start at a leaf curr = 0 for i in range(n): if degrees[i] == 1: curr = i+1 break if curr == 0 or len(neighbors[curr-1]) == 0: print("No") exit() curr = neighbors[curr-1][0] def check(prev,parent,curr,level,degrees,neighbors,k): #print("curr: ",curr) #print("level: ",level) if level == 0: return len(parent) == 1 and degrees[curr-1] == 1,[] checked = [] for neighbor in neighbors[curr-1]: #print("neighbor: ",neighbor) #print("checked: ",checked) #print("parent: ",parent) if len(prev) != 0 and prev[0] == neighbor: checked += [neighbor] continue if len(parent) != 0 and parent[0] == neighbor: continue result,garbage = check([],[curr],neighbor,level-1,degrees,neighbors,k) if result: checked += [neighbor] else: #print("adding the parent") if len(parent) == 0: parent += [neighbor] else: return False,[] if len(checked) > 2 and len(parent) == 0 and level == k: #print("first check") return True,[] elif len(checked) > 2 and len(parent) == 1 and level != k: #print("second check") return True,parent else: #print("len(checked): ",len(checked)) #print("len(parent): ",len(parent)) #print("level: ",level) #print("the end fail statement") return False,[] prev = [] parent = [] counter = 1 while(counter <= k): result,parent = check(prev,[],curr,counter,degrees,neighbors,k) if not(result): print("No") exit() if counter == k: print("Yes") exit() prev = [curr] curr = parent[0] counter += 1 ```
instruction
0
90,131
13
180,262
Yes
output
1
90,131
13
180,263