HDU 2818&&POJ 1988 并查集简单应用
2014-07-19 16:32
381 查看
因为并查集是递归找根节点是自下向上的 ,可以通过找根节点的过程中更新low值
所以以箱子的底部为根节点
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <iostream>
#include <algorithm>
using namespace std;
#define N 500000+5
#define IN freopen("in.txt","r",stdin)
int fa
,have
,low
;//
void init(int n)
{
for(int i=0; i<=n; i++){
fa[i]=i;
have[i]=1;
low[i]=0;
}
}
int find(int x)
{
if(fa[x]==x)
return x;
else
{
int f=fa[x];
fa[x]=find(fa[x]);
low[x]+=low[f];//更新操作
return fa[x];
}
}
void merge(int x,int y)
{
int fx=find(x),fy=find(y);
if(fx==fy)//
return ;
fa[fx]=fy;
low[fx]+=have[fy];//因为是X堆放在Y堆上,所以X堆的底部要加上Y堆所有的箱子个数
have[fy]+=have[fx];//因为X,Y都已经是同一个父亲只需要更新父亲节点的have值
}
int main(){
int p;
//IN;
scanf("%d",&p);
init(30000);//初始化
char c[2];
int a,b;
while(p--){
scanf("%s",c);
if(c[0]=='M'){
scanf("%d%d",&a,&b);
merge(a,b);
}
else
{
scanf("%d",&a);
find(a);//查询前需要更新
printf("%d\n",low[a]);
}
}
return 0;
}
所以以箱子的底部为根节点
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <iostream>
#include <algorithm>
using namespace std;
#define N 500000+5
#define IN freopen("in.txt","r",stdin)
int fa
,have
,low
;//
void init(int n)
{
for(int i=0; i<=n; i++){
fa[i]=i;
have[i]=1;
low[i]=0;
}
}
int find(int x)
{
if(fa[x]==x)
return x;
else
{
int f=fa[x];
fa[x]=find(fa[x]);
low[x]+=low[f];//更新操作
return fa[x];
}
}
void merge(int x,int y)
{
int fx=find(x),fy=find(y);
if(fx==fy)//
return ;
fa[fx]=fy;
low[fx]+=have[fy];//因为是X堆放在Y堆上,所以X堆的底部要加上Y堆所有的箱子个数
have[fy]+=have[fx];//因为X,Y都已经是同一个父亲只需要更新父亲节点的have值
}
int main(){
int p;
//IN;
scanf("%d",&p);
init(30000);//初始化
char c[2];
int a,b;
while(p--){
scanf("%s",c);
if(c[0]=='M'){
scanf("%d%d",&a,&b);
merge(a,b);
}
else
{
scanf("%d",&a);
find(a);//查询前需要更新
printf("%d\n",low[a]);
}
}
return 0;
}
相关文章推荐
- HDU 2818&&POJ 1988 并查集简单应用
- Hdu 1829 A Bug's Life && Poj 1182 食物链 (并查集偏移量的应用)
- POJ 1988 Cube Stacking【并查集的简单应用 堆木块】
- POJ 1988 Cube Stacking【并查集的简单应用 堆木块】
- POJ 2236 Wireless Network 【并查集的简单应用 判断是否在同一连通分量】
- 图论基础之并查集的简单看法:HDU 1232 畅通工程&&More is better
- HDU 1232 & 1213并查集应用 练习
- POJ 1988 并查集的应用 很好地体现了并查集的一些特点
- 二分图的拓展与应用:HDU 2819&&POJ 1486&&HDU 3488&&HDU1853
- POJ 2492 A Bug's Life【并查集的简单应用同类的判断】
- poj 1988_并查集(*)
- POJ 1573 && hdu 1035(简单模拟)
- POJ 1573 && hdu 1035 Robot Motion【简单模拟】
- POJ 2492 A Bug's Life 并查集的应用
- 计算几何基础与应用:HDU 1348&&ZOJ 1648&&POJ 2398&&ZOJ 1010
- hdu 3038 How Many Answers Are Wrong【并查集的简单应用】
- HDU 2818 Building Block, poj 1988 Cube Stacking(带权并查集)
- POJ 1573 && hdu 1035 Robot Motion【简单模拟】
- poj 1611 The Suspects 初级->数据结构->简单并查集的应用
- HDU 1325&&POJ 1308 Is It A Tree? 并查集判断能否树(能否形成环)