福建工程学院寒假作业第一周F题

Subsequence

TimeLimit:1000MS  MemoryLimit:65536K
64-bit integer IO format:%lld
 
问题描述:
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.
 
SampleInput
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5

SampleOutput
2
3
思路:这题求的是满足要求的子序列里最短的序列长度,我们会想一段一段的进行筛选,也就是尺取法;我们可以先定两个标记i、j指向含N个元素的数组的首位,用sum来存储子序列,如果sum小于目标数M,则i++,否则sum减去j指向的元素且j++,随即计数器ans存储短的那个子序列的长度。
详见代码:

j=sum=i=0;
ans=N+1;

while (1)
{
while(i<N&&sum<M)
sum+=a[i++];
if(sum<M)//如果在之前一个while里加完还是小于M则不可能再比M大了
break;
ans=ans<i-j?ans:i-j;
sum-=a[j];
j++;
}

posted @ 2017-01-22 10:52  Thanks_up  阅读(229)  评论(0编辑  收藏  举报