题目链接:Is It A Tree?
判断所给出的关系能否构成一棵树。这个棵树是有向的。比如1 2 1 3 4 2 0 0 这就不是题目中所说的树。注意空集也是树,比如0 0 是一棵树。
坑爹的是。HDU和POJ的一样的题目。
HDU 一个孤点算一棵树。
POJ一个孤点不算一棵树。
HDU AC代码:
//HDU 1325
#include<stdio.h>
#include<string.h>
#include<set>
using namespace std;
const int maxn=100000+10;
int father[maxn];
int rd[maxn];//节点的入度。
int cas,s;
set<int> ss;
set<int>::iterator t;
int find(int x)
{
if(x==father[x])
return x;
return father[x]=find(father[x]);
}
void merge(int x,int y)
{
int fx,fy;
fx=find(x);
fy=find(y);
if(fx!=fy)
{
father[fx]=fy;
s++;
}
}
void init()
{
s=0;
int i;
ss.clear();
for(i=1;i<=maxn;i++)
father[i]=i;
memset(rd,0,sizeof rd);
}
int main()
{
int a,b;
cas=1;
init();
while(scanf("%d %d",&a,&b)!=EOF)
{
if(a==-1 && b==-1) break;
if(a==0 && b==0)
{
int cnt,mark=0,count=0,num=0;
for(t=ss.begin();t!=ss.end();t++)
{
cnt=*t;
if(rd[cnt]>1)
mark=1;
else if(rd[cnt]==0)
count++;
else if(rd[cnt]==1)
num++;
}
if(ss.size()==0)//空集也是树
{
printf("Case %d is a tree.\n",cas++);
init();
continue;
}
if(ss.size()==1)//一个孤点也是一棵树
{
printf("Case %d is a tree.\n",cas++);
init();
continue;
}
if(s==ss.size()-1)//无环。
{
if(mark==0 && count==1 && num+count==ss.size())//所有节点中只有一个节点入度为0,其他节点入度都为1.
printf("Case %d is a tree.\n",cas++);
else
printf("Case %d is not a tree.\n",cas++);
}
else
printf("Case %d is not a tree.\n",cas++);
init();
}
else
{
rd[b]++;
merge(a,b);
ss.insert(a),ss.insert(b);
}
}
return 0;
}
POJ AC代码:
// 1 1 0 0 不是一棵树
#include<stdio.h>
#include<string.h>
#include<set>
using namespace std;
const int maxn=100000+10;
int father[maxn];
int rd[maxn];
int cas,s;
set<int> ss;
set<int>::iterator t;
int find(int x)
{
if(x==father[x])
return x;
return father[x]=find(father[x]);
}
void merge(int x,int y)
{
int fx,fy;
fx=find(x);
fy=find(y);
if(fx!=fy)
{
father[fx]=fy;
s++;
}
}
void init()
{
s=0;
int i;
ss.clear();
for(i=1;i<=maxn;i++)
father[i]=i;
memset(rd,0,sizeof rd);
}
int main()
{
int a,b;
cas=1;
init();
while(scanf("%d %d",&a,&b)!=EOF)
{
if(a==-1 && b==-1) break;
if(a==0 && b==0)
{
int cnt,mark=0,count=0,num=0;
for(t=ss.begin();t!=ss.end();t++)
{
cnt=*t;
if(rd[cnt]>1)
mark=1;
else if(rd[cnt]==0)
count++;
else if(rd[cnt]==1)
num++;
}
if(ss.size()==0)
{
printf("Case %d is a tree.\n",cas++);
init();
continue;
}
if(ss.size()==1)
{
printf("Case %d is not a tree.\n",cas++);
init();
continue;
}
if(s==ss.size()-1)
{
if(mark==0 && count==1 && num+count==ss.size())
printf("Case %d is a tree.\n",cas++);
else
printf("Case %d is not a tree.\n",cas++);
}
else
printf("Case %d is not a tree.\n",cas++);
init();
}
else
{
rd[b]++;
merge(a,b);
ss.insert(a),ss.insert(b);
}
}
return 0;
}