Error message here!

Hide Error message here!

Error message here!

Hide Error message here!

Error message here!

Close

# 并查集（Java）

AdamLeeXi 2019-02-13 16:50:00 阅读数:171 评论数:0 点赞数:0 收藏数:0

1，init() 初始化

void init()
{
for(int i = 0 ; i < parent.length ; i ++)
{
parent[i] = i ;
weight[i] = 1 ;
}
nums = parent,length ;
}

2，find()查找对应节点的根节点

find() 在查找根节点时，一直比较节点与父节点是否相同，如果相同则说明该节点为根节点

int find(int p){ while(parent[p] != p) { p = parent[p] ; } return p ;}

3，union()连接两节点对应的父节点

union()在连接两个节点的父节点时，需要比较两个节点的父节点的“重量”，将重量较大的节点看作为父节点将其合并，每合并一次，对应的nums的数量就会减一。

public static void union(int p,int q,int[] nodes,int[] weight)
{
int n = find(p,nodes) ;
int m = find(q,nodes) ;
if(n == m ) return ; //两节点的父节点相同，说明已经连接
if(weight[n] > weight[m])
{
nodes[m] = n ;
weight[n] += weight[m] ;
nums -- ;
}
else{
nodes[n] = m ;
weight[m] += weight[n] ;
nums -- ;
}
} 

1013 Battle Over Cities （25 分）

It is vitally important to have all the cities connected by highways in a war. If a city is occupied by the enemy, all the highways from/toward that city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities connected. Given the map of cities which have all the remaining highways marked, you are supposed to tell the number of highways need to be repaired, quickly.

For example, if we have 3 cities and 2 highways connecting

### Input Specification:

Each input file contains one test case. Each case starts with a line containing 3 numbers

For each of the

### Sample Input:

3 2 3
1 2
1 3
1 2 3


### Sample Output:

1
0
0这道题目是对并查集的一种典型应用，可以转化为：每次占领一个城市，并查集连接时便略过该城市，最后查看有几个互不相干的集合n，便说明了至少还需要n-1条路，代码如下：
import java.util.*;
public class BattleOverCities2 {
static int[] weight ;
static int[] parent;
static int nums ;
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
int cities = scanner.nextInt();
int checked = scanner.nextInt();
for(int i = 0 ; i < roads ; i ++)
{
}
int[] check = new int[checked] ;
for(int i = 0 ; i < checked ; i ++)
{
check[i] = scanner.nextInt(); //check[]用来记录被占领的城市
}
scanner.close();
for(int i = 0 ; i < checked ; i ++)
{
init(cities);
System.out.println(nums-2);
}
}
public static void init(int cities)
{
parent = new int[cities+1] ;
nums = cities ;
weight = new int[cities+1] ;
for(int i = 1 ; i < cities + 1 ; i ++)
{
parent[i] = i ;
weight[i] = 1 ;
}
}
public static int find(int citiy)
{
while(citiy != parent[citiy])
{
citiy = parent[parent[citiy]];
}
return citiy ;
}
public static void union(int[] road )
{
if(citiy1 == citiy2) return ;
if(weight[citiy1] > weight[citiy2])
{
parent[citiy2] = citiy1 ;
weight[citiy1] += weight[citiy2] ;
}
else{
parent[citiy1] = citiy2 ;
weight[citiy2] += weight[citiy1] ;
}
nums -- ;
}
public static void solve(int[][] road , int check)
{
for(int i = 0 ; i < road.length ; i ++)
{
continue ;
}
}
}

1021 Deepest Root （25 分）

A graph which is connected and acyclic can be considered a tree. The hight of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.

### Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer

### Output Specification:

For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print Error: K components where K is the number of connected components in the graph.

### Sample Input 1:

5
1 2
1 3
1 4
2 5


### Sample Output 1:

3
4
5


### Sample Input 2:

5
1 3
1 4
2 5
3 4


### Sample Output 2:

Error: 2 components这道题目需要求图的生成树的最大深度是多少，首先需要判断图是否都相连，这里用到了并查集，如果互不相连的集合数目大于1，则返回互不相连的个数，如果为1，则使用dfs找到生成树的最大深度，代码如下：
import java.util.*;
public class DeepestRoot {
static int nums ;
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
nums = scanner.nextInt() ;
int[] nodes = new int[nums + 1] ;
int[] weight = new int[nums + 1] ;
Map<Integer,List<Integer>> map = new HashMap<>() ;
for(int i = 1 ; i < nums + 1 ; i ++)
{
nodes[i] = i ;
weight[i] = 1 ;
}
int t = nums ;
for(int i = 1 ; i < t ; i ++)
{
int p = scanner.nextInt() ;
int q = scanner.nextInt() ;
union(p,q,nodes,weight);
if(!map.containsKey(p))
map.put(p, new ArrayList<Integer>()) ;
if(!map.containsKey(q))
map.put(q, new ArrayList<Integer>()) ;
}
scanner.close();
if(nums != 1)
{
System.out.println("Error: "+nums+" components");
}
else{
int max = 0 ;
Map<Integer,List<Integer>> mp = new HashMap<>() ;
for(int i = 1 ; i < t + 1 ; i ++)
{
if(map.get(i).size() == 1)
{
int c = dfs(map,i,0,new int[t+1],0) ;
if(c > max)
{
mp.put(c, new ArrayList<>()) ;
max = c ;
}
else if(c == max)
}
}
Collections.sort(mp.get(max));
System.out.print(mp.get(max).get(0));
for(int i = 1 ; i < mp.get(max).size() ; i ++)
{
System.out.println();
System.out.print(mp.get(max).get(i));
}
}
}
public static int dfs(Map<Integer,List<Integer>> map,int q,int count,int[] checked,int max)
{
checked[q] = 1 ;
int p = 0 ;
for(int i = 0 ; i < map.get(q).size() ; i ++)
{
int t = map.get(q).get(i);
if(checked[t] == 1) continue ;
int l = dfs(map,t,count+1,checked,max) ;
if(max < l) max = l ;
p ++ ;
}
if(p == 0) return count ;
return max ;
}
public static int find(int n,int[] parent)
{
while(parent[n] != n)
{
n = parent[n] ;
}
return n ;
}
public static void union(int p,int q,int[] nodes,int[] weight)
{
int n = find(p,nodes) ;
int m = find(q,nodes) ;
if(n == m ) return ;
if(weight[n] > weight[m])
{
nodes[m] = n ;
weight[n] += weight[m] ;
nums -- ;
}
else{
nodes[n] = m ;
weight[m] += weight[n] ;
nums -- ;
}
}
}






https://www.cnblogs.com/handsomelixinan/p/10370710.html

30万现金开奖等你来领