zoukankan      html  css  js  c++  java
  • poj 1988 Cube Stacking【带权并查集】

    设s[x]为x所在栈里的个数,c[x]表示x下面有几个,合并的时候直接合并s,然后路径压缩的时候更新c即可

    #include<iostream>
    #include<cstdio>
    using namespace std;
    const int N=30005;
    int n=30000,m,f[N],s[N],c[N];
    char o[5];
    int read()
    {
    	int r=0,f=1;
    	char p=getchar();
    	while(p>'9'||p<'0')
    	{
    		if(p=='-')
    			f=-1;
    		p=getchar();
    	}
    	while(p>='0'&&p<='9')
    	{
    		r=r*10+p-48;
    		p=getchar();
    	}
    	return r*f;
    }
    int zhao(int x)
    {
    	if(x==f[x])
    		return x;
    	int nw=zhao(f[x]);
    	c[x]+=c[f[x]];
    	return f[x]=nw;
    }
    int main()
    {
    	m=read();
    	for(int i=1;i<=n;i++)
    		s[i]=1,f[i]=i;
    	while(m--)
    	{
    		scanf("%s",o+1);
    		if(o[1]=='M')
    		{
    			int x=read(),y=read(),fx=zhao(x),fy=zhao(y);
    			f[fx]=fy;
    			c[fx]=s[fy];
    			s[fy]+=s[fx];
    		}
    		else
    		{
    			int x=read();
    			zhao(x);
    			printf("%d
    ",c[x]);
    		}
    	}
    	return 0;
    }
    
  • 相关阅读:
    关于DRY原则
    类型之惑
    ThoughtWorks测试
    编程非易事
    瀑布与迭代的真实区别
    对TDD原则的理解
    自我练习
    C# CreateProcess的测试
    乱侃OOD
    复杂系统的五个属性
  • 原文地址:https://www.cnblogs.com/lokiii/p/9974294.html
Copyright © 2011-2022 走看看