题目地址:poj 1308
首先注意trick:空树(直接 0,0) 也是树
然后,首先用并查集保证是一颗无向树的结构。 没有环,而且合并的次数等于结点的次数减1.
然后保证没有一个结点被指向两次,这样就符合题意了,只是,不题目没说数据范围.... 搞个100000;
代码:
#include<iostream>
#include<set>
#include<map>
using namespace std;
const int maxn=100000;
int fa[maxn];
int find(int x)
{
return fa[x]==x?x:fa[x]=find(fa[x]);
}
void init()
{
for(int i=0;i<maxn;i++)
{
fa[i]=i;
}
}
set<int> s;
set<int> s_to;
int n,m;
int cnt=0;
int main()
{
int a,b;
int index=0;
init();
bool ok=1;
n=0;
int cc_minus=0;
while(cin>>a>>b)
{
if(a==-1&&b==-1) break;
if(a==0&&b==0)
{
if((ok&&s.size()-1==cc_minus)||s.size()==0) cout<<"Case "<<++index<<" is a tree."<<endl;
else cout<<"Case "<<++index<<" is not a tree."<<endl;
init();
ok=1;
cc_minus=0;
s.clear();
s_to.clear();
}
else{
s.insert(a);
s.insert(b);
if(s_to.find(b)!=s_to.end())
{
ok=0;
}
else
{
s_to.insert(b);
}
int x=find(a-1);
int y=find(b-1);
if(x!=y)
{
fa[x]=y;
cc_minus++;
}
else ok=0;
}
}
}