⭐⭐⭐⭐⭐【并查集+树】Is It A Tree?

题目描述

代码实现

//其实可以不用并查集做吧,直接DFS开搞啊啊 
#include <cstdio>
#include <unordered_map>
using namespace std;
const int maxn = 10010;

unordered_map<int,int> father;
unordered_map<int,int> inDegree;

int find(int x){
	if(father[x] == x){
		return x;
	}else{
		int root = find(father[x]);
		father[x] = root;
		return root;
	}
}

void Union(int u,int v){
	int fatherU = find(u);
	int fatherV = find(v);
	if(fatherU != fatherV){
		father[fatherV] = fatherU;
	}
	return;
}

int main(){
	int u,v;
	bool isTree=true;
	int cnt=1;
	while(scanf("%d %d",&u,&v)!=EOF&&u!=-1&&v!=-1){
		if(u==0&&v==0){
			int check=0;
			int root;
			for(unordered_map<int,int>::iterator it=father.begin();it!=father.end();it++){
				//printf("father:%d\n",find(it->first));
				if(find(it->first)==it->first){
					root = it->second;
					check++;
				}
			}
			
			if(check>1){
				isTree=false;
			}else{
				if(inDegree.count(root)!=0){
					isTree=false;
				}
			}
			
			
			if(isTree){
				printf("Case %d is a tree.\n",cnt);
			}else{
				printf("Case %d is not a tree.\n",cnt);
			}
			
			//初始化操作
			father.clear();
			inDegree.clear();
			isTree=true;
			cnt++;
		}else{
			//判断u是否访问过
			if(father.count(u)==0){
				father[u]=u;
			}
			
			//判断v是否访问过
			if(father.count(v)==0){
				father[v]=find(u);
			}else{
				Union(u,v);				
			}
			
			inDegree[v]++;
			if(inDegree[v]>1){
				//printf("There\n");
				isTree=false;
			}	
		}
	}
	return 0;
}

码后反思

  1. 这道题我第一次做,做错了,因为没有考虑到根结点root的入度一定要为0,所以没有过题!
  2. 这道题其实就是判断两个方面:
    1. 图连通;
    2. 根节点入度为0,其他结点入度为1;
      其中要先判断第一个图连通,再判断根节点的入度为0。因为不连通的话,就会有很多根结点了。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值