pushpush(双向队列/列表)

                                            pushpush

                                                                时间限制: 1 Sec  内存限制: 128 MB
                                                                                提交: 111  解决: 66
                                                                [提交] [状态] [讨论版] [命题人:admin]

题目描述

You are given an integer sequence of length n, a1,…,an. Let us consider performing the following n operations on an empty sequence b.
The i-th operation is as follows:
1.Append ai to the end of b.
2.Reverse the order of the elements in b.
Find the sequence b obtained after these n operations.

Constraints
1≤n≤2×105
0≤ai≤109
n and ai are integers.

输入

Input is given from Standard Input in the following format:
n
a1 a2 … an

输出

Print n integers in a line with spaces in between. The i-th integer should be bi.

样例输入

4
1 2 3 4

样例输出

4 2 1 3

提示

After step 1 of the first operation, b becomes: 1.
After step 2 of the first operation, b becomes: 1.
After step 1 of the second operation, b becomes: 1,2.
After step 2 of the second operation, b becomes: 2,1.
After step 1 of the third operation, b becomes: 2,1,3.
After step 2 of the third operation, b becomes: 3,1,2.
After step 1 of the fourth operation, b becomes: 3,1,2,4.
After step 2 of the fourth operation, b becomes: 4,2,1,3.
Thus, the answer is 4 2 1 3.

                                                                                        [提交]        [状态]

题意:给n个数a和一个空序列b,每次执行两个操作,①将a[i]放到b的末尾,②翻转b序列,输出执行完n个数后的b序列。

思路:容易想到是将a[i]前后前后地放到b里面,那么用queue或者list都能方便实现。

你可以放入一个数然后反转换另一端放入一个数,前后端来回放数;

queue代码

#include <bits/stdc++.h>
using namespace std;
deque<int> q;
int main()
{
    int n;
    scanf("%d",&n);

    for(int i=1;i<=n;i++)
    {
        int a;
        scanf("%d",&a);
        if(i%2==0)
            q.push_front(a);
        else
            q.push_back(a);
    }
    if(n%2==0)
    {
        printf("%d",q.front());
        q.pop_front();
        while(!q.empty())
        {
            printf(" %d",q.front());
            q.pop_front();
        }
        printf("\n");
    }
    else
    {
        printf("%d",q.back());
        q.pop_back();
        while(!q.empty())
        {
            printf(" %d",q.back());
            q.pop_back();
        }
        printf("\n");
    }

    return 0;
}

list代码


#include <bits/stdc++.h>

#define inf 0x3f3f3f3f

using namespace std;

typedef long long ll;

list<int>l;

int main()

{

    int n, m, t=1;

    scanf("%d",&n);

    for(int i=0; i<n; ++i)

    {

        scanf("%d",&m);

        t = !t;

        if(t) l.push_back(m);

        else l.push_front(m);

    }

    if(!(n%2)) l.reverse();

    for(auto i=l.begin();i!=l.end();++i)

        printf("%d ",*i);

    return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_41021816/article/details/81316716