杭电多校第九场 1007Boring data structure problem (hdu7072 双向链表

题意:

给定4种操作,l往左边加入一个数,r往右边加入一个数,g x删除x这个数,q查询中位数。

加入的数从1开始递增

思路:

没什么思维难度,但是链表写的不熟练,然后想用并查集代替,结果不知道为什么大数据的地方挂了,小数据怎么样都能过。

然后学习了一下std的链表写法,只能说是非常优美。

做法就是两个双向链表,然后平衡两边的个数。

一个链表也行,但是跳mid的时候容易出错。

下附代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e7+5;
char s[5];
struct node{
    int nxt,pre,b,v;
}a[maxn];
struct A{
    int _size,_start,_end;
    inline void addl(int x){
        if (_start) a[_start].pre=x;
        a[x].nxt=_start;
        a[x].pre=0;
        _start=x;
        if (!_end) _end=x;
        _size++;
    }
    inline void addr(int x){
        if (_end) a[_end].nxt=x;
        a[x].pre=_end;
        a[x].nxt=0;
        _end=x;
        if (!_start) _start=x;
        _size++;
    }
    inline int popr(){
        if (_size==0){
            _start=0;
            _end=0;
            return 0;
        }
        while (a[_end].v) _end=a[_end].pre;
        a[_end].nxt=0;
        return _end;
    }
    inline int popl(){
        if (_size==0){
            _start=0;
            _end=0;
            return 0;
        }
        while (a[_start].v) _start=a[_start].nxt;
        a[_start].pre=0;
        return _start;
    }
    inline void removel(){
        _size--;
        if (_size==0){
            _start=0;
            _end=0;
            return;
        }
        _start=a[_start].nxt;
        a[_start].pre=0;
    }
    inline void remover(){
        _size--;
        if (_size==0){
            _start=0;
            _end=0;
            return ;
        }
        _end=a[_end].pre;
        a[_end].nxt=0;
    }
}l,r;
int main(){
    int q;
    scanf("%d",&q);
    int tot=0;
    while (q--){
        scanf("%s",s);
        if(s[0]=='L'){
            l.addl(++tot);
            a[tot].b=1;
        }
        else if (s[0]=='R'){
            r.addr(++tot);
            a[tot].b=2;
        }
        else if (s[0]=='Q'){
            printf("%d
",r.popl());
        }
        else {
            int x;
            scanf("%d",&x);
            if (a[x].b==1) l._size--;
            else r._size--;
            a[x].v=1;
        }
        if (l._size>r._size){
            int x=l.popr();
            a[x].b=2;
            l.remover();
            r.addl(x);
        }
        else  if (l._size<r._size-1){
            int x=r.popl();
            a[x].b=1;
            r.removel();
            l.addr(x);
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/i-caigou-TT/p/15156300.html