[J - Minimal Subarray Length UVALive - 6609] 区间问题

J - Minimal Subarray Length UVALive - 6609

这里写图片描述

1.比赛时没想到用数组存和。。。就遇到了许多尴尬的情况。
如示例:

6 100
10 10 60 80 90 10
9 10
1 1 2 2 2 2 2 -2 4

已经满足条件后,需要向前扫,保留减掉后仍然满足>=x的情况。
比赛时写的代码倒是想到了这个情况,但是还是没有覆盖到所有情况,就如样例2.

        int nowlen=0, sum=0,ans=inf;
        int ave=0;
        for(i=0; i<n; i++)
        {
            if(sum<=0&&sum<x)
            {
                sum=0;
                nowlen = 0;
                ave=i;
            }
            sum+=a[i];
            nowlen++;
            if(sum>=x)
            {
                ans=min(ans,nowlen);
                for(int j=ave; j<i; j++)
                {
                    if(sum-a[j]>=x)
                    {
                        nowlen--;
                        sum=sum-a[j];
                    }
                    else break;
                }
                ans=min(ans,nowlen);
                sum=a[i];
                ave=i;
                nowlen=1;
                if(sum>=x) ans=min(ans,nowlen);
            }
        }

Accepted code

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <algorithm>
#define inf 0x3f3f3f
using namespace std;
int main()
{
    int t;
    int i, j;
    int a[512345],b[512345],c[512345];
    cin>>t;
    while(t--)
    {
        int n,x;
        int ans = inf;
        cin>>n>>x;
        memset(c,1,sizeof(c));
        for(i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            b[i]=a[i];
        }
        for(i=0;i<n;i++)
        {
            if(b[i-1]<=0)
            {
                c[i]=1;
                b[i]=a[i];
            }
            else
            {
                b[i]=b[i-1] + a[i];
                c[i]=c[i-1] +1;
            }
            if(b[i]>=x)
            {

                ans=min(ans,c[i]);
                for(int j=i;j>=0;j--)
                {
                    if(b[i]-b[j]>=x) {ans=min(ans,i-j);break;}
                }
            }
        }
        if(ans!=inf) cout<<ans<<endl;
        else cout<<"-1"<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值