标签:
UVAlive 3027 Corporative Network
题目:
Time Limit: 3000MS | Memory Limit: 30000K | |
Total Submissions: 3450 | Accepted: 1259 |
Description
Input
Output
Sample Input
1 4 E 3 I 3 1 E 3 I 1 2 E 3 I 2 4 E 3 O
Sample Output
0 2 3 5
-----------------------------------------------------------------------------------------------------------------------------------------------------------
思路:
操作只有询问到root距离以及改变父结点,因此可以用并查集实现。为每个结点添加信息d表示到父结点的距离,对于I操作,将d初始化为abs(u-v)%1000,对于每次询问E添加功能:压缩路径的同时改变d,即在p[u]=root的同时有d[u]=dist(u->root)
代码:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #define FOR(a,b,c) for(int a=(b);a<(c);a++) 5 using namespace std; 6 const int maxn= 20000 +10; 7 8 int p[maxn],d[maxn]; 9 int find_set(int u){ 10 //寻找root结点->路径压缩+维护d 11 if(u==p[u]) return u; 12 else 13 { 14 int root=find_set(p[u]); 15 d[u] += d[p[u]]; //更新d为d->root的距离 16 return p[u]=root; //路径压缩 17 } 18 } 19 20 int main(){ 21 int T,n; scanf("%d",&T); 22 while (T--){ 23 scanf("%d",&n); 24 FOR(i,1,n+1){ p[i]=i; d[i]=0; } 25 char ch[5];int x,y; 26 while(scanf("%s",ch) && ch[0]!=‘O‘){ 27 if(ch[0]==‘E‘){ scanf("%d",&x);find_set(x);printf("%d\n",d[x]); } 28 else { scanf("%d%d",&x,&y); p[x]=y; d[x]=abs(x-y) % 1000; } 29 } 30 } 31 return 0; 32 }
【暑假】[实用数据结构]UVAlive 3027 Corporative Network
标签:
原文地址:http://www.cnblogs.com/lidaxin/p/4710412.html