【hihoCoder 1819 --- 棧的加強版】
題目來源:點擊進入【hihoCoder 1819 — 棧的加強版】
Description
請你實現一個加強版的棧,支持以下操作:
push x: 向棧頂加入一個整數x
pop: 從棧頂彈出一個整數,並且輸出該整數
inc k x: 將處於棧底的前k個整數加x。
Input
第一行包含一個整數N,代表操作的數量。
以下N行每行一條操作。
1 ≤ N ≤ 200000, 0 ≤ x ≤ 100000, 1 ≤ k ≤ 當前棧的大小
Output
對於每一個pop操作,輸出彈出的整數數值。
Sample Input
6
push 1
inc 1 2
push 2
inc 2 2
pop
pop
Sample Output
4
5
解題思路
C/C++直接暴力是過不了的,但是java直接暴力好像能過,只能歸功於java的兩倍時間。
如果不暴力的話我們可以根據棧的特點:先進後出。設置一個add數組標記第i位加強多少,每次輸出一個就將add[i]標記到add[i-1]然後將add[i]=0;這樣我們輸出時只需將第i位和add[i]之和輸出即可。
AC代碼(C++):
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <map>
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int MAXN = 200005;
const int MOD = 1e9+7;
int arr[MAXN],add[MAXN];
int main(){
SIS;
int n,top=0,x,y;
string s;
cin >> n;
while(n--){
cin >> s;
if(s=="push"){
cin >> x;
arr[++top]=x;
}else if(s=="pop"){
add[top-1]+=add[top];
cout << arr[top]+add[top] << endl;
add[top]=0;
top--;
}else{
cin >> x >> y;
add[x]+=y;
}
}
return 0;
}