Minimal Subarray Length

本文介绍了一种算法,用于解决给定整数序列中找到满足特定条件的最短连续子序列的问题。输入包括测试用例数量、序列长度及目标值等,输出则是满足条件的最短子序列长度。
You are given an integer sequence of length N and another value X. You have to find a contiguous
subsequence of the given sequence such that the sum is greater or equal to X. And you have to find
that segment with minimal length.
Input
First line of the input file contains T the number of test cases. Each test case starts with a line
containing 2 integers N (1 ≤ N ≤ 500000) and X (−109 ≤ X ≤ 109
). Next line contains N integers
denoting the elements of the sequence. These integers will be between −109
to 109
inclusive.
Output
For each test case output the minimum length of the sub array whose sum is greater or equal to X. If
there is no such array, output ‘-1’.
Sample Input
3
5 4
1 2 1 2 1
6 -2
-5 -6 -7 -8 -9 -10
5 3
-1 1 1 1 -1
Sample Output
3
-1

3

题意:求关于数组的子串,其中最小长度满足条件的长度

(个人能力有限,目前只知道这种投机取巧的方法)

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

int num[500005];

int main()
{

    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n,x;
        scanf("%d%d",&n,&x);
        for(int i=0;i<n;++i)
        {
            scanf("%d",&num[i]);
        }
        if(x<=0)
        {
            int c=0;
            for(int i=0;i<n;++i)
            {
                if(num[i]>=x){c=1;break;}
            }
            if(c)printf("1\n");
            else printf("-1\n");
            continue;
        }
        int ans=1000000000,start=0;
        long long  sum=0;
        for(int i=0;i<n;++i)
        {

            sum=sum+num[i];
            if(sum<=0)
            {
                sum=0;
                start=i+1;
            }
            if(sum>=x)
            {
           int tmp=0;
                for(int j=i;j>=0;--j)
                {
                    if(tmp+num[j]>=x)
                    {
                        start=j;
                        break;
                    }
                    tmp+=num[j];
                }
                ans=min(ans,i-start+1);
            }
        }
        if(ans>500001)printf("-1\n");
        else
            printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值