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;
}
相关推荐
范纹杉想快点毕业3 分钟前
嵌入式系统架构之道:告别“意大利面条”,拥抱状态机与事件驱动
java·开发语言·c++·嵌入式硬件·算法·架构·mfc
近津薪荼7 分钟前
递归专题(4)——两两交换链表中的节点
数据结构·c++·学习·算法·链表
2501_940315268 分钟前
【无标题】2390:从字符串中移除*
java·开发语言·算法
乐观勇敢坚强的老彭9 分钟前
c++寒假营day01下午
c++·算法
散峰而望20 分钟前
【算法竞赛】树
java·数据结构·c++·算法·leetcode·贪心算法·推荐算法
鱼很腾apoc23 分钟前
【实战篇】 第14期 算法竞赛_数据结构超详解(下)
c语言·开发语言·数据结构·学习·算法·青少年编程
123_不打狼36 分钟前
AE(自编码器)与 VAE(变分自编码器)核心区别:原理、目标与应用
深度学习·算法·机器学习·vae
Anastasiozzzz38 分钟前
LeetCode hot100 45 跳跃游戏2
算法·leetcode·游戏
近津薪荼40 分钟前
递归专题(3)——反转链表
数据结构·c++·学习·算法·链表
Tisfy43 分钟前
LeetCode 3013.将数组分成最小总代价的子数组 II:两个堆维护k-1小 + 滑动窗口
算法·leetcode·题解·优先队列··有序集合·滑动窗口