您的位置:首页 > 其它

【并查集】HDU 1325 Is It A Tree?

2017-04-27 10:01 411 查看
推断是否为树

森林不是树

空树也是树

成环不是树

数据:

1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 1 0 0

1 2 2 3 4 5 0 0

2 5 0 0

ans:

no

no

yes

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <malloc.h>
#include <ctype.h>
#include <math.h>
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
typedef long long LL;
const int maxn =10000+5;
const int maxe = 15000+5;
const int INF = 460002326;
const int mod = 1000000009;//q[i]表示点i 相应的点 rank[i]表示入度
int fa[maxn],q[maxn],rank[maxn],taj,flag;//taj表示当前点的编号个数
void init()
{
flag=0;
taj=1;
for(int i=0; i<maxn; i++)
fa[i]=i,q[i]=-1,rank[i]=0;
}
int find(int x)
{
if(fa[x]==x)
return x;
else
{
fa[x]=find(fa[x]);
return fa[x];
}
}
void merge(int x,int y)
{
int fx=find(x),fy=find(y);
if(fx==fy)
{
flag=1;//反复
return ;
}
else
{
fa[fy]=fx;
rank[y]++;//入度+1
return ;
}
}
void dian(int a,int b)
{
if(q[a]==-1)
q[a]=taj++;
if(q[b]==-1)
q[b]=taj++;
}
int main()
{
int a,b,cas=0;
//   freopen("in.txt","r",stdin);
while(scanf("%d%d",&a,&b),a+b>=0)
{
init();//初始化
if(a==0&&b==0)// 0 0 也算树
{
printf("Case %d is a tree.\n",++cas);
continue;
}
a=q[a],b=q[b];
merge(a,b);
while(scanf("%d%d",&a,&b))
{
if(a+b==0) break;
dian(a,b);
a=q[a],b=q[b];
merge(a,b);
}
a=0;
for(int i=1; i<maxn; i++)
find(i);
for(int i=1; i<maxn; i++)
{
if(q[i]!=-1&&fa[q[i]]==q[i])//根节点
a++;
if(rank[i]>1)
flag=1;
}
printf("Case %d is ",++cas);
if(a==1&&flag==0&&taj>2)
puts("a tree.");
else puts("not a tree.");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: