对于各种并查集写法速度的研究 January 24, 2017 2018.3.3:更新了测试代码,加入了更多写法,修复了一些致命错误 测试机CPU为Intel® Celeron® Processor G3900,内存为8GB DDR4,系统为Debian 9。 编译命令为g++ test.cpp -o test -O3。 先放测试代码: ```c++ #include #include #include #include #define N 1024 #define T 100000 int fa[N+233],st[N+233],sz[N+233]; int find1(int x) { return x==fa[x]?x:fa[x]=find1(fa[x]); } inline int find2(int x) { return x==fa[x]?x:fa[x]=find2(fa[x]); } inline int find3(int x) { while(x!=fa[x])x=fa[x]=fa[fa[x]];return x; } inline int find4(int x) { int se=0;st[0]=x; while(fa[x]!=x)st[++se]=x=fa[x]; while(se)fa[st[--se]]=x; return x; } inline int find5(int x) { int t=x,p; while(x!=fa[x])x=fa[x]; while(t!=x)p=fa[t],fa[t]=x,t=p; return x; } int find6(int x) { return 0>fa[x]?x:fa[x]=find6(fa[x]); } inline int find7(int x) { return 0>fa[x]?x:fa[x]=find7(fa[x]); } inline int find8(int x) { while(fa[x]>=0&&fa[fa[x]]>=0)x=fa[x]=fa[fa[x]];return fa[x]<0?x:fa[x]; } long long global_checksum; unsigned int count,seed; std::mt19937 ran_(0); void init_rand(int x) { ran_=std::mt19937(x); ran_(),ran_(),ran_(); count=0; } int rand() { if(count&1023)seed=ran_(); count++; seed^=seed<<13; seed^=seed>>17; seed^=seed<<5; return seed; } inline long long test(int(*f)(int)) { init_rand(19260817); long long last,timeusage=0,checksum=0; for(int t=0;tsz[y])sz[x]+=sz[y],fa[y]=x;else sz[y]+=sz[x],fa[x]=y;} } timeusage+=clock()-last; for(int i=0;isz[y])fa[y]=x;else{fa[x]=y;if(sz[x]==sz[y])sz[y]++;}} } timeusage+=clock()-last; for(int i=0;i