首页 > 其他 > 详细

POJ 3061 Subsequence

时间:2016-08-08 17:21:59      阅读:216      评论:0      收藏:0      [点我收藏+]
Subsequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 12311   Accepted: 5169

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

 
 
 
解析:尺取法,即反复地推进区间的开头和末尾,求取满足条件的最小区间的方法。主要用于解答求取某个序列满足某种条件的连续的最小区间的问题。可依照以下四个步骤进行:
  1. 初始化左右指针
  2. 不断移动右指针,直到满足条件
  3. 如果步骤2中的条件无法满足,则终止,否则更新结果
  4. 移动左指针,跳到步骤2

 

 

 

#include <cstdio>
#include <algorithm>
using namespace std;

const int INF = 0x7fffffff;
const int MAXN = 100000+5;
int a[MAXN];
int n, s;

void solve()
{
    //尺取法
    int l = 0, r = 0;   //初始化左右指针
    int sum = 0, res = INF;
    while(1){
        while(r < n && sum < s){   //不断移动右指针,直到满足条件
            sum += a[r++];
        }
        if(sum < s) //条件无法满足,终止
            break;
        res = min(res, r-l);    //更新结果,相应区间为[l, r)
        sum -= a[l++];  //移动左指针
    }
    printf("%d\n", res == INF ? 0 : res);
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--){
        scanf("%d%d", &n, &s);
        for(int i = 0; i < n; ++i)
            scanf("%d", &a[i]);
        solve();
    }
    return 0;
}

  

POJ 3061 Subsequence

原文:http://www.cnblogs.com/inmoonlight/p/5750053.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!