P1901 发射站
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef long long ll;
// 左右两侧第一小于等于值(存在重复情况)
int n, m, a[1000005], b[1000005];
int lt[1000005], rt[1000005];
int t[1000005];
stack<int> st1; // 存下标
stack<int> st2; // 存下标
int main() {
cin>>n;
for (int i = 1; i <= n; i++) {
cin>>a[i]>>b[i];
lt[i]=rt[i]=-1;
}
// 找右侧第大于值
for (int i = 1; i <= n; i++) {
// a[i]栈顶对应数字,说明栈顶遇到了第一个它,不然早就出栈
while (st1.size()&&a[i]>a[st1.top()]) {
rt[st1.top()] = i;
st1.pop(); // 不出栈,rt[st1.top()]会被后的i更新
}
st1.push(i);
}
// 找左侧第大于值
for (int i = n; i >= 1; i--) {
// a[i]栈顶对应数字小,说明栈顶遇到了第一个比它小的,不然早就出栈
while (st2.size()&&a[i]>a[st2.top()]) {
lt[st2.top()] = i;
st2.pop(); // 不出栈,rt[st1.top()]会被后面的i更新
}
st2.push(i);
}
// 统计每个发射站发出的能量给谁了
for (int i = 1; i <= n; i++) {
if(lt[i]!=-1) t[lt[i]]+=b[i];
if(rt[i]!=-1) t[rt[i]]+=b[i];
}
// 打擂台找最大
int ans = 0;
for (int i = 1; i <= n; i++) {
ans = max(ans, t[i]);
}
cout << ans;
return 0;
}P8082 [COCI 2011/2012 #4] KEKS //先从前面删,如果还有删的次数那就从后面删
#include<bits/stdc++.h>
using namespace std;
#define endl'\n'
int n,m=INT_MAX;
stack<char>s;
string a;
int k;
long long ans[10000005],ans3,ans2[100005];
int main(){
cin>>n>>k>>a;
for(int i=0;i<a.size();i++){
while(s.size()&&s.top()<a[i]){
if(k==0){
break;
}
s.pop();
k--;
}
s.push(a[i]);
}
while(k--){
s.pop();
}
string ans="";
while(s.size())ans+=s.top(),s.pop();
reverse(ans.begin(),ans.end());
cout<<ans<<endl;
return 0;
}
P1823 [COI 2007] Patrik 音乐会的等待 提交答案加入题单复制题目
#include<bits/stdc++.h>
using namespace std;
#define endl'\n'
int n,m=LLONG_MAX;
stack<long long>s;
long long a[100000005],ans,ans3,t[500005];
int main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=n;i++){
t[i]=1;// 统计第i个数⽬前重复了⼏个
while(s.size()&&a[i]>=a[s.top()]){
ans+=t[s.top()];
if(a[i]==a[s.top()]){
t[i]=t[s.top()]+1;
}
s.pop();
}
if(s.size()!=0){
ans++;
}
s.push(i);
}
cout<<ans;
return 0;
}
P2422 良好的感觉```
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef long long ll;
const int N = 2e5 + 10;
ll n;
ll a[N];
ll b[N], c[N]; // 左边第⼀个⼩于和右边第⼀⼩于a[i]的位置
ll d[N];
ll s[N];
stack<ll> st;
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin >> n;
for(int i=1; i<=n; i++) {
cin >> a[i];
s[i] = s[i-1] + a[i];
}
for(int i=n; i>=1; i--) {
while(st.size() && a[st.top()] > a[i]) {
b[st.top()] = i;
st.pop();
}
st.push(i);
}
while(st.size()) st.pop();
for(int i=1; i<=n; i++) {
c[i] = n + 1;
while(st.size() && a[st.top()] > a[i]) {
c[st.top()] = i;
st.pop();
}
st.push(i);
}
ll ans = 0;
for(int i=1; i<=n; i++) {
// 算出a[i]作为最⼩值的区间范围
// 右边界 c[i], 左边界 b[i]
ll x = s[c[i]-1] - s[b[i]]; // 前缀和
ans = max(ans, x*a[i]);
}
cout << ans;
return 0;
}