(UVALive - 2678) Subsequence(前缀和,优化)

链接:https://vjudge.net/problem/UVALive-2678
Time limit3000 msOSLinux

题意:由n个正整数组成的一个序列,给定整数S,求长度最短的连续序列,使他们的和大于等于S。(1<=n<=10^5,S<10^9)

分析:最直接的思路,枚举子序列的起点和终点,时间复杂度为O(n^3),会T,
优化一下,预处理前缀和,时间复杂度降为O(n^2),也会T
假设终点为j,起点为i,s[]数组为前缀和, 那么题目要求的是最小的j-i+1,满足s[j]-s[i-1]>=S
对于终点j,找到最大的i,s[i-1]<=s[j]-S ,而S是前缀和,并且所给的序列均为正数,所以s是递增的
那么可以用二分,时间复杂度为O(nlogn)

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <sstream>
#include <string>
#include <set>
using namespace std;
#define mem(a,n) memset(a,n,sizeof(a))
typedef long long LL;
const LL mod=1e9+7;
const double eps=1e-6;
const LL INF=0x3f3f3f3f;
const int N=1e5+5;
char str1[N],str2[N];
LL s[N];
int main()
{
    int n,S;
    while(~scanf("%d%d",&n,&S))
    {
        LL x;
        s[0]=0;
        for(int i=1; i<=n; i++)
        {
            scanf("%lld",&x);
            s[i]=s[i-1]+x;
        }
        int ans=INF;
        for(int i=1; i<=n; i++)
        {
            int pos=lower_bound(s,s+i,s[i]-S)-s;
            if(pos>0) ans=min(ans,i-pos+1);
        }
        printf("%d\n",ans==INF?0:ans);
    }
    return 0;
}

还可以继续优化: 复杂度降为O(n)

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <sstream>
#include <string>
#include <set>
using namespace std;
#define mem(a,n) memset(a,n,sizeof(a))
typedef long long LL;
const LL mod=1e9+7;
const double eps=1e-6;
const LL INF=0x3f3f3f3f;
const int N=1e5+5;
char str1[N],str2[N];
LL s[N];
int main()
{
    int n,S;
    while(~scanf("%d%d",&n,&S))
    {
        LL x;
        s[0]=0;
        for(int i=1; i<=n; i++)
        {
            scanf("%lld",&x);
            s[i]=s[i-1]+x;
        }
        int ans=INF,j=1;
        for(int i=1; i<=n; i++)
        {
            if(s[j-1]>s[i]-S) continue;
            while(s[j]<=s[i]-S) j++;找到最大的起点位置
            ans=min(ans,i-j+1);
        }
        printf("%d\n",ans==INF?0:ans);
    }
    return 0;
}

这里由浅入深,一步一步,结合题目条件和特点优化, 关键在于 前缀和 和 数组s是递增的这两个地方

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值