gnib即bing

UVA 11987 Almost Union-Find (并查集,可持久化)

大白书:p246 UVA 11987Almost Union-Find

加一个id[],不修改,而是insert,然后改id

const int MAXN = 100010 * 2;
const int MOD = 1000000;
 
int fa[MAXN], num[MAXN];
int sum[MAXN];
 
int idx[MAXN];
 
void init(int n)
{
   REP(i, n + 1)
    {
       idx[i] = i;
       fa[i] = i;
       num[i] = 1;
       sum[i] = i;
    }
}
 
int find(int x)
{
   if (x != fa[x])
       fa[x] = find(fa[x]);
   return fa[x];
}
 
int main()
{
   int n, m;
   int x, y;
   while (cin >> n >> m)
    {
       init(n);
       int k = n + 1;///!!!!!!
       while (m--)
       {
           RI(x);
           if (x == 1)
           {
                RII(x, y);
                int xx = idx[x];
                int yy = idx[y];
                int fax = find(xx);
                int fay = find(yy);
                if (fax != fay)
                {
                    fa[fax] = fay;
                    num[fay] += num[fax];
                    sum[fay] += sum[fax];
                }
           }
           else if (x == 2)
           {
                RII(x, y);
                int xx = idx[x];
                int yy = idx[y];
                int fax = find(xx);
                int fay = find(yy);
                if (fax != fay)
                {
                    num[fax]--;
                    sum[fax] -= x;
                    num[fay]++;
                    sum[fay] += x;
 
                    idx[x] = k;
                    num[k] = 1;
                    sum[k] = x;
                    fa[k] = fay;
                    k++;
                }
           }
           else
           {
                RI(x);
                int xx = idx[x];
                int fax = find(xx);
                printf("%d %d\n",num[fax], sum[fax]);
           }
       }
//       FE(i, 1, n)
//       {
//            int fax = find(idx[i]);
//            cout << i << "" << idx[i] << " " << fax << "" << num[fax] << " " << sum[fax] <<endl;
//       }
    }
}


阅读更多
文章标签: 并查集
个人分类: 数据结构
上一篇bnu 33684 Never Wait for Weights (权值并查集)
下一篇hdu 4267 A Simple Problem with Integers(分类别维护多个树状数组)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭