LG3377 【模板】左偏树(可并堆)

好博客

1
2

上面那个用数组写的跑的快,且便于封装,就用他的代码了。

代码

#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<ctime>
#include<iostream>
#include<string>
#include<vector>
#include<list>
#include<deque>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<complex>
#pragma GCC optimize ("O0")
using namespace std;
template<class T> inline T read(T&x){
    T data=0;
    int w=1;
    char ch=getchar();
    while(!isdigit(ch))
    {
        if(ch=='-')
            w=-1;
        ch=getchar();
    }
    while(isdigit(ch))
        data=10*data+ch-'0',ch=getchar();
    return x=data*w;
}
typedef long long ll;
const int INF=0x7fffffff;

struct LeftTree
{
    static const int MAXN=1e5+7;
    int ch[MAXN][2],fa[MAXN];
    int val[MAXN],dis[MAXN];
    int merge(int x,int y)
    {
        if(x==0||y==0)
            return x+y;
        if(val[x]>val[y]||(val[x]==val[y]&&x>y))
            swap(x,y);
        ch[x][1]=merge(ch[x][1],y);
        fa[ch[x][1]]=x;
        if(dis[ch[x][0]]<dis[ch[x][1]])
            swap(ch[x][0],ch[x][1]);
        dis[x]=dis[ch[x][1]]+1;
        return x;
    }
    int find(int x)
    {
        while(fa[x])
            x=fa[x];
        return x;
    }
    void pop(int x)
    {
        val[x]=-1;
        fa[ch[x][0]]=fa[ch[x][1]]=0;
        merge(ch[x][0],ch[x][1]);
    }
}LT;

int main()
{
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    int n,m;
    read(n);read(m);
    for(int i=1;i<=n;++i)
        read(LT.val[i]);
    while(m--)
    {
        int opt;
        read(opt);
        if(opt==1)
        {
            int x,y;
            read(x);read(y);
            if(LT.val[x]==-1||LT.val[y]==-1)
                continue;
            int fx=LT.find(x),fy=LT.find(y);
            if(fx==fy)
                continue;
            LT.merge(fx,fy);
        }
        else if(opt==2)
        {
            int x;
            read(x);
            if(LT.val[x]==-1)
                puts("-1");
            else
            {
                int fx=LT.find(x);
                printf("%d\n",LT.val[fx]);
                LT.pop(fx);
            }
        }
    }
//  fclose(stdin);
//  fclose(stdout);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/autoint/p/9542358.html