2005年浙江大学计算机及软件工程研究生机试真题并查集UnionFindjava实现

来源:互联网 发布:刷脸开机软件 编辑:程序博客网 时间:2024/06/05 22:01

//并查集中将两个阵营的团队结合public static void mix(int pre[],int x,int y){int a = findRoot(pre,x);int b = findRoot(pre,y);if(a!=b)pre[a] = b;//赋有将共同的boss}

并查集在检查连通性方面非常好,一般用在求两点之间有没有路径等方面

其主要包括三个方面:

1.查找根结点(检查你所要找的点所属的根结点,对于一些联通的点来说任一节点都可以作为根结点,但对于这些联通的点来说根结点只有一个)

2.状态压缩(就是把联通的点的所有的根结点都定位同一个根结点)

3.将两个连通区域的点构建连通性。

查找根结点,状态压缩

public static int findRoot(int pre[],int x){int temp = x;while(pre[temp]!=temp)//找根{temp = pre[temp];}//状态压缩int j = x;while(pre[j]!=temp){//追本溯源凡是x上级的都把他们的根赋予他们int pr = pre[j];pre[j] = temp;j = pre[j];}return temp;}
构建连通性

//并查集中将两个阵营的团队结合public static void mix(int pre[],int x,int y){int a = findRoot(pre,x);int b = findRoot(pre,y);if(a!=b)pre[a] = b;//赋有将共同的boss}
2005年浙江大学计算机及软件工程研究生机试真题

下面是完整的实现代码

import java.util.Scanner;public class unionFind1012Jo {//并查集,首先是找到其中的根结点,再进一步进行状态压缩public static int findRoot(int pre[],int x){int temp = x;while(pre[temp]!=temp)//找根{temp = pre[temp];}//状态压缩int j = x;while(pre[j]!=temp){//追本溯源凡是x上级的都把他们的根赋予他们int pr = pre[j];pre[j] = temp;j = pre[j];}return temp;}//并查集中将两个阵营的团队结合public static void mix(int pre[],int x,int y){int a = findRoot(pre,x);int b = findRoot(pre,y);if(a!=b)pre[a] = b;//赋有将共同的boss}public static void main(String[] args) {// TODO Auto-generated method stubint[] pre = new int[1000];Scanner in = new Scanner(System.in);int count = 0;while((count = in.nextInt())!=0){for(int i = 1;i< 1000;i++){pre[i] = i;}    int num = count-1;int i = in.nextInt();while(i-->0){int a = in.nextInt();int b = in.nextInt();if(findRoot(pre,a)!=findRoot(pre,b)){mix(pre,a,b);num--;}}System.out.println(num);}}}



0 0
原创粉丝点击