1329 - Corporative Network(并查集)
来源:互联网 发布:mysql indexof 编辑:程序博客网 时间:2024/05/18 15:29
题目链接
该题是比较经典的并查集题目,经典在需要在路径压缩时维护一些量。 由于每棵树除了根结点不能换之外,其他结点的位置可以任意改变,这恰好符合并查集的特点。
但是如果用最朴素的方法维护每个结点到根的距离,那么每次新加入的结点就要向上遍历一遍所有结点,时间复杂度难以承受(因为无法路径压缩) 。 所以我们可以在路径压缩的时候顺便求出d值 。 在每次返回某个结点的祖先之前先将当前结点的d值更新,即加上当前父结点的d值, 然后就可以路径压缩了。
所以这么做的原因是为了防止并查集退化成一条长长的链表,为了不牺牲路径压缩这个好东西。
细节参见代码:
#include<bits/stdc++.h>using namespace std;typedef long long ll;const int mod = 1000;const int maxn = 20000 + 5;const int INF = 1000000000;int T,n,m,x,y,p[maxn],d[maxn];void init(int v) { for(int i=1;i<=v;i++) p[i] = i,d[i] = 0;}int findset(int x) { if(p[x] == x) return x; else { int root = findset(p[x]); d[x] += d[p[x]]; return p[x] = root; }}char s[5];int main() { scanf("%d",&T); while(T--) { scanf("%d",&n); init(n); while(~scanf("%s",s)&&s[0]!='O') { if(s[0] == 'E') { scanf("%d",&x); findset(x); printf("%d\n",d[x]); } else { scanf("%d%d",&x,&y); p[x] = y ; d[x] = abs(x - y)%mod; } } } return 0;}
0 0
- 1329 - Corporative Network(并查集)
- UVA 1329Corporative Network【并查集】
- UVA 1329 Corporative Network(并查集)
- UVa:1329 Corporative Network(带权并查集)
- UVA - 1329 Corporative Network 合作网络(并查集)
- UVa 1329 Corporative Network(并查集)
- UVa 1329 Corporative Network (加权并查集)
- UVA 1329 Corporative Network(并查集:路径压缩)
- UVa 1329 Corporative Network(带权并查集)
- uva 1329 - Corporative Network(数据结构:并查集)
- UVA 1329 - Corporative Network(带权并查集)
- uva 1329 - Corporative Network(加权并查集)
- LA3027:Corporative Network(并查集) uva 1329
- UVA 1329 Corporative Network——加权并查集
- Corporative Network(带权并查集)
- UVALive - 3027Corporative Network(带权并查集)
- poj 1962 Corporative Network(并查集)
- UVALive - 3027 - Corporative Network (并查集!!)
- Aizu 2249Road Construction(SPFA算法变形,好题)
- 代码语言编写技巧
- 学习重点
- TCP/IP 协议栈及 OSI 参考模型详解
- linux源代码 net文件夹
- 1329 - Corporative Network(并查集)
- Android贴吧系统学习-----悬浮布局的做法
- Ubuntu 输入密码之后闪现一下又回答输入密码界面
- 解决树莓派2 HDMI输出的闪屏问题
- ajax+springmvc不执行success方法
- 闪讯利用openwrt路由器拨号教程(一)
- BestCoder Round #56 1002 hdu 5464 (背包问题)
- 位运算符的注意事项
- SQL扩展之T-SQL中的数据定义语言