Subsequence/POJ 3061/尺取
题目
A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 10000, and a positive integer S (S < 100 000 000) are given. Write a program to find the minimal length of the subsequence of consecutive elements of the sequence, the sum of which is greater than or equal to S.
题目来源:POJ 3061
题目链接
题意
有n个数,给出s,要求找出最少的连续的数使它们的和大于等于s,并输出这些最少的数的个数。
解法
用两个指针去维护一段区间,可以知道当尾指针移动时,头指针也是单调移动的,所以我们只需不断移动两个指针使这段区间的和一直满足大于等于s,并比较区间的长度,找出最小值。
代码:
#include <cstring>
#include <stdio.h>
#include <math.h>
using namespace std;
int T,n,k,l,t,ans,a[100010],sum[100010];
bool flag;
int main()
{
scanf("%d",&T);
while (T--)
{
scanf("%d%d",&n,&k);
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
for (int i=1;i<=n;i++) sum[i]=sum[i-1]+a[i];//前缀和
l=1;t=1; //头指针l,尾指针t
ans=n;
flag=false;
while(t<=n)
{
while (sum[t]-sum[l]+a[l]<k && t<=n) t++;
while (sum[t]-sum[l]>=k && l<=t) l++;
if (sum[t]-sum[l]+a[l]>=k) flag=true;
if (t-l+1<ans) ans=t-l+1;
t++;
}
if (!flag) printf("0\n"); else printf("%d\n",ans);
}
return 0;
}