30分求调

P2866 [USACO06NOV] Bad Hair Day S

注意审题,是从前往后看 ```cpp #include<bits/stdc++.h> using namespace std; stack<int> sta; int n,a[80005]; long long s; int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&a[i]); } for(int i=1;i<=n;i++) { while(!sta.empty()&&a[sta.top()]<=a[i]) { sta.pop(); } // if(sta.empty()) // { // s+=n-i; // } // else // { // s+=sta.top()-i-1; // } 没必要这么麻烦 s+=sta.size(); sta.push(i); } printf("%lld",s); return 0; } ``` 更改一下入栈顺序就可以了
by _____QWQ_____ @ 2024-04-12 17:26:34


还有一种比较简单的方法 @[gloomy_](/user/914443) ```cpp #include <stack> #include <iostream> using namespace std; long long ans,n; stack<int> st; int main() { cin>>n; for(int i=1;i<=n;i++) { int x; cin>>x; while(!st.empty()&&st.top()<=x) { st.pop(); } ans+=st.size(); st.push(x); } cout<<ans; return 0; } ``` 也不难懂
by _____QWQ_____ @ 2024-04-12 17:27:27


@[_____QWQ_____](/user/1092781) 谢谢
by gloomy_ @ 2024-04-12 18:31:23


|