E. Binary Deque[双指针好思维题]

Binary Deque

题面翻译

有多组数据。

每组数据给出 n n n 个数,每个数为 0 0 0 或 1 1 1 。你可以选择从两边删数,求至少删几个数才可以使剩下的数总和为 s s s 。

如果不能达到 s s s ,则输出 − 1 -1 −1 。

题目描述

Slavic has an array of length n consisting only of zeroes and ones. In one operation, he removes either the first or the last element of the array.

What is the minimum number of operations Slavic has to perform such that the total sum of the array is equal to s after performing all the operations? In case the sum s can't be obtained after any amount of operations, you should output -1.

样例 #1

样例输入 #1

复制代码
7
3 1
1 0 0
3 1
1 1 0
9 3
0 1 0 1 1 1 0 0 1
6 4
1 1 1 1 1 1
5 1
0 0 1 1 0
16 2
1 1 0 0 1 0 0 1 1 0 0 0 0 0 1 1
6 3
1 0 1 0 0 0

样例输出 #1

复制代码
0
1
3
2
2
7
-1
cpp 复制代码
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
int t, n, m;
int w[2000005];
int main()
{
    cin >> t;
    while (t--)
    {
        int num1 = 0, num2 = 0, temp = 0,sum=0;
        cin >> n >> m;
        for (int i = 1; i <= n; i++)
            cin >> w[i],sum += w[i];
        if (sum < m){//特判
            cout << -1 << endl;结束
            continue;
        }
        int num = 0;
        int ans = 0;
        for (int i = 1, j = 1; i <= n;i++) {
            num += w[i];
            while (j<i && num>m){
            //双指针前后符合并且和太大了就做减法
                num -= w[j++];//减去
            }
            if (num == m){
                ans = max(ans, i - j + 1);//不断更新
            }
        }
        cout <<n-ans << endl;
    }
    return 0;
}
相关推荐
Bigger5 分钟前
🚀 真正实用的前端算法技巧:从 semver-compare 到智能版本排序
前端·javascript·算法
海梨花14 分钟前
【力扣Hot100】刷题日记
算法·leetcode·1024程序员节
DuHz42 分钟前
使用稀疏采样方法减轻汽车雷达干扰——论文阅读
论文阅读·算法·汽车·信息与通信·信号处理
hansang_IR1 小时前
【算法速成课 3】康托展开(Cantor Expansion)/ 题解 P3014 [USACO11FEB] Cow Line S
c++·算法·状态压缩·康托展开·排列映射
m0_748233641 小时前
【类与对象(中)】C++类默认成员函数全解析
开发语言·c++·算法
scilwb1 小时前
STM32 实战:驯服失控的 M3508 电机 - PID 位置环频率的“坑”与“药”
算法·代码规范
chonbw1 小时前
226.翻转二叉树
算法·leetcode
周杰伦_Jay3 小时前
【 RocketMQ 全解析】分布式消息队列的架构、消息转发与快速实践、事务消息
分布式·算法·架构·rocketmq·1024程序员节
sprintzer3 小时前
10.16-10.25力扣计数刷题
算法·leetcode
王哈哈^_^3 小时前
【数据集】【YOLO】【目标检测】建筑垃圾数据集 4256 张,YOLO建筑垃圾识别算法实战训推教程。
人工智能·深度学习·算法·yolo·目标检测·计算机视觉·数据集