链接: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是递增的这两个地方