message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1.
instruction
0
85,835
13
171,670
Tags: constructive algorithms, graphs, greedy, implementation Correct Solution: ``` import sys t=int(sys.stdin.readline()) for _ in range(t): n,l,r=map(int,sys.stdin.readline().split()) prev=0 cur=0 start=1 if l==r and l==n*(n-1)+1: print(1) else: ans=[] while(True): cur+=(n-start)*2 if l<=cur: pos=l-prev total=r-l+1 if(pos%2==1): ans.append(start) total-=1 x=start+pos//2 +1 while(total>0): ans.append(x) if x==n: start+=1 if start==n: start=1 x=start total-=1 if total>0: ans.append(start) total-=1 x+=1 else: x=start+pos//2 while(total>0): ans.append(x) if x==n: start+=1 if start==n: start=1 x=start total-=1 if total>0: ans.append(start) total-=1 x+=1 break prev=cur start+=1 print(*ans) ```
output
1
85,835
13
171,671
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1.
instruction
0
85,836
13
171,672
Tags: constructive algorithms, graphs, greedy, implementation Correct Solution: ``` from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def generateForStartVertex(startVertex,n): if startVertex==n: return [1] res=[] other=startVertex+1 while other<=n: res.append(startVertex) res.append(other) other+=1 return res @bootstrap def calc(l,r,startVertex,startIndex,n,res): nextStartIndex=startIndex+2*(n-startVertex) if startVertex==n: nextStartIndex+=1 currIdx=startIndex if l<nextStartIndex: #run calculation for this startVertex, else skip for x in generateForStartVertex(startVertex,n): if l<=currIdx<=r: res.append(x) currIdx+=1 if startVertex+1<=n and r>=nextStartIndex: # need to run next startVertex yield calc(l,r,startVertex+1,nextStartIndex,n,res) yield res def main(): t=int(input()) allans=[] for _ in range(t): n,l,r=readIntArr() res=[] calc(l,r,1,1,n,res) allans.append(res) multiLineArrayOfArraysPrint(allans) return #import sys #input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) import sys input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] inf=float('inf') MOD=10**9+7 main() ```
output
1
85,836
13
171,673
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1.
instruction
0
85,837
13
171,674
Tags: constructive algorithms, graphs, greedy, implementation Correct Solution: ``` def solve(): n, l, r = [int(i) for i in input().split()] seq = [] i = 1 while l <= r: while l > 2 * n - 2: if l == 3: i = 1 break l -= 2 * n - 2 r -= 2 * n - 2 n -= 1 i += 1 if l%2 == 0: seq.append(l // 2 + i) else: seq.append(i) l += 1 return " ".join(str(i) for i in seq) T = int(input()) for _ in range(T): print(solve()) ```
output
1
85,837
13
171,675
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` def calcStartIndex(vertex,n): i=vertex return 1+2*(i-1)*n-i*i+i def main(): t=int(input()) allans=[] for _ in range(t): n,l,r=readIntArr() startVertex=1 b=n while b>0: while startVertex+b<=n and calcStartIndex(startVertex+b,n)<=l: startVertex+=b b//=2 sv=startVertex idx=calcStartIndex(sv,n) ans=[] adder=1 addTurn=False while idx<=r: #sv,sv+1,sv,sv+2,...sv,n. then sv+=1. if sv==n, then put 1 instead of sv if addTurn: curr=sv+adder adder+=1 else: curr=sv if idx>=l: if sv<n: ans.append(curr) else: ans.append(1) addTurn=not addTurn idx+=1 if curr==n: sv+=1 adder=1 addTurn=False allans.append(ans) multiLineArrayOfArraysPrint(allans) return #import sys #input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) import sys input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] inf=float('inf') MOD=10**9+7 main() ```
instruction
0
85,838
13
171,676
Yes
output
1
85,838
13
171,677
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` import sys input = sys.stdin.buffer.readline from bisect import bisect_left T = int(input()) for _ in range(T): n, l, r = map(int, input().split()) ls = [ (n-u)*2 for u in range(n+1) ] ls[0] = 1 for i in range(1, n+1): ls[i] += ls[i-1] p = bisect_left(ls, l) sp = [] if p == 0: sp = [0, 0, 0] else: d = l - ls[p-1] sp = [p, p+(d+1)//2, 0 if d%2 else 1] def getp(ls): if ls[0] == 0 or ls == [n-1, n, 1]: return 1 elif ls[2] == 0: return ls[1] elif ls[1] == n: return ls[0]+1 else: return ls[0] def nextp(ls): a, b, c = ls if a == 0: return [1, 2, 0] elif c == 0: return [a, b, 1] elif b < n: return [a, b+1, 0] else: return [a+1, a+2, 0] res = [] for _ in range(r-l+1): #print(sp) res.append(getp(sp)) sp = nextp(sp) print(' '.join(map(str, res))) ```
instruction
0
85,839
13
171,678
Yes
output
1
85,839
13
171,679
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` import bisect t=int(input()) for _ in range(t): n,l,r=map(int,input().split()) ans=[] sums=[] tmp=0 for i in range(n-1,0,-1): tmp+=i sums.append(tmp) for i in range(l-1,r): if i%2==0: k=i//2 g=bisect.bisect_right(sums,k) tmp=0 if g==n-1: ans.append(1) else: ans.append(g+1) else: k=(i-1)//2 g=bisect.bisect_right(sums,k) tmp=(g*(2*(n-1)-(g-1)))//2 ans.append(2+g+k-tmp) print(*ans) ```
instruction
0
85,840
13
171,680
Yes
output
1
85,840
13
171,681
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` #!/usr/bin/env python3 import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n, l, r = map(int, input().split()) num = r - l + 1 init_num = 1 index = 0 for i in range(1, n): init_num = i if l <= (n - i) * 2: index = l l = 0 break else: l -= (n - i) * 2 # Last block if l > 0: print(1) continue ans = [] for i in range(1, n): if i < init_num: continue for j in range((n - i) * 2): if i == init_num and j < index - 1: continue elif j % 2 == 0: ans.append(i) num -= 1 else: ans.append((j+1) // 2 + i) num -= 1 if num == 0: break if num == 0: break if num > 0: ans.append(1) print(*ans) ```
instruction
0
85,841
13
171,682
Yes
output
1
85,841
13
171,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` from sys import stdin, gettrace from math import sqrt if not gettrace(): def input(): return next(stdin)[:-1] # def input(): # return stdin.buffer.readline() def main(): def solve(): n,l,r = map(int, input().split()) lv = int((2*n+1 - sqrt((2*n-1)**2 -4*(l-1)))/2) lvs = -2*n+2*n*lv-lv*lv+lv lrd = l - lvs - 1 res = [] i = lv j = lv+lrd//2 + 1 for _ in range(l-1, r, 2): res += [i,j] if j < n: j += 1 else: i +=1 j = i+1 if r == n*(n-1)+1: res[r-l] = 1 print(' '.join(map(str, res[:r-l+1]))) q = int(input()) for _ in range(q): solve() if __name__ == "__main__": main() ```
instruction
0
85,842
13
171,684
No
output
1
85,842
13
171,685
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` import math # решена def task_1343_c(): b = int(input()) array = [int(num) for num in input().split()] maxPositive = 0 minNegative = -10000000000 res = 0 for i in range(b): if array[i] < 0: if i != 0 and array[i - 1] >= 0: res += maxPositive maxPositive = 0 minNegative = max(minNegative, array[i]) else: if i != 0 and array[i - 1] < 0: res += minNegative minNegative = -10000000000 maxPositive = max(maxPositive, array[i]) if minNegative == -10000000000: res += maxPositive else: res += maxPositive + minNegative print(res) # не работает от слова совсем def task_1341_b(): heightLen, doorSize = map(int, input().split()) heights = [int(num) for num in input().split()] perf = [0 for i in range(heightLen)] a = 0 for i in range(heightLen - 1): if i == 0: perf[i] = 0 else: if heights[i - 1] < heights[i] and heights[i] > heights[i + 1]: a += 1 perf[i] = a perf[heightLen - 1] = a max_global = 0 left_global = 0 for i in range(heightLen - doorSize): max_local = perf[i + doorSize - 1] - perf[i] if max_local > max_global: max_global = max_local left_global = i print(max_global + 1, left_global + 1) # решил, чтоб её def task_1340_a(): n = int(input()) array = [int(i) for i in input().split()] for i in range(n - 1): if array[i] < array[i + 1]: if array[i] + 1 != array[i + 1]: print("No") return print("Yes") #решил def task_1339_b(): n = int(input()) array = [int(num) for num in input().split()] array.sort() output = [0 for i in range(0, n)] i = 0 h = 0 j = n - 1 while i <= j: output[h] = array[i] h += 1 i += 1 if h < n: output[h] = array[j] h += 1 j -= 1 for val in reversed(output): print(val, end=' ') # решена def task_1338_a(): n = int(input()) inputArr = [int(num) for num in input().split()] max_sec = 0 for i in range(1, n): local_sec = 0 a = inputArr[i - 1] - inputArr[i] if a <= 0: continue else: b = math.floor(math.log2(a)) local_sec = b + 1 for j in range(b, -1, -1): if a < pow(2, j): continue inputArr[i] += pow(2, j) a -= pow(2, j) if local_sec > max_sec: max_sec = local_sec print(max_sec) def task_1334_d(): n, l ,r = map(int, input().split()) if l == 9998900031: print(1) return res = [] count = 0 start_pos = l for i in range(1, n + 1): count += (n + 1 - i) * 2 if count >= l: for j in range(n - i): res.append(i) res.append(j + i + 1) if count > r: break else: start_pos -= (n + 1 - i) * 2 res.append(1) for i in range(start_pos - 1, start_pos + (r - l)): print(res[i], end=" ") print() a = int(input()) for i in range(a): task_1334_d() ```
instruction
0
85,843
13
171,686
No
output
1
85,843
13
171,687
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` def genGroup(n): s = [1] for i in range(2, n): s.append(n) s.append(i) s.append(n) return s for tc in range(int(input())): n, beg, end = map(int, input().split()) past = 0 i = 1 while past + 2*i < beg: past += 2*i i += 1 group = i + 1 s = genGroup(group) pos = beg - past - 1 res = [] for i in range(end-beg+1): res.append(s[pos]) pos += 1 if pos == len(s): pos = 0 group += 1 s = genGroup(group) print(*res) ```
instruction
0
85,844
13
171,688
No
output
1
85,844
13
171,689
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` def main(): for _ in inputt(): n, l, r = inputi() i = 1 l -= 1 if l == n * (n - 1): print(1) continue while l >= 2 * (n - i): l -= 2 * (n - i) r -= 2 * (n - i) i += 1 j = i + 1 + l // 2 while l < r: if l % 2: print(j, end = " ") j += 1 if j > n: i += 1 j = i + 1 elif l != n * (n - 1): print(i, end = " ") else: print(1, end = " ") l += 1 print() # region M # region fastio import sys, io, os BUFSIZE = 8192 class FastIO(io.IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = io.BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(io.IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): for x in args: file.write(str(x)) file.write(kwargs.pop("end", "\n")) sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion # region import inputt = lambda t = 0: range(t) if t else range(int(input())) inputi = lambda: map(int, input().split()) inputl = lambda: list(inputi()) from math import * from heapq import * from bisect import * from itertools import * from functools import reduce, lru_cache from collections import Counter, defaultdict import re, copy, operator, cmath from builtins import * # endregion # region main if __name__ == "__main__": main() # endregion # endregion ```
instruction
0
85,845
13
171,690
No
output
1
85,845
13
171,691
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tree or determine that it is impossible. Input The first line contains integer n (1 ≤ n ≤ 2·105) — number of vertices in a tree. The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ n). If pi ≠ 0 there is an edge between vertices i and pi. It is guaranteed that the given graph is a tree. Output If it's possible to destroy all vertices, print "YES" (without quotes), otherwise print "NO" (without quotes). If it's possible to destroy all vertices, in the next n lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any. Examples Input 5 0 1 2 1 2 Output YES 1 2 3 5 4 Input 4 0 1 2 3 Output NO Note In the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order. <image>
instruction
0
86,279
13
172,558
Tags: constructive algorithms, dfs and similar, dp, greedy, trees Correct Solution: ``` from collections import defaultdict,deque import sys import bisect import math input=sys.stdin.readline mod=1000000007 def bfs(root,count): q=deque([root]) vis.add(root) while q: vertex=q.popleft() for child in graph[vertex]: if ans[child]==0: ans[child]=count+1 count+=1 if child not in vis: q.append(child) vis.add(child) graph=defaultdict(list) n=int(input()) p=[int(i) for i in input().split() if i!='\n'] if n&1: for i in range(n): if p[i]!=0: graph[p[i]].append(i+1) graph[i+1].append(p[i]) length=[0]*(n+1) for i in graph: length[i]=len(graph[i]) CHECK,OBSERVE=1,0 stack=[(OBSERVE,1,0)] ans=[0]*(n+1) count=0 while stack: state,vertex,parent=stack.pop() if state==OBSERVE: stack.append((CHECK,vertex,parent)) for child in graph[vertex]: if child != parent: stack.append((OBSERVE,child,vertex)) else: if length[vertex]%2==0: count+=1 ans[vertex]=count length[parent]-=1 vis=set() bfs(1,count) out=[0]*(n) for i in range(1,n+1): out[ans[i]-1]=i print('YES') for i in out: sys.stdout.write(str(i)+'\n') else: print('NO') ```
output
1
86,279
13
172,559
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tree or determine that it is impossible. Input The first line contains integer n (1 ≤ n ≤ 2·105) — number of vertices in a tree. The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ n). If pi ≠ 0 there is an edge between vertices i and pi. It is guaranteed that the given graph is a tree. Output If it's possible to destroy all vertices, print "YES" (without quotes), otherwise print "NO" (without quotes). If it's possible to destroy all vertices, in the next n lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any. Examples Input 5 0 1 2 1 2 Output YES 1 2 3 5 4 Input 4 0 1 2 3 Output NO Note In the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order. <image> Submitted Solution: ``` def delete_v(i): # print(edges) for e in edges: if e[0] == i or e[1] == i: vertices[e[0]] -= 1 # print(e[0]) vertices[e[1]] -= 1 # print(e[1]) edges[edges.index(e)] = (-1,-1) # print(vertices) # print(edges) vertices[i] = -1 n = int(input()) vertices = [0 for i in range(n+1)] edges = [] p = input().split() for i in range(n): if int(p[i]) != 0: edges.append((i+1, int(p[i]))) vertices[i+1] += 1 vertices[int(p[i])] += 1 if (len(vertices) - 1) % 2 == 0: print('NO') else: print('YES') for i in range(n): # print(vertices) for i in range(1,n+1): if vertices[i] % 2 == 0: print(i) delete_v(i) break; # print(edges) ```
instruction
0
86,280
13
172,560
No
output
1
86,280
13
172,561
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tree or determine that it is impossible. Input The first line contains integer n (1 ≤ n ≤ 2·105) — number of vertices in a tree. The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ n). If pi ≠ 0 there is an edge between vertices i and pi. It is guaranteed that the given graph is a tree. Output If it's possible to destroy all vertices, print "YES" (without quotes), otherwise print "NO" (without quotes). If it's possible to destroy all vertices, in the next n lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any. Examples Input 5 0 1 2 1 2 Output YES 1 2 3 5 4 Input 4 0 1 2 3 Output NO Note In the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order. <image> Submitted Solution: ``` #def tree(aim,x): # # for i in aim: # if (line_num[i] % 2 == 0) and (not(i in ans)): # wk1 = line_num[i] # line_num[i] = 0 # aim1 = [] # for j in range(len(line[i])): # if not(line[i][j] in ans): # line_num[line[i][j]] -= 1 # aim1.append(line[i][j]) # ans[x] = i # tree(aim1, x + 1) # for j in range(x + 1, len(ans)): # ans[j] = 0 # line_num[i] = wk1 # for j in range(len(line[i])): # if not(line[i][j] in ans): # line_num[line[i][j]] += 1 # # f = True # count = x # for i in range(1, n + 1): # if (not (i in ans)): # if line_num[i] > 0: # f = False # break # else: # ans[count] = i # count += 1 # if f: # print("YES") # for i in ans: # print(i) # quit() # # return False #---------------------------------------------------------------------------------- def bfs(head): while head < len(ans): for j in line[ans[head]]: wk1 = 0 for k in line[j]: if k in ans: wk1 += 1 if (not (j in ans)) and ((line_num[j] - wk1) % 2 == 0): ans.append(j) if len(ans) == n: print("YES") for j in ans: print(j) quit() head += 1 n = int(input()) p = [int(i) for i in input().split()] line_num = [0]*(n + 1) line = [] for i in range(n + 1): line.append([]) for i in range(n): if p[i] != 0: line_num[i + 1] += 1 line[i + 1].append(p[i]) line_num[p[i]] += 1 line[p[i]].append(i + 1) aim = [] for i in range(1, n + 1): aim.append(i) #ans = [0] * n #tree(aim,0) #print("NO") for i in range(n): if line_num[i] % 2 == 0: ans = [i] bfs(0) print("NO") ```
instruction
0
86,281
13
172,562
No
output
1
86,281
13
172,563
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tree or determine that it is impossible. Input The first line contains integer n (1 ≤ n ≤ 2·105) — number of vertices in a tree. The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ n). If pi ≠ 0 there is an edge between vertices i and pi. It is guaranteed that the given graph is a tree. Output If it's possible to destroy all vertices, print "YES" (without quotes), otherwise print "NO" (without quotes). If it's possible to destroy all vertices, in the next n lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any. Examples Input 5 0 1 2 1 2 Output YES 1 2 3 5 4 Input 4 0 1 2 3 Output NO Note In the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order. <image> Submitted Solution: ``` a = dir(__name__) print(a) print('ONLINE_JUDGE' in a) ```
instruction
0
86,282
13
172,564
No
output
1
86,282
13
172,565
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tree or determine that it is impossible. Input The first line contains integer n (1 ≤ n ≤ 2·105) — number of vertices in a tree. The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ n). If pi ≠ 0 there is an edge between vertices i and pi. It is guaranteed that the given graph is a tree. Output If it's possible to destroy all vertices, print "YES" (without quotes), otherwise print "NO" (without quotes). If it's possible to destroy all vertices, in the next n lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any. Examples Input 5 0 1 2 1 2 Output YES 1 2 3 5 4 Input 4 0 1 2 3 Output NO Note In the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order. <image> Submitted Solution: ``` import sys def empty(g): for gg in g: if gg != -1: return False return True def removeVertex(g): for i, gg in enumerate(g): if gg == -1: continue if len(gg) % 2 == 0: for v in gg: g[v].remove(i) g[i] = -1 return i, True return 0, False n = int(input()) graph = [[] for i in range(n)] edges = list(map(int, input().split())) order = [] assert len(edges) == n for i, e in enumerate(edges): if e != 0: graph[i].append(e-1) graph[e-1].append(i) while not empty(graph): r, y = removeVertex(graph) if not y: print('NO') sys.exit(0) else: order.append(r+1) print('YES') for v in order: print(v) ```
instruction
0
86,283
13
172,566
No
output
1
86,283
13
172,567
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image>
instruction
0
86,802
13
173,604
Tags: constructive algorithms, dfs and similar, graphs Correct Solution: ``` import sys import io, os input = sys.stdin.buffer.readline #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from collections import deque def main(): t = int(input()) for _ in range(t): n, m = map(int, input().split()) g = [[] for i in range(n)] ind = [0]*n edge1 = [] edge0 = [] for i in range(m): t, x, y = map(int, input().split()) x, y = x-1, y-1 if t == 1: g[x].append(y) ind[y] += 1 edge1.append((x, y)) else: edge0.append((x, y)) q = deque([]) order = [] for i in range(n): if ind[i] == 0: q.append(i) while q: v = q.popleft() order.append(v) for u in g[v]: ind[u] -= 1 if ind[u] == 0: q.append(u) if len(order) != n: print('NO') continue d = {} for i, v in enumerate(order): d[v] = i print('YES') for i in range(len(edge1)): x, y = edge1[i] print(x+1, y+1) for i in range(len(edge0)): x, y = edge0[i] if d[x] < d[y]: print(x+1, y+1) else: print(y+1, x+1) if __name__ == '__main__': main() ```
output
1
86,802
13
173,605
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image>
instruction
0
86,803
13
173,606
Tags: constructive algorithms, dfs and similar, graphs Correct Solution: ``` def solve(): n, m = map(int, input().split()) edges = [] adj = [[] for _ in range(n)] indeg = [0] * n for _ in range(m): t, x, y = map(int, input().split()) x -= 1 y -= 1 edges.append((x, y)) if t == 1: adj[x].append(y) indeg[y] += 1 q = [i for i in range(n) if indeg[i]==0] count = 0 order = [0] * n while q: top = q.pop() order[top] = count count += 1 for nei in adj[top]: indeg[nei] -= 1 if indeg[nei] == 0: q.append(nei) if count < n: print("NO") return print("YES") for x, y in edges: if order[x] > order[y]: x, y = y, x print(x+1, y+1) t = int(input()) for _ in range(t): solve() ```
output
1
86,803
13
173,607
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image>
instruction
0
86,804
13
173,608
Tags: constructive algorithms, dfs and similar, graphs Correct Solution: ``` import math import time from collections import defaultdict, deque from sys import stdin, stdout from bisect import bisect_left, bisect_right import sys class Graph: def __init__(self, n): sys.setrecursionlimit(200005) self.graph = defaultdict(lambda: []) self.vertices = n self.toposorted = [] def addEdge(self, a, b): # tested self.graph[a].append(b) def cycleUntill(self, visited, curr, parent): # tested visited[curr] = True for i in self.graph[curr]: if(not visited[i]): if(self.cycleUntill(visited, i, curr)): return True elif(i != parent): return True return False def cycle(self): # tested n = self.vertices visited = [False]*(n+2) for i in range(1, n+1): if(not visited[i]): if(self.cycleUntill(visited, i, -1)): return True return False def topologicalSort(self): in_degree = [0]*(self.vertices+10) for i in self.graph: for j in self.graph[i]: in_degree[j] += 1 queue = deque() for i in range(1,self.vertices+1): if in_degree[i] == 0: queue.append(i) cnt = 0 while queue: u = queue.popleft() self.toposorted.append(u) for i in self.graph[u]: in_degree[i] -= 1 if in_degree[i] == 0: queue.append(i) cnt += 1 if cnt != self.vertices: return False else: # Print topological order return True t = int(stdin.readline()) for _ in range(t): n, m = map(int, stdin.readline().split()) g = Graph(n) undir = [] for _ in range(m): ty, a, b = map(int, stdin.readline().split()) if(ty == 1): g.addEdge(a, b) else: undir.append([a, b]) if(not g.topologicalSort()): print("NO") else: print("YES") index = defaultdict(lambda: 0) for i in range(n): index[g.toposorted[i]] = i for a, b in undir: if(index[a] < index[b]): print(a, b) else: print(b, a) for i in g.graph.keys(): for j in g.graph[i]: print(i, j) ```
output
1
86,804
13
173,609
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image>
instruction
0
86,805
13
173,610
Tags: constructive algorithms, dfs and similar, graphs Correct Solution: ``` import collections import os,io 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()) graph1=[] graph2=[] graph3=[0]*(n+1) undirected=[] for i in range(n+1): graph1.append([]) graph2.append([]) for i in range(m): t,x,y=map(int,input().split()) if t==0: undirected.append([x,y]) else: graph1[x].append(y) graph2[y].append(x) s=collections.deque([]) for i in range(1,n+1): if len(graph1[i])==0: s.append(i) l=[] while s: p=s.popleft() l.append(p) for i in graph2[p]: m=i graph3[i]+=1 if graph3[i]==len(graph1[i]): s.append(i) flag=0 for i in range(1,n+1): if graph3[i]!=len(graph1[i]): flag=1 break if flag==1: print('NO') continue print('YES') for i in range(1,n+1): for j in graph1[i]: print(i) print(j) positions=[0]*(n+1) for i in range(len(l)): positions[l[i]]=i for i in range(len(undirected)): x=undirected[i][0] y=undirected[i][1] if positions[x]<positions[y]: print(y) print(x) else: print(x) print(y) ```
output
1
86,805
13
173,611
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image>
instruction
0
86,806
13
173,612
Tags: constructive algorithms, dfs and similar, graphs Correct Solution: ``` import sys def toposort(graph): res = [] found = [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: res.append(~node) elif not found[node]: found[node] = 1 stack.append(~node) stack += graph[node] # cycle check for node in res: if any(found[nei] for nei in graph[node]): return None found[node] = 0 return res[::-1] t=int(input()) for _ in range(t): n, m = map(int,input().split()) g = [[] for _ in range(n + 1)] ug = [] for i in range(m): t, u, v = map(int,input().split()) if t == 0: ug.append([u, v]) else: g[u].append(v) sorted = toposort(g) if not sorted: print("NO") else: print("YES") index = [0] * (n + 1) for i in range(n + 1): index[sorted[i]] = i for i in range(n + 1): for u in g[i]: print(i, u) for u, v in ug: if index[u] < index[v]: print(u, v) else: print(v, u) ```
output
1
86,806
13
173,613
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image>
instruction
0
86,807
13
173,614
Tags: constructive algorithms, dfs and similar, graphs Correct Solution: ``` import os import sys from io import BytesIO, IOBase from collections import defaultdict,deque def kahns_topo(graph,in_degree,vertices): queue = deque() for i in range(vertices): if in_degree[i] == 0: queue.append(i) cnt = 0 top_order = [] while queue: u = queue.popleft() top_order.append(u) for i in graph[u]: in_degree[i] -= 1 if in_degree[i] == 0: queue.append(i) cnt += 1 if cnt != vertices: return [] else: return top_order def main(): for _ in range(int(input())): g = defaultdict(list) n,ver=map(int,input().split()) in_degree=[0]*n edges=[] for i in range(ver): t,a,b=map(int,input().split()) a-=1;b-=1 if t==1: g[a].append(b) in_degree[b]+=1 edges.append([a,b]) #topological sort c=kahns_topo(g,in_degree,n) if c==[]: print("NO") else: #check positions pos=[0]*len(c) for i in range(len(c)): pos[c[i]]=i print("YES") for i in edges: if pos[i[0]] < pos[i[1]]: print(i[0]+1,i[1]+1) else: print(i[1]+1,i[0]+1) if __name__ == "__main__": main() ```
output
1
86,807
13
173,615
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image>
instruction
0
86,808
13
173,616
Tags: constructive algorithms, dfs and similar, graphs Correct Solution: ``` from collections import deque def bfs(indegree): q = deque() for i in range(len(indegree)): if indegree[i] == 0: q.append(i) while q: curr = q.popleft() topo.append(curr) for neighbor in g[curr]: indegree[neighbor] -= 1 if indegree[neighbor] == 0: q.append(neighbor) if __name__ == '__main__': t = int(input()) for _ in range(t): n,m = map(int,input().split()) g = [[]*n for _ in range(n)] edgeList = [] for _ in range(m): t,u,v = map(int,input().split()) u -= 1 v -= 1 if t == 1: g[u].append(v) edgeList.append([u, v]) indegree = [0]*n for vertex in g: for j in vertex: indegree[j] += 1 topo = [] bfs(indegree) pos = [0]*n for i in range(len(topo)): pos[topo[i]] = i bad = False for i in range(n): for neighbor in g[i]: if pos[i] > pos[neighbor]: bad = True if bad or len(topo) != n: print("NO") else: print("YES") for x,y in edgeList: if pos[x] < pos[y]: print(x+1, y+1) else: print(y+1, x+1) ```
output
1
86,808
13
173,617
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image>
instruction
0
86,809
13
173,618
Tags: constructive algorithms, dfs and similar, graphs Correct Solution: ``` import os import sys from io import BytesIO, IOBase from collections import defaultdict def kahn_top_sort(g, n): # Returns the topological order. If graph of N vertices contains a cycle, then the order list will be of length < n. from collections import deque order = [] indeg = [0]*n for i in range(n): for nbr in g[i]: indeg[nbr] += 1 q = deque() for i in range(n): if indeg[i] == 0: q.append(i) while q: node = q.popleft() order.append(node) for nbr in g[node]: indeg[nbr] -= 1 if indeg[nbr] == 0: q.append(nbr) return order # def dfs_top_sort(g, n): # # Returns the topological ordering for a DAG. If cycle exists in the graph, it returns an empty list. # def topsort(g, node): # if visited[node] == 1: # return True # if visited[node] == 2: # return False # visited[node] = 1 # for nbr in g[node]: # if topsort(g, nbr): # return True # visited[node] = 2 # stk.append(node) # return False # visited = [0]*n # 0 - unvisited, 1 - on call stack, 2 - explored # stk = [] # topsort # for i in range(n): # if visited[i] == 0: # # if it contains cycle # if topsort(g, i): # return [] # return stk[::-1] def main(): t = int(input()) for _ in range(t): n, m = map(int, input().split()) dg_edgelist = [] all_edgelist = [] for _ in range(m): t, x, y = map(int, input().split()) all_edgelist.append([x - 1, y - 1]) if t == 1: dg_edgelist.append([x - 1, y - 1]) g = defaultdict(list) for a, b in dg_edgelist: g[a].append(b) # topsort = dfs_top_sort(g, n) topsort = kahn_top_sort(g, n) # print(dfs_top_sort(g, n), kahn_top_sort(g, n)) if len(topsort) == n: print('YES') order = [0]*n for i, node in enumerate(topsort): order[node] = i for i in range(m): x, y = all_edgelist[i] if order[x] > order[y]: all_edgelist[i] = [y, x] for edge in all_edgelist: print(edge[0] + 1, edge[1] + 1) else: print('NO') # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
output
1
86,809
13
173,619
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 consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image> Submitted Solution: ``` import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from bisect import bisect_left as bl, bisect_right as br, insort #from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations def data(): return sys.stdin.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n') def out(var) : sys.stdout.write(str(var)+'\n') #from decimal import Decimal from fractions import Fraction #sys.setrecursionlimit(100000) INF = float('inf') mod = int(1e9)+7 def find_SCC(coupl): SCC, S, P = [], [], [] depth = [0] * len(coupl) stack = list(range(len(coupl))) while stack: node = stack.pop() if node < 0: d = depth[~node] - 1 if P[-1] > d: SCC.append(S[d:]) del S[d:], P[-1] for node in SCC[-1]: depth[node] = -1 elif depth[node] > 0: while P[-1] > depth[node]: P.pop() elif depth[node] == 0: S.append(node) P.append(len(S)) depth[node] = len(S) stack.append(~node) stack += coupl[node] return SCC[::-1] for _ in range(int(data())): n,m=mdata() g=[[] for i in range(n)] l=[] ans=[] for i in range(m): t,x,y=mdata() x-=1 y-=1 if t==0: l.append((x,y)) else: g[x].append(y) ans.append(str(x+1)+' '+str(y+1)) comp=find_SCC(g) val=[0]*(n+1) for i,j in enumerate(comp): if len(j)>1: out("NO") break val[j[0]]=i else: out("YES") for x,y in l: if val[x]<val[y]: ans.append(str(x+1)+' '+str(y+1)) else: ans.append(str(y+1) + ' ' + str(x+1)) outl(ans) ```
instruction
0
86,810
13
173,620
Yes
output
1
86,810
13
173,621
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 consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image> Submitted Solution: ``` import sys input = sys.stdin.readline def canon(e): return tuple(sorted(e)) def solve(): n, m = map(int, input().split()) adj = [[] for _ in range(n)] un = [] indeg = [0] * n for _ in range(m): t, x, y = map(int, input().split()) x -= 1 y -= 1 if t == 0: un.append((x, y)) else: adj[x].append(y) indeg[y] += 1 O = [] Q = [i for i in range(n) if indeg[i] == 0] for i in Q: O.append(i) for j in adj[i]: indeg[j] -= 1 if indeg[j] == 0: Q.append(j) if len(O) != n: print('NO') return print('YES') order = [-1] * n for i, v in enumerate(O): order[v] = i for x, y in un: if order[x] < order[y]: print(x+1, y+1) else: print(y+1, x+1) for i in range(n): for j in adj[i]: print(i+1, j+1) for _ in range(int(input())): solve() ```
instruction
0
86,811
13
173,622
Yes
output
1
86,811
13
173,623
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 consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image> Submitted Solution: ``` from collections import defaultdict as dc # import math N = int(input()) for _ in range(N): n,m = map(int,input().split()) res = [] gress = [0]*(n+1) dn = dc(list) for _ in range(m): d,x,y = map(int,input().split()) if d==1: dn[x].append(y) gress[y]+=1 res.append([d,x,y]) zp = [i for i in range(1,n+1) if gress[i]==0] zp.reverse() count = 0 p = [0]*(n+1) #print(zp,gress,dn) while zp: u = zp.pop() count+=1 p[u] = count #print(p) for v in dn[u]: gress[v]-=1 if gress[v]==0: zp.append(v) #print(p,zp) if count==n: print('YES') for d,x,y in res: if d==1: print(x, y) elif p[x]<p[y]: print(x, y) else: print(y, x) else: print('NO') ```
instruction
0
86,812
13
173,624
Yes
output
1
86,812
13
173,625
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 consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image> Submitted Solution: ``` from collections import defaultdict as dc def tpsort(): q = [i for i in range(1,n+1) if ins[i] == 0] tpcnt = 0 while q: ele = q.pop() tp[ele] = tpcnt tpcnt += 1 for each in di[ele]: ins[each] -= 1 if ins[each] == 0: q.append(each) return tpcnt == n for _ in range(int(input())): n,m = map(int,input().split()) di = dc(list) edges = [] ins = [0] * (n+1) tp = [0] * (n+1) for i in range(m): t,a,b = map(int,input().split()) edges.append([t,a,b]) if t == 1: di[a].append(b) ins[b] += 1 x = tpsort() if not x: print("NO") else: print("YES") for t,a,b in edges: if t == 0: if tp[a] > tp[b]: print(b,a) else: print(a,b) else: print(a,b) ```
instruction
0
86,813
13
173,626
Yes
output
1
86,813
13
173,627
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 consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image> Submitted Solution: ``` import sys input = sys.stdin.readline t = int(input()) for xx in range(t): n,m = list(map(int,input().split())) E = [] ED = [] EU = [] N = [[] for _ in range(n)] ND = [[] for _ in range(n)] V = [0 for _ in range(n)] R1 = [] R2 = [] for _ in range(m): a,b,c = list(map(int,input().split())) if a==1: b-=1 c-=1 N[b].append(c) ND[b].append(c) E.append((b,c)) ED.append((b,c)) R1.append(b) R1.append(c) R2.append(c) else: b-=1 c-=1 ND[c].append(b) ND[b].append(c) EU.append((b,c)) R1 = set(R1) R2 = set(R2) root = R1 - R2 if t<1000: if len(list(root))==0 and len(ED)>0: print('NO') else: if len(list(root))==0: root = 0 print('YES') V = [0 for _ in range(n)] V[0] = 1 Q = [0] T = [0] else: print('YES') V = [0 for _ in range(n)] Q = [] T = [] for rr in list(root): V[rr] = 1 Q.append(rr) T.append(rr) # print(ND) while Q: L = list(Q) LL = [] for node in L: for child in ND[node]: if V[child] == 0: T.append(child) LL.append(child) V[child] = 1 Q = LL for edge in ED: print(edge[0]+1, edge[1]+1) for edge in EU: a,b = edge[0], edge[1] if a in T and b in T: if T.index(b) < T.index(a): a,b = b,a print(a+1,b+1) else: if xx==41: V = [0 for _ in range(n)] DEP = [0 for _ in range(n)] if len(list(root))==0: V[0] = 1 Q = [0] T = [0] else: root = list(root) Q,T = [],[] for rr in root: V[rr] = 1 Q.append(rr) T.append(rr) depth = 0 while Q: L = list(Q) LL = [] for node in L: DEP[node] = depth for child in N[node]: if V[child] == 0: T.append(child) LL.append(child) V[child] = 1 depth += 1 Q = list(LL) ok = 1 for edge in ED: a,b = edge[0],edge[1] if a in T and b in T: if DEP[b] < DEP[a]: ok = 0 if ok==0: print('NO') # print(N) # print(ED) # print(EU) # print(T) # print(root) else: print('YES') V = [0 for _ in range(n)] if len(list(root))==0: root = 0 V[root] = 1 Q = [root] T = [root] else: root = list(root) Q,T = [],[] for rr in root: V[rr] = 1 Q.append(rr) T.append(rr) while Q: L = list(Q) LL = [] for node in L: for child in ND[node]: if V[child] == 0: T.append(child) LL.append(child) V[child] = 1 Q = LL for edge in ED: print(edge[0]+1, edge[1]+1) for edge in EU: a,b = edge[0], edge[1] if a in T and b in T: if DEP[b] < DEP[a]: a,b = b,a print(a+1,b+1) print(N) print(ED) print(EU) print(T) print(root) print(DEP) ```
instruction
0
86,814
13
173,628
No
output
1
86,814
13
173,629
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 consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image> Submitted Solution: ``` import io import os from collections import Counter, defaultdict, deque from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def solve(N, M, edges): graph = [[] for i in range(N)] ugraph = [set() for i in range(N)] for t, u, v in edges: u -= 1 v -= 1 if t == 0: ugraph[u].add(v) ugraph[v].add(u) else: graph[u].append(v) roots = set(range(N)) for u in range(N): for v in graph[u]: roots.discard(v) if not roots: return "NO" comp = {} @bootstrap def f(path, pathSet, compId): u = path[-1] if u in comp: yield False return comp[u] = compId for v in list(ugraph[u]): if v in pathSet: # Can't be u, v # print('discarding') ugraph[u].discard(v) for v in graph[u]: if v in pathSet: yield True return path.append(v) pathSet.add(v) ret = yield f(path, pathSet, compId) if ret: yield ret return path.pop() pathSet.remove(v) yield False asdf = 0 for u in roots: if f([u], {u}, asdf): return "NO" asdf += 1 if len(comp) != N: return "NO" # print(N, M, edges) # print(roots) # print(comp) for u in range(N): for v in ugraph[u]: if u in ugraph[v]: # Both directions still exist, tie break with comp id if comp[u] > comp[v]: graph[u].append(v) # print('cross', u, v) else: graph[u].append(v) # print('internal', u, v) # Final pass to check for cycles @bootstrap def checkCycle(path, pathSet): for v in graph[path[-1]]: if v in pathSet: yield True return path.append(v) pathSet.add(v) ret = yield checkCycle(path, pathSet) if ret: yield ret return path.pop() pathSet.remove(v) yield False roots = set(range(N)) for u in range(N): for v in graph[u]: roots.discard(v) for u in roots: if checkCycle([u], {u}): return "NO" ans = [str(u + 1) + " " + str(v + 1) for u in range(N) for v in graph[u]] if len(ans) != M: return "NO" return "YES\n" + "\n".join(ans) if False: # print(solve(4, 4, [[1, 1, 2], [1, 2, 3], [0, 3, 1], [1, 4, 1]])) import random random.seed(0) for tc in range(100): N = random.randint(2, 5) M = random.randint(1, N * (N - 1) // 2) edges = set((random.randint(1, N), random.randint(1, N)) for i in range(M)) edges = [(random.randint(0, 1), u, v) for u, v in edges if u != v] M = len(edges) solve(N, M, edges) print() exit() if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline T = int(input()) for tc in range(T): N, M = [int(x) for x in input().split()] edges = [[int(x) for x in input().split()] for i in range(M)] # 1 indexed ans = solve(N, M, edges) print(ans) ```
instruction
0
86,815
13
173,630
No
output
1
86,815
13
173,631
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 consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image> Submitted Solution: ``` import sys def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s); sys.stdout.write('\n') def wi(n): sys.stdout.write(str(n)); sys.stdout.write('\n') def wia(a, sep=' '): sys.stdout.write(sep.join([str(x) for x in a])); sys.stdout.write('\n') def solve(n, m, e0, e1): g = [[] for _ in range(n)] for e in e1: g[e[0]].append(e[1]) res, found = [], [0] * n stack = list(range(n)) while stack: node = stack.pop() if node < 0: res.append(~node) elif not found[node]: found[node] = 1 stack.append(~node) stack += g[node] # cycle check for node in res: if any(found[nei] for nei in g[node]): ws('NO') return found[node] = 0 topo_sorted = res[::-1] idx = [0] * n for i in range(n): idx[topo_sorted[i]] = i ws('YES') for e in e1: wia(list(e)) for e in e0: if idx[e[0]] < idx[e[1]]: wia(list(e)) else: wia([e[1], e[0]]) def main(): for _ in range(ri()): n, m = ria() e0 = [] e1 = [] for i in range(m): ti, xi, yi = ria() xi -= 1 yi -= 1 if ti == 0: e0.append((xi, yi)) else: e1.append((xi, yi)) solve(n, m, e0, e1) if __name__ == '__main__': main() ```
instruction
0
86,816
13
173,632
No
output
1
86,816
13
173,633
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 consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≤ x_i, y_i ≤ n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5; ∑ m ≤ 2 ⋅ 10^5). Output For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image> Submitted Solution: ``` import sys sys.setrecursionlimit(10**9) def LN(): return next(sys.stdin,'') def INTS(s): fields=s.split() if len(fields)==1: return int(fields[0]) else: return list(map(int,s.split())) def dfs(u): seen.add(u) for v in g[u]: if v not in seen: dfs(v) ord.append(u) nt=INTS(LN()) try: for tx in range(nt): n,m=INTS(LN()) edges=[] g=[[] for _ in range(n)] for _ in range(m): t,x,y=INTS(LN()) x,y=x-1,y-1 if t==1: g[x].append(y) edges.append((x,y)) seen=set() ord=[] for u in range(n): if u not in seen: dfs(u) ord=ord[::-1] pos={} for u in range(n): pos[ord[u]]=u cyc=False for u in range(n): for v in g[u]: if pos[u] > pos[v]: cyc=True break if cyc: break if cyc: print('NO') else: print('YES') for u,v in edges: if pos[u]<pos[v]: print(u+1, v+1) else: print(v+1, u+1) except Exception as v: print(v) ```
instruction
0
86,817
13
173,634
No
output
1
86,817
13
173,635
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color.
instruction
0
87,033
13
174,066
Tags: brute force, dfs and similar, dsu, graphs Correct Solution: ``` #code by aanchaltiwari__ def dfs(x, y, color): visited = [False for i in range(n + 1)] visited[x] = True stack = [x] while stack: node = stack.pop() for child, childcolor in g[node]: if visited[child] == False and childcolor == color: visited[child] = True stack.append(child) if visited[y] == True: return True return False n, m = map(int, input().split()) g = {i: [] for i in range(1, n + 1)} s = set() for i in range(m): u, v, c = map(int, input().split()) s.add(c) g[u].append([v, c]) g[v].append([u, c]) s = list(s) # print(g) # print(s) ans = [[0 for i in range(n+1)]for j in range(n+1)] for i in range(1, n + 1): for j in range(1, n + 1): for c in s: if i != j: if dfs(i, j, c): ans[i][j] += 1 # print(ans) q = int(input()) for i in range(q): u, v = map(int, input().split()) print(ans[u][v]) ```
output
1
87,033
13
174,067
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color.
instruction
0
87,034
13
174,068
Tags: brute force, dfs and similar, dsu, graphs Correct Solution: ``` def find(c, x): p = dsu[c] if x == p[x]: return x return find(c, p[x]) def union(c, x, y): x = find(c, x) y = find(c, y) if x == y: return p = dsu[c] p[x] = y n, m = map(int, input().split()) dsu = [[i for i in range(n + 1)] for _ in range(m + 1)] for _ in range(m): a, b, c = map(int, input().split()) union(c, a, b) q = int(input()) for _ in range(q): a, b = map(int, input().split()) count = 0 for c in range(1, m + 1): if find(c, a) == find(c, b): count += 1 print(count) ```
output
1
87,034
13
174,069
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color.
instruction
0
87,035
13
174,070
Tags: brute force, dfs and similar, dsu, graphs Correct Solution: ``` class CodeforcesTask505BSolution: def __init__(self): self.result = '' self.n_m = [] self.edges = [] self.q = 0 self.queries = [] def read_input(self): self.n_m = [int(x) for x in input().split(" ")] for x in range(self.n_m[1]): self.edges.append([int(y) for y in input().split(" ")]) self.q = int(input()) for x in range(self.q): self.queries.append([int(y) for y in input().split(" ")]) def process_task(self): graphs = [[[] for x in range(self.n_m[0])] for c in range(self.n_m[1])] for edge in self.edges: graphs[edge[2] - 1][edge[0] - 1].append(edge[1]) graphs[edge[2] - 1][edge[1] - 1].append(edge[0]) results = [] for query in self.queries: to_visit = [(query[0], c) for c in range(self.n_m[1])] used = set() visited = [[False] * self.n_m[0] for x in range(self.n_m[1])] while to_visit: visiting = to_visit.pop(-1) if visiting[1] not in used and not visited[visiting[1]][visiting[0] - 1]: visited[visiting[1]][visiting[0] - 1] = True if visiting[0] == query[1]: used.add(visiting[1]) else: to_visit.extend([(x, visiting[1]) for x in graphs[visiting[1]][visiting[0] - 1]]) colors = len(used) results.append(colors) self.result = "\n".join([str(x) for x in results]) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask505BSolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ```
output
1
87,035
13
174,071
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color.
instruction
0
87,036
13
174,072
Tags: brute force, dfs and similar, dsu, graphs Correct Solution: ``` class Union: def __init__(self, size): self.ancestor = [i for i in range(size+1)] def find(self, node): if self.ancestor[node] == node: return node self.ancestor[node] = self.find(self.ancestor[node]) return self.ancestor[node] def merge(self, a, b): a, b = self.find(a), self.find(b) self.ancestor[a] = b n, m = map(int, input().split()) unions = [Union(n) for _ in range(m+1)] graph = [[] for _ in range(n+1)] for _ in range(m): a, b, c = map(int, input().split()) graph[a].append((b, c)) graph[b].append((a, c)) unions[c].merge(a, b) for _ in range(int(input())): a, b = map(int, input().split()) ans = 0 for i in range(1, m+1): ans += unions[i].find(a) == unions[i].find(b) print(ans) ```
output
1
87,036
13
174,073
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color.
instruction
0
87,037
13
174,074
Tags: brute force, dfs and similar, dsu, graphs Correct Solution: ``` import math,sys,bisect,heapq from collections import defaultdict,Counter,deque from itertools import groupby,accumulate #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 #def input(): return sys.stdin.readline().strip() input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ ilele = lambda: map(int,input().split()) alele = lambda: list(map(int, input().split())) ilelec = lambda: map(int1,input().split()) alelec = lambda: list(map(int1, input().split())) 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)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) n,m = ilele() Color = defaultdict(set) G = defaultdict(set) C = set() def addEdge(a,b): G[a].add(b) G[b].add(a) def addColor(a,b,c): Color[(a,b)].add(c) Color[(b,a)].add(c) C.add(c) for i in range(m): a,b,c = ilele() addColor(a,b,c) addEdge(a,b) vis = [False]*(n+1) Ans = [] def fun(node,dest,vis,grp): #print(node,vis,grp) if not grp: return if node == dest: for i in grp: Ans.append(i) return vis[node] = True for i in G.get(node,[]): #print(i) if not vis[i]: newvis = vis.copy() #newvis[c] =True z = grp.intersection(Color[node,i]) #print(z) fun(i,dest,newvis,z) #print(Color,G) for i in range(int(input())): a,b = ilele() vis = [False]*(n+1) grp = C.copy() fun(a,b,vis,grp) #print(Ans) print(len(set(Ans))) Ans =[] ```
output
1
87,037
13
174,075
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color.
instruction
0
87,038
13
174,076
Tags: brute force, dfs and similar, dsu, graphs Correct Solution: ``` def main(): def dfs(index, color): visited[index] = True for p in adj[index]: if not visited[p[0]] and p[1] == color: dfs(p[0], color) n, m = map(int, input().split()) adj = [[] for _ in range(n)] for _ in range(m): a, b, c = map(int, input().split()) adj[a - 1].append((b - 1, c)) adj[b - 1].append((a - 1, c)) q = int(input()) for _ in range(q): a, b = map(int, input().split()) ans = 0 for i in range(1, m + 1): visited = [False] * n dfs(a - 1, i) if visited[b - 1]: ans += 1 print(ans) if __name__ == "__main__": main() ```
output
1
87,038
13
174,077
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color.
instruction
0
87,039
13
174,078
Tags: brute force, dfs and similar, dsu, graphs Correct Solution: ``` n,m=map(int,input().split()) g=[[] for _ in range(n)] for _ in range(m): a,b,c=map(int,input().split()) g[a-1].append((b-1,c-1)) g[b-1].append((a-1,c-1)) def dfs(x,c,t): if x==t:return True v[x]=1 for j in g[x]: if j[1]==c and v[j[0]]==0: if dfs(j[0],c,t):return True return False q=int(input()) o=[0]*q v=[] for i in range(q): f,y=map(int,input().split()) for c in range(100): v=[0]*n if dfs(f-1,c,y-1):o[i]+=1 print('\n'.join(list(map(str,o)))) ```
output
1
87,039
13
174,079
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color.
instruction
0
87,040
13
174,080
Tags: brute force, dfs and similar, dsu, graphs Correct Solution: ``` from sys import stdin,stdout input = stdin.readline def main(): n, m = map(int,input().split()) sets = [list(range(n+1)) for i in range(m)] sizes = [[1]*(n+1) for i in range(m)] def get(a,ind): if sets[ind][a] != a: sets[ind][a] = get(sets[ind][a],ind) return sets[ind][a] def union(a, b,ind): a = get(a,ind) b = get(b,ind) if a == b:return if sizes[ind][a] > sizes[ind][b]: a,b = b,a sets[ind][a] = b sizes[ind][b] += sizes[ind][a] for i in range(m): a, b, c = map(int,input().split()) a -= 1 b -= 1 c -= 1 union(a,b,c) q = int(input()) for i in range(q): ans = 0 u,v = map(int,input().split()) u-=1 v-=1 for j in range(m): ans += int(get(u,j) == get(v,j)) print(ans) main() ```
output
1
87,040
13
174,081
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color. Submitted Solution: ``` n,m = map(int, input().split()) l = [] for i in range(m): a,b,c = map(int, input().split()) if len(l) <= c-1: for i in range(c-len(l)): l.append([]) p = l[c-1] m = [] for i in range(len(p)): if a in p[i] or b in p[i]: m.append(i) new = [a,b] for i in range(len(m)): new = new + p[m[i]] for i in range(len(m)): p.pop(m[i]-i) p.append(new) l[c-1] = p q = int(input()) for i in range(q): counter = 0 u,v = map(int, input().split()) for j in range(len(l)): yes = 0 for k in range(len(l[j])): if yes == 0 and u in l[j][k] and v in l[j][k]: yes = 1 counter += 1 print(counter) ```
instruction
0
87,041
13
174,082
Yes
output
1
87,041
13
174,083
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color. Submitted Solution: ``` def solution(): n,m = [int(x) for x in input().split(' ')] graphs = {} edges = {} for i in range(m): x,y,c = input().split(' ') if c not in graphs: graphs[c]={} if x not in graphs[c]: graphs[c][x] = [] if y not in graphs[c]: graphs[c][y] = [] graphs[c][x].append(y) graphs[c][y].append(x) q = int(input()) queries = [] for i in range(q): x,y = input().split(' ') ans = 0 for c,graph in graphs.items(): ans+=1 if areConnected(x,y,graph) else 0 print(ans) def areConnected(x,y,graph): if x not in graph or y not in graph: return False queu = [x] already = [x] while len(queu) != 0: current = queu[0] if current == y: return True del queu[0] already.append(current) for i in graph[current]: if i not in already and i not in queu: if i == y: return True queu.append(i) return False solution() ```
instruction
0
87,042
13
174,084
Yes
output
1
87,042
13
174,085
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color. Submitted Solution: ``` # !/usr/bin/env python3 # coding: UTF-8 # Modified: <19/Feb/2019 06:31:43 PM> # ✪ H4WK3yE乡 # Mohd. Farhan Tahir # Indian Institute Of Information Technology (IIIT),Gwalior # Question Link # # # ///==========Libraries, Constants and Functions=============/// import sys inf = float("inf") mod = 1000000007 def get_array(): return list(map(int, sys.stdin.readline().split())) def get_ints(): return map(int, sys.stdin.readline().split()) def input(): return sys.stdin.readline() # ///==========MAIN=============/// N = 105 graph = [[] for _ in range(N)] component = [0] * N visited = [False] * N def explore(node): global cnt visited[node] = True component[node] = cnt for neighbour, color in graph[node]: if visited[neighbour] == False: explore(neighbour) def dfs(n): global cnt cnt = 0 for i in range(1, n + 1): if visited[i] == False: cnt += 1 explore(i) def explore_o(node, c): global ans, s visited[node] = True for neighbour, color in graph[node]: if visited[neighbour] == False and color == c: if neighbour == v: s.add(color) explore_o(neighbour, c) def dfs_o(u): global visited, ans, flag, s ans = 0 s = set() for neighbour, color in graph[u]: visited = [False] * N visited[u] = True flag = 0 if neighbour == v: s.add(color) continue explore_o(neighbour, color) return len(s) def main(): global n, m n, m = get_ints() for _ in range(m): u, x, c = get_ints() graph[u].append((x, c)) graph[x].append((u, c)) dfs(n) global v for tc in range(int(input())): u, v = get_ints() if component[u] != component[v]: print(0) continue print(dfs_o(u)) if __name__ == "__main__": main() ```
instruction
0
87,043
13
174,086
Yes
output
1
87,043
13
174,087
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #'%.9f'%ans ########################################################## from collections import defaultdict def dfs(s,f): if s==v: return True vis[s]=1 for i in g[s]: if vis[i[0]]==0 and i[1]==f: if(dfs(i[0],f)): return True return False #for _ in range(int(input())): #n = int(input()) n,m = map(int, input().split()) g=[[] for i in range(n+2)] for i in range(m): u,v,d = map(int, input().split()) g[u].append([v,d]) g[v].append([u,d]) q= int(input()) for _ in range(q): u, v= map(int, input().split()) cnt=0 for i in range(1,101): vis=[0]*101 if (dfs(u,i)): cnt+=1 print(cnt) #g=[[] for i in range(n+1)] #arr = list(list(map(int, input().split()))) ```
instruction
0
87,044
13
174,088
Yes
output
1
87,044
13
174,089
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color. Submitted Solution: ``` n,m = [int(_) for _ in input().split()] d = [[] for i in range(n+1)] for i in range(m): a,b,c = [int(_) for _ in input().split()] d[a].append((b,c)) d[b].append((a,c)) q = int(input()) def query(d,a,b): if a > b: a,b = b,a l = [] for i in range(len(d[a])): l.append(d[a][i]) cnt = 0 v = [False] * (n+1) while len(l) > 0: if l[0][0] == b: cnt += 1 del l[0] continue for i in range(len(d[l[0][0]])): if v[d[l[0][0]][i][0]] == False and d[l[0][0]][i][1] == l[0][1]: l.append(d[l[0][0]][i]) if d[l[0][0]][i][0] != b: v[d[l[0][0]][i][0]] = True del l[0] return cnt for qu in range(q): a,b = [int(_) for _ in input().split()] print(query(d,a,b)) ```
instruction
0
87,045
13
174,090
No
output
1
87,045
13
174,091
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color. Submitted Solution: ``` def dfs_paths(graph, start, goal, path=list()): if not path: path.append(start) if start == goal: yield path for vertex in graph[start] - set(path): yield from dfs_paths(graph, vertex, goal, path=path + [vertex]) n, m = map(int, input().split()) graph = {} for _ in range(m): a, b, c = map(int, input().split()) if c not in graph: graph[c] = {} if a not in graph[c]: graph[c][a] = set() if b not in graph[c]: graph[c][b] = set() graph[c][a].add(b) graph[c][b].add(a) q = int(input()) for _ in range(q): u, v = map(int, input().split()) count = 0 for k in graph: if u not in graph[k] or v not in graph[k]: continue if len(list(dfs_paths(graph[k], u, v))) > 0: count += 1 print(count) ```
instruction
0
87,046
13
174,092
No
output
1
87,046
13
174,093
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color. Submitted Solution: ``` def IsPossible(graph,colors,start,end,color,u): #print (start,end) if start == end: return True arr = [] stack = [start] while stack: curr = stack.pop() if curr not in arr: arr.append(curr) for kid in graph[curr]: for color1 in colors[(curr,kid)]: if kid == end and color1 != color: return False if color1 == color and kid != u: stack.append(kid) if kid == end: #print ('here',curr,kid) return True return False def Solve(graph,colors,u,v): count = 0 for kid in graph[u]: for color in colors[(u,kid)]: if IsPossible(graph,colors,kid,v,color,u): count += 1 return count def main(): graph = {} colors = {} n,m = map(int,input().split()) for i in range(1,n+1): graph[i] = [] for i in range(m): a,b,c = map(int,input().split()) if (a,b) not in colors.keys(): colors[(a,b)] = [c] else: colors[(a,b)].append(c) if (b,a) not in colors.keys(): colors[(b,a)] = [c] else: colors[(b,a)].append(c) if b not in graph[a]: graph[a].append(b) if a not in graph[b]: graph[b].append(a) q = int(input()) for i in range(q): u,v = map(int,input().split()) print (Solve(graph,colors,u,v)) main() ```
instruction
0
87,047
13
174,094
No
output
1
87,047
13
174,095
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color. Submitted Solution: ``` import sys input = sys.stdin.readline def multi_input(): return map(int, input().split()) def array_print(arr): print(' '.join(map(str, arr))) def dfs(n, previous, start, end, graph, color, temp_color): if start == end: return 1 ans = 0 for i in graph[start]: if i[1] == color and [start, i[0], i[1]] not in visited: node = i[0] visited.append([start, i[0], i[1]]) ans += dfs(n, start, node, end, graph, color, i[1]) return ans graph = {} n, m = multi_input() for i in range(n+1): graph[i] = [] for i in range(m): u, v, c = multi_input() graph[u].append([v, c]) graph[v].append([u, c]) q = int(input()) for q1 in range(q): u, v = multi_input() visited = [] ans = 0 for i in graph[u]: if [u, i[0], i[1]] not in visited: visited.append([u, i[0], i[1]]) ans += dfs(n, 0, i[0], v, graph, i[1], i[1]) print(ans) ```
instruction
0
87,048
13
174,096
No
output
1
87,048
13
174,097
Provide a correct Python 3 solution for this coding contest problem. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7
instruction
0
87,494
13
174,988
"Correct Solution: ``` #中国人郵便問題 import sys input = sys.stdin.readline INF = float('inf') v, e = map(int, input().split()) adj = [[INF]*v for _ in range(v)] for i in range(v): adj[i][i] = 0 odd_vertices = [0]*v total_d = 0 for _ in range(e): s, t, d = map(int, input().split()) adj[s][t] = adj[t][s] = min(adj[s][t], d) odd_vertices[s] ^= 1 odd_vertices[t] ^= 1 total_d += d def warshall(): for k in range(v): for i in range(v): for j in range(v): if adj[i][k] != INF and adj[k][j] != INF: adj[i][j] = min(adj[i][j],adj[i][k] + adj[k][j]) def solve(): if sum(odd_vertices) == 0: return total_d else: warshall() odd = [] for i in range(v): if odd_vertices[i] == 1: odd += [i] n = len(odd) dp = [INF]*(1<<n) dp[0] = 0 for state in range(1<<n): for sp in range(n): if not((state>>sp) & 1): for ep in range(n): d = adj[odd[sp]][odd[ep]] if sp != ep and not((state>>ep) & 1) and d != INF: new_state = state|(1<<sp)|(1<<ep) dp[new_state] = min(dp[new_state], dp[state]+d) return total_d + dp[-1] print(solve()) ```
output
1
87,494
13
174,989
Provide a correct Python 3 solution for this coding contest problem. For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7
instruction
0
87,495
13
174,990
"Correct Solution: ``` def warshall_floyd(distance_table, point_size): for k in range(point_size): for i in range(point_size): for j in range(point_size): if distance_table[i][j] > distance_table[i][k] + distance_table[k][j]: distance_table[i][j] = distance_table[i][k] + distance_table[k][j] class bit: def __createtable(): table = [None] * 64 mask64 = (1 << 64) - 1 hash = 0x03F566ED27179461 for i in range(64): table[hash >> 58] = i hash = (hash << 1) & mask64 return table __table = __createtable() def number_of_trailing_zeros(x): if x == 0:return 64 mask64 = (1 << 64) - 1 return bit.__table[((bit.lowest_one(x) * 0x03F566ED27179461) & mask64) >> 58] def lowest_one(i): return i & -i def ccp(distance_table, point_size, v): if v: i = bit.number_of_trailing_zeros(v) v ^= (1 << i) return min(ccp(distance_table, point_size, v ^ (1 << j)) + distance_table[i][j] for j in range(point_size) if v & 1 << j) else: return 0 import sys readline = sys.stdin.readline point_size, e = map(int, readline().split()) distance_table = [[float('inf')] * point_size for _ in range(point_size)] cost = 0 v = 0 for _ in range(e): s, t, d = map(int, readline().split()) distance_table[s][t] = min(distance_table[s][t], d) distance_table[t][s] = min(distance_table[t][s], d) v ^= 1 << s ^ 1 << t cost += d warshall_floyd(distance_table, point_size) print(cost + ccp(distance_table, point_size, v)) ```
output
1
87,495
13
174,991