还是并查集,不过我觉得最后判断最少路径自己处理的麻烦了,得去看看大神代码.......
code:
/*
ID: yueqiq
PROG: numtri
LANG: C++
*/
#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <limits>
#include <vector>
#include <bitset>
#include <string>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <string.h>
#include <iostream>
#include <algorithm>
#define Si set<int>
#define LL long long
#define pb push_back
#define PS printf(" ")
#define Vi vector<int>
#define LN printf("\n")
#define lson l,m,rt << 1
#define rson m+1,r,rt<<1|1
#define SD(a) scanf("%d",&a)
#define PD(a) printf("%d",a)
#define SET(a,b) memset(a,b,sizeof(a))
#define FF(i,a) for(int i(0);i<(a);i++)
#define FD(i,a) for(int i(a);i>=(1);i--)
#define FOR(i,a,b) for(int i(a);i<=(b);i++)
#define FOD(i,a,b) for(int i(a);i>=(b);i--)
#define readf freopen("input.txt","r",stdin)
#define writef freopen("output.txt","w",stdout)
const int maxn = 1001;
const int INF = 0x3fffffff;
const int dx[]={0,1,0,-1};
const int dy[]={1,0,-1,0};
const double pi = acos(-1.0);
using namespace std;
int N,M;
bool use[maxn];
int num[maxn],pre[maxn];
void Make_Set(int k){
num[k]=1;
pre[k]=k;
}
int Find_Set(int k){
if(k!=pre[k]){
pre[k]=Find_Set(pre[k]);//回溯赋值,压缩路径
}
return pre[k];
}
//union the set of x,y
void Union_Set(int x,int y){
x=Find_Set(x);
y=Find_Set(y);
if(x==y) return;
if(num[x]>=num[y]){
pre[y]=x;
num[x]+=num[y];
}else{
pre[x]=y;
num[y]+=num[x];
}
}
int main()
{
while(~scanf("%d",&N)&&N){
SD(M);
SET(use,false);
FOR(i,1,N) Make_Set(i);
int a,b;
FF(i,M){
SD(a);SD(b);
Union_Set(a,b);
}
int k=0;
FOR(i,1,N){
int t=Find_Set(i);
if(!use[t]){
k++;
use[t]=true;
}
}
//puts("------------------------");
PD(k-1);LN;
//puts("------------------------");
}
return 0;
}