本文介绍了一个使用并查集实现的判断输入边集是否构成树的算法,并通过一个具体实例(POJ 1308 Is It A Tree)进行了演示。文章详细解释了如何确保每个节点恰好只有一个父节点且所有节点相互连通。
是一个判断是否为树的题目
下面是树的定义
There is exactly one node, called the root, to which no directed edges point. //根节点没有父节点
Every node except the root has exactly one edge pointing to it. //每一个节点有且仅有一个父节点
//这就是判断不要fv!=v且fv!=fu的原因 如果有一种相等就会导致有两个父节点了哦
There is a unique sequence of directed edges from the root to each node. //这是说各个节点连通
要另外判断一下是否是空树
//poj 1308 Is It A Tree
//并查集
//第一次错误 没有考虑到样例三的情况 根在合并前还没有出现的情况
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
const int maxn=100000;
int pa[maxn];
int findset(int x){ return pa[x]!=x?pa[x]=findset(pa[x]):x;}
int k=0;
int main()
{
int u,v;
while(scanf("%d %d",&u,&v)&&u>=0&&v>=0)
{
for(int i=1;i<maxn;i++)
{
pa[i]=i;
}
map<int,int> m;//这里用map来映射一个每个点的值和编号 防止值过大 开不下
int num=0;
bool flag=true;
if(u==0&&v==0){ printf("Case %d is a tree.\n",++k); continue; }
while(u!=0&&v!=0)
{
if(m.count(u)==0) m[u]=++num;
if(m.count(v)==0) m[v]=++num;
int fu=findset(m[u]),fv=findset(m[v]);
if(fu==fv) flag=false;//每一个节点有且仅有一个父节点
if(fv!=m[v]) flag=false;
else{pa[m[v]]=fu;}
scanf("%d %d",&u,&v);
}
int fa=findset(1);
for(int i=2;i<=num&&flag;i++)//这是说各个节点连通
{
if(findset(i)!=fa) flag=false;
}
if(flag){printf("Case %d is a tree.\n",++k); }
else {printf("Case %d is not a tree.\n",++k); }
}
return 0;
}