【Poj】-3061-Subsequence

来源:互联网 发布:ubuntu 安装svnserver 编辑:程序博客网 时间:2024/06/12 22:59

Subsequence
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 11823 Accepted: 4962

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

210 155 1 3 5 10 7 4 9 2 85 111 2 3 4 5

Sample Output

23

直接用公式时注意upper和lower的区别,还要理清位置关系,计算地址的差值得到答案

使num[n]-num[m]>=k即要使num[n]-k>=num[m];

#include<cstdio>#include<algorithm>using namespace std;int main(){int t;scanf("%d",&t);while(t--){int n,k,a[100010];int num[100010]={0};scanf("%d %d",&n,&k);for(int i=1;i<=n;i++){scanf("%d",&a[i]);num[i]=num[i-1]+a[i];}if(num[n]<k)printf("0\n");else{int ans=n,y;for(int i=n;i>=1;i--){if(num[i]<k)break;y=upper_bound(num+1,num+1+n,num[i]-k)-(num+1);//因为从1开始不是从0开始,所以减去num+1的地址ans=min(ans,i-y);//就已经把y的值(和num[i]相差大于k的数的下标)减一 }printf("%d\n",ans);}}return 0;}

0 0