您的位置:首页 > 其它

poj 1308 Is It A Tree?

2012-11-21 12:17 330 查看
题目链接:http://poj.org/problem?id=1308

题目大意:

给一些有向边(父结点指向子结点),判断该有向图是不是一颗树.

题目思路:

利用并查集.

合并的时候,

(1)当前子节点必然不能有父节点.

(2)当前父节点的祖先不能指向子节点.

其余随便.

ps:空树也是一颗树.

代码:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

#define ll long long
#define ls rt<<1
#define rs ls|1
#define lson l,mid,ls
#define rson mid+1,r,rs
#define middle (l+r)>>1
#define eps (1e-8)
#define type int
#define clr_all(x,c) memset(x,c,sizeof(x))
#define clr(x,c,n) memset(x,c,sizeof(x[0])*(n+1))
#define MOD 1000000009
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define _max(x,y) (((x)>(y))? (x):(y))
#define _min(x,y) (((x)<(y))? (x):(y))
#define _abs(x) ((x)<0? (-(x)):(x))
#define getmin(x,y) (x= (x<0 || (y)<x)? (y):x)
#define getmax(x,y) (x= ((y)>x)? (y):x)
template <class T> void _swap(T &x,T &y){T t=x;x=y;y=t;}
int TS,cas=1;
const int M=1000000+5;
int n,m,s,a,b;
int fa[M];
map<int,int>mp;

int find(int x){
return (fa[x]==-1)? x:(fa[x]=find(fa[x]));
}

bool uni(int x,int y){
int xf=find(x),yf=find(y);
if(xf==yf || x!=xf) return 0;
fa[x]=yf;
return 1;
}

void run(){
int i,j;
if(a==0 && b==0){printf("Case %d is a tree.\n",cas++);return;}
clr_all(fa,-1);
mp.clear();
bool ok=1;
m=0,n=1;
mp[a]=++m;
mp[b]=++m;
ok=uni(mp[b],mp[a]);
while(scanf("%d%d",&a,&b) && (a || b)) if(ok){
n++;
if(mp[a]==0) mp[a]=++m;
if(mp[b]==0) mp[b]=++m;
if(ok) ok=uni(mp[b],mp[a]);
}
if(ok){
if(m-1!=n) ok=0;
int rt=find(1);
for(i=2;i<=m;i++)
if(find(i)!=rt){ok=0;break;}
}
if(ok) printf("Case %d is a tree.\n",cas++);
else printf("Case %d is not a tree.\n",cas++);
}

void preSof(){
}

int main(){
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
preSof();
//run();
while(~scanf("%d%d",&a,&b) && (a!=-1 || b!=-1)) run();
//for(scanf("%d",&TS);cas<=TS;cas++) run();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: