洛谷 P5092【加权并查集】

这是一个关于BCT创客大赛的程序代码,实现了并查集的数据结构,用于处理合并与查询操作。代码中包含初始化、查找、合并及查询功能,适用于解决集合合并与元素所属集合查询的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

话说这不是bct创客大赛普及组的第三题吗

#include <bits/stdc++.h>
#define int long long

using namespace std;

int read() {
  int x;
  scanf ("%lld", &x);
  return x;
  /*
  char ch;
  int opt = 1, num;
  while (!isdigit(ch = getchar())) {
    if (ch == '-')
      opt = -1;
  }
  num = ch ^ 48;
  while (isdigit(ch = getchar()))
    num = (num << 3LL) + (num << 1LL) + (ch ^ 48);
  return num * opt;
  */
}

const int N = 1e6 + 233;
int fa[N], w[N], fr[N];

int find(int x) {
  if (fa[x] == x)
    return x;
  int tx = find(fa[x]);
  fr[x] += fr[fa[x]];
  return fa[x] = tx;
}

void merge(int x, int y) {
  swap (x, y);
  int tx = find(x);
  int ty = find(y);
  fr[tx] += w[ty];
  fa[tx] = ty;
  w[ty] += w[tx];
}

void init(int n) {
  for (int i = 1; i <= n; i ++)
    fa[i] = i;
  for (int i = 1; i <= n; i ++)
    w[i] = 1;
  for (int i = 1; i <= n; i ++)
    fr[i] = 0;
}

int query(int x) {
  // return w[x];
  int ta = find(x);
  return w[ta] - fr[x] - 1;
}

signed main() {
  int n = read();
  init(33333);
  while (n --) {
    char ch;
    cin >> ch;
    if (ch == 'M') {
      int a, b;
      a = read(), b = read();
      merge(a, b);
    } else {
      int x;
      x = read();
      printf ("%lld\n", query(x));
    }
  }
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值