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.
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.
For each the case the program has to print the result on separate line of the output file.if no answer, print 0.
2 10 15 5 1 3 5 10 7 4 9 2 8 5 11 1 2 3 4 5
2 3
题解:本题的意思是在保持原来顺序不变的条件下,求得几个连续元素之和大于S的最短序列长度。以第一组数据为例:
10 15
5 1 3 5 10 7 4 9 2 8
求第n项与前n项之和得:5 6 9 14 24 31 35 44 46 54 (记为a[i])
t=a[i-1]-s,在序列中小于t的长度为n,a[i-1]到开始位置的长度为m,则在原始序列中由a[i-1]开始向前推长度为m-n+1的数8 2 9之和大于15,长度为3,依次往下推,求出最短长度。
附加:upper_bound与lower_bound的区别:
lower:使用方法如下,
int num[20] = {1,2,3,4,5,5,5,6,7,10};
int k = 7;
int pos1 = lower_bound(num,num+10,k) - num;
以上代码的指的是在数组num中小于k的元素个数(不包含k本身)。pos1=8.
而upper与lower的区别在于:upper包含k本身。pos1=9.
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int i,j,k,n;
while(scanf("%d",&i)!=EOF)
{
while(i--)
{
int a[200000];
scanf("%d%d",&j,&n);
scanf("%d",&a[0]);
for(k=1;k<j;k++)
{
scanf("%d",&a[k]);
a[k]=a[k]+a[k-1];
}
int t=0,sum=j;
if(a[j-1]<n)
{
printf("0\n");
continue;
}
for(k=j-1;k>=0;k--)
{
if(a[k]<n)
break;
t=upper_bound(a , a + j , a[k] - n) - a;
sum=min(sum,k-t+1);
}
printf("%d\n",sum);
}
}
return 0;
}