zoukankan      html  css  js  c++  java
  • 并查集模板

    我的模板最适合我,不知道适不适合浏览本篇博客的各位。如果有觉得好的地方,可以取走;不好的地方看看就好。

    下面是我的模板:

     1 //并查集模板
     2 
     3 //头文件&&预处理(适合窝自己的)
     4 #include <set>
     5 #include <cstdio>
     6 #include <algorithm>
     7 using namespace std;
     8 
     9 //变量的声明
    10 //我一般都会有fa[Max](父亲),r[Max](树的高度)这两个数组
    11 
    12 //对每个元素进行初始化
    13 void init(int n){
    14     for(int i=0; i<n; i++){
    15         fa[i]=i;
    16         r[i]=0;
    17     }
    18 }
    19 
    20 //查询树的根
    21 int fi(int x){
    22     return fa[x]==x?x:fa[x]=fi(fa[x]);  //将一棵树上的所有元素直接连在根上
    23 }
    24 
    25 //合并两个集合
    26 void unite(int x,int y){
    27     int p1=fi(x),p2=fi(y);
    28     if(p1==p2) return;  //根都一样当然就不用继续进行操作啦==
    29     if(r[p1]>r[p2])   fa[p2]=p1;  //将树的高度较小的连在树高的上
    30     else{
    31         fa[p1]=p2;
    32         if(r[p1]==r[p2]) r[p2]++;  //此处画个图就懂了
    33     }
    34 }
    35 
    36 //判断两个元素是否在同一个集合里面只需判断它们的根是不是一样的就行了
    37 bool check(int x,int y){
    38     return fi(x)==fi(y);
    39 }
    40 
    41 //主函数
    42 int main(){
    43     /*
    44         巴拉巴拉的一堆输入,同时将一系列需要的函数进行调用==
    45     */
    46     //如果需要判断有多少个集合的话,我都是用set来进行处理的,前面定义一个set就用s吧
    47     for(int i=1;i<=N;i++){
    48         if(!s.count(fi(i))){
    49             s.insert(fi(i));
    50         }
    51     }
    52     //集合数=s.size();
    53 }
    54 
    55 //具体的看我的迷之并查集分类里面的题==
    56 //emmmm,上一句纯属帮其他几篇博客拉浏览量
    版权声明:本文允许转载,转载时请注明原博客链接,谢谢~
  • 相关阅读:
    Condition-线程通信更高效的方式
    中断线程详解(Interrupt)
    Fiddler2 java代码拦截设置
    Apache HttpComponents 通过代理发送HTTP请求
    Tomcat性能优化之(一) 启动GZIP压缩
    Apache HttpComponents 文件上传例子
    Apache HttpComponents Custom protocol interceptors通过拦截器自定义压缩
    Apache HttpComponents 多线程处理HTTP请求
    Apache HttpComponents POST提交带参数提交
    Apache HttpComponents 获取Cookie
  • 原文地址:https://www.cnblogs.com/Dillonh/p/8490006.html
Copyright © 2011-2022 走看看