http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3138


如何删除?增加一个新结点,标号为所有结点(包括新结点)的最大编号+1

然后将旧结点的影响变为0,同时初始化新结点:

void delet(int x)
{
	int tx = find(id[x]);
	--num[tx], sum[tx] -= x; ///将旧结点的影响变为0
	id[x] = ++cnt;
	fa[id[x]] = id[x], num[id[x]] = 1, sum[id[x]] = x;
}


完整代码:


/*0.179s*/

#include<bits/stdc++.h>
using namespace std;
const int mx = 200005;

int fa[mx], id[mx], num[mx], cnt; ///id[i]表示i的实际节点编号
long long sum[mx];

void init(int n)
{
	for (int i = 1; i <= n; ++i)
	{
		id[i] = fa[i] = sum[i] = i;
		num[i] = 1;
	}
	cnt = n;
}

int find(int x) {return fa[x] == x ? x : fa[x] = find(fa[x]);}

void merge(int x, int y)
{
	x = find(id[x]), y = find(id[y]);
	fa[x] = y, num[y] += num[x], sum[y] += sum[x];
}

void delet(int x)
{
	int tx = find(id[x]);
	--num[tx], sum[tx] -= x;///将旧结点的影响变为0
	id[x] = ++cnt;///建立新结点
	fa[id[x]] = id[x], num[id[x]] = 1, sum[id[x]] = x;///初始化新结点
}

int main()
{
	int n, m, op, x, y;
	while (~scanf("%d%d", &n, &m))
	{
		init(n);
		while (m--)
		{
			scanf("%d", &op);
			if (op == 1)
			{
				scanf("%d%d", &x, &y);
				if (find(id[x]) != find(id[y]))
					merge(x, y);
			}
			else if (op == 2)
			{
				scanf("%d%d", &x, &y);
				if (find(id[x]) != find(id[y]))
					delet(x), merge(x, y);
			}
			else
			{
				scanf("%d", &x);
				printf("%d %lld\n", num[find(id[x])], sum[find(id[x])]);
			}
		}
	}
	return 0;
}