并查集

来源:互联网 发布:分布式数据库的优势 编辑:程序博客网 时间:2024/06/06 12:45

【一次做cf,用递归版的超时了,非递归版的就ac了】

递归版

#include <bits/stdc++.h>using namespace std;const int N=1e3;int fa[N];int find(int x){      return fa[x]==x?x:find(fa[x]);  }    void Union(int x, int y){      int fx = find(x);      int fy = find(y);      fa[fy] = fx;  }  

非递归版

#include <bits/stdc++.h>using namespace std;const int N=1e3;int fa[N];int find(int x){    int i=x, r=x, j;    while(fa[r]!=r) r=fa[r];    while(fa[i]!=r)    {        j=fa[i];        fa[i]=r;        i=j;    }    return r;}void Union(int a,int b){    int fx=find(a);    int fy=find(b);    if(fx!=fy) fa[fx]=fy;}




0 0