跳到正文

个人记录

带权并查集

AprXIX_SheezpEnd约 22 分钟
原文
文章信息与版本

文章信息

发布
2025年3月3日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 22 分钟

版本

  1. v2当前
  2. v1

什么是带权并查集

带权并查集就是在普通并查集的前提下,维护了每个点与最上方的点的关系。这样说起来或许比较抽象,那么我们可以根据具体题目来理解

例题1

问题:

有nn个数字,下标11 ~ nn,但是并不知道每个数字是多少

先给出mm个数字段的累加和,再查询qq个数字段的累加和

给出数字段累加和的操作 ll rr vv,代表ll ~ rr范围上的数字,累加和为vv

查询数字段累加和的操作 ll rr,代表查询ll ~ rr范围上的数字累加和

请根据m个给定,完成q个查询,如果某个查询无法给出答案,打印”UNKNOWN”

1 <= n, m, q <= 10^5

https://www.luogu.com.cn/problem/P8779

code:

C++
#include <bits/stdc++.h>
using namespace std;

const long long N = 1e5 + 10;

long long n, m, q;

long long f[N], val[N];

long long find(long long x){
	if(f[x] != x){
		long long fa = f[x];
		f[x] = find(f[x]);
		val[x] += val[fa];//更新每个点到头节点的距离,是固定写法
	}
	return f[x];
}

void read(){
	cin >> n >> m >> q;
	n++;
	for(long long i = 1;i <= n; i++) f[i] = i;
	return ;
}

void compute(){
	for(long long i = 1;i <= m; i++){
		long long l, r, s;
		cin >> l >> r >> s;
		r++;
		long long x = find(l);
		long long y = find(r);
		if(x != y){
			f[x] = y;
			val[x] = val[r] - val[l] + s;//合并两个并查集 固定公式“后-前+权值”
		}
	}
	for(long long i = 1;i <= q; i++){
		long long l, r;
		cin >> l >> r;
		r++;
		long long x = find(l);
		long long y = find(r);
		if(x != y){
			cout << "UNKNOWN\n";
		}
		else{
			cout << val[l] - val[r] << '\n';
		}
	}
	return ;
}

int main(){
	read();
	compute();
	return 0;
}

例题2

问题:

一共有30000搜战舰,编号1~30000,一开始每艘战舰各自成一队

如果若干战舰变成一队,那么队伍里的所有战舰竖直地排成一列

实现如下两种操作,操作一共调用t次

M l r : 合并l号战舰所在队伍和r号战舰所在队伍

l号战舰的队伍,整体移动到,r号战舰所在队伍的最末尾战舰的后面

如果l号战舰和r号战舰已经是一队,不进行任何操作

C l r : 如果l号战舰和r号战舰不在一个队伍,打印-1

如果l号战舰和r号战舰在一个队伍,打印它俩中间隔着几艘战舰

1 <= t <= 5 * 10^5

https://www.luogu.com.cn/problem/P1196

code:

C++
#include <bits/stdc++.h>
using namespace std;

int f[30001], val[30001], sz[30001];

int t;

int n = 30000;

void read(){
	cin >> t;
	for(int i = 1;i <= n; i++) f[i] = i, val[i] = 0, sz[i] = 1;
	return ;
}

int find(int x){
	if(f[x] != x){
		int fa = f[x];
		f[x] = find(f[x]);
		val[x] += val[fa];//固定写法 维护到头结点的距离
	}
	return f[x];
}

void compute(){
	for(int i = 1;i <= t; i++){
		char op;
		int x, y;
		cin >> op >> x >> y;
		if(op == 'M'){
			x = find(x);
			y = find(y);
			f[x] = y;
			val[x] = sz[y];//手动赋到头节点的值
			sz[y] += sz[x];//这里是维护了并查集大小
		}
		else{
			int xx = find(x);
			int yy = find(y);
			if(xx != yy){
				cout << -1 << '\n';
			}
			else{
				cout << abs(val[x]-val[y])-1 << '\n';
			}
		}
	}
	return ;
}

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	read();
	compute();
	return 0;
}

例题3

问题:

所有变量都用字符串表示,并且给定若干组等式

比如等式 [“ab”, “ef”] = 8,代表ab / ef = 8

[“ct”, “ef”] = 2,代表ct / ef = 2

所有等式都是正确的并且可以进行推断,给定所有等式之后,会给你若干条查询

比如查询,[“ab”, “ct”],根据上面的等式推断,ab / ct = 4

如果某条查询中的变量,从来没在等式中出现过,认为答案是-1.0

如果某条查询的答案根本推断不出来,认为答案是-1.0

返回所有查询的答案

https://leetcode.cn/problems/evaluate-division/

做法:

这个题和第一题思路基本一致

但是要用map存

C++
int find(int x){
	if(f[x] != x){
		int fa = f[x];
		f[x] = find(f[x]);
		val[x] *= val[fa];
	}
	return f[x];
}

查询更新赋值时要改为*

C++
f[x] = y;
val[x] = val[r] / val[l] * s;

合并同理

C++
cout << val[l] / val[r];

最后算答案的时候要改为/

例题4

问题:

一共有n只动物,编号1 ~ n,每只动物都是A、B、C中的一种,A吃B、B吃C、C吃A

一共有k句话,希望你判断哪些话是假话,每句话是如下两类句子中的一类

1 X Y : 第X只动物和第Y只动物是同类

2 X Y : 第X只动物吃第Y只动物

当前的话与前面的某些真话冲突,视为假话

当前的话提到的X和Y,有任何一个大于n,视为假话

当前的话如果关于吃,又有X==Y,视为假话

返回k句话中,假话的数量

1 <= n <= 5 * 10^4 1 <= k <= 10^5

https://www.luogu.com.cn/problem/P2024

做法:

我们认为每个并查集的点到头节点的权值的意义 0 为同类, 1 为a吃头节点, 2 为头节点吃a

code:

C++
int find(int x) {
	if(f[x] != x) {
		int fa = f[x];
		f[x] = find(f[x]);
		val[x] += val[fa];
		val[x] %= 3;
	}
	return f[x];
}
C++
if(x > n || y > n) {
	ans++;//特判
} else if(op == 2 && x == y) {
	ans++;//特判
} else {
	int xx = find(x);
	int yy = find(y);
	if(op == 1) {
		if(xx != yy) {
			f[xx] = yy;
			val[xx] = (val[y] - val[x] + 3) % 3;//后-前+权值
		} else {
			if((val[x] - val[y] + 3) % 3 != 0) {
				ans++;
			}
		}
	} else {
		if(xx != yy) {
			f[xx] = yy;
			val[xx] = (val[y] - val[x] + 4) % 3;//后-前+权值
		} else {
			if((val[x] - val[y] + 3) % 3 != 1) {
				ans++;
			}
		}
	}
}

例题5

问题(这个题不是带权并查集的题):

一共有n个犯人,编号1 ~ n,一共有两个监狱,你可以决定每个犯人去哪个监狱

给定m条记录,每条记录 l r v,表示l号犯人和r号犯人的仇恨值

每个监狱的暴力值 = 该监狱中仇恨最深的犯人之间的仇恨值

冲突值 = max(第一座监狱的暴力值,第二座监狱的暴力值)

犯人的分配方案需要让这个冲突 值最小,返回最小能是多少

1 <= n <= 20000 1 <= m <= 100000 1 <= 仇恨值 <= 10^9

https://www.luogu.com.cn/problem/P1525

code:

敌人的敌人是朋友

C++
#include <bits/stdc++.h>
using namespace std;

const int N = 2e4 + 10;

const int M = 1e5 + 10;

int n, m;

int f[N], e[N];

struct node {
	int a, b, c;
} arr[M];

int find(int x) {
	if(f[x] != x) f[x] = find(f[x]);
	return f[x];
}

void read() {
	cin >> n >> m;
	for(int i = 1; i <= m; i++) {
		cin >> arr[i].a >> arr[i].b >> arr[i].c;
	}
	for(int i = 1; i <= n; i++) f[i] = i;
	sort(arr+1,arr+1+m,[](node x,node y) {
		return x.c > y.c;
	});
	return ;
}

void compute() {
	int ans = 0;
	for(int i = 1; i <= m; i++) {
		int l = arr[i].a;
		int r = arr[i].b;
		int v = arr[i].c;
		int x = find(l);
		int y = find(r);
		if(x == y) {
			ans = v;
			break;
		} else {
			if(e[l] == 0) {
				e[l] = r;
			} else {
				f[find(e[l])] = y;
			}
			if(e[r] == 0){
				e[r] = l;
			}
			else{
				f[find(e[r])] = x;
			}
		}
	}
	cout << ans;
	return ;
}

int main() {
	read();
	compute();
	return 0;
}

例题6

问题: 一共n个数,编号0 ~ n-1,实现如下三种类型的操作,一共调用m次

I x v : 声明 第x个数 = v

I x y v : 声明 第x个数 ^ 第y个数 = v

Q k a1 .. ak : 查询 一共k个数,编号为a1 .. ak,这些数字异或起来的值是多少

对每个Q的操作打印答案,如果根据之前的声明无法推出答案,打印”I don’t know.”

如果处理到第s条声明,发现了矛盾,打印”The first s facts are conflicting.”

注意只有声明操作出现,s才会增加,查询操作不占用声明操作的计数

发现矛盾之后,所有的操作都不再处理

1 <= n <= 20000 1 <= m <= 40000 1 <= k <= 15

做法:

C++
int find(int x){
	if(f[x] != x){
		int fa = f[x];
		f[x] = find(f[x]);
		val[x] ^= val[fa];
	}
	return f[x];
}

查询更新赋值时要改为^

C++
f[x] = y;
val[x] = val[r] ^ val[l] ^ s;

合并同理

那么单点赋值怎么办

我们可以建一个超级原点

和他连起来的就是已经赋值的

这个是题解

code:

Java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;

public class Main{

	public static int MAXN = 20002;

	public static int MAXK = 21;

	public static int t, n, m;

	public static boolean conflict;

	public static int cnti;

	public static int[] father = new int[MAXN];

	public static int[] exclu = new int[MAXN];

	public static int[] nums = new int[MAXK];

	public static int[] fas = new int[MAXK];

	public static void prepare() {
		conflict = false;
		cnti = 0;
		for (int i = 0; i <= n; i++) {
			father[i] = i;
			exclu[i] = 0;
		}
	}

	public static int find(int i) {
		if (i != father[i]) {
			int tmp = father[i];
			father[i] = find(tmp);
			exclu[i] ^= exclu[tmp];
		}
		return father[i];
	}

	public static boolean opi(int l, int r, int v) {
		cnti++;
		int lf = find(l), rf = find(r);
		if (lf == rf) {
			if ((exclu[l] ^ exclu[r]) != v) {
				conflict = true;
				return false;
			}
		} else {
			if (lf == n) {
				lf = rf;
				rf = n;
			}
			father[lf] = rf;
			exclu[lf] = exclu[r] ^ exclu[l] ^ v;
		}
		return true;
	}

	public static int opq(int k) {
		int ans = 0;
		for (int i = 1, fa; i <= k; i++) {
			fa = find(nums[i]);
			ans ^= exclu[nums[i]];
			fas[i] = fa;
		}
		Arrays.sort(fas, 1, k + 1);
		for (int l = 1, r = 1; l <= k; l = ++r) {
			while (r + 1 <= k && fas[r + 1] == fas[l]) {
				r++;
			}
			if ((r - l + 1) % 2 != 0 && fas[l] != n) {
				return -1;
			}
		}
		return ans;
	}

	public static void main(String[] args) throws IOException {
		FastReader in = new FastReader();
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		t = 0;
		n = in.nextInt();
		m = in.nextInt();
		while (n != 0 || m != 0) {
			prepare();
			out.println("Case " + (++t) + ":");
			for (int i = 1; i <= m; i++) {
				String op = in.next();
				if (op.equals("I")) {
					int l, r, v;
					in.numbers();
					if (!conflict) {
						if (in.size == 2) {
							l = in.a;
							r = n;
							v = in.b;
						} else {
							l = in.a;
							r = in.b;
							v = in.c;
						}
						if (!opi(l, r, v)) {
							out.println("The first " + cnti + " facts are conflicting.");
						}
					}
				} else {
					int k = in.nextInt();
					for (int j = 1; j <= k; j++) {
						nums[j] = in.nextInt();
					}
					if (!conflict) {
						int ans = opq(k);
						if (ans == -1) {
							out.println("I don't know.");
						} else {
							out.println(ans);
						}
					}
				}
			}
			out.println();
			n = in.nextInt();
			m = in.nextInt();
		}
		out.flush();
		out.close();
		in.close();
	}

	// 快读
	static class FastReader {
		final private int BUFFER_SIZE = 1 << 16;
		private final InputStream in;
		private final byte[] buffer;
		private int pointer, bytesRead;

		public int a;
		public int b;
		public int c;
		public int size;

		public FastReader() {
			in = System.in;
			buffer = new byte[BUFFER_SIZE];
			pointer = bytesRead = 0;
		}

		private byte read() throws IOException {
			if (pointer >= bytesRead) {
				fillBuffer();
				if (bytesRead == -1) {
					return -1;
				}
			}
			return buffer[pointer++];
		}

		private void fillBuffer() throws IOException {
			bytesRead = in.read(buffer, 0, BUFFER_SIZE);
			pointer = 0;
		}

		private void skipWhiteSpace() throws IOException {
			byte c;
			while ((c = read()) != -1) {
				if (c > ' ') {
					pointer--;
					break;
				}
			}
		}

		private String readLine() throws IOException {
			StringBuilder sb = new StringBuilder();
			while (true) {
				byte c = read();
				if (c == -1 || c == '\n') {
					break;
				}
				if (c == '\r') {
					byte nextc = read();
					if (nextc != '\n') {
						pointer--;
					}
					break;
				}
				sb.append((char) c);
			}
			if (sb.length() == 0 && bytesRead == -1) {
				return null;
			}
			return sb.toString();
		}

		public String next() throws IOException {
			skipWhiteSpace();
			if (bytesRead == -1) {
				return null;
			}
			StringBuilder sb = new StringBuilder();
			byte c = read();
			while (c != -1 && c > ' ') {
				sb.append((char) c);
				c = read();
			}
			return sb.toString();
		}

		public int nextInt() throws IOException {
			skipWhiteSpace();
			if (bytesRead == -1) {
				throw new IOException("No more data to read (EOF)");
			}
			boolean negative = false;
			int result = 0;
			byte c = read();
			if (c == '-') {
				negative = true;
				c = read();
			}
			while (c >= '0' && c <= '9') {
				result = result * 10 + (c - '0');
				c = read();
			}
			if (c != -1 && c > ' ') {
				pointer--;
			}
			return negative ? -result : result;
		}

		public void numbers() throws IOException {
			a = b = c = size = 0;
			String line = readLine();
			if (line == null) {
				return;
			}
			String[] parts = line.trim().split("\\s+");
			if (parts.length == 0) {
				return;
			}
			size = Math.min(parts.length, 3);
			if (size >= 1) {
				a = Integer.parseInt(parts[0]);
			}
			if (size >= 2) {
				b = Integer.parseInt(parts[1]);
			}
			if (size >= 3) {
				c = Integer.parseInt(parts[2]);
			}
		}

		public void close() throws IOException {
			if (in != null) {
				in.close();
			}
		}
	}

}
原文