(并查集)合根植物



标题:合根植物


w星球的一个种植园,被分成 m * n 个小格子(东西方向m行,南北方向n列)。每个格子里种了一株合根植物。
这种植物有个特点,它的根可能会沿着南北或东西方向伸展,从而与另一个格子的植物合成为一体。


如果我们告诉你哪些小格子间出现了连根现象,你能说出这个园中一共有多少株合根植物吗?


输入格式:
第一行,两个整数m,n,用空格分开,表示格子的行数、列数(1<m,n<1000)。
接下来一行,一个整数k,表示下面还有k行数据(0<k<100000)
接下来k行,第行两个整数a,b,表示编号为a的小格子和编号为b的小格子合根了。


格子的编号一行一行,从上到下,从左到右编号。
比如:5 * 4 的小格子,编号:
1  2  3  4
5  6  7  8
9  10 11 12
13 14 15 16
17 18 19 20


样例输入:
5 4
16
2 3
1 5
5 9
4 8
7 8
9 10
10 11
11 12
10 14
12 16
14 18
17 18
15 19
19 20
9 13
13 17




样例输出:
5


其合根情况参考图[p1.png]


顺序思路。

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Test {//并查集
    static int pre[];
    static int rank[];
    public static void main(String[] args) {
    	Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		int m = input.nextInt();
		pre = new int[n*m+1];
		rank = new int[n*m+1];
		for(int i=1;i<n*m+1;i++){
			pre[i] = i;
		}
		
		Set<Integer> set = new HashSet();
		int num = input.nextInt();
		while(--num>=0){
			int a = input.nextInt();
			int b = input.nextInt();
			int fa = find(a);
			int fb = find(b);
			if(fa!=fb){
				pre[fa] = fb;
			}
			
		}
		for(int i=1;i<n*m+1;i++){
			find(i);
			set.add(pre[i]);
		}
		
		System.out.println(set.size());
    }
    
    
    
    public static int find(int x){
    	if(pre[x]==x){
    		return x;
    	}
    	return pre[x] = find(pre[x]);
    }
    
   
    
}


逆序思路:

import java.util.Scanner;
import java.util.Set;

public class Main{
	
	
	static int[] pre;
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		int m = input.nextInt();
		pre = new int[n*m+1];
		for(int i=1;i<n*m+1;i++){
			pre[i] = i;
		}
		
		int total = n*m;
		
		
		
		int sum = input.nextInt();
		while(--sum>=0){
			int a = input.nextInt();
			int b = input.nextInt();
			
			int fa = find(a);
			int fb = find(b);
			if(fa!=fb){
				pre[fa] = fb;
				total--;
			}
			
		}
		System.out.println(total);
		
	}
	
	
	//递归压缩路径
	public static int find(int n){
		if(pre[n]==n){
			return n;
		}
		return pre[n] = find(pre[n]);
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SUNbrightness

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值