用两个栈来模拟光标的移动,sum来维护A栈的前缀和,f用来维护最大值。
1 #include <iostream> 2 #include <algorithm> 3 #include <stack> 4 using namespace std; 5 stack<int> A, B; 6 constexpr size_t N = 1e6 + 5; 7 int sum[N], f[N]; 8 9 int main() { 10 int m; 11 cin >> m; 12 f[0] = -1e7;//初始化一定记住 13 while (m --) { 14 char cmd; 15 int x; 16 cin >> cmd; 17 if (cmd == 'I') { 18 cin >> x; 19 A.push(x); 20 sum[A.size()] = sum[A.size() - 1] + x; 21 f[A.size()] = max(f[A.size() - 1], sum[A.size()]); 22 } 23 if (cmd == 'D') 24 if (!A.empty()) 25 A.pop(); 26 27 if (cmd == 'L') { 28 if(!A.empty()) { 29 B.push(A.top()); 30 A.pop(); 31 } 32 } 33 34 if (cmd == 'R') { 35 if (!B.empty()) { 36 A.push(B.top()); 37 B.pop(); 38 sum[A.size()] = sum[A.size() - 1] + A.top(); 39 f[A.size()] = max(f[A.size() - 1], sum[A.size()]); 40 } 41 } 42 43 if (cmd == 'Q') { 44 cin >> x; 45 cout << f[x] << endl; 46 } 47 } 48 return 0; 49 } 50