罗马游戏

题目描述

题解:(模板放上即可)

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1000050;
template<typename T>
inline void read(T&x)
{
    T f = 1,c = 0;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){c=c*10+ch-'0';ch=getchar();}
    x = f * c;
}
int n,m,v[N],dis[N],fa[N],ls[N],rs[N];
char ch[2];
int get_top(int x)
{
    while(fa[x])x=fa[x];
    return x;
}
int merge(int x,int y)
{
    if(!x||!y)return x+y;
    if(v[x]>v[y])swap(x,y);
    rs[x]=merge(rs[x],y);
    fa[rs[x]]=x;
    if(dis[ls[x]]<dis[rs[x]])swap(ls[x],rs[x]);
    dis[x] = dis[rs[x]]+1;
    return x;
}
int pop(int x)
{
    x = get_top(x);
    fa[x] = -1;
    int ret = v[x];
    x = merge(ls[x],rs[x]);
    fa[x] = 0;
    return ret;
}
int main()
{
    read(n);
    for(int i=1;i<=n;i++)read(v[i]),dis[i] = 1;
    read(m);
    for(int x,y,i=1;i<=m;i++)
    {
        scanf("%s",ch);
        if(ch[0]=='M')
        {
            read(x),read(y);
            if(fa[x]==-1||fa[y]==-1)continue;
            x = get_top(x);
            y = get_top(y);
            if(x==y)continue;
            x = merge(x,y);
            fa[x] = 0;
        }else
        {
            read(x);
            if(fa[x]==-1)
            {
                puts("0");
                continue;
            }
            printf("%d\n",pop(x));
        }
    }
    return 0;
}

 

posted @ 2019-01-20 14:55  LiGuanlin  阅读(100)  评论(0编辑  收藏  举报