poj 1308 Is It A Tree?

题目链接: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值