4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
1 0 2 998Huge input, scanf is recommended.HintHint
第一种方法:使用标记,遍历的过程中进行统计 #include<iostream> #include<algorithm> #include<vector> #include<cstring> using namespace std; const int maxn = 1000 + 5; vector<int> G[maxn]; int p[maxn]; void init(int N) { memset(p, 0, sizeof(p)); for(int i = 1; i <= N; i++) p[i] = i; } int _find(int x) {return (p[x]==x ? x : _find(p[x]));} void _merge(int x, int y) { if(_find(x)!=_find(y)) p[_find(y)] = _find(x); } void initG(int N) {for(int i = 1; i < N; i++) G[i].clear();} void read_tree(int M) { int u, v; for(int i = 0; i < M; i++) { cin >> u >> v; _merge(u, v); } } int main() { int N, M, cnt; while((cin >> N) && N) { cin >> M; init(N); initG(N); read_tree(M); cnt = 0; for(int i = 1; i <= N; i++) if(p[i] == i) cnt++; cout << cnt-1 << endl; } return 0; } 第二种方法:使用并查集, 采用紫书上的框架即可 #include<iostream> #include<algorithm> #include<vector> #include<cstring> using namespace std; const int maxn = 1000 + 5; vector<int> G[maxn]; int p[maxn]; void init(int N) { memset(p, 0, sizeof(p)); for(int i = 1; i <= N; i++) p[i] = i; } int _find(int x) {return (p[x]==x ? x : _find(p[x]));} void _merge(int x, int y) { if(_find(x)!=_find(y)) p[_find(y)] = _find(x); } void initG(int N) {for(int i = 1; i < N; i++) G[i].clear();} void read_tree(int M) { int u, v; for(int i = 0; i < M; i++) { cin >> u >> v; _merge(u, v); } } int main() { int N, M, cnt; while((cin >> N) && N) { cin >> M; init(N); initG(N); read_tree(M); cnt = 0; for(int i = 1; i <= N; i++) if(p[i] == i) cnt++; cout << cnt-1 << endl; } return 0; }
原文地址:http://blog.csdn.net/czkct/article/details/45647093