考察单调递减栈
当tower.high小于等于栈顶元素时直接入栈;
当tower.high大于栈顶元素时出栈并更新左右value值;
特别的:当出栈元素等于栈内下一个元素时,将出栈元素value传递给这个等高元素,以便同时传给栈内更高的元素;
结束时:加一个至高元素来更新栈内元素;
struct tower
{
int high, value, position;
};
void solve() {
int n; cin >> n;
vector<tower> towers;
for(int i=0;i<n;i++){
int a, b; cin >> a >> b;
towers.push_back({ a,b,i+1 });
}
towers.push_back({ inf * 2,0,0 });
stack<tower> sta;
vector<int> values(n + 1);
for (tower to:towers) {
while (!sta.empty()&&to.high > sta.top().high) {
tower t= sta.top();
values[to.position] += t.value;
sta.pop();
if (!sta.empty()) {
if (sta.top().high == t.high) {
sta.top().value += t.value;
continue;
}
values[sta.top().position] += t.value;
}
}
sta.push(to);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
ans = max(ans, values[i]);
}
cout << ans;
}

京公网安备 11010502036488号