#include <bits/stdc++.h>
using namespace std;
#define int long long
struct DSU {
vector<int> par, sz;
void init(int n) {
par.resize(n + 1);
sz.resize(n + 1, 1);
for (int i = 1; i <= n; i++) par[i] = i;
}
int find(int u) {
return par[u] == u ? u : par[u] = find(par[u]);
}
bool unite(int u, int v) {
u = find(u); v = find(v);
if (u == v) return false;
if (sz[u] < sz[v]) swap(u, v);
par[v] = u;
sz[u] += sz[v];
return true;
}
};
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, q;
cin >> n >> q;
DSU dsu;
dsu.init(n);
// Store attraction between component roots: {smaller, larger}
set<pair<int, int>> attract;
while (q--) {
char type;
cin >> type;
int x, y;
cin >> x >> y;
int px = dsu.find(x);
int py = dsu.find(y);
if (type == 'U') {
// Merge components
// Before merging, move attractions from old roots if needed
dsu.unite(x, y);
}
else if (type == 'A') {
// Add attraction between current components
if (px == py) continue; // same component, ignore?
if (px > py) swap(px, py);
attract.insert({px, py});
}
else if (type == 'Q') {
if (px == py) {
cout << "R\n";
}
else {
if (px > py) swap(px, py);
if (attract.count({px, py})) {
cout << "A\n";
}
else {
cout << "?\n";
}
}
}
}
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |