基本思路和上篇博文基本一样啦。
没什么特别需要注意的。
所以学会这个算法 成就感莫名很高?
((°Д°)ъ还是菜鸟)
题目————》hdu 1213
AC代码:(忘记写注释了)
#include<iostream>
#include<cstdio>
using namespace std;
int front[1005];
void initialize(int n){
for (int i = 1; i <= n; i++){
front[i] = i;
}
}
int found(int x){
int r = x;
while (front[r] != r){
r = front[r];
}
int u = x, y;
while (front[u] != r){
y = front[u];
front[u] = r;
u = y;
}
return r;
}
void join(int x, int y){
int fx = found(x), fy = found(y);
if (fx != fy){
front[fx] = fy;
}
}
int main(){
freopen("TestDate.txt", "r", stdin);
int t;
cin >> t;
int n, m;
int x, y;
while (t--){
cin >> n >> m;
initialize(n);
while (m--){
cin >> x >> y;
join(x, y);
}
int num = 0;
for (int i = 1; i <= n; i++){
if (front[i] == i){
num++;
}
}
cout << num << endl;
}
return 0;
}