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
遇到的问题和思路:
一道简单的并查集,假设都连到第一个城市就OK了。
给出AC代码(一定要用C++交,G++就是TLE了)
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> using namespace std; const int MAX = 1000 + 10; int n, m; int par[MAX - 1], rank1[MAX - 1]; void init(){ for(int i = 0; i < MAX; i++){ rank1[i] = 0; par[i] = i; } } int find(int x){ if(par[x] == x)return x; else return par[x] = find(par[x]); } void unite(int x, int y){ x = find(x); y = find(y); if(x == y)return ; if(rank1[y] > rank1[x]){ par[x] = y; } else { par[y] = x; if(rank1[x] == rank1[y])rank1[y]++; } } bool same(int x, int y){ return find(x) == find(y); } void solve(){ int a, b; for(int i = 0; i < m; i++){ scanf("%d%d", &a, &b); unite(a, b); } int res = 0; for(int i = 2; i <= n; i++){ if(!same(1, i)){ unite(1, i); res++; } } printf("%d\n", res); } int main(){ while(scanf("%d", &n) && n){ scanf("%d", &m); init(); solve(); } return 0; }