SGU - 271 Book Pile (双向队列)

本文介绍了一种通过双向链表和vector实现的书名序列操作算法。该算法能高效处理书名添加及前k个书名顺序翻转的操作,同时保持良好的数据结构优化。

题意:

给出一个书名的序列从上到下,现在有两宗操作,1是add一个书名,2是最开始的k个
书名顺序翻转,求出操作结束之后的序列。

思路:

看似很简单的题需要思考其数据结构的优化,方法是:
记录前k个书名,其余的记录在一个数组中就行了,我们选用vector保存其它书名。
用双向链表保存k个书名,那么链表的头尾可以控制认为是那个是正反顺序。具体看
代码。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

int n,m,k;
deque<string>que;
vector<string>str;

int main()
{
    //freopen("in.txt","r",stdin);

    cin>>n>>m>>k;
    string book;
    for(int i = 1;i <= n; i++) {
        cin>>book;
        que.push_back(book);
    }
    while(que.size() > k) {
        str.push_back(que.back());
        que.pop_back();
    }
    string op;
    int dirction = 1;   //1表示输入的顺序
    for(int i = 1;i <= m; i++) {
        cin>>op;
        if(op[0] == 'A') {
            int t;
            if(op[5] == ')')
                t = 1;
            else if(op[6] == ')') {
                t = 2;
            }
            else t = 3;
            string temp(op,4,t);
            if(dirction) {
                que.push_front(temp);
                if(que.size() > k) {
                    str.push_back(que.back());
                    que.pop_back();
                }
            }
            else {
                que.push_back(temp);
                if(que.size() > k) {
                    str.push_back(que.front());
                    que.pop_front();
                }
            }
        }
        else {
            dirction = 1 - dirction;
        }
    }

    if(dirction) {
        while(!que.empty()) {
            cout<<que.front()<<endl;
            que.pop_front();
        }
    }
    else {
        while(!que.empty()) {
            cout<<que.back()<<endl;
            que.pop_back();
        }
    }
    for (int i = str.size() - 1; i >= 0; i--)
            cout << str[i] << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值