HDU Monkey King(左偏树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1512

这个题目其实是用左偏树来做的,可是队友直接用优先队列搞了,分析了下复杂度还真对
因为最坏情况下是n*logn*logn的复杂度,也就是说不会有很多次打架的,十万次查询很多都是-1
除非是从小打到大
也就是每次合并优先队列的时候小的往大的里面并,次数最坏也不会太多
我就是左偏树+并查集搞定的,速度当然快些
并查集节i用于并查集,root用于记录当前节点所在集合的左偏树的根节点标号。
每次更新的时候保证并查集根节点对应的root正确就行了!
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 150000;
struct node{
    int left,right;
    int value,dis;
}po[maxn];
int n,m;
struct point{
    int i;
    int root;
}rec[maxn];
int merge(int a,int b){
    if(a==0) return b;
    if(b==0) return a;
    if(po[a].value < po[b].value) swap(a,b);
    po[a].right=merge(po[a].right,b);
    if(po[po[a].left].dis < po[po[a].right].dis) swap(po[a].left,po[a].right);
    if(po[a].right==0) po[a].dis=0;
    else po[a].dis=po[po[a].right].dis+1;
    return a;
}
int init(int n){
    for(int i=1;i<=n;i++){
        rec[i].i=i;
        rec[i].root=i;
    }
    return 0;
}
int find_root(int pos){
    int now=pos,then;
    while(pos!=rec[pos].i)
    pos=rec[pos].i;
    while(now!=pos){
        then=rec[now].i;
        rec[now].i=pos;
        now=then;
    }
    return pos;
}
void Read( int &x ) {
    char ch;
    x = 0;
    ch = getchar();
    while( !(ch >= '0' && ch <= '9') ) ch = getchar();
    while( ch >= '0' && ch <= '9' ) {
        x = x * 10 + ch - '0' ;
        ch = getchar();
    }
}
int union_set(int a,int b,int c){
    if(a < b) {
        rec[a].i=b;
        rec[b].root=c;
    }else{
        rec[b].i=a;
        rec[a].root=c;
    }
    return 0;
}
int main(){
    int i,j,k,a,b,root_a,root_b,p,q,x,y;
    while(scanf("%d",&n)!=EOF){
        init(n);
        for(i=1;i<=n;i++){
           Read(po[i].value);
            po[i].left=po[i].right=po[i].dis=0;
        }
        Read(m);
        while(m--){
            Read(a);
            Read(b);
            root_a=find_root(a);
            root_b=find_root(b);
            if(root_a==root_b) {
                printf("-1\n");
                continue;
            }
            x=rec[root_a].root;
            y=rec[root_b].root;
            p=merge(po[x].left,po[x].right);
            q=merge(po[y].left,po[y].right);
            po[x].left=po[x].right=po[x].dis=0;
            po[x].value/=2;
            po[y].left=po[y].right=po[y].dis=0;
            po[y].value/=2;
            p=merge(p,x);
            q=merge(q,y);
            p=merge(p,q);
            union_set(root_a,root_b,p);
            printf("%d\n",po[p].value);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值