跳到正文

个人记录

P3367 【模板】并查集

molasses约 2 分钟
原文
文章信息与版本

文章信息

发布
2019年8月8日
收录
2026年8月17日
更新
2026年8月17日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;

struct Unionfindset {
  vector<int> pa, rank;

  Unionfindset(int n) {
    pa = vector<int>(n + 1);
    for (int i = 0; i <= n; ++i) pa[i] = i;
    rank = vector<int>(n + 1, 0);
  }
  
  int get(int v) {
    int p = v;
    while (pa[p] != p) p = pa[p];
    while (v != p) {
      int t = pa[v];
      pa[v] = p;
      v = t;
    }
    return v;
  }

  void merge(int x, int y) {
    int xx = get(x), yy = get(y);
    if (xx == yy) return;
    if (rank[xx] > rank[yy]) {
      pa[yy] = xx;
    } else {
      pa[xx] = yy;
      if (rank[xx] == rank[yy]) ++rank[yy];
    }
  }
};

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n, m;
  cin >> n >> m;
  Unionfindset u(n);
  while (m--) {
    int z, x, y;
    cin >> z >> x >> y;
    if (z == 1) {
      u.merge(x, y);
    } else if (z == 2) {
      cout << (u.get(x) == u.get(y) ? "Y\n" : "N\n");
    }
  }
  return 0;
}
原文