题目大意:
- 倒香槟,如果满了就溢下去,直到浪费。
- 查询某一盘子的香槟。
注意到:如果抹一层满了,无论如何加香槟都直接跳过去,所以可以开个 数组,指向第一个非满的可以溢出到的一层,直接开始查询,降低复杂度。
至于第一次找出溢出可以的一层,可以用单调栈优化。
#include<iostream>
#include<stack>
#define int long long
#define INF 1e18
const int N = 3e5 + 5;
int n,a[N],q,fa[N],used[N];
void in(int &n) {
char ch = getchar();
int f = 1,ans = 0;
while(ch < '0' || ch > '9') {
if(ch == '-') f *= -1;
ch = getchar();
}
while(ch <= '9' && ch >= '0') ans = (ans << 1) + (ans << 3) + ch - '0',ch = getchar();
n = ans * f;
}
void out(int n) {
if(n < 0) putchar('-'),n *= -1;
if(n > 9) out(n / 10);
putchar(n % 10 + '0');
}
void out(int n,char c) {
out(n),putchar(c);
}
int solve(int pos,int x) {
if(a[pos] - used[pos] > x) { //不需要溢出。
used[pos] += x;
return pos;
}
fa[pos] = solve(fa[pos],x + used[pos] - a[pos]); //指向第一个非满的可以溢出到的。
used[pos] = a[pos]; //装满了。
return fa[pos]; //反回第一个非满的可以溢出到的。
}
signed main() {
in(n),in(q);
std::stack<int> s;
for(int i = 1; i <= n; i ++) {
in(a[i]);
while(!s.empty() && a[s.top()] < a[i]) {
int u = s.top();
s.pop();
fa[u] = i;
}
s.push(i); //单调栈 。
}
a[n + 1] = INF;
used[n + 1] = - INF; //保证浪费的一层永远装不满。
while(!s.empty()) {
int u = s.top();
s.pop();
fa[u] = n + 1;
} //浪费的指针。
while(q --) {
char op;
scanf("%c",&op);
int pos,x;
in(pos);
if(op == '?') {
out(used[pos],'\n'); //直接输出。
} else {
in(x);
solve(pos,x);
}
}
return 0;
}复杂度证明:
- 每个盘子只会被装满一次,复杂度 。
- 没装满的一次询问只会有一次,复杂度 。
- 已经装满了但其他路线的没更新,直接指到头,差不多总共 。
- 单调栈复杂度 。
