Subsequence
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 |
设两个指针(只代表位置)p, q, 推进q, 当sum{p, q} >= S时,推进p直到sum{p, q} <S。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
#define ll long long
#define rep(x, y, z) for(int x=y;x<z;x++)
const int maxn=1e6+7;
const int INF=1e9+7;
int T;
int n, s;
int a[maxn];
int ans;
int p, q;
ll sum;
void init(){
ans=INF;
sum=0;
p=q=0;
}
void solve(){
ans=n+1;
rep(i, 0, n){
sum += a[i];
if(sum >= s){
ans=min(ans, i+1-p);
rep(j, p, i){
sum -= a[j];
if(sum >= s)
ans=min(ans, i-j);
else { p=j+1;break;}
}
}
}
if(ans>n) ans=0;
printf("%d\n", ans);
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
scanf("%d", &T);
while(T--){
init();
scanf("%d%d", &n, &s);
rep(i, 0, n){
scanf("%d", &a[i]);
}
solve();
}
return 0;
}