带权并查集
并查集是一种极其极其优美的数据结构,研发出来的那个人太顶了!这里题目意思一种操作是吧x极其上面全部,放在y上面,一种操作是问x下面有几个箱子。
那么很容易联想到这个是集合合并问题,但是简单的fa数组无法对元素个数进行统计,那么就涉及到带权的并查集了。
对于给出的2个集合,因为是把x放在y上面,那么在给x找父亲的时候,要把子树的大小全部累加到父节点中去。
并且在合并的时候,开一个数组另外记当前集合的元素个数,累加进另外一个集合中去即可。
Code
#pragma GCC target("avx,sse2,sse3,sse4,popcnt")
#pragma GCC optimize("O2,O3,Ofast,inline,unroll-all-loops,-ffast-math")
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <ctype.h>
#include <cstring>
using namespace std;
#define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define all(vv) vv.begin(), vv.end()
#define endl "\n"
typedef long long ll; typedef unsigned long long ull; typedef long double ld;
const ll MOD = 1e9 + 7;
inline ll read() { ll s = 0, w = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1; for (; isdigit(ch); ch = getchar()) s = (s << 1) + (s << 3) + (ch ^ 48); return s * w; }
inline void write(ll x) { if (!x) { putchar('0'); return; } char F[40]; ll tmp = x > 0 ? x : -x; if (x < 0)putchar('-'); int cnt = 0; while (tmp > 0) { F[cnt++] = tmp % 10 + '0'; tmp /= 10; } while (cnt > 0)putchar(F[--cnt]); }
inline ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll qpow(ll a, ll b) { ll ans = 1; while (b) { if (b & 1) ans *= a; b >>= 1; a *= a; } return ans; } ll qpow(ll a, ll b, ll mod) { ll ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; b >>= 1; (a *= a) %= mod; }return ans % mod; }
inline int lowbit(int x) { return x & (-x); }
const int N = 3e4 + 7;
int fa[N], siz[N], ran[N];
int find(int x) {
if (fa[x] == x) return x;
int t = fa[x];
fa[x] = find(t);
ran[x] += ran[t]; //子树大小累加进父亲中
return fa[x];
}
void merge(int a, int b) {
int x = find(a), y = find(b);
fa[x] = y; //并查集关系数组
ran[x] += siz[y]; //x下方的个数累加
siz[y] += siz[x]; //集合总数累加
}
int main() {
int n = read();
for (int i = 1; i <= n; ++i) fa[i] = i; //赋值 i
fill(siz + 1, siz + n + 1, 1); //全部赋值1
while (n--) {
char op;
scanf(" %c", &op);
if (op == 'M') {
int a = read(), b = read();
merge(a, b);
}
else {
int a = read();
find(a);
printf("%d\n", ran[a]);
}
}
return 0;
}

京公网安备 11010502036488号