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;
}