并查集模板
并查集模板:
1 #include<iostream> 2 #include<algorithm> 3 #include<cstring> 4 #include<cstdio> 5 using namespace std; 6 typedef long long ll; 7 int f[1003], n, m; 8 int Rank[1003]; 9 void init() { 10 for(int i = 1; i <= n; i++) { 11 f[i] = i; 12 Rank[i]=0; 13 } 14 } 15 int getf(int v) { 16 return v == f[v] ? v : (f[v] = getf(f[v]));//包含路径压缩优化 17 } 18 void Merge(int n, int v) { 19 int t1 = getf(n); 20 int t2 = getf(v); 21 if(Rank[t1]<Rank[t2]) f[t1]=t2;//这是秩优化 22 else f[t2]=t1; 23 if(Rank[t1]==Rank[t2]) Rank[t1]++; 24 } 25 int main() { 26 int t; 27 cin >> t; 28 while(t--) { 29 cin >> n >> m; 30 int a, b; 31 init(); 32 for(int i = 1; i <= m; i++) { 33 scanf("%d%d", &a, &b); 34 Merge(a, b); 35 } 36 int ans = 0; 37 for(int i = 1; i <= n; i++) { 38 if(f[i] == i) ans++; 39 } 40 printf("%d\n", ans); 41 } 42 return 0; 43 }
模板题: HDU1213