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.
There is a unique sequence of directed edges from the root to each node.
For example, consider the illustrations below, in which nodes are represented by circles and edges are represented
题意:给定一些点,判断最后是不是构成一棵树。
题解:看上去这道题和HDU1272一样,只不过1272可以水过。。这道题的坑点有点多,一是要判断入度不能>=2,二是判断不能有多个根点,最后要处理奇怪的输入输出,PS:本人因为输出没有.而wa掉多次。。
AC代码:
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 1000005;
int vis[maxn];
int n,m;
int fa[maxn];
int rude[maxn];
int fi(int x)
{
return fa[x]==x?x:fa[x]=fi(fa[x]);
}
void unionset(int x,int y)
{
int p1= fi(x);
int p2= fi(y);
if(p1==p2)return;
fa[p1]=p2;
}
void intc()
{
for(int i=1;i<=100000;i++)
{
fa[i]=i;
vis[i]=0;
rude[i]=0;
}
}
int kk()
{
int kk=0;
for(int i=1;i<=100000;i++)
{
if(vis[i]&&fa[i]==i)kk++;
if(vis[i]&&rude[i]>=2)kk=2;
}
return kk;
}
int main()
{
int ans = 1;
int t=1;
while(cin>>n>>m)
{
if(ans==1)
{
ans=2;
intc();
}
if(n<=-1&&m<=-1)break;
if(n==0&&m==0)
{
if(kk()>=2)ans=0;
if(ans)printf("Case %d is a tree.\n",t++);
if(ans==0)
{
printf("Case %d is not a tree.\n",t++);
ans=2;
}
intc();
continue;
}
vis[n]=1;
vis[m]=1;
if(fi(n)==fi(m))ans=0;
else unionset(n,m);
rude[m]++;
}
return 0;
}