Loading...

并查集的实现

在这里插入图片描述 在这里插入图片描述

代码求解

father数组: 每个集合元素往上的指针,下标对应节点编号,初始时每个节点指向自己。

size数组:记录每个集合的大小,初始时每个集合大小为1。

stack数组 : 用于扁平化过程中收集沿途节点。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
public static int MAXN = 1000001;
	public static int[] father = new  int[MAXN];
	public static int[] size = new int[MAXN];
	public static int[] stack = new int[MAXN];

	public static int n;

	public static void build(){
		for(int i=0;i<=n;i++){
			father[i]=i;
			size[i]=i;
		}
	}

	public static int find(int i){
		int size = 0;
		while (i!=father[i]) {
			stack[size++]=i;
			i=father[i];
		}

		while (size>0) {
			father[stack[--size]]=i;
		}

		return i;
	}

	public static boolean isSameSet(int x,int y){
		return find(x)==find(y);
	}

	public static void union(int x,int y){
		int fx = find(x);
		int fy = find(y);

		if (fx!=fy) {
			if(size[fx]>=size[fy]){
				size[fx]+=size[fy];
				father[fy]=fx;
			}else{
				size[fy]+=size[fx];
				father[fx]=fy;
			}
		}
	}

	public static void main(String[] args)throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StreamTokenizer in = new StreamTokenizer(br);
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

		while (in.nextToken()!=StreamTokenizer.TT_EOF) {
			n = (int)in.nval;
			build();
			in.nextToken();
			int m = (int)in.nval;

			for(int i=0;i<m;i++){
				in.nextToken();
				int op = (int)in.nval;
				in.nextToken();
				int x = (int)in.nval;
				in.nextToken();
				int y = (int)in.nval;
				if(op==1){
					out.println(isSameSet(x, y)?"Yes":"No");
				}else{
					union(x, y);
				}
			}
		}
		out.flush();
		out.close();
		br.close();
	}
Code Road Record