您的位置:首页 > 其它

UVA 1329 - Corporative Network

2015-01-13 09:53 375 查看
求节点到根结点的距离。用一个D数组保存每一个节点到根结点的距离。
在I操作的时候路径压缩,更新D数组。
#include<stdio.h>#include<string.h>int abs(int x){return x>0?x:-x;}const int maxn=20000+20;int pa[maxn],d[maxn];int find(int x){if(pa[x]!=x){int root=find(pa[x]);d[x]+=d[pa[x]];//更新这一点到达根节点的距离。//printf("YY %d",x);return pa[x]=root;//这一步是更新父节点}else return x;}int main(){int tt;scanf("%d",&tt);while(tt--){for(int i=0;i<=maxn;i++){pa[i]=i,d[i]=0;}int n;scanf("%d",&n);char ch[10];while(scanf("%s",ch)!=EOF){if(ch[0]=='O') break;if(ch[0]=='E'){int x;scanf("%d",&x);find(x);printf("%d\n",d[x]);}else if(ch[0]=='I'){int x,y;scanf("%d%d",&x,&y);pa[x]=y;d[x]=abs(x-y)%1000;}}}return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: