题意:判断一个图是否为树
思路:满足两个条件,只有一个根,非根节点入度只能为1
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int maxn=10000;
int father[maxn];//父节点
int into[maxn];//入度
int flag[maxn];//标记是否出现
bool istree;//合并时 中间标记
void InIt()//初始化
{
for(int i=1; i<=maxn; i++)
{
father[i]= i;
into[i]= 0;
flag[i]= 1;
}
}
int find(int v) //查找
{
if(father[v]!=v)
father[v]=find(father[v]);
return father[v];
}
void merge(int x,int y) //合并
{
int xf=find(x);
int yf=find(y);
if(xf==yf)
{
istree=0;
return ;
}
father[xf]= yf;
}
int main()
{
int x,y,t,n;
t=1;
while(scanf("%d%d",&x,&y)!=EOF)
{
istree=1;
n=0;
InIt();//初始化
if(x<0||y<0) return 0;
if(x==0&&y==0)
{
cout<<"Case "<<t++<<" is a tree."<<endl;
continue;
}
if(x!=y)into[y]=1;
if(flag[x]==1)
{
n++;
flag[x]=0;
if(flag[y]==1)
{
n++;
flag[y]=0;
}
merge(x,y);
while(scanf("%d%d",&x,&y),(x!=0&&y!=0))
{
if(x!=y)
into[y]=1;
if(flag[x]==1)
{
n++;
flag[x]=0;
}
if(flag[y]==1)
{
n++;
flag[y]=0;
}
merge(x,y);
}int sum=0;
for(int i=1; i<=maxn; i++)
sum+=into[i];
if(sum==n-1&&istree)
cout<<"Case "<<t++<<" is a tree."<<endl;
else
cout<<"Case "<<t++<<" is not a tree."<<endl;
}
}return 0;
}
#include <stdio.h>
#include <memory.h>
const int MAX_SIZE = 105;
int parent[MAX_SIZE];
bool flag[MAX_SIZE];
void make_set(){ //初始化
for(int x = 1; x < MAX_SIZE; x ++){
parent[x] = x;
flag[x] = false;
}
}
int find_set(int x){ //寻找根节点,带路径压缩
if(x != parent[x])
parent[x] = find_set(parent[x]);
return parent[x];
}
void union_set(int x, int y){ //合并
x = find_set(x);
y = find_set(y);
if(x == y) return;
parent[y] = x;
}
bool single_root(int n){ //判断是不是只有一个根,条件(1)
int i = 1;
while (i <= n && !flag[i]){
++i;
}
int root = find_set(i);
while (i <= n){
if (flag[i] && find_set(i) != root){
return false;
}
++i;
}
return true;
}
int main(){
int x, y;
bool is_tree = true;
int range = 0;
int idx = 1;
make_set();
while (scanf("%d %d", &x, &y) != EOF){
if (x < 0 || y < 0){
break;
}
if (x == 0 || y == 0){
if (is_tree && single_root(range)){
printf("Case %d is a tree.\n", idx++);
}
else{
printf("Case %d is not a tree.\n", idx++);
}
is_tree = true;
range = 0;
make_set();
continue;
}
if (!is_tree){
continue;
}
range = x > range ? x : range;
range = y > range ? y : range;
flag[x] = flag[y] = true;
if (find_set(x) == find_set(y)){ //如果两者属于一个集合(也就是有共同祖先),并且两者还有父子关系,那么无法形成树,条件2
is_tree = false;
}
union_set(x, y);
}
return 0;
}</span>