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;
}
相关推荐
葫三生2 分钟前
如何评价《论三生原理》在科技界的地位?
人工智能·算法·机器学习·数学建模·量子计算
拓端研究室2 小时前
视频讲解:门槛效应模型Threshold Effect分析数字金融指数与消费结构数据
前端·算法
随缘而动,随遇而安4 小时前
第八十八篇 大数据中的递归算法:从俄罗斯套娃到分布式计算的奇妙之旅
大数据·数据结构·算法
IT古董5 小时前
【第二章:机器学习与神经网络概述】03.类算法理论与实践-(3)决策树分类器
神经网络·算法·机器学习
水木兰亭8 小时前
数据结构之——树及树的存储
数据结构·c++·学习·算法
Jess078 小时前
插入排序的简单介绍
数据结构·算法·排序算法
老一岁8 小时前
选择排序算法详解
数据结构·算法·排序算法
xindafu9 小时前
代码随想录算法训练营第四十二天|动态规划part9
算法·动态规划
xindafu9 小时前
代码随想录算法训练营第四十五天|动态规划part12
算法·动态规划
ysa0510309 小时前
Dijkstra 算法#图论
数据结构·算法·图论