| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 22790 | Accepted: 7814 |
Description
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 by lines with arrowheads. The first two of these are trees, but the last is not.

In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these you are to determine if the collection satisfies the definition of a tree or not.
Input
Output
Sample Input
6 8 5 3 5 2 6 4 5 6 0 0 8 1 7 3 6 2 8 9 7 5 7 4 7 8 7 6 0 0 3 8 6 8 6 4 5 3 5 6 5 2 0 0 -1 -1
Sample Output
Case 1 is a tree. Case 2 is a tree. Case 3 is not a tree.
题意:判断由这些组成的树是不是一棵树;
解题:并查集的应用;
注意:
1.空树也是树;
2.不能有环;
3.不能是森林;
参考代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int father[30000+1],rank[30000+1];
bool flag[30000+1];
void init(int n){
for (int i=0;i<=n;i++){
father[i]=i;
rank[i]=1;
flag[i]=false;
}
}
int find(int x){
if (x!=father[x])
father[x] = find(father[x]); //路径压缩
return father[x];
}
void Union(int x,int y){
int i=find(x);
int j=find(y);
if (i==j)
return;
if (rank[i]<rank[j])
father[i]=j;
else{
father[j]=i;
if (rank[i]==rank[j]) //两棵树同高
rank[i]++;
}
}
bool same(int i,int j){
if (find(i)==find(j))
return true;
return false;
}
int main(){
int a,b,t=1;
while (cin>>a>>b){
if (a==b&&a==-1)
break;
if (a==0&&b==0){
cout<<"Case "<<t++<<" is a tree."<<endl;
continue;
}
flag[a]=flag[b]=true;
init(1000);
bool tree=true;
if (a==b)
tree=false;
else
Union(a,b);
int first=a;
while (cin>>a>>b){
if (a==0&&b==0)
break;
if (find(a)==find(b))
tree=false;
flag[a]=flag[b]=true;
Union(a,b);
}
for (int i=1;i<=1000;i++){
if (flag[i]==true&&find(i)!=find(first)){
tree=false;
break;
}
}
if (tree==false)
cout<<"Case "<<t++<<" is not a tree."<<endl;
else
cout<<"Case "<<t++<<" is a tree."<<endl;
}
return 0;
}
2959



被折叠的 条评论
为什么被折叠?



