1. 程式人生 > >POJ3061 Subsequence 尺取法(雙指標)

POJ3061 Subsequence 尺取法(雙指標)

Subsequence    

POJ - 3061 

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,輸出最短子序列的長度

區間【5,10】

區間【4,15】 

 總結演算法:

  1. 當前區間和小於S時,右端點右移
  2. 當前區間和大於等於S時,左端點右移

尺取法:通過移動左右兩個端點,遍歷一個序列,求得最短區間的演算法;

時間複雜度O(n);

應用尺取法求解問題有兩個特徵:

  1. 問題的答案是滿足某個條件的最短連續序列,或區間
  2. 任意兩個合法區域(滿足題目要求的區間)[a,b]  ,  [c,d] ,若a>c,必有d>=b