提交时间:2024-04-06 18:09:55
运行 ID: 142249
#include<iostream> #include<cstdio> #include<stack> using namespace std; struct node { int idx, h; }; stack<node> stk; long long ans=0; int n,i=0,h,b; void lss() { ans+=(h-b)*(i-stk.top().idx-1); // cout<<ans<<endl; stk.push({i,h}); return; } void eqal() { ans+=(h-b)*(i-stk.top().idx-1); // cout<<ans<<endl; stk.pop();//去掉前一个同高的柱子 stk.push({i,h}); return; } void grat() { while(!stk.empty() && h>stk.top().h) { ans+=(stk.top().h-b)*(i-stk.top().idx-1); // cout<<ans<<endl; b=stk.top().h; stk.pop(); } if(!stk.empty() && h==stk.top().h) eqal(); else if(!stk.empty()) lss(); else { stk.push({i,h}); } return; } int main() { cin>>n>>h; i++; // cout<<"i="<<i<<", h="<<h<<endl; while(!h) { i++; cin>>h; // cout<<"i="<<i<<", h="<<h<<endl; } stk.push({i,h}); while(i<n) //如果设i<=n,无法结束 { i++; cin>>h; // cout<<"i="<<i<<", h="<<h<<endl; while(!h) { i++; cin>>h; // cout<<"i="<<i<<", h="<<h<<endl; } b=0; if(!stk.empty() && h<stk.top().h) lss(); else if(!stk.empty() && h==stk.top().h) eqal(); else if(!stk.empty()) grat(); } cout<<ans; return 0; }