insert 1, insert 2, insert 3...insert k

C++实现区间内合法1的数量
这篇文章介绍了一种使用C++编程语言解决的问题,计算给定数组中每个数字右侧存在至少一个1的子区间数量。使用vector代替栈来避免内存限制,并通过动态维护合法1的位置求解。

题目

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
//stack<int> p[maxn], st;
//用stack会MLE,vector不会
vector<int> p[maxn], st;//p[i]表示i这个数字左边最近的合法的1的位置(即这个1和数字i之间有2,3,...,i-1)
                        //st维护当前合法的1的位置    
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n, i, j;
    long long res = 0;
    cin >> n;
    for(i = 1; i <= n; i++){//枚举区间右端点i,[1, i]有多少个合法的1,就有多少个合法的以i为            
                            //右端点的区间
        int x;
        cin >> x;
        if(x == 1){
            p[1].push_back(i);
            st.push_back(i);
            res += st.size();
        }
        else if(p[x - 1].empty()){
            while(!st.empty()) st.pop_back();
        }
        else{
            int pos = p[x - 1].back();
            p[x - 1].pop_back();
            p[x].push_back(pos);
            while(!st.empty() && st.back() > pos) st.pop_back();
            res += st.size();
        }
    }
    cout << res;
    return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__night_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值