String Formation(deque,贪心)

题目描述
Takahashi has a string S consisting of lowercase English letters.
Starting with this string, he will produce a new one in the procedure given as follows.
The procedure consists of Q operations. In Operation i (1≤i≤Q), an integer Ti is provided, which means the following:
·If Ti=1: reverse the string S.
·If Ti=2: An integer Fi and a lowercase English letter Ci are additionally provided.
○If Fi=1 : Add Ci to the beginning of the string S.
○If Fi=2 : Add Ci to the end of the string S.
Help Takahashi by finding the final string that results from the procedure.

Constraints
·1≤|S|≤105
·S consists of lowercase English letters.
·1≤Q≤2×105
·Ti=1 or 2.Fi=1 or 2, if provided.
·Ci is a lowercase English letter, if provided.

输入
Input is given from Standard Input in the following format:

S
Q
Query1
:
QueryQ
In the 3-rd through the (Q+2)-th lines, Queryi is one of the following:
1
which means Ti=1, and:
2 Fi Ci
which means Ti=2.

输出
Print the resulting string.

样例输入
【样例1】
a
4
2 1 p
1
2 2 c
1
【样例2】
a
6
2 2 a
2 1 b
1
2 2 c
1
1
【样例3】
y
1
2 1 x

样例输出
【样例1】
cpa
【样例2】
aabc
【样例3】
xy

提示
样例1解释
There will be Q=4 operations. Initially, S is a.
Operation 1: Add p at the beginning of S. S becomes pa.
Operation 2: Reverse S. S becomes ap.
Operation 3: Add c at the end of S. S becomes apc.
Operation 4: Reverse S. S becomes cpa.
Thus, the resulting string is cpa.

样例2解释
There will be Q=6 operations. Initially, S is a.
Operation 1: S becomes aa.
Operation 2: S becomes baa.
Operation 3: S becomes aab.
Operation 4: S becomes aabc.
Operation 5: S becomes cbaa.
Operation 6: S becomes aabc.
Thus, the resulting string is aabc.

思路:

分析可以知道最耗时间的操作就是翻转

因为操作次数很多,如果每次都翻转,肯定会超时

所以可以对每次翻转做一个标记,最后看标记的次数是偶数还是奇数再决定要不要翻转输出即可

对于每次需要添加在前面的操作,如果翻转了就添加在后面

对于每次需要添加在后面的操作,如果翻转了就添加在前面


AC代码

#include <iostream>
#include <deque>
#include <algorithm>
 
using namespace std;
 
string str;
int q,t;
bool flag;
 
deque<char> arr;
 
int main()
{
    ios::sync_with_stdio(false);
    cin >> str >> q;
    for(int i = 0; i < str.size(); i++)
    {
        arr.push_back(str[i]);
    }
    while(q--)
    {
        int f;
        cin >> t;
        if(t == 1)
        {
            if(flag) flag = 0;
            else flag = 1;
        }
        else
        {
            char ch;
            cin >> f >> ch;
            if( (f == 1 && flag == 0) || (f == 2 && flag == 1) )
            {
                arr.push_front(ch);
            }
            else
            {
                arr.push_back(ch);
            }
        }
    }
    if(flag) reverse(arr.begin(),arr.end());
    for(int i = 0; i < arr.size(); i++)
    {
        cout << arr[i];
    }
    cout << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值