Disjoint-set (concentrated essence stencil !!!!)

Copyright: private individuals do question summed up ~ https://blog.csdn.net/tb_youth/article/details/88621865

Conventional inlet template comparison: disjoint-set routine template
following the essence template:

    #include <iostream>
    const int MAXN = 1e6+10;
    using namespace std;
    int pre[MAXN];
    int height[MAXN];
    int sum; 
    /*
    递归写法精华版find: 
    省掉初始化自己的上级是自己,直接用0表示是自己
    若用其他数字表示上级是自己,
    比如-1,最多用memset(pre,-1,sizeof(-1)),这样初始化更快 
    return pre[x] = find(pre[x])这句代码路径压缩包含其中(递归回溯实现)
    如果数据很大,出现爆栈的情况 ,那么就使用非递归写法 
    */
    int find(int x)
    {
    	if(pre[x] == 0)
    	   return x;
    	return pre[x] = find(pre[x]);
    }
    /*
    merge 一般不用写优化,如果要优化的话参考 下面第二个merge 
    */ 
    void merge(int x,int y)
    {
    	int fx = find(x),fy = find(y);
    	if(fx != fy)
    	{
    		pre[fx] = fy;
    		sum--;//看具体问题 
    	}
    } 
    /*
    //merge优化 
    void merge(int x,int y)
    {
    	int fx = find(x),fy = find(y);
    	if(fx != fy)
    	{
    		if(height[fx] < height[fy]) //高的作为主干 
    		    pre[fx] = fy;
    		else
    		{
    			pre[fy] = fx;
    			if(height[fx] == height[fy])
    			   height[fx]++;
    		} 
    		sum--;//看具体问题 
    	}
    } */
    int main()
    {
    	int m,n;
    	cin>>n>>m;
    	int k,a,b;
    	sum = n*m;
    	cin>>k;
    	for(int i = 0; i < k; i++)
    	{
    		cin>>a>>b;
    		merge(a,b);
    	}
    	cout<<sum<<endl;
    	return 0;
    }

Guess you like

Origin blog.csdn.net/tb_youth/article/details/88621865