先做了树的判定,在做了这道题,花费一上午的时间,对于并查集的使用,用深刻许多,对于这道题我们可以这样做:
1,首先判断有几个集合
2,判断每个集合是不是都能成树
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int out[10003];
int num1[250003],num2[250003];
int father[100001];
int find(int x)
{
if(x==father[x])
return father[x];
return father[x] = find(father[x]);
}
bool uniom(int a,int b)
{
int x = find(a);
int y = find(b);
if(x==y)return true;
return false;
}
void merge(int a,int b)
{
int x = find(a);
int y = find(b);
if(x<=y)
father[x] = y;
else
father[y] = x;
}
void init(int n)
{
memset(out,0,sizeof(out));
for(int i=1;i<=n;i++)
father[i] = i;
}
int main()
{
int n,m;
int a,b;
int count = 1;
while(~scanf("%d%d",&n,&m),n+m)
{
init(n);
int cn = 0;
for(int i=1;i<=m;i++)
{
scanf("%d%d",&a,&b);
num1[++cn] = a;
num2[cn] = b;
}
int tolly = n;
for(int i=1;i<=cn;i++)
{
if(uniom(num1[i],num2[i]))
out[find(num1[i])] = 1;
else
{
merge(num1[i],num2[i]);
tolly--;
}
}
for(int i=1;i<=n;i++)
if(father[i]==i &&out[i])tolly--;
if(tolly==0)printf("Case %d: No Trees.\n",count++);
else
if(tolly==1)
printf("Case %d: There is one tree.\n",count++);
else
printf("Case %d: A forest of %d trees.\n",count++,tolly);
}
}