题解 | #能量辐射#

能量辐射

https://www.nowcoder.com/practice/04c83aedd3e043879ed4464baae0b564

考察单调递减栈
当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;
}

alt

全部评论

相关推荐

LastWh1spe...:ssob真有些人和那个没睡醒一样
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务