poj 1703 java

本文介绍了一个使用Java实现的并查集算法案例,该算法用于处理元素间的连接关系,并通过一系列查询来判断元素是否属于同一集合。文章展示了如何通过并查集解决实际问题,包括查找与合并操作的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.*;

public class test {

	static int a[];
	static int ans[];
	
	public static void main(String[] args)throws Exception {
		
		BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
		
		int test = Integer.parseInt(buf.readLine());
		
		for(int t=0;t<test;t++){
			String str[] = buf.readLine().split(" ");
			int n = Integer.parseInt(str[0]);
			int m = Integer.parseInt(str[1]);
			
			a = new int[n+1];
			ans = new int[n+1];
			for(int i=1;i<=n;i++)
				a[i] = i;
			
			for(int i=0;i<m;i++){
				str = buf.readLine().split(" ");
				int x = Integer.parseInt(str[1]);
				int y = Integer.parseInt(str[2]);
				if(str[0].equals("D")){
					Union(x,y);
				}else{
					if(n == 2)
						System.out.println("In different gangs.");
					else if(find(x)==find(y)){
						if(ans[x]==ans[y])
							System.out.println("In the same gang.");
						else
							System.out.println("In different gangs.");
					}else
						System.out.println("Not sure yet.");
				}
			}
			
		}

	}

	public static int find(int x) {
		if(a[x]==x)
			return x;
		int rt = find(a[x]);
		ans[x] = (ans[x]+ans[a[x]])%2;    // 类别偏移量         假设 之前 ans[fx]被赋值为1  因为原为0,所以在其下的子结点都需要改为与原来相反的值
		return a[x] = rt;
	}

	public static void Union(int x, int y) {
		
		int fx = find(x);
		int fy = find(y);
		a[fx] = fy;
		ans[fx] = (ans[x]+ans[y]+1)%2;        // 祖先结点 的ans值永远是 0     所以由x,y两点来判断 它们祖先结点 是否在同一部落
		                                      //ans[x],ans[y] 都为0或1 说明都跟自己的祖先结点 同一部落或不同部落  则 x的祖先与y的祖先也应该
	}                                         //在不同部落  此时 ans[fx] = 1;ans[fy]值 依旧是0

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值