杭电2818——带权并差集
写在题前
- 这个题的思路真的想了好久,看着像是带权并差集,但感觉又不是,想来想去才知道。
- 唉!菜的很啊!
解题思路
除了正常的父亲数组,我们还需要两个数组ans和num:
- ans [ i ] :记录 i 节点下面有多少个节点;向上更新(是向堆的上面更新,具体见代码)
- num [ i ]:记录 i 节点的堆一共有几个;
用meg函数建立联系,同时注意更新两个数组。
写在题后
注意有坑,注意有坑,注意有坑!!!重要的话说三遍。
- 题目中的数组长度是三万,但是你只给三万的话会超时(哈哈,别想了,给六万他也超),本人测试了好多次,最后得出,这个长度得十万(反正九万的话,超时了)。
ac代码
# include <iostream>
# include <algorithm>
# include <cstdio>
# include <cstdlib>
# include <string>
# include <cstring>
# include <vector>
# include <map>
using namespace std;
typedef long long ll;
const int maxn = 100010;//注意开辟数组的大小
int id[maxn];
int num[maxn];//记录节点所在堆的总数量
int ans[maxn];//记录节点下面节点的数量:即答案
int fin(int x) {//使用路径压缩
if (x != id[x]) {
int t = id[x];
id[x] = fin(id[x]);
ans[x] += ans[t];
//虽然ans数组是向上更新,但是在建立关系的时候是反着建立关系的
//因此这个时候需要向下更新,如果不理解的,可以先去学习一些基础的带权并差集
}
return id[x];
}
void meg(int x, int y) {
int a = fin(x);
int b = fin(y);
if (a != b) {
id[a] = b;
//注意,注意,注意,这里建立关系的时候,一定是:a的父亲指向b
//这样方便操作
ans[a] = num[b];
//因为是反着建立关系,所以a的下面是没有节点的,
//现在直接将b堆的总数量赋值给a就行了
num[b] += num[a];
//更新num数组,这个很简单。
}
}
int main() {
ios::sync_with_stdio(false);
int n;
while (cin >> n) {
for (int i = 0; i < n + 10; i++) {
id[i] = i;
num[i] = 1;
}
memset(ans, 0, sizeof(ans));
string anw;
while (n--) {
cin >> anw;
if (anw[0] == 'M') {
int x;
int y;
cin >> x >> y;
meg(x, y);
}
else if (anw[0] == 'C') {
int x;
cin >> x;
fin(x);
//注意要用fin函数更新ans数组
//可能有的加点的ans值没有更新
cout << ans[x] << endl;
}
}
}
return 0;
}