bzoj3376/poj1988[Usaco2004 Open]Cube Stacking 方块游戏

来源:互联网 发布:上海爱知锻造有限公司 编辑:程序博客网 时间:2024/06/10 01:21

题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=3376

题目大意:

编号为1到n的n(1≤n≤30000)个方块正放在地上.每个构成一个立方柱.

有P(1≤P≤100000)个指令.指令有两种:

1.移动(M):将包含X的立方柱移动到包含Y的立方柱上.

2.统计(C):统计名含X的立方柱中,在X下方的方块数目.

题解:

带权并查集

存三个东西,x所在立方柱的最顶端fa[x],x所在立方柱的最底端d[x],x上面有多少个立方柱f[x](下面的图画错了不包含x qwq..画的时候一点感觉都没有)。


那么要求的x下方的数目就可以用f[d[x]]-f[x]来表示。

#include<cstdio>#include<cstdlib>#include<cstring>#include<algorithm>#include<iostream>using namespace std;#define maxn 30100int fa[maxn],f[maxn],d[maxn];int ffind(int x){if (fa[x]!=x){int y=fa[x];fa[x]=ffind(fa[x]);f[x]=f[x]+f[y];d[x]=d[y];}return fa[x];}int main(){//freopen("cubes.in","r",stdin);//freopen("cubes.out","w",stdout);int q,i,x,y;char c;scanf("%d",&q);for (i=1;i<=30000;i++) fa[i]=d[i]=i,f[i]=0;for (i=1;i<=q;i++){scanf("\n%c%d",&c,&x);if (c=='C') {int ls=d[ffind(x)];int oz=ffind(ls);//更新printf("%d\n",f[ls]-f[x]);}else//把x放到y上{scanf("%d",&y);int fx=ffind(x),fy=ffind(y);fa[fy]=fx;int ls=ffind(d[fx]);//更新f[fy]=f[d[fx]]+1;d[fx]=d[fy];}}return 0;}


0 0
原创粉丝点击