Subsequence
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 12664 | Accepted: 5346 |
Description
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
The first line is the number of test cases. 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.if no answer, print 0.
Sample Input
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
Sample Output
2
3
Source
题目大意:
给你n个数的序列,让你找一个连续的子序列,使其和不小于S,让你输出这个子序列的最短长度。如果找不到这样的子序列,输出0即可。
思路:
1、本题可以维护前缀和然后进行一波二分查找。时间复杂度O(nlogn),相对而言尺取法更优,时间复杂度O(n)。
2、如果设定a1+a2+a3+a4+a5+.......+at>=S&&a1+a2+a3+a4+a5+.......+at-1<S,
那么显然:a2+a3+a4+a5+.......+at<S.
那么如果也有:a2+a3+a4+a5+............+att>S,
那么一定有:tt>t;
3、那么根据以上特性,我们设定一个起点t,一个终点s,一个和sum,表示当前子序列的起点和终点,以及子序列的和。
算法过程如下:
①首先初始化t=s=sum=0;
②如果sum<S,sum+=a【t】;t++;
③否则ans=min(t-s,ans);sum-=a【s】,s++;
4、按照上述描述过程实现代码即可。
Ac代码:
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
int a[1000000];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,ss;
scanf("%d%d",&n,&ss);
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int s,t,sum;
s=0;t=0;sum=0;
int ans=0x3f3f3f3f;
while(1)
{
while(t<n&&sum<ss)
{
sum+=a[t];
t++;
}
if(sum<ss)break;
else ans=min(ans,t-s);
sum-=a[s];
s++;
}
if(ans==0x3f3f3f3f)printf("0\n");
else
printf("%d\n",ans);
}
}