第一行包含一個數字N,表示操作的個數。
接下來包含N 行,每行包含一條命令。
對於每個Q k 命令,輸出一個整數表示這個操作的答案。
8
I 2
I -1
I 1
Q 3
L
D
R
Q 2
2
3
• 對於50% 的數據,N <= 1000。
• 對於80% 的數據,N <= 100000。
• 對於100% 的數據,N <= 1000000,插入的數字絕對值大小不會超過1000。
對頂棧,前一個棧記錄數列光標前的數, 後一個棧記錄數列光標後的數,棧頂都是光標方向,這樣一來,操作就很容易了:
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
char c;
int atop, btop;
int n, a[1000005], b[1000005];
int f[1000005], sum[1000005];
int read()
{
int x = 0, flag = 1; char ch = getchar();
while (ch < '0' || ch > '9') { if (ch == '-') flag = -1;ch = getchar();}
while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
return x * flag;
}//快讀
char readx()
{
char ch = getchar();
while (ch != 'I' && ch != 'D' && ch != 'L' && ch != 'R' && ch != 'Q') ch = getchar();
return ch;
}
int main()
{
f[0] = -1e9;
n = read();
for (int i = 1; i <= n; ++i)
{
int x;
c = readx();
if (c == 'I')
{
x = read();
a[++atop] = x;
sum[atop] =sum[atop - 1] + x;
f[atop] = max(f[atop - 1], sum[atop]);
}
if (c == 'D') atop--;
if (c == 'L') {
b[++btop] = a[atop];
atop--;
}
if (c == 'R') {
a[++atop] = b[btop];
btop--;
sum[atop] = sum[atop - 1] + a[atop];
f[atop] = max(f[atop - 1], sum[atop]);
}
if (c == 'Q') {
int k;
k = read();
printf("%d\n", f[k]);
}
}
}