1 条题解
-
1XzyStudio (admin) LV 8 MOD RP++ 机房蒟蒻 tayz @ 2023-10-09 11:25:37
并查集模板题,没背过的赶紧背啦
Python:
n, m = input().split() n = int(n);m = int(m) f = dict() def find(x): if f[x] == x: return x else: f[x] = find(f[x]) return f[x] for i in range(1, n+1): f[i] = i for i in range(1, m+1): p1, p2, p3 = input().split() p1 = int(p1);p2 = int(p2);p3 = int(p3) if p1 == 1: f[find(p2)] = find(p3) else: if find(p2) == find(p3): print("Yes") else: print("No")
C++:
#include<bits/stdc++.h> using namespace std; int i, j, k, n, m, s, ans, f[10010], p1, p2, p3; int find(int k){ if(f[k]==k)return k; return f[k]=find(f[k]); } int main(){ cin>>n>>m; for(i=1;i<=n;i++) f[i]=i; for(i=1;i<=m;i++){ cin>>p1>>p2>>p3; if(p1==1) f[find(p2)]=find(p3); else if(find(p2)==find(p3)) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }
- 1