关闭

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

标签: 并查集
1077人阅读 评论(0) 收藏 举报
分类:

大白书: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;
//       }
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:109016次
    • 积分:2305
    • 等级:
    • 排名:第16259名
    • 原创:121篇
    • 转载:4篇
    • 译文:0篇
    • 评论:13条
    最新评论