并查集Merge函数的顺序会对结果有影响?
查看原帖
并查集Merge函数的顺序会对结果有影响?
831787
ruo11楼主2023/3/19 10:20

rt,以下是两段仅改变merge函数的代码段
WA:

#include<bits/stdc++.h>
#define endl '\n'
#define All(x) x.begin(),x.end()
using namespace std;
using ll = long long;
using pll = pair<int, int>;
const int _N = 2e5 + 5, inf = 0x3f3f3f3f, mode = 1e9 + 7;

int n, m, x, y, fa[_N];
char op,pos[_N];

int Get(int x) {
	if (fa[x] == x) return x;
	return fa[x] = Get(fa[x]);
}

void merge(int x, int y) {
	fa[x] = fa[Get(y)];//y子集合并在x父节点
}

int main() {
	ios::sync_with_stdio(0), cin.tie(nullptr);
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
	    fa[i] = i;
        cin>>pos[i];
	}

	for (int i = 1,u,v; i <= n - 1; i++) {
		cin >> u >> v;
		if (pos[u] == pos[v]) merge(u, v);
	}
	
	while (m--) {
		cin >> x >> y >> op;
		if (Get(x) == Get(y) && pos[x] != op) cout << "0";
		else cout << "1";
	}

	return 0;
}

AC:

#include<bits/stdc++.h>
#define endl '\n'
#define All(x) x.begin(),x.end()
using namespace std;
using ll = long long;
using pll = pair<int, int>;
const int _N = 2e5 + 5, inf = 0x3f3f3f3f, mode = 1e9 + 7;

int n, m, x, y, fa[_N];
char op,pos[_N];

int Get(int x) {
	if (fa[x] == x) return x;
	return fa[x] = Get(fa[x]);
}

void merge(int x, int y) {
	fa[Get(x)] = fa[y];//x子集合并在y父节点
}

int main() {
	ios::sync_with_stdio(0), cin.tie(nullptr);
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
	    fa[i] = i;
        cin>>pos[i];
	}

	for (int i = 1,u,v; i <= n - 1; i++) {
		cin >> u >> v;
		if (pos[u] == pos[v]) merge(u, v);
	}
	
	while (m--) {
		cin >> x >> y >> op;
		if (Get(x) == Get(y) && pos[x] != op) cout << "0";
		else cout << "1";
	}

	return 0;
}
2023/3/19 10:20
加载中...