bzoj1455: 罗马游戏

链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1455

题意:中文题。。

分析:裸的可并堆练习题。我是在黄学长那学的左偏堆(http://hzwer.com/2563.html)。看我黄学长的定义后,我理解了左偏堆。但是!细看代码实现你会发现,与定义有出入,一开始我还以为黄学长哪里出错了,因为很简单的出几组数据就能发现黄学长的代码建的不是二叉树,而是"多叉",因为有些父亲和儿子互相不匹配。最后想了半天才看出fa[i]并不一定是指向父亲,而是可能指向到祖先路径上的任何一个祖先,而且黄学长查询祖先是用的是并查集的路径压缩。最后我得出了几点想法。(1)路径压缩是能减少寻找祖先的时间的。(2)节点i的父亲是谁不重要,节点i所在的堆的祖先(堆顶)是谁才重要,但是节点i的父亲必须有指向i的边,这样才能合并。上次匆匆看了下黄学长的代码以为会了,这次回头一看却发现很多细节,也给了我一些启发,在学新东西的时候如果能加入以前学习的知识点,比如这题的路径压缩,不仅可以巩固之前所学知识点,还能练习结合多个知识点。

代码:

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<math.h>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int N=1000010;
const int MAX=151;
const int MOD=1000007;
const int MOD1=100000007;
const int MOD2=100000009;
const int INF=2100000000;
const double EPS=0.00000001;
typedef long long ll;
typedef unsigned long long ull;
int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
char s[3];
int n,m,q[N];
int fa[N],l[N],r[N],d[N],h[N];
void init() {
    scanf("%d", &n);h[0]=-1;
    for (int i=1;i<=n;i++) {
        scanf("%d", &d[i]);
        fa[i]=i;l[i]=r[i]=h[i]=q[i]=0;
    }
}
int find_fa(int x) {
    return fa[x]==x?x:fa[x]=find_fa(fa[x]);
}
int mergee(int a,int b) {
    if (!a) return b;
    if (!b) return a;
    if (d[b]<d[a]) { a^=b;b^=a;a^=b; }
    r[a]=mergee(r[a],b);
    if (h[r[a]]>h[l[a]]) { l[a]^=r[a];r[a]^=l[a];l[a]^=r[a]; }
    h[a]=h[r[a]]+1;
    return a;
}
void deal() {
    int a,b;
    scanf("%d", &m);
    while (m--) {
        scanf("%s", s);
        if (s[0]=='M') {
            scanf("%d%d", &a, &b);
            if (q[a]||q[b]) continue ;
            a=find_fa(a);b=find_fa(b);
            if (a!=b) fa[a]=fa[b]=mergee(a,b);
        } else {
            scanf("%d", &a);
            if (q[a]) printf("0\n");
            else {
                a=find_fa(a);q[a]=1;
                printf("%d\n", d[a]);
                fa[a]=mergee(l[a],r[a]);
                fa[fa[a]]=fa[a];
            }
        }
    }
}
int main()
{
    init();
    deal();
    return 0;
}


/*
7
1 2 3 4 5 6 7
12
M 1 2
M 2 3
M 3 4
M 7 6
M 6 5
K 4
K 4
K 4
K 4
K 7
K 7
K 7
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值