HDU-3635 Dragon Balls 並查集路徑壓縮
http://acm.hdu.edu.cn/showproblem.php?pid=3635
題目大意:
初始時,有n個龍珠,編號從1到n,分別對應的放在編號從1到n的城市中。
現在又2種操作:
T A B,表示把A球所在城市全部的龍珠全部轉移到B城市。(第一次時,因為A球所在的城市只有一個球,所以只移動1個,如果有多個,則全部移動)。
Q A,表示查詢A。要求得到的資訊分別是:A現在所在的城市,A所在城市的龍珠數目,A轉移到該城市移動的次數(如果沒有移動就輸出0)
通過路徑壓縮來更新轉移的次數,比如每次移動時,我只需要把這個城市的根結點的轉移次數+1,等到以後路徑壓縮時,子結點自己移動的次數加上根結點移動的次數,就是這個結點總共的移動次數,不明白的可以自己動手畫畫。。
#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 10015;
const int inf = 1<<30;
int n,q;
int p[maxn],counts[maxn],tran[maxn];
int find( int x )
{
if( p[x] == x )
return x;
else{
int temp = p[x];
p[x] = find(p[x]);
tran[x] += tran[temp];
return p[x];
}
}
void merge( int u,int v )
{
int x = find(u);
int y = find(v);
if( x != y ){
p[x] = y;
tran[x] ++;
counts[y] += counts[x];
counts[x] = 0;
}
}
void init()
{
for( int i = 1; i <= n; i ++ ){
p[i] = i;
counts[i] = 1;
tran[i] = 0;
}
}
int main()
{
//freopen("data.txt","r",stdin);
int cas,u,v;
char ch;
scanf("%d",&cas);
for( int c = 1; c <= cas; c ++ ){
scanf("%d%d",&n,&q);
init();
printf("Case %d:\n",c);
for( int i = 1; i <= q; i ++ ){
scanf("%*c%c", &ch);
if( ch == 'T' ){
scanf("%d%d",&u,&v);
merge(u,v);
}
else{
scanf("%d",&u);
v = find(u);
printf("%d %d %d\n",v,counts[v],tran[u]);
}
}
}
return 0;
}
int find(int x)
{
int k, j, r;
r = x;
while(r != parent[r]) //查詢跟節點
r = parent[r]; //找到跟節點,用r記錄下
k = x;
while(k != r) //非遞迴路徑壓縮操作
{
j = parent[k]; //用j暫存parent[k]的父節點
parent[k] = r; //parent[x]指向跟節點
k = j; //k移到父節點
}
return r; //返回根節點的值
}
相關文章
- 並查集系列之「路徑壓縮( path compression ) 」並查集路徑壓縮
- HDU 4496D-City2013通化邀請賽D題(並查集 需要壓縮路徑)並查集
- 洛谷 P3366 【模板】最小生成樹(並查集+壓縮路徑(縮短到最高上一級的步驟))並查集
- Xcode外掛路徑、快取路徑、圖片壓縮工具路徑、程式碼片段路徑、symbolicatecrash路徑XCode快取Symbol
- Nginx網路壓縮 CSS壓縮 圖片壓縮 JSON壓縮NginxCSSJSON
- pigz 並行壓縮並行
- 並查集到帶權並查集並查集
- tar的打包-壓縮與解壓縮,並解壓到指定的目錄
- 社交網路 (並查集的應用)並查集
- 並查集(一)並查集的幾種實現並查集
- 並查集(小白)並查集
- (UVA - 208)Firetruck(路徑輸出問題,回溯+並查集/floyd演算法+dfs)並查集演算法
- 常用的壓縮解壓縮以及網路通訊命令
- 用 Huffman 樹實現檔案壓縮並解壓
- 【shell】用shell實現自動壓縮日誌並且清理壓縮包
- Linux上進行並行壓縮Linux並行
- Codeforces 455C Civilization:樹的直徑 + 並查集【合併樹後直徑最小】並查集
- 並查集(Union Find)並查集
- 並查集應用並查集
- The Door Problem 並查集並查集
- 並查集練習並查集
- 並查集的使用並查集
- 並查集—應用並查集
- 寫模板, 並查集。並查集
- JAVA壓縮和解壓縮Java
- zip壓縮和解壓縮
- 並查集(二)並查集的演算法應用案例上並查集演算法
- linux壓縮解壓縮Linux
- 字串的壓縮和解壓縮字串
- The Suspects-並查集(4)並查集
- [leetcode] 並查集(Ⅰ)LeetCode並查集
- [leetcode] 並查集(Ⅱ)LeetCode並查集
- [leetcode] 並查集(Ⅲ)LeetCode並查集
- 並查集演算法並查集演算法
- 並查集深度應用並查集
- 【轉】種類並查集並查集
- 並查集java實現並查集Java
- 並查集-Java實現並查集Java