poj 1308(并查集)

package com.liang.poj;

import java.util.Scanner;

public class Test1308_Union_Fand_set {
	static int N = 100001;
	static int[] node = new int[N];
	static int[] rank = new int[N];
	static int count = 1;
	static boolean tag = true;

	public static void main(String[] args) throws Exception {
		Scanner scan = new Scanner(System.in);
		makeSet();
		while (scan.hasNext()) {

			int a = scan.nextInt();
			int b = scan.nextInt();

			if (a == -1 && b == -1) {
				break;
			}

			if (a == 0 && b == 0) {
				if (tag) {
					if (!judge()) {
						System.out.println("Case " + count++ + " is not a tree.");
					} else {
						System.out.println("Case " + count++ + " is a tree.");
					}
				} else {
					System.out.println("Case " + count++ + " is not a tree.");
				}
				makeSet();
			} else {
				merge(a, b);
			}

		}
	}

	public static void makeSet() { // 初始化单元素集合
		tag = true;
		for (int i = 1; i < N; i++) {
			node[i] = 0;
			rank[i] = 0;
		}
	}

	public static int find(int x) { // 带路径压缩的查找
		if (node[x] == 0) {
			node[x] = x;
			return x;
		} else {
			if (x != node[x]) {
				x = find(node[x]);
			}
			return x;
		}
	}

	public static void merge(int a, int b) { // 合并集合a,集合b
		int fa = find(a);
		int fb = find(b);
		if (fa == fb) {
			if (fa == 0 && fb == 0) {

				if (rank[fa] >= rank[fb]) {
					node[fb] = fa;
					rank[fa]++;
				} else {
					node[fa] = fb;
					rank[fb]++;
				}
			} else {
				tag = false;
			}
		} else {
			if (rank[fa] >= rank[fb]) {
				node[fb] = fa;
				rank[fa]++;
			} else {
				node[fa] = fb;
				rank[fb]++;
			}
		}
	}

	public static boolean judge() {
		int sum = 0;
		for (int i = 1; i < node.length; i++) {
			if (node[i] == 0) {
				continue;
			} else {
				if (i == node[i]) {
					sum++;
				}
				if (sum >= 2) {
					return false;
				}
			}
		}
		return true;
	}

}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值