在hdu 1272 的基础上稍加修改就ac了
1272已经判断了无向情况下是否是树形结构,因此我们只需要多判断一下入度为0的点是否只有一个就好了
#include<iostream> #define maxn 100000+5 using namespace std; int a,b; int flag; int father[maxn]; int sign[maxn]; int r[maxn]; void ready() { for(int i=1;i<maxn;i++) r[i]=0,father[i]=i,sign[i]=0; } int dfs(int x) { if(father[x]!=x) { father[x]=father[father[x]]; } return father[x]; } void build(int x,int y) { if(x==y) flag=0; else { if(dfs(x)==dfs(y)) flag=0; else { father[dfs(x)]=dfs(y); } } r[y]++; } int main() { int casee=1; while(cin>>a>>b) { ready(); flag=1; if(a<0&&b<0){break;} if(!a&&!b) {cout<<"Case "<<casee++<<" is a tree."<<endl;continue;} build(a,b);sign[a]=sign[b]=1; while(cin>>a>>b&&a&&b) { build(a,b); sign[a]=sign[b]=1; } int k=0,d=0; for(int i=1;i<maxn;i++) { if(sign[i]&&dfs(i)==i) k++; if(sign[i]&&r[i]==0) d++; } if(k==1&&flag&&d==1) cout<<"Case "<<casee++<<" is a tree."<<endl; else cout<<"Case "<<casee++<<" is not a tree."<<endl; } return 0; }
时间: 2024-10-19 03:48:49