Subsequence
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 24441 | Accepted: 10320 |
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
题意:给定一个序列,找出最短的子序列长度,使得其和大于或等于S。
分析:首先,序列都是正数,如果一个区间其和大于等于S了,那么不需要在向后推进右端点了,因为其和也肯定大于等于S但长度更长,所以,当区间和小于S时右端点向右移动,和大于等于S时,左端点向右移动以进一步找到最短的区间,如果右端点移动到区间末尾其和还不大于等于S,
结束区间的枚举。
这个题目区间和明显是有趋势的:单调变化,所以根据题目要求很容易求解,但是在使用之间需要对区间前缀和进行预处理计算。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<string>
using namespace std;
const int N=1e5+10;
const int inf=0x3f3f3f3f;
typedef long long LL;
LL s[N];
int main()
{
int T;
scanf("%d",&T);
while(T--){
int n;
LL num;
scanf("%d %lld",&n,&num);
int st=0,en=0;
for(int i=0;i<n;i++) scanf("%lld",&s[i]);
LL sum=0;
int ans=inf;
while(true){
//cout<<"****"<<sum<<endl;
while(en<n&&sum<num){
sum+=s[en++];
}
if(sum<num) break;
ans=min(ans,en-st);
sum-=s[st++];
}
printf("%d\n",ans==inf?0:ans);
}
return 0;
}