备战NOIP——模板复习2

这里只有模板,并不作讲解,仅为路过的各位做一个参考以及用做自己复习的资料,转载注明出处。

并查集模板

路径压缩

/*Copyright: Copyright (c) 2018
*Created on 2018-10-28  
*Author: 十甫
*Version 1.0 
*Title: 并查集-路径压缩
*Time: 4 mins
*/ 
#include<cstdio>
#include<iostream>
using namespace std;
const int size = 10005;

int f[size];
inline int getf(int k) {
    if(f[k] != k) f[k] = getf(f[k]);
    return f[k];
}
inline void merge(int a, int b) {
    int fa = getf(a), fb = getf(b);
    if(fa == fb) return;
    else f[fa] = fb;
}
inline void init(int n) {
    for(int i = 1;i <= n;i++) {
        f[i] = i;
    }
}
int main() {
    int n, m;
    scanf("%d%d", &n, &m);
    init(n);
    while(m--) {
        int man, a, b;
        scanf("%d%d%d", &man, &a, &b);
        if(man) {
            merge(a, b);
        } else {
            int fa = getf(a), fb = getf(b);
            if(fa == fb) printf("YES\n");
            else printf("NO\n");
        }
    }
    return 0;
}

路径压缩+伪·按秩合并

/*Copyright: Copyright (c) 2018
*Created on 2018-10-28  
*Author: 十甫
*Version 2.0 
*Title: 并查集-路径压缩+伪·按秩合并
*Time: 12 mins
*/ 
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
const int size = 10005;

int f[size];
inline int getf(int k) {
    if(f[k] != k) f[k] = getf(f[k]);
    return f[k];
}
inline void merge(int a, int b) {
    int fa = getf(a), fb = getf(b);
    if(fa == fb) return;
    else {
        if(rand() % 2) f[fa] = fb;
        else f[fb] = fa;
    }
}
inline void init(int n) {
    srand(time(NULL));
    for(int i = 1;i <= n;i++) {
        f[i] = i;
    }
}
int main() {
    int n, m;
    scanf("%d%d", &n, &m);
    init(n);
    while(m--) {
        int man, a, b;
        scanf("%d%d%d", &man, &a, &b);
        if(man) {
            merge(a, b);
        } else {
            int fa = getf(a), fb = getf(b);
            if(fa == fb) printf("YES\n");
            else printf("NO\n");
        }
    }
    return 0;
}

 

posted @ 2018-10-28 15:06  十甫  阅读(138)  评论(0编辑  收藏  举报