登 录
判断是不是一颗树,简单的并查集
只要注意几种情况就可以了:
1. 0 0 空树也是树
2. 1 1 不是树,自己不能指向自己
3. 1 2 2 1 不能形成环
4. 1 2 3 4 森林不是树
其实只要注意0 0,其它的几种情况就是树的定义/* * File: main.cpp * Author: mi * * Created on 2011年2月20日, 下午8:42 */ #include <cstdlib> #include <stdio.h> #include <string.h> #define N 150 using namespace std; /* * */ int father[N],rank[N]; void make_set() { int i; for(i=1;i<150;i++) { father[i]=i; rank[i]=0; } } int find_set(int x) { if(x!=father[x]) father[x]=find_set(father[x]); return father[x]; } void Union(int x,int y) { int rootx=find_set(x),rooty=find_set(y); if(rootx==rooty) return ; father[rooty]=rootx; } int main(int argc, char** argv) { int a,b,c=1,flag,first; while(scanf("%d%d",&a,&b)&&(a>=0||b>=0)) { if(a==0&&b==0) { printf("Case %d is a tree./n",c++); continue; } memset(father,0,sizeof(father)); memset(rank,0,sizeof(rank)); flag=0; make_set(); rank[a]=rank[b]=1; first=a; if(a==b) flag=1; else Union(a,b); while(scanf("%d%d",&a,&b)&&(a||b)) { int rootx=find_set(a),rooty=find_set(b); rank[a]=rank[b]=1; if(rootx==rooty) flag=1; else Union(a,b); } for(int i=1;i<150;i++) if(rank[i]&&find_set(i)!=find_set(first)) flag=1; if(flag) printf("Case %d is not a tree./n",c++); else printf("Case %d is a tree./n",c++); } return 0; }
抱歉!评论已关闭.