zoukankan      html  css  js  c++  java
  • 【洛谷】P1551 亲戚(并查集模板)

    题目地址:https://www.luogu.com.cn/problem/P1551

    运用算法

    并查集

    代码

    #include <iostream>
    #include <string>
    #include <stack>
    #include <cstdio>
    using namespace std;
    
    int n, m, a[10001];
    
    void init() {
        // 初始化并查集
        for (int i = 1; i <= n; i++)
              a[i] = i;
    }
    
    int getf(int v) {
        if (a[v] == v) return v; // 自己就是爸爸
        else {
              a[v] = getf(a[v]); // 路径压缩
              return a[v]; 
        }
    }
    
    void marge(int v, int u) {
        int t1, t2;
        t1 = getf(v);
        t2 = getf(u);
        if (t1 != t2) { // 两个的爸爸不一样 
              a[t2] = t1; // 按左归化 
        }
    }
    
    int main() {
        cin >> n >> m;
    	
        init();
    	
        for (int i = 1; i <= m; i++) {
              int x, y, op;
              cin >> op >> x >> y;
              if (op == 1) marge(x, y); 
              else {
                    if (getf(x) == getf(y)) cout << "Y" << endl;
                    else cout << "N" << endl;
              }
        }
    
        return 0; 
    }
    
  • 相关阅读:
    hihocoder 1038
    hihocoder 1039
    poj 2774
    bzoj 4690&&4602
    poj 2417
    STL
    poj 1026
    poj 1064
    poj 1861(prim)
    poj 1129
  • 原文地址:https://www.cnblogs.com/luoling8192/p/12860107.html
Copyright © 2011-2022 走看看