message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1 Submitted Solution: ``` from collections import UserList class Stack(UserList): def __init__(self, *args): UserList.__init__(self, *args) self.contains = set() def __contains__(self, x): return x in self.contains def __and__(self, x): return self.contains & x def push(self, x): if x in self.contains: return self.data.append(x) self.contains |= {x} def pop(self): x = self.data.pop() self.contains -= {x} return x def is_contain_cycle(g, v): visited = set() for i in range(v): if i in visited: continue route = Stack([None]) dfs_stack = [(i, None)] while dfs_stack: u, prev = dfs_stack.pop() while route[-1] != prev: route.pop() visited |= {u} if u in route: return True dfs_stack.extend((v, u) for v in g[u]) route.push(u) return False from sys import stdin from collections import defaultdict readline = stdin.readline v, e = map(int, readline().split()) g = defaultdict(set) for i in range(e): s, t = map(int, readline().split()) g[s] |= {t} print(1 if is_contain_cycle(g, v) else 0) ```
instruction
0
58,825
13
117,650
No
output
1
58,825
13
117,651
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1 Submitted Solution: ``` import sys sys.setrecursionlimit(200000) def do_dfs(root, add_duplicated=True): global edges, visited, duplicated def main(i): visited[i] = True for edge in edges[i]: if visited[edge]: if edge == root: return True if add_duplicated: duplicated.add(edge) continue if main(edge): return True return False return main(root) n, m = map(int, input().split()) edges = [set() for _ in range(n)] for _ in range(m): s, t = map(int, input().split()) edges[s].add(t) visited = [False] * n duplicated = set() for i in range(n): if not visited[i]: if do_dfs(i): print(1) break else: visited = [False] * n for i in duplicated: root = i if do_dfs(i, False): print(1) break else: print(0) ```
instruction
0
58,826
13
117,652
No
output
1
58,826
13
117,653
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1 Submitted Solution: ``` nv,ne = [int(i) for i in input().split()] g = [[] for i in range(nv)] for i in range(ne): s,t = [int(j) for j in input().split()] g[s].append(t) visited = [False for i in range(nv)] f = 0 def pursue_from(index): global f if visited[index]: return visited[index] = True for next_index in g[index]: if next_index == 0: f = 1 return pursue_from(next_index) pursue_from(0) print(f) ```
instruction
0
58,827
13
117,654
No
output
1
58,827
13
117,655
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given a tree consisting of n nodes. Every node u has a weight a_u. It is guaranteed that there is only one node with minimum weight in the tree. For every node u (except for the node with the minimum weight), it must have a neighbor v such that a_v<a_u. You should construct a tree to minimize the weight w calculated as follows: * For every node u, deg_u ⋅ a_u is added to w (deg_u is the number of edges containing node u). * For every edge \{ u,v \}, ⌈ log_2(dist(u,v)) ⌉ ⋅ min(a_u,a_v) is added to w, where dist(u,v) is the number of edges in the path from u to v in the given tree. Input The first line contains the integer n (2 ≤ n ≤ 5 ⋅ 10^5), the number of nodes in the tree. The second line contains n space-separated integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), the weights of the nodes. The next n-1 lines, each contains 2 space-separated integers u and v (1 ≤ u,v ≤ n) which means there's an edge between u and v. Output Output one integer, the minimum possible value for w. Examples Input 3 1 2 3 1 2 1 3 Output 7 Input 5 4 5 3 7 8 1 2 1 3 3 4 4 5 Output 40 Note In the first sample, the tree itself minimizes the value of w. In the second sample, the optimal tree is: <image> Submitted Solution: ``` a=input() b=input() c=input() d=input() if(a=='3' and b=='1 2 3' and c=='1 2' and d=='1 3'): print(7) else: print("HAHA") ```
instruction
0
58,864
13
117,728
No
output
1
58,864
13
117,729
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given a tree consisting of n nodes. Every node u has a weight a_u. It is guaranteed that there is only one node with minimum weight in the tree. For every node u (except for the node with the minimum weight), it must have a neighbor v such that a_v<a_u. You should construct a tree to minimize the weight w calculated as follows: * For every node u, deg_u ⋅ a_u is added to w (deg_u is the number of edges containing node u). * For every edge \{ u,v \}, ⌈ log_2(dist(u,v)) ⌉ ⋅ min(a_u,a_v) is added to w, where dist(u,v) is the number of edges in the path from u to v in the given tree. Input The first line contains the integer n (2 ≤ n ≤ 5 ⋅ 10^5), the number of nodes in the tree. The second line contains n space-separated integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), the weights of the nodes. The next n-1 lines, each contains 2 space-separated integers u and v (1 ≤ u,v ≤ n) which means there's an edge between u and v. Output Output one integer, the minimum possible value for w. Examples Input 3 1 2 3 1 2 1 3 Output 7 Input 5 4 5 3 7 8 1 2 1 3 3 4 4 5 Output 40 Note In the first sample, the tree itself minimizes the value of w. In the second sample, the optimal tree is: <image> Submitted Solution: ``` a=input() b=input() c=input() d=input() if(a=='3' and b=='1 2 3' and c=='1 2' and d=='1 3'): print(7) else: print("HAHA^^") ```
instruction
0
58,865
13
117,730
No
output
1
58,865
13
117,731
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya is an unexperienced programming contestant. Recently he has come across the following problem: You are given a non-directed graph which consists of n nodes and m edges. Your task is to determine whether the graph contains a Hamiltonian path. Petya wrote a quick bug-free code which he believes solves this problem. After that Petya decided to give this problem for April Fools Day contest. Unfortunately, Petya might have made a mistake, and it's quite possible that his algorithm is wrong. But this isn't a good excuse to leave the contest without submitting this problem, is it? Input The first line contains two integers n, m (1 ≤ n ≤ 20; 0 ≤ m ≤ 400). Next m lines contain pairs of integers vi, ui (1 ≤ vi, ui ≤ n). Output Follow the format of Petya's code output. Examples Input 2 3 1 2 2 1 1 1 Output Yes Input 3 0 Output No Input 10 20 3 10 4 6 4 9 7 5 8 8 3 10 9 7 5 2 9 2 10 6 10 4 1 1 7 2 8 4 7 2 1 8 5 4 10 2 8 5 5 2 Output No Submitted Solution: ``` s = [int(i) for i in input().split(" ")] n = s[0] m = s[1] a = [0 for i in range(n)] for i in range(m): s = [int(i) for i in input().split(" ")] a[s[0]-1] += 1 a[s[1]-1] += 1 if sum([i % 2 for i in a]) == 0: print("Yes") else: print("No") ```
instruction
0
59,163
13
118,326
No
output
1
59,163
13
118,327
Provide a correct Python 3 solution for this coding contest problem. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible
instruction
0
59,561
13
119,122
"Correct Solution: ``` # -*- coding: utf-8 -*- import sys from collections import Counter def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') sys.setrecursionlimit(10 ** 9) INF = 10 ** 18 MOD = 10 ** 9 + 7 N = INT() A = LIST() C = sorted(Counter(A).items()) if C[0][1] > 2: print('Impossible') exit() is2src = C[0][1] == 2 src = C[0][0] depth = src - is2src + 1 if len(C) != depth: print('Impossible') exit() for i, (k, v) in enumerate(C[1:], 1): prevk, prevv = C[i-1] if k != prevk + 1: print('Impossible') exit() if 2 > v: print('Impossible') exit() print('Possible') ```
output
1
59,561
13
119,123
Provide a correct Python 3 solution for this coding contest problem. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible
instruction
0
59,562
13
119,124
"Correct Solution: ``` N = int(input()) A = list(map(int, input().split())) A.sort() maxv1 = A[-1] maxv2 = A[-2] if maxv1 != maxv2: print("Impossible") exit() K = maxv1 if K % 2 == 0: for i in range(K // 2): for j in range(2): if K - i in A: A.remove(K - i) else: print("Impossible") exit() if K // 2 in A: A.remove(K // 2) else: print("Impossible") exit() else: for i in range(K // 2 + 1): for j in range(2): if K - i in A: A.remove(K - i) else: print("Impossible") exit() if len(A) == 0: print("Possible") exit() else: for a in A: if K % 2 == 0: if a < K // 2 + 1: print("Impossible") exit() else: if a < (K + 1) // 2 + 1: print("Impossible") exit() print("Possible") ```
output
1
59,562
13
119,125
Provide a correct Python 3 solution for this coding contest problem. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible
instruction
0
59,563
13
119,126
"Correct Solution: ``` from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter import itertools from itertools import permutations,combinations import sys import bisect import string import math import time #import random def I(): return int(input()) def MI(): return map(int,input().split()) def LI(): return [int(i) for i in input().split()] def LI_(): return [int(i)-1 for i in input().split()] def StoI(): return [ord(i)-97 +10 for i in input()] def ItoS(nn): return chr(nn+97) def GI(V,E,Directed=False,index=0): org_inp=[] g=[[] for i in range(n)] for i in range(E): inp=LI() org_inp.append(inp) if index==0: inp[0]-=1 inp[1]-=1 if len(inp)==2: a,b=inp g[a].append(b) if not Directed: g[b].append(a) elif len(inp)==3: a,b,c=inp aa=(inp[0],inp[2]) bb=(inp[1],inp[2]) g[a].append(bb) if not Directed: g[b].append(aa) return g,org_inp def show(*inp,end='\n'): if show_flg: print(*inp,end=end) YN=['Yes','No'] mo=10**9+7 inf=float('inf') l_alp=string.ascii_lowercase u_alp=string.ascii_uppercase #sys.setrecursionlimit(10**5) input=lambda: sys.stdin.readline().rstrip() show_flg=False show_flg=True ans='Possible' n=I() a=LI() M=max(a) m=min(a) c=[0]*(M+1) for i in range(n): c[a[i]]+=1 if sum([min(c[i],1) for i in range(m,M+1)])!=M-m+1: ans='Impossible' if c[m]!=1+M%2: ans='Impossible' print(ans) ```
output
1
59,563
13
119,127
Provide a correct Python 3 solution for this coding contest problem. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible
instruction
0
59,564
13
119,128
"Correct Solution: ``` import math #import numpy as np import queue from collections import deque,defaultdict import heapq as hpq from sys import stdin,setrecursionlimit #from scipy.sparse.csgraph import dijkstra #from scipy.sparse import csr_matrix ipt = stdin.readline setrecursionlimit(10**7) def main(): n = int(ipt()) a = [int(i) for i in ipt().split()] a.sort(reverse=True) res = [] k = a[0] d = defaultdict(int) for i in a: d[i] += 1 if k&1: if a[-1] <= k//2: print("Impossible") exit() if d[k//2+1] != 2: print("Impossible") exit() for i in range(k//2+2,k+1): if d[i] < 2: print("Impossible") exit() else: if a[-1] < k//2: print("Impossible") exit() if d[k//2] != 1: print("Impossible") exit() for i in range(k//2+1,k+1): if d[i] < 2: print("Impossible") exit() print("Possible") return if __name__ == '__main__': main() ```
output
1
59,564
13
119,129
Provide a correct Python 3 solution for this coding contest problem. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible
instruction
0
59,565
13
119,130
"Correct Solution: ``` def main(): from collections import Counter as ct n = int(input()) a = list(map(int, input().split())) c = ct(a) min_a = min(a) max_a = max(a) if min_a == 1: if c[min_a] == 1: pass elif a == [1, 1]: print("Possible") return 0 else: print("Impossible") return 0 if c[min_a] == 1 and (max_a+1)//2 > min_a: print("Impossible") return 0 if c[min_a] == 2 and (max_a+2)//2 > min_a: print("Impossible") return 0 if c[min_a] > 2: print("Impossible") return 0 for i in range(min_a+1, max_a+1): if c[i] < 2: print("Impossible") return 0 print("Possible") main() ```
output
1
59,565
13
119,131
Provide a correct Python 3 solution for this coding contest problem. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible
instruction
0
59,566
13
119,132
"Correct Solution: ``` from collections import Counter N = int(input()) a = [int(i) for i in input().split()] def solve() : cnt = list(Counter(a).items()) cnt.sort() if cnt[0][1] == 1 and cnt[-1][0] != 2 * cnt[0][0] : return 'Impossible' if cnt[0][1] == 2 and cnt[-1][0] != 2 * cnt[0][0] - 1 : return 'Impossible' if cnt[0][1] > 2 : return 'Impossible' for i in range(1, len(cnt)) : if cnt[i][0] != cnt[i-1][0] + 1 : return 'Impossible' if cnt[i][1] < 2 : return 'Impossible' return 'Possible' print(solve()) ```
output
1
59,566
13
119,133
Provide a correct Python 3 solution for this coding contest problem. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible
instruction
0
59,567
13
119,134
"Correct Solution: ``` from collections import Counter n = int(input()) a = list(map(int, input().split())) c = Counter(a) m = max(a) flag = True if m%2 == 0: for i in range(1,m+1): if i<m//2: if c[i]!=0: flag = False break elif i==m//2: if c[i]!=1: flag = False break else: if c[i]<2: flag = False break else: for i in range(1,m+1): if i<=m//2: if c[i]!=0: flag = False break elif i==m//2+1: if c[i]!=2: flag = False break else: if c[i]<2: flag = False break print('Possible' if flag else 'Impossible') ```
output
1
59,567
13
119,135
Provide a correct Python 3 solution for this coding contest problem. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible
instruction
0
59,568
13
119,136
"Correct Solution: ``` from collections import Counter N = int(input()) A = list(map(int,input().split())) ctr = Counter(A) maxa = max(A) mina = min(A) def ok(): if mina != (maxa+1)//2: return False if maxa%2: if ctr[mina] != 2: return False else: if ctr[mina] != 1: return False for n in range(mina+1, maxa+1): if ctr[n] < 2: return False return True print('Possible' if ok() else 'Impossible') ```
output
1
59,568
13
119,137
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible Submitted Solution: ``` import sys sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python import math from copy import copy, deepcopy from copy import deepcopy as dcp from operator import itemgetter from bisect import bisect_left, bisect, bisect_right#2分探索 #bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下 from collections import deque, defaultdict #deque(l), pop(), append(x), popleft(), appendleft(x) #q.rotate(n)で → にn回ローテート from collections import Counter#文字列を個数カウント辞書に、 #S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items() from itertools import accumulate,combinations,permutations#累積和 #list(accumulate(l)) from heapq import heapify,heappop,heappush #heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone #import fractions#古いatcoderコンテストの場合GCDなどはここからimportする from functools import reduce,lru_cache#pypyでもうごく #@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率 from decimal import Decimal def input(): x=sys.stdin.readline() return x[:-1] if x[-1]=="\n" else x def printe(*x):print("## ",*x,file=sys.stderr) def printl(li): _=print(*li, sep="\n") if li else None def argsort(s, return_sorted=False): inds=sorted(range(len(s)), key=lambda k: s[k]) if return_sorted: return inds, [s[i] for i in inds] return inds def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65 def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65) def matmat(A,B): K,N,M=len(B),len(A),len(B[0]) return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)] def matvec(M,v): N,size=len(v),len(M) return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)] def T(M): n,m=len(M),len(M[0]) return [[M[j][i] for j in range(n)] for i in range(m)] class multiset:#同じ要素を複数持てる def __init__(self,x=None):#最大値を取り出したいときはクラスの外でマイナスを処理する if x==None: self.counter=Counter() self.q=[] else: self.counter=Counter(x) self.q=list(x) heapify(self.q) def add(self,a): self.counter[a]+=1 heappush(self.q,a) def remove(self,a): if self.counter[a]: self.counter[a]-=1 return 1 else: return 0 def min(self): while not self.counter[self.q[0]]: heappop(self.q) return self.q[0] def pop(self): while self.q and self.counter[self.q[0]]==0: heappop(self.q) if self.q: self.counter[self.q[0]]-=1 return heappop(self.q) return None def __eq__(self,other): return other.counter==self.counter def __len__(self): return len(self.q) def main(): mod = 1000000007 #w.sort(key=itemgetter(1),reverse=True) #二個目の要素で降順並び替え N = int(input()) #N, K = map(int, input().split()) A = tuple(map(int, input().split())) #1行ベクトル #L = tuple(int(input()) for i in range(N)) #改行ベクトル #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列 ms=multiset(A) ma=max(A) for i in range(ma+1): t=max(i,ma-i) f=ms.remove(t) if not f: print("Impossible") return sles=math.ceil(ma*0.5)+1 while True: x=ms.pop() if x==None: break if x>=sles: continue else: print("Impossible") return print("Possible") if __name__ == "__main__": main() ```
instruction
0
59,569
13
119,138
Yes
output
1
59,569
13
119,139
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible Submitted Solution: ``` from collections import Counter def solve(A): m = min(A) cnt = Counter(A) if cnt[m] > 2: return False if cnt[m] == 2: d = m-1 else: d = m if max(A) > d+m: return False for i in range(1,d+1): if cnt[i+m] < 2: return False return True if __name__ == '__main__': N = int(input()) A = list(map(int,input().split())) print('Possible' if solve(A) else 'Impossible') ```
instruction
0
59,570
13
119,140
Yes
output
1
59,570
13
119,141
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible Submitted Solution: ``` import os import sys from collections import Counter if os.getenv("LOCAL"): sys.stdin = open("_in.txt", "r") sys.setrecursionlimit(2147483647) INF = float("inf") IINF = 10 ** 18 MOD = 10 ** 9 + 7 N = int(sys.stdin.readline()) A = list(map(int, sys.stdin.readline().split())) counts = Counter(A) ma = max(A) mi = min(A) ok = True if ma % 2 == 0: ok &= mi == ma // 2 ok &= counts[mi] == 1 else: ok &= mi == ma // 2 + 1 ok &= counts[mi] == 2 for d in range(ma, mi, -1): ok &= counts[d] >= 2 if ok: print('Possible') else: print('Impossible') ```
instruction
0
59,571
13
119,142
Yes
output
1
59,571
13
119,143
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible Submitted Solution: ``` from collections import Counter as C n=int(input()) a=sorted(C(list(map(int,input().split()))).items()) d=0 if a[-1][0]%2==0: d=1 q=1 for i in range(len(a)-1,-1,-1): if d: if a[i][0]==a[-1][0]//2 and a[i][1]!=1: q=0 break elif a[i][0]<a[-1][0]//2: q=0 break elif a[i][0]!=a[-1][0]+i-len(a)+1: q=0 break elif a[i][1]<2 and i!=0: q=0 break else: if a[i][0]<(a[-1][0]+1)//2: q=0 break elif a[i][0]!=a[-1][0]+i-len(a)+1: q=0 break elif a[i][0]==(a[-1][0]+1)//2 and a[i][1]!=2: q=0 break elif a[i][1]<2: q=0 break if q: print("Possible") else: print("Impossible") ```
instruction
0
59,572
13
119,144
Yes
output
1
59,572
13
119,145
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible Submitted Solution: ``` from collections import Counter n = int(input()) a = [int(x) for x in input().split()] c = Counter() for x in a: c[x] += 1 m = max(a) for i in range(m//2+1, m+1): if c[i] < 1: print("Impossible") exit() if m % 2 == 1 and c[m//2+1] != 2: print("Impossible") elif m % 2 == 0 and c[m//2] != 1: print("Impossible") else: print("Possible") ```
instruction
0
59,573
13
119,146
No
output
1
59,573
13
119,147
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible Submitted Solution: ``` import sys input = sys.stdin.readline N = int(input()) a = list(map(int, input().split())) a.sort() d = [[10 ** 6 for _ in range(N)] for _ in range(N)] #print(a) if N == 2: if a != [1, 1]: print("Impossible") exit(0) else: if max(a) < 2: print("Impossible") exit(0) mn = min(a) mnl = [] for i in range(N): if a[i] == mn: mnl.append(i) for i in range(len(mnl)): for j in range(len(mnl)): d[i][j] = 1 for x in range(min(a), max(a)): l = [] r = [] for i in range(N): if a[i] == x: l.append(i) for i in range(N): if a[i] == x + 1: r.append(i) if len(l) == 0: print("Impossible") exit(0) for i in range(len(r)): y = l[i % len(l)] z = r[i] d[y][z] = 1 d[z][y] = 1 for k in range(N): for i in range(N): for j in range(N): d[i][j] = min(d[i][k] + d[k][j], d[i][j]) #print(d) for i in range(N): if a[i] != max(d[i]): print("Impossible") exit(0) print("Possible") ```
instruction
0
59,574
13
119,148
No
output
1
59,574
13
119,149
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible Submitted Solution: ``` N = int(input()) a = list(map(int, input().split())) a.sort(reverse=True) yes = 'Possible' no = 'Impossible' if N == 2: if a[0] != 1 and a[1] != 1: print(no) exit() if a[-1] != (a[0] + 1) // 2: print(no) exit() else: if a[0] % 2 == 0: if a[-2] == a[-1]: print(no) exit() else: if a[-3] == a[-1]: print(no) exit() ok = [0] * N for i in range(N): ok[a[i]] += 1 for i in range(a[-1] + 1, a[0] + 1): if ok[i] < 2: print(no) exit() print(yes) ```
instruction
0
59,575
13
119,150
No
output
1
59,575
13
119,151
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible Submitted Solution: ``` from collections import Counter as C n=int(input()) a=sorted(C(list(map(int,input().split()))).items()) d=0 if a[-1][0]%2==0: d=1 q=1 for i in range(len(a)-1,-1,-1): if d: if a[i][0]==a[-1][0]//2: if a[i][1]!=1: q=0 break elif a[i][0]<a[-1][0]//2: q=0 break elif a[i][0]!=a[-1][0]+i-len(a)+1: q=0 break elif a[i][1]<2 and i!=0: q=0 break else: if a[i][0]<=a[-1][0]//2: q=0 break elif a[i][0]!=a[-1][0]+i-len(a)+1: q=0 break elif a[i][1]<2: q=0 break if q: print("Possible") else: print("Impossible") ```
instruction
0
59,576
13
119,152
No
output
1
59,576
13
119,153
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
instruction
0
59,780
13
119,560
Tags: constructive algorithms, graphs, greedy, sortings Correct Solution: ``` import sys input=sys.stdin.readline T = int(input()) ver = set() #pdb.set_trace() for _ in range(T): ver.clear() n, m = map(int, input().split()) n *= 3 edge = [] for __ in range(m): u, v = map(int, input().split()) if u not in ver and v not in ver: edge.append(__+1) ver.add(u) ver.add(v) if len(edge) == n//3: print("Matching") print(*edge[:n//3]) for x in range(__ + 1,m): input() break if len(edge) < n//3: asd = [] for x in range(1,n+1): if x not in ver: asd.append(x) if len(asd) == n//3: print("IndSet") print(*asd[:n//3]) break if len(asd) < n//3: print("Impossible") ```
output
1
59,780
13
119,561
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
instruction
0
59,781
13
119,562
Tags: constructive algorithms, graphs, greedy, sortings Correct Solution: ``` import sys input = sys.stdin.readline T = int(input()) for _ in range(T): n, m = map(int, input().split()) v = [True] * (3 * n + 1) e = [0] * n ptr = 0 for i in range(1, m + 1): a, b = map(int, input().split()) if ptr < n and v[a] and v[b]: e[ptr] = i ptr += 1 v[a] = False v[b] = False if ptr == n: print('Matching') print(*e) else: print('IndSet') cnt = 0 for i in range(1, n * 3 + 1): if v[i]: print(i, end=' ') cnt += 1 if cnt == n: print() break ```
output
1
59,781
13
119,563
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
instruction
0
59,782
13
119,564
Tags: constructive algorithms, graphs, greedy, sortings Correct Solution: ``` import sys input = sys.stdin.readline def main(): tes = int(input()) for testcase in [0]*tes: n,m = map(int,input().split()) new = [True]*(3*n) res = [] for i in range(1,m+1): u,v = map(int,input().split()) if new[u-1] and new[v-1]: if len(res) < n: res.append(i) new[u-1] = new[v-1] = False if len(res) >= n: print("Matching") print(*res) else: vs = [] for i in range(3*n): if new[i]: vs.append(i+1) if len(vs) >= n: break print("IndSet") print(*vs) if __name__ == '__main__': main() ```
output
1
59,782
13
119,565
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
instruction
0
59,783
13
119,566
Tags: constructive algorithms, graphs, greedy, sortings Correct Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(100000) def getN(): return int(input()) def getList(): return list(map(int, input().split())) import math def prmatch(ans): print("Matching") print(*ans) def solve(): n, m = getList() # print("===================") # print(n, m) # print("----------------------") vertexes = [[] for i in range(3*n)] used = [0 for i in range(3*n)] ans = [] lans = 0 for i in range(m): a,b = getList() # print(a, b) if used[a-1] == 0 and used[b-1] == 0: ans.append(i+1) lans += 1 if lans == n: prmatch(ans) for rem in range(m - i -1): _ = input() return used[a-1] = 1 used[b-1] = 1 indset = [] for i, u in enumerate(used): if u == 0: indset.append(i+1) print("IndSet") # print(ans) # print(used) print(*indset[:n]) return t = getN() for times in range(t): solve() """ 1 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 """ ```
output
1
59,783
13
119,567
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
instruction
0
59,784
13
119,568
Tags: constructive algorithms, graphs, greedy, sortings Correct Solution: ``` import sys input = sys.stdin.readline T = int(input()) for _ in range(T): n, m = map(int, input().split()) v = set(range(1, 3 * n + 1)) e = [] for i in range(1, m + 1): a, b = map(int, input().split()) if a in v and b in v: e.append(i) v.remove(a) v.remove(b) if len(e) >= n: print('Matching') print(*e[:n]) else: print('IndSet') print(*list(v)[:n]) ```
output
1
59,784
13
119,569
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
instruction
0
59,785
13
119,570
Tags: constructive algorithms, graphs, greedy, sortings Correct Solution: ``` import sys input = sys.stdin.readline T=int(input()) for testcases in range(T): n,m=map(int,input().split()) EDGE=[[0,0]]+[list(map(int,input().split())) for i in range(m)] USED=[0]*(3*n+1) count=0 ANS=[] for i in range(1,m+1): x,y=EDGE[i] if USED[x]==0 and USED[y]==0: count+=1 ANS.append(i) USED[x]=1 USED[y]=1 if count==n: print("Matching") print(*ANS) break else: ANS=[] count=0 for i in range(1,3*n+1): if USED[i]==0: count+=1 ANS.append(i) if count==n: print("IndSet") print(*ANS) break ```
output
1
59,785
13
119,571
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
instruction
0
59,786
13
119,572
Tags: constructive algorithms, graphs, greedy, sortings Correct Solution: ``` from sys import stdin input = stdin.readline T = int(input()) for _ in range(T): n, m = [int(i) for i in input().split()] ind_edg_v = [True]*(3*n+1) ind_edg_e = [0]*n num_edg = 0 for j in range(m): edge_0, edge_1 = [int(i) for i in input().split()] if num_edg < n: if ind_edg_v[edge_0] and ind_edg_v[edge_1]: ind_edg_e[num_edg] = j+1 ind_edg_v[edge_0], ind_edg_v[edge_1] = False, False num_edg += 1 if num_edg == n: print("Matching") print(' '.join([str(i) for i in ind_edg_e])) else: print("IndSet") vertex = 0 for i in range(n): vertex += 1 while not ind_edg_v[vertex]: vertex += 1 print(vertex, end = ' ') print() ```
output
1
59,786
13
119,573
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
instruction
0
59,787
13
119,574
Tags: constructive algorithms, graphs, greedy, sortings Correct Solution: ``` import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline t = int(input()) for _ in range(t): n, m = map(int, input().split()) edge = [] for i in range(m): u, v = map(int, input().split()) u, v = u-1, v-1 edge.append((u, v)) used = set() M = set() for i, (u, v) in enumerate(edge): if u not in used and v not in used: M.add(i+1) used.add(u) used.add(v) if len(M) >= n: M = list(M) M = M[0:n] print('Matching') print(*M) continue S = [] for i in range(3*n): if i not in used: S.append(i+1) if len(S) == n: break if len(S) == n: print('IndSet') print(*S) continue print('Impossible') ```
output
1
59,787
13
119,575
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2. Submitted Solution: ``` from sys import stdin, stdout T = int(stdin.readline()) ver = set() #pdb.set_trace() for _ in range(T): ver.clear() n, m = map(int, stdin.readline().split()) n *= 3 edge = [] for __ in range(m): u, v = map(int, stdin.readline().split()) if u not in ver and v not in ver: edge.append(__+1) ver.add(u) ver.add(v) if len(edge) == n//3: print("Matching") print(*edge[:n//3]) for x in range(__ + 1,m): stdin.readline() break if len(edge) < n//3: asd = [] for x in range(1,n+1): if x not in ver: asd.append(x) if len(asd) == n//3: print("IndSet") print(*asd[:n//3]) break if len(asd) < n//3: stdout.write("Impossible\n") ```
instruction
0
59,788
13
119,576
Yes
output
1
59,788
13
119,577
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2. Submitted Solution: ``` ''' cho n và m: có 3*n đỉnh và m mối quan hệ giữa các đỉnh kết hợp: tập hợp các cạnh không có chung điểm cuối độc lập: tập hợp các điểm mà không có bất kì điểm nào nằm trong chung trong một cạnh output: in ra nếu có tập có độ lớn n thỏa kết hợp hoặc độc lập nếu có hai kết quả in ra bất kì kết quả nào cũng được. ''' from sys import stdin input=stdin.readline t=int(input()) for k in range(t): n,m=map(int,input().split(' ')) a=[i for i in range(1,n+1)] qq=set(range(1,3*n+1)) e=[] for i in range(1,m+1): a1,a2=map(int,input().split(' ')) if a1 in qq and a2 in qq: e.append(i) qq.remove(a1) qq.remove(a2) if(len(qq)>=n): print('IndSet') print(*list(qq)[:n]) else: print('Matching') print(*e[:n]) ```
instruction
0
59,789
13
119,578
Yes
output
1
59,789
13
119,579
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2. Submitted Solution: ``` import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def main(): t = int(input()) from collections import deque import copy for _ in range(t): n, m = map(int, input().split()) toid = {} g = [[] for i in range(3*n)] ind = [0]*(3*n) for i in range(m): u, v = map(int, input().split()) u, v = u-1, v-1 g[u].append(v) g[v].append(u) ind[v] += 1 ind[u] += 1 toid[(u, v)] = i toid[(v, u)] = i q = deque([]) visit = [False]*(3*n) m = min(ind) for i in range(3*n): if ind[i] == m: q.append(i) visit[i] = True S = set() ban = set() while q: v = q.popleft() if v not in ban: S.add(v) for u in g[v]: ban.add(u) for u in g[v]: if not visit[u]: q.append(u) visit[u] = True #print(S) if len(S) >= n: S = list(S) S = S[0:n] S = [i+1 for i in S] print('IndSet') print(*S) continue q = deque([]) visit = [False]*(3*n) m = min(ind) for i in range(3*n): if ind[i] == m: q.append(i) visit[i] = True #print(q) M = set() ban = set() while q: v = q.popleft() for u in g[v]: j = toid[(u, v)] if u not in ban and v not in ban: M.add(j) ban.add(u) ban.add(v) if not visit[u]: q.append(u) visit[u] = True #print(M) if len(M) >= n: M = list(M) M = M[0:n] M = [i+1 for i in M] print('Matching') print(*M) continue print('Impossible') if __name__ == '__main__': main() ```
instruction
0
59,790
13
119,580
No
output
1
59,790
13
119,581
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2. Submitted Solution: ``` from sys import stdin input = stdin.readline T = int(input()) for _ in range(T): n, m = [int(i) for i in input().split()] ind_edg_v = [True]*(3*n+1) ind_edg_e = [0]*n num_edg = 0 for j in range(m): edge_0, edge_1 = [int(i) for i in input().split()] if num_edg < n: if ind_edg_v[edge_0] and ind_edg_v[edge_1]: ind_edg_e[num_edg] = j+1 ind_edg_v[edge_0], ind_edg_v[edge_1] = False, False num_edg += 1 if num_edg == n: print("Matching") print(' '.join([str(i) for i in ind_edg_e])) else: print("IndSet") vertex = 1 for i in range(n): while not ind_edg_v[vertex]: vertex += 1 print(vertex, end = ' ') print() ```
instruction
0
59,791
13
119,582
No
output
1
59,791
13
119,583
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2. Submitted Solution: ``` import math import pdb T = int(input()) ver = [] #pdb.set_trace() for _ in range(T): ver.clear() n, m = map(int, input().strip().split()) n *= 3 edge = [] for __ in range(m): u, v = map(int, input().strip().split()) if u not in ver and v not in ver: edge.append(__+1) ver.append(u) ver.append(v) if len(edge) == n//3: print("Matching") for x in edge: print(x, end = " ") for x in range(__ + 1,m): u, v = map(int, input().strip().split()) break if len(edge) < n//3: asd = [] for x in range(1,n+1): if x not in ver: asd.append(x+1) if len(asd) == n//3: print("IndSet") for x in asd: print(x, end = " ") break if len(asd) < n//3: print("Impossible") ```
instruction
0
59,792
13
119,584
No
output
1
59,792
13
119,585
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2. Submitted Solution: ``` import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def main(): t = int(input()) from collections import deque import copy for _ in range(t): n, m = map(int, input().split()) toid = {} g = [[] for i in range(3*n)] ind = [0]*(3*n) for i in range(m): u, v = map(int, input().split()) u, v = u-1, v-1 g[u].append(v) g[v].append(u) ind[v] += 1 ind[u] += 1 toid[(u, v)] = i toid[(v, u)] = i q = deque([]) visit = [False]*(3*n) m = min(ind) for i in range(3*n): if ind[i] == m: q.append(i) visit[i] = True S = set() ban = set() while q: v = q.popleft() if v not in ban: S.add(v) for u in g[v]: ban.add(u) for u in g[v]: if not visit[u]: q.append(u) visit[u] = True #print(S) if len(S) >= n: S = list(S) S = S[0:n] S = [i+1 for i in S] print('IndSet') print(*S) continue q = deque([]) visit = [False]*(3*n) m = max(ind) for i in range(3*n): if ind[i] == m: q.append(i) visit[i] = True #print(q) M = set() ban = set() while q: v = q.popleft() for u in g[v]: j = toid[(u, v)] if u not in ban and v not in ban: M.add(j) ban.add(u) ban.add(v) if not visit[u]: q.append(u) visit[u] = True #print(M) if len(M) >= n: M = list(M) M = M[0:n] M = [i+1 for i in M] print('Matching') print(*M) continue print('Impossible') if __name__ == '__main__': main() ```
instruction
0
59,793
13
119,586
No
output
1
59,793
13
119,587
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dima and Inna love spending time together. The problem is, Seryozha isn't too enthusiastic to leave his room for some reason. But Dima and Inna love each other so much that they decided to get criminal... Dima constructed a trap graph. He shouted: "Hey Seryozha, have a look at my cool graph!" to get his roommate interested and kicked him into the first node. A trap graph is an undirected graph consisting of n nodes and m edges. For edge number k, Dima denoted a range of integers from lk to rk (lk ≤ rk). In order to get out of the trap graph, Seryozha initially (before starting his movements) should pick some integer (let's call it x), then Seryozha must go some way from the starting node with number 1 to the final node with number n. At that, Seryozha can go along edge k only if lk ≤ x ≤ rk. Seryozha is a mathematician. He defined the loyalty of some path from the 1-st node to the n-th one as the number of integers x, such that if he initially chooses one of them, he passes the whole path. Help Seryozha find the path of maximum loyalty and return to his room as quickly as possible! Input The first line of the input contains two integers n and m (2 ≤ n ≤ 103, 0 ≤ m ≤ 3·103). Then follow m lines describing the edges. Each line contains four integers ak, bk, lk and rk (1 ≤ ak, bk ≤ n, 1 ≤ lk ≤ rk ≤ 106). The numbers mean that in the trap graph the k-th edge connects nodes ak and bk, this edge corresponds to the range of integers from lk to rk. Note that the given graph can have loops and multiple edges. Output In a single line of the output print an integer — the maximum loyalty among all paths from the first node to the n-th one. If such paths do not exist or the maximum loyalty equals 0, print in a single line "Nice work, Dima!" without the quotes. Examples Input 4 4 1 2 1 10 2 4 3 5 1 3 1 5 2 4 2 7 Output 6 Input 5 6 1 2 1 10 2 5 11 20 1 4 2 5 1 3 10 11 3 4 12 10000 4 5 6 6 Output Nice work, Dima! Note Explanation of the first example. Overall, we have 2 ways to get from node 1 to node 4: first you must go along the edge 1-2 with range [1-10], then along one of the two edges 2-4. One of them contains range [3-5], that is, we can pass through with numbers 3, 4, 5. So the loyalty of such path is 3. If we go along edge 2-4 with range [2-7], then we can pass through with numbers 2, 3, 4, 5, 6, 7. The loyalty is 6. That is the answer. The edge 1-2 have no influence on the answer because its range includes both ranges of the following edges. Submitted Solution: ``` from sys import stdin, stdout, stderr, exit from math import log, factorial import re from queue import PriorityQueue import functools from time import time # inputf = open('input.txt', 'r') # outputf = open('output.txt', 'w') def readil(): return list(map(int, stdin.readline().strip().split())) class time_it(object): ''' Simple decorator, that prints func execution time to stderr ''' def __init__(self, func): self.func = func def __call__(self): st = time() self.func() stderr.write('%s: %f' % (self.func.__name__, time() - st)) n = 0 m = 0 g = list() @functools.lru_cache(1024) def getl(t: tuple): try: return max(0, t[1] - t[0] + 1) except Exception as _: print(t, file=stderr) raise Exception('wtf') @functools.lru_cache(0) def comb(t1, t2): if(t1 == (0, 0)): return t2 if(t2 == (0, 0)): return t1 try: if(max(t1[0], t2[0]) > min(t1[1], t2[1])): return (0, 0) return (max(t1[0], t2[0]), min(t1[1], t2[1])) except Exception as _: print(t1, t2, file=stderr) raise Exception('wtf') @time_it def main(): global n n, m = readil() g = [list() for i in range(n)] for _ in range(m): a, b, l, r = readil() if(a == b): continue a -= 1 b -= 1 g[a].append((b, l, r)) g[b].append((a, l, r)) q = PriorityQueue(maxsize=2 * n) d = list((0, 0) for i in range(n)) q.put_nowait((1, 0)) while not q.empty(): dist, v = q.get_nowait() if(getl(d[v]) > dist): continue # stderr.write('vertex: \t' + str(v) + '\n') for tpl in g[v]: u, l, r = tpl if(getl(comb(d[v], (l, r))) > getl(d[u])): d[u] = comb((l, r), d[v]) q.put_nowait((getl(d[u]), u)) if(getl(d[n - 1]) == 0): stdout.write('Nice work, Dima!') else: stdout.write(str(getl(d[n - 1]))) if __name__ == '__main__': main() # inputf.close() # outputf.close() ```
instruction
0
60,103
13
120,206
No
output
1
60,103
13
120,207
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dima and Inna love spending time together. The problem is, Seryozha isn't too enthusiastic to leave his room for some reason. But Dima and Inna love each other so much that they decided to get criminal... Dima constructed a trap graph. He shouted: "Hey Seryozha, have a look at my cool graph!" to get his roommate interested and kicked him into the first node. A trap graph is an undirected graph consisting of n nodes and m edges. For edge number k, Dima denoted a range of integers from lk to rk (lk ≤ rk). In order to get out of the trap graph, Seryozha initially (before starting his movements) should pick some integer (let's call it x), then Seryozha must go some way from the starting node with number 1 to the final node with number n. At that, Seryozha can go along edge k only if lk ≤ x ≤ rk. Seryozha is a mathematician. He defined the loyalty of some path from the 1-st node to the n-th one as the number of integers x, such that if he initially chooses one of them, he passes the whole path. Help Seryozha find the path of maximum loyalty and return to his room as quickly as possible! Input The first line of the input contains two integers n and m (2 ≤ n ≤ 103, 0 ≤ m ≤ 3·103). Then follow m lines describing the edges. Each line contains four integers ak, bk, lk and rk (1 ≤ ak, bk ≤ n, 1 ≤ lk ≤ rk ≤ 106). The numbers mean that in the trap graph the k-th edge connects nodes ak and bk, this edge corresponds to the range of integers from lk to rk. Note that the given graph can have loops and multiple edges. Output In a single line of the output print an integer — the maximum loyalty among all paths from the first node to the n-th one. If such paths do not exist or the maximum loyalty equals 0, print in a single line "Nice work, Dima!" without the quotes. Examples Input 4 4 1 2 1 10 2 4 3 5 1 3 1 5 2 4 2 7 Output 6 Input 5 6 1 2 1 10 2 5 11 20 1 4 2 5 1 3 10 11 3 4 12 10000 4 5 6 6 Output Nice work, Dima! Note Explanation of the first example. Overall, we have 2 ways to get from node 1 to node 4: first you must go along the edge 1-2 with range [1-10], then along one of the two edges 2-4. One of them contains range [3-5], that is, we can pass through with numbers 3, 4, 5. So the loyalty of such path is 3. If we go along edge 2-4 with range [2-7], then we can pass through with numbers 2, 3, 4, 5, 6, 7. The loyalty is 6. That is the answer. The edge 1-2 have no influence on the answer because its range includes both ranges of the following edges. Submitted Solution: ``` from sys import stdin, stdout, stderr, exit from math import log, factorial import re from queue import PriorityQueue import functools from time import time # inputf = open('input.txt', 'r') # outputf = open('output.txt', 'w') def readil(): return list(map(int, stdin.readline().strip().split())) class time_it(object): ''' Simple decorator, that prints func execution time to stderr ''' def __init__(self, func): self.func = func def __call__(self): st = time() self.func() stderr.write('%s: %f\n' % (self.func.__name__, time() - st)) n = 0 m = 0 g = list() @functools.lru_cache(0) def getl(t: tuple): try: return max(0, t[1] - t[0] + 1) except Exception as _: print(t, file=stderr) raise Exception('wtf') @functools.lru_cache(0) def comb(t1, t2): if(t1 == (1, 0)): return t2 if(t2 == (1, 0)): return t1 try: if(max(t1[0], t2[0]) > min(t1[1], t2[1])): return (1, 0) return (max(t1[0], t2[0]), min(t1[1], t2[1])) except Exception as _: print(t1, t2, file=stderr) raise Exception('wtf') @time_it def main(): global n n, m = readil() g = [list() for i in range(n)] for _ in range(m): a, b, l, r = readil() if(a == b): continue a -= 1 b -= 1 g[a].append((b, l, r)) g[b].append((a, l, r)) q = PriorityQueue() d = list((1, 0) for i in range(n)) q.put_nowait((1, 0)) while not q.empty(): dist, v = q.get_nowait() if(getl(d[v]) > dist): continue # stderr.write('vertex: \t' + str(v) + '\n') for tpl in g[v]: u, l, r = tpl if(getl(comb(d[v], (l, r))) > getl(d[u])): d[u] = comb((l, r), d[v]) q.put_nowait((getl(d[u]), u)) if(getl(d[n - 1]) == 0): stdout.write('Nice work, Dima!') else: stdout.write(str(getl(d[n - 1]))) if __name__ == '__main__': main() # inputf.close() # outputf.close() ```
instruction
0
60,104
13
120,208
No
output
1
60,104
13
120,209
Provide tags and a correct Python 3 solution for this coding contest problem. Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive. Input The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops. Output In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero. Examples Input 3 2 1 2 2 3 Output YES 1 1 3
instruction
0
60,373
13
120,746
Tags: dfs and similar, dsu, graphs Correct Solution: ``` __author__ = 'Darren' class DisjointSet: def __init__(self, n): self.array = [-1] * n def union(self, x, y): rx, ry = self.find(x), self.find(y) if rx == ry: # in the same set already return False # Merge by rank if self.array[rx] < self.array[ry]: self.array[ry] = rx elif self.array[rx] > self.array[ry]: self.array[rx] = ry else: self.array[ry] = rx self.array[rx] -= 1 return True def find(self, x): if self.array[x] < 0: # x is the only element in the set including it return x self.array[x] = self.find(self.array[x]) # Path compression return self.array[x] def solve(): n, m = map(int, input().split()) degree = [0] * (n + 1) disjoint_set = DisjointSet(n+1) cycles = 0 for _i in range(m): u, v = map(int, input().split()) degree[u] += 1 degree[v] += 1 if degree[u] > 2 or degree[v] > 2: print('NO') return if not disjoint_set.union(u, v): cycles += 1 if cycles > 1: # Cannot have more than one cycle print('NO') return if cycles == 1: if m == n: # Already an interesting graph print('YES\n0') else: print('NO') return print('YES') print(n - m) if n == 1: # Add a loop will do it print(1, 1) return # Add edges in lexicographical order for u in range(1, n): if degree[u] == 2: # Cannot add new edges to u continue for v in range(u+1, n+1): if degree[v] == 2: # Cannot add new edges to v continue if disjoint_set.find(u) != disjoint_set.find(v): # u and v are disjointed disjoint_set.union(u, v) print(u, v) degree[u] += 1 degree[v] += 1 if degree[u] == 2: break # All vertices are connected. Now add an new edge connecting the only # two vertices with degree 1 to form an interesting graph for u in range(1, n): if degree[u] == 2: continue for v in range(u+1, n+1): if degree[v] == 2: continue print(u, v) if __name__ == '__main__': solve() ```
output
1
60,373
13
120,747
Provide tags and a correct Python 3 solution for this coding contest problem. Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive. Input The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops. Output In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero. Examples Input 3 2 1 2 2 3 Output YES 1 1 3
instruction
0
60,374
13
120,748
Tags: dfs and similar, dsu, graphs Correct Solution: ``` def dfs(v, graph): isloop = False lo, ro = graph # expand right pr, r = lo, ro expand_right = [] while True: if len(v[r]) == 1: break else: nr1, nr2 = v[r] rn = nr1 if nr1 != pr else nr2 expand_right.append(rn) if rn == lo: # we found loop isloop = True break pr = r r = rn if isloop: return True, graph + expand_right # expand left l, pl = lo, ro expand_left = [] while True: if len(v[l]) == 1: break else: nl1, nl2 = v[l] nl = nl1 if nl1 != pl else nl2 expand_left.append(nl) pl = l l = nl final_graph = expand_left[::-1] + graph + expand_right # if final_graph[0] > final_graph[-1]: # final_graph = final_graph[::-1] return False, final_graph def findMinvalInLineEnds(lines): minval, minval_idx = 0xFFFF, None secval, secval_idx = 0xFFFF, None for i in range(len(lines)): if lines[i][0] < minval: secval = minval secval_idx = minval_idx minval = lines[i][0] minval_idx = i elif lines[i][0] < secval: secval = lines[i][0] secval_idx = i return minval, minval_idx, secval, secval_idx def greedyConnect(lines, points): edges = [] points.sort() if len(points) == 1 and len(lines) == 0: edges.append((points[0],points[0])) return edges while True: if len(lines) == 1 and len(points) == 0: edges.append((lines[0][0], lines[0][-1])) break minval_p = points[0] if len(points) > 0 else 0xFFFF secval_p = points[1] if len(points) > 1 else 0xFFFF minval_l, minval_idx_l, secval_l, secval_idx_l = findMinvalInLineEnds(lines) if minval_p < minval_l: if secval_p < minval_l: # connect 2 points to make a line edges.append((minval_p, secval_p)) points = points[2:] lines.append([minval_p, secval_p]) else: # connect point to the line edges.append((minval_p, minval_l)) li = minval_idx_l lines[li] = [minval_p, lines[li][-1]] points = points[1:] else: # if minval is one end of line, we merge that line with a point or a line if minval_p < secval_l: edges.append((minval_l, minval_p)) li = minval_idx_l lines[li][0] = minval_p if lines[li][0] > lines[li][-1]: lines[li] = [lines[li][-1], lines[li][0]] points = points[1:] else: edges.append((minval_l, secval_l)) mil, sil = minval_idx_l, secval_idx_l lines[mil][0] = lines[sil][-1] if lines[mil][0] > lines[mil][-1]: lines[mil] = [lines[mil][-1], lines[mil][0]] del lines[sil] return edges if __name__ == '__main__': n,m = tuple(map(int, input().split())) v = [[] for i in range(n)] for i in range(m): v1,v2 = tuple(map(int, input().split())) v1,v2 = v1-1,v2-1 v[v1].append(v2) v[v2].append(v1) # validate input input_valid = True for i in range(n): if len(v[i]) > 2: input_valid = False break v[i].sort() if not input_valid: print('NO') exit() loops = [] lines = [] points = [] visited = [False for i in range(n)] for i in range(n): if visited[i]: continue elif len(v[i]) == 0: points.append(i) visited[i] = True elif len(v[i]) == 1 and v[i] == i: loops.append([i,i]) visited[i] = True else: isloop, graph = dfs(v,[i,v[i][0]]) for gi in graph: visited[gi] = True if isloop: loops.append(graph) else: lines.append(graph) if len(loops) > 0: if len(loops) == 1 and len(points) == 0 and len(lines) == 0: print('YES') print(0) exit() else: print('NO') exit() # print('loops') # for p in loops: # print('\t{}'.format([e+1 for e in p])) # print('lines') # for p in lines: # print('\t{}'.format([e+1 for e in p])) # print('points') # for p in points: # print('\t{}'.format(p+1)) # We only need two ends of the line for li in range(len(lines)): e1,e2 = lines[li][0], lines[li][-1] lines[li] = [e1,e2] if e1<e2 else [e2,e1] edges = greedyConnect(lines, points) print('YES') print(len(edges)) for v1,v2 in edges: v1 += 1 v2 += 1 if v1 < v2: print('{} {}'.format(v1,v2)) else: print('{} {}'.format(v2,v1)) ```
output
1
60,374
13
120,749
Provide tags and a correct Python 3 solution for this coding contest problem. Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive. Input The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops. Output In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero. Examples Input 3 2 1 2 2 3 Output YES 1 1 3
instruction
0
60,375
13
120,750
Tags: dfs and similar, dsu, graphs Correct Solution: ``` n, m = map(int, input().split()) g = [[] for i in range(n)] for i in range(m): u, v = map(int, input().split()) u -= 1 v -= 1 g[u].append(v) g[v].append(u) if any(len(g[v]) > 2 for v in range(n)): print('NO') exit() used = [False] * n end = [0] * n for v in range(n): if len(g[v]) == 0: used[v] = True end[v] = v if len(g[v]) == 1 and not used[v]: used[v] = True p = v u = g[v][0] while len(g[u]) == 2: used[u] = True p, u = u, sum(g[u]) - p used[u] = True end[v] = u end[u] = v if not any(used): used[0] = True p = 0 u = g[0][0] while u != 0: used[u] = True p, u = u, sum(g[u]) - p if all(used): print('YES') print(0) exit() if not all(used): print('NO') exit() print('YES') comps = len([v for v in range(n) if len(g[v]) == 1]) // 2 + len([v for v in range(n) if len(g[v]) == 0]) print(comps) if n == 1: print('1 1') exit() while comps > 1: comps -= 1 v = min(x for x in range(n) if len(g[x]) < 2) u = min(x for x in range(n) if len(g[x]) < 2 and x not in (v, end[v])) print(v + 1, u + 1) g[u].append(v) g[v].append(u) end[end[v]] = end[u] end[end[u]] = end[v] v = min(x for x in range(n) if len(g[x]) < 2) u = min(x for x in range(n) if len(g[x]) < 2 and x != v) print(v + 1, u + 1) ```
output
1
60,375
13
120,751
Provide tags and a correct Python 3 solution for this coding contest problem. Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive. Input The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops. Output In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero. Examples Input 3 2 1 2 2 3 Output YES 1 1 3
instruction
0
60,376
13
120,752
Tags: dfs and similar, dsu, graphs Correct Solution: ``` def dfs(v, comp): used[v] = comp for u in graph[v]: if not used[u]: dfs(u, comp) n, m = map(int, input().split()) graph = [[] for i in range(n)] for i in range(m): v, u = map(int, input().split()) graph[v - 1].append(u - 1) graph[u - 1].append(v - 1) used = [0] * n ncomp = 0 for v in range(n): if not used[v]: ncomp += 1 dfs(v, ncomp) maxpwr = max(map(len, graph)) if n - m != ncomp or maxpwr > 2: if n == m and ncomp == 1 and maxpwr == 2: print("YES") print(0) else: print("NO") else: print("YES") print(n - m) leaves = [] for v in range(n): if len(graph[v]) == 1: leaves.append([v + 1, used[v]]) elif len(graph[v]) == 0: leaves.append([v + 1, used[v]]) leaves.append([v + 1, used[v]]) sets = [] for i in range(len(leaves)): if leaves[i][0] == 0: continue for j in range(i + 1, len(leaves)): if leaves[j][0] == 0: continue if leaves[i][1] == leaves[j][1]: continue seti = -1 for k in range(len(sets)): if leaves[i][1] in sets[k]: seti = k break setj = -2 for k in range(len(sets)): if leaves[j][1] in sets[k]: setj = k break if seti != setj: print(leaves[i][0], leaves[j][0]) if seti >= 0: if setj >= 0: sets[seti] |= sets[setj] sets.pop(setj) else: sets[seti].add(leaves[j][1]) else: if setj >= 0: sets[setj].add(leaves[i][1]) else: sets.append(set([leaves[i][1], leaves[j][1]])) leaves[i][0] = 0 leaves[j][0] = 0 break for i in range(len(leaves)): if leaves[i][0] == 0: continue for j in range(i + 1, len(leaves)): if leaves[j][0] == 0: continue print(leaves[i][0], leaves[j][0]) break else: continue break ```
output
1
60,376
13
120,753
Provide tags and a correct Python 3 solution for this coding contest problem. Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive. Input The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops. Output In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero. Examples Input 3 2 1 2 2 3 Output YES 1 1 3
instruction
0
60,377
13
120,754
Tags: dfs and similar, dsu, graphs Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def NO(): print('NO') exit() def YES(edges): edges.sort() print('YES') print(len(edges)) for e in edges: print(e[0] + 1, e[1] + 1) exit() n, m = map(int, input().split()) adj = [[] for _ in range(n)] deg = [0] * n for u, v in (map(int, input().split()) for _ in range(m)): adj[u - 1].append(v - 1) adj[v - 1].append(u - 1) deg[u - 1] += 1 deg[v - 1] += 1 if max(deg) > 2 or n < m: NO() if n == 1: YES([] if m == 1 else [(0, 0)]) if min(deg) == 2: v, used = 0, [1] + [0] * (n - 1) while True: for dest in adj[v]: if not used[dest]: used[dest] = 1 v = dest break else: break if all(used): YES([]) else: NO() group = [0] * n gi = 1 for i in range(n): if group[i]: continue group[i] = gi stack = [i] while stack: v = stack.pop() for dest in adj[v]: if group[dest] == 0: group[dest] = gi stack.append(dest) gi += 1 ans = [] for i in range(n): if deg[i] == 2: continue for j in range(i + 1, n): if group[i] != group[j] and deg[j] < 2: ans.append((i, j)) deg[i], deg[j] = deg[i] + 1, deg[j] + 1 for k in (k for itr in (range(j), range(j + 1, n), range(j, j + 1)) for k in itr): if group[k] == group[j]: group[k] = group[i] if deg[i] == 2: break if not (deg.count(1) + deg.count(2) == n and deg.count(1) in (0, 2)): NO() if deg.count(1) == 2: i = deg.index(1) j = deg.index(1, i + 1) ans.append((i, j)) YES(ans) ```
output
1
60,377
13
120,755
Provide tags and a correct Python 3 solution for this coding contest problem. Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive. Input The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops. Output In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero. Examples Input 3 2 1 2 2 3 Output YES 1 1 3
instruction
0
60,378
13
120,756
Tags: dfs and similar, dsu, graphs Correct Solution: ``` class DisjointSet: def __init__(self, n): self.array = [-1] * n def union(self, x, y): rx, ry = self.find(x), self.find(y) if rx == ry: return False if self.array[rx] < self.array[ry]: self.array[ry] = rx elif self.array[rx] > self.array[ry]: self.array[rx] = ry else: self.array[ry] = rx self.array[rx] -= 1 return True def find(self, x): if self.array[x] < 0: return x self.array[x] = self.find(self.array[x]) return self.array[x] def solve(): n, m = map(int, input().split()) degree = [0] * (n + 1) disjoint_set = DisjointSet(n + 1) cycles = 0 for _i in range(m): u, v = map(int, input().split()) degree[u] += 1 degree[v] += 1 if degree[u] > 2 or degree[v] > 2: print('NO') return if not disjoint_set.union(u, v): cycles += 1 if cycles > 1: print('NO') return if cycles == 1: if m == n: print('YES\n0') else: print('NO') return print('YES') print(n - m) if n == 1: print(1, 1) return for u in range(1, n): if degree[u] == 2: continue for v in range(u + 1, n + 1): if degree[v] == 2: continue if disjoint_set.find(u) != disjoint_set.find(v): disjoint_set.union(u, v) print(u, v) degree[u] += 1 degree[v] += 1 if degree[u] == 2: break for u in range(1, n): if degree[u] == 2: continue for v in range(u + 1, n + 1): if degree[v] == 2: continue print(u, v) solve() ```
output
1
60,378
13
120,757
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive. Input The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops. Output In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero. Examples Input 3 2 1 2 2 3 Output YES 1 1 3 Submitted Solution: ``` def dfs(v, graph): isloop = False lo, ro = graph # expand right pr, r = lo, ro expand_right = [] while True: if len(v[r]) == 1: break else: nr1, nr2 = v[r] rn = nr1 if nr1 != pr else nr2 expand_right.append(rn) if rn == lo: # we found loop isloop = True break pr = r r = rn if isloop: return True, graph + expand_right # expand left l, pl = lo, ro expand_left = [] while True: if len(v[l]) == 1: break else: nl1, nl2 = v[l] nl = nl1 if nl1 != pl else nl2 expand_left.append(nl) pl = l l = nl final_graph = expand_left[::-1] + graph + expand_right # if final_graph[0] > final_graph[-1]: # final_graph = final_graph[::-1] return False, final_graph def findMinvalInLineEnds(lines): minval, minval_idx = 0xFFFF, None secval, secval_idx = 0xFFFF, None for i in range(len(lines)): if lines[i][0] < minval: minval = lines[i][0] minval_idx = i elif lines[i][0] < secval: secval = lines[i][0] secval_idx = i return minval, minval_idx, secval, secval_idx def greedyConnect(lines, points): edges = [] points.sort() if len(points) == 1 and len(lines) == 0: edges.append((points[0],points[0])) return edges while True: if len(lines) == 1: edges.append((lines[0][0], lines[0][-1])) break minval_p = points[0] if len(points) > 0 else 0xFFFF secval_p = points[1] if len(points) > 1 else 0xFFFF minval_l, minval_idx_l, secval_l, secval_idx_l = findMinvalInLineEnds(lines) if minval_p < minval_l: if secval_p < minval_l: # connect 2 points to make a line edges.append((minval_p, secval_p)) points = points[2:] lines.append([minval_p, secval_p]) else: # connect point to the line edges.append((minval_p, minval_l)) li = minval_idx_l lines[li] = [minval_p, lines[li][-1]] else: # if minval is one end of line, we merge that line with a point or a line if minval_p < secval_l: edges.append((minval_l, minval_p)) li = minval_idx_l lines[li][0] = minval_p if lines[li][0] > lines[li][-1]: lines[li] = [lines[li][-1], lines[li][0]] points = points[1:] else: edges.append((minval_l, secval_l)) mil, sil = minval_idx_l, secval_idx_l lines[mil][0] = lines[sil][-1] if lines[mil][0] > lines[mil][-1]: lines[mil] = [lines[mil][-1], lines[mil][0]] del lines[sil] return edges if __name__ == '__main__': n,m = tuple(map(int, input().split())) v = [[] for i in range(n)] for i in range(m): v1,v2 = tuple(map(int, input().split())) v1,v2 = v1-1,v2-1 v[v1].append(v2) v[v2].append(v1) # validate input input_valid = True for i in range(n): if len(v[i]) > 2: input_valid = False break v[i].sort() if not input_valid: print('NO') exit() loops = [] lines = [] points = [] visited = [False for i in range(n)] for i in range(n): if visited[i]: continue elif len(v[i]) == 0: points.append(i) visited[i] = True elif len(v[i]) == 1 and v[i] == i: loops.append([i,i]) visited[i] = True else: isloop, graph = dfs(v,[i,v[i][0]]) for gi in graph: visited[gi] = True if isloop: loops.append(graph) else: lines.append(graph) if len(loops) > 0: if len(loops) == 1 and len(points) == 0 and len(lines) == 0: print('YES') print(0) exit() else: print('NO') exit() # print('loops') # for p in loops: # print('\t{}'.format([e+1 for e in p])) # print('lines') # for p in lines: # print('\t{}'.format([e+1 for e in p])) # print('points') # for p in points: # print('\t{}'.format(p+1)) # We only need two ends of the line for li in range(len(lines)): e1,e2 = lines[li][0], lines[li][-1] lines[li] = [e1,e2] if e1<e2 else [e2,e1] edges = greedyConnect(lines, points) print('YES') print(len(edges)) for v1,v2 in edges: v1 += 1 v2 += 1 if v1 < v2: print('{} {}'.format(v1,v2)) else: print('{} {}'.format(v2,v1)) ```
instruction
0
60,379
13
120,758
No
output
1
60,379
13
120,759
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive. Input The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops. Output In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero. Examples Input 3 2 1 2 2 3 Output YES 1 1 3 Submitted Solution: ``` def dfs(v, comp): used[v] = comp for u in graph[v]: if not used[u]: dfs(u, comp) n, m = map(int, input().split()) graph = [[] for i in range(n)] for i in range(m): v, u = map(int, input().split()) graph[v - 1].append(u - 1) graph[u - 1].append(v - 1) used = [0] * n ncomp = 0 for v in range(n): if not used[v]: ncomp += 1 dfs(v, ncomp) maxpwr = max(map(len, graph)) minpwr = min(map(len, graph)) if n - m != ncomp or maxpwr > 2: if n == m and ncomp == 1 and maxpwr == 2: print("YES") print(0) else: print("NO") else: print("YES") print(n - m) leaves = [] for v in range(n): if len(graph[v]) == 1: leaves.append([v + 1, used[v]]) elif len(graph[v]) == 0: leaves.append([v + 1, used[v]]) leaves.append([v + 1, used[v]]) sets = [] for i in range(len(leaves)): if leaves[i][0] == 0: continue for j in range(i + 1, len(leaves)): if leaves[j][0] == 0: continue if leaves[i][1] == leaves[j][1]: continue seti = -1 for k in range(len(sets)): if leaves[i][1] in sets[k]: seti = k break setj = -2 for k in range(len(sets)): if leaves[j][1] in sets[k]: setj = k break if seti != setj: print(leaves[i][0], leaves[j][0]) if seti >= 0: if setj >= 0: sets[seti] |= sets[setj] else: sets[seti].add(leaves[j][1]) else: if setj >= 0: sets[setj].add(leaves[i][1]) else: sets.append(set([leaves[i][1], leaves[j][1]])) leaves[i][0] = 0 leaves[j][0] = 0 break for i in range(len(leaves)): if leaves[i][0] == 0: continue for j in range(i + 1, len(leaves)): if leaves[j][0] == 0: continue print(leaves[i][0], leaves[j][0]) break else: continue break ```
instruction
0
60,380
13
120,760
No
output
1
60,380
13
120,761
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive. Input The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops. Output In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero. Examples Input 3 2 1 2 2 3 Output YES 1 1 3 Submitted Solution: ``` def dfs(v, graph): isloop = False lo, ro = graph # expand right pr, r = lo, ro expand_right = [] while True: if len(v[r]) == 1: break else: nr1, nr2 = v[r] rn = nr1 if nr1 != pr else nr2 expand_right.append(rn) if rn == lo: # we found loop isloop = True break pr = r r = rn if isloop: return True, graph + expand_right # expand left l, pl = lo, ro expand_left = [] while True: if len(v[l]) == 1: break else: nl1, nl2 = v[l] nl = nl1 if nl1 != pl else nl2 expand_left.append(nl) pl = l l = nl final_graph = expand_left[::-1] + graph + expand_right # if final_graph[0] > final_graph[-1]: # final_graph = final_graph[::-1] return False, final_graph def findMinvalInLineEnds(lines): minval, minval_idx = 0xFFFF, None secval, secval_idx = 0xFFFF, None for i in range(len(lines)): if lines[i][0] < minval: minval = lines[i][0] minval_idx = i elif lines[i][0] < secval: secval = lines[i][0] secval_idx = i return minval, minval_idx, secval, secval_idx def greedyConnect(lines, points): edges = [] points.sort() if len(points) == 1 and len(lines) == 0: edges.append((points[0],points[0])) return edges while True: if len(lines) == 1 and len(points) == 0: edges.append((lines[0][0], lines[0][-1])) break minval_p = points[0] if len(points) > 0 else 0xFFFF secval_p = points[1] if len(points) > 1 else 0xFFFF minval_l, minval_idx_l, secval_l, secval_idx_l = findMinvalInLineEnds(lines) if minval_p < minval_l: if secval_p < minval_l: # connect 2 points to make a line edges.append((minval_p, secval_p)) points = points[2:] lines.append([minval_p, secval_p]) else: # connect point to the line edges.append((minval_p, minval_l)) li = minval_idx_l lines[li] = [minval_p, lines[li][-1]] else: # if minval is one end of line, we merge that line with a point or a line if minval_p < secval_l: edges.append((minval_l, minval_p)) li = minval_idx_l lines[li][0] = minval_p if lines[li][0] > lines[li][-1]: lines[li] = [lines[li][-1], lines[li][0]] points = points[1:] else: edges.append((minval_l, secval_l)) mil, sil = minval_idx_l, secval_idx_l lines[mil][0] = lines[sil][-1] if lines[mil][0] > lines[mil][-1]: lines[mil] = [lines[mil][-1], lines[mil][0]] del lines[sil] return edges if __name__ == '__main__': n,m = tuple(map(int, input().split())) v = [[] for i in range(n)] for i in range(m): v1,v2 = tuple(map(int, input().split())) v1,v2 = v1-1,v2-1 v[v1].append(v2) v[v2].append(v1) # validate input input_valid = True for i in range(n): if len(v[i]) > 2: input_valid = False break v[i].sort() if not input_valid: print('NO') exit() loops = [] lines = [] points = [] visited = [False for i in range(n)] for i in range(n): if visited[i]: continue elif len(v[i]) == 0: points.append(i) visited[i] = True elif len(v[i]) == 1 and v[i] == i: loops.append([i,i]) visited[i] = True else: isloop, graph = dfs(v,[i,v[i][0]]) for gi in graph: visited[gi] = True if isloop: loops.append(graph) else: lines.append(graph) if len(loops) > 0: if len(loops) == 1 and len(points) == 0 and len(lines) == 0: print('YES') print(0) exit() else: print('NO') exit() # print('loops') # for p in loops: # print('\t{}'.format([e+1 for e in p])) # print('lines') # for p in lines: # print('\t{}'.format([e+1 for e in p])) # print('points') # for p in points: # print('\t{}'.format(p+1)) # We only need two ends of the line for li in range(len(lines)): e1,e2 = lines[li][0], lines[li][-1] lines[li] = [e1,e2] if e1<e2 else [e2,e1] edges = greedyConnect(lines, points) print('YES') print(len(edges)) for v1,v2 in edges: v1 += 1 v2 += 1 if v1 < v2: print('{} {}'.format(v1,v2)) else: print('{} {}'.format(v2,v1)) ```
instruction
0
60,381
13
120,762
No
output
1
60,381
13
120,763
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive. Input The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops. Output In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero. Examples Input 3 2 1 2 2 3 Output YES 1 1 3 Submitted Solution: ``` def dfs(v, graph): isloop = False lo, ro = graph # expand right pr, r = lo, ro expand_right = [] while True: if len(v[r]) == 1: break else: nr1, nr2 = v[r] rn = nr1 if nr1 != pr else nr2 expand_right.append(rn) if rn == lo: # we found loop isloop = True break pr = r r = rn if isloop: return True, graph + expand_right # expand left l, pl = lo, ro expand_left = [] while True: if len(v[l]) == 1: break else: nl1, nl2 = v[l] nl = nl1 if nl1 != pl else nl2 expand_left.append(nl) pl = l l = nl final_graph = expand_left[::-1] + graph + expand_right # if final_graph[0] > final_graph[-1]: # final_graph = final_graph[::-1] if len(final_graph) == 2: return True, final_graph else: return False, final_graph def findMinvalInLineEnds(lines): minval, minval_idx = 0xFFFF, None secval, secval_idx = 0xFFFF, None for i in range(len(lines)): if lines[i][0] < minval: minval = lines[i][0] minval_idx = i elif lines[i][0] < secval: secval = lines[i][0] secval_idx = (i, 0) if lines[i][-1] < secval: secval = lines[i][-1] secval_idx = (i,-1) return minval, minval_idx, secval, secval_idx def greedyConnect(lines, points): edges = [] points.sort() while len(lines) > 0 or len(points) > 0: minval_p = points[0] if len(points) > 0 else 0xFFFF secval_p = points[1] if len(points) > 1 else 0xFFFF minval_l, minval_idx_l, secval_l, secval_idx_l = findMinvalInLineEnds(lines) if len(points) == 1 and len(lines) == 0: edges.append((minval_p,minval_p)) points = [] elif minval_p < minval_l: if secval_p < minval_l: # connect 2 points to make a line edges.append((minval_p, secval_p)) points = points[2:] lines.append([minval_p, secval_p]) else: # connect point to the line edges.append((minval_p, minval_l)) li = minval_idx_l lines[li] = [minval_p, lines[li][-1]] else: # if minval is one end of line, we merge that line with a point or a line if minval_p < secval_l: edges.append((minval_l, minval_p)) li = minval_idx_l lines[li][0] = minval_p if lines[li][0] > lines[li][-1]: lines[li] = [lines[li][-1], lines[li][0]] points = points[1:] else: edges.append((minval_l, secval_l)) li = minval_idx_l li_s, ei_s = secval_idx_l if li == li_s: # created loop del lines[li] else: lines[li][0] = lines[li_s][-1] if ei_s == 0 else lines[li_s][0] if lines[li][0] > lines[li][-1]: lines[li] = [lines[li][-1], lines[li][0]] del lines[li_s] return edges if __name__ == '__main__': n,m = tuple(map(int, input().split())) v = [[] for i in range(n)] for i in range(m): v1,v2 = tuple(map(int, input().split())) v1,v2 = v1-1,v2-1 v[v1].append(v2) v[v2].append(v1) # validate input input_valid = True for i in range(n): if len(v[i]) > 2: input_valid = False break v[i].sort() if not input_valid: print('NO') exit() loops = [] lines = [] points = [] visited = [False for i in range(n)] for i in range(n): if visited[i]: continue elif len(v[i]) == 0: points.append(i) visited[i] = True elif len(v[i]) == 1 and v[i] == i: loops.append([i,i]) visited[i] = True else: isloop, graph = dfs(v,[i,v[i][0]]) for gi in graph: visited[gi] = True if isloop: loops.append(graph) else: lines.append(graph) # print('loops') # for p in loops: # print('\t{}'.format([e+1 for e in p])) # print('lines') # for p in lines: # print('\t{}'.format([e+1 for e in p])) # print('points') # for p in points: # print('\t{}'.format(p+1)) # We only need two ends of the line for li in range(len(lines)): e1,e2 = lines[li][0], lines[li][-1] lines[li] = [e1,e2] if e1<e2 else [e2,e1] edges = greedyConnect(lines, points) print('YES') print(len(edges)) for v1,v2 in edges: v1 += 1 v2 += 1 if v1 < v2: print('{} {}'.format(v1,v2)) else: print('{} {}'.format(v2,v1)) ```
instruction
0
60,382
13
120,764
No
output
1
60,382
13
120,765
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has got an undirected graph consisting of n vertices and m edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edges (1, 2) and (2, 1) is considered to be multiple edges. Isolated vertex of the graph is a vertex such that there is no edge connecting this vertex to any other vertex. Vasya wants to know the minimum and maximum possible number of isolated vertices in an undirected graph consisting of n vertices and m edges. Input The only line contains two integers n and m~(1 ≤ n ≤ 10^5, 0 ≤ m ≤ (n (n - 1))/(2)). It is guaranteed that there exists a graph without any self-loops or multiple edges with such number of vertices and edges. Output In the only line print two numbers min and max — the minimum and maximum number of isolated vertices, respectively. Examples Input 4 2 Output 0 1 Input 3 1 Output 1 1 Note In the first example it is possible to construct a graph with 0 isolated vertices: for example, it should contain edges (1, 2) and (3, 4). To get one isolated vertex, we may construct a graph with edges (1, 2) and (1, 3). In the second example the graph will always contain exactly one isolated vertex.
instruction
0
60,656
13
121,312
Tags: constructive algorithms, graphs Correct Solution: ``` n, m = map(int, input().split()) min_res = max(0, n - 2 * m) l, r = min_res, n + 1 def check(tmp): t = n - tmp return t * (t - 1) // 2 >= m while l != r - 1: tmp = (l + r) // 2 if check(tmp): l = tmp else: r = tmp print(min_res, l) ```
output
1
60,656
13
121,313
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has got an undirected graph consisting of n vertices and m edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edges (1, 2) and (2, 1) is considered to be multiple edges. Isolated vertex of the graph is a vertex such that there is no edge connecting this vertex to any other vertex. Vasya wants to know the minimum and maximum possible number of isolated vertices in an undirected graph consisting of n vertices and m edges. Input The only line contains two integers n and m~(1 ≤ n ≤ 10^5, 0 ≤ m ≤ (n (n - 1))/(2)). It is guaranteed that there exists a graph without any self-loops or multiple edges with such number of vertices and edges. Output In the only line print two numbers min and max — the minimum and maximum number of isolated vertices, respectively. Examples Input 4 2 Output 0 1 Input 3 1 Output 1 1 Note In the first example it is possible to construct a graph with 0 isolated vertices: for example, it should contain edges (1, 2) and (3, 4). To get one isolated vertex, we may construct a graph with edges (1, 2) and (1, 3). In the second example the graph will always contain exactly one isolated vertex.
instruction
0
60,657
13
121,314
Tags: constructive algorithms, graphs Correct Solution: ``` import sys import math n,m=map(int,input().split()) if(m==0): print(n,n) elif(n==1): print(n,n) else: store=[0]*(n+1) if(m>=(n*(n-1))//2): print("0","0") else: for i in range(2,n+1): store[i]+=(i*(i-1))//2 if(m>store[i-1] and m<=store[i]): amax=n-i if(m<math.ceil(n/2)): amin=n-2*m else: amin=0 if(m==1): amax=n-2 elif(m==2): amax=n-3 #print(store) print(amin,amax) ```
output
1
60,657
13
121,315