当前位置: 代码迷 >> 综合 >> Subsequence UVAlive 2678(尺取法)
  详细解决方案

Subsequence UVAlive 2678(尺取法)

热度:92   发布时间:2023-11-22 01:17:26.0

题目链接

https://vjudge.net/problem/UVALive-2678

题目

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.

Input

Many test cases will be given. For each test case the program has to read the numbers N and S,
separated by an interval, from the first line. The numbers of the sequence are given in the second line
of the test case, separated by intervals. The input will finish with the end of file.

Output

For each the case the program has to print the result on separate line of the output file.

Sample Input

10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5

Sample Output

2
3

题意

给定一个长度为N的整数序列,和一个值S,求最小的连续区间长度使得该区间之和大于等于S。

分析

尺取法:反复推进区间的开头和末尾
先推进区间末尾,使区间满足条件,即区间之和大于等于S;然后推进区间开头,使区间不满足条件;如此反复进行即可得出答案。
因为区间末尾顶多变化N次,区间开头变化的次数总小于等于区间末尾的变化次数,所以时间复杂度O(N)。

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#define INF 0x3f3f3f3fusing namespace std;const int maxn=1e5+100;
int N,S,a[maxn],ans,sum;int main()
{while(~scanf("%d%d",&N,&S)){memset(a,0,sizeof(a));for(int i=1;i<=N;i++)scanf("%d",&a[i]);sum=a[1],ans=INF;int i=1,j=1;//尺取法while(i<=N && j<=N){//推进区间的开头while(sum<S && j<=N) j++,sum+=a[j];if(sum<S) break;ans=min(ans,j-i+1);//推进区间的末尾do{sum-=a[i++];if(sum>=S){ans=min(ans,j-i+1);}}while(sum>=S && i<=N);}printf("%d\n",ans==INF?0:ans);}return 0;
}
  相关解决方案