首页 > 其他 > 详细

poj3061---Subsequence

时间:2015-05-01 12:04:15      阅读:90      评论:0      收藏:0      [点我收藏+]
Subsequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 9358   Accepted: 3767

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

分析:这是一道用的尺取法,首先将所有的数字存在一个数组a里面,sum数组里面存的sum[1]=a[0],sum[2]=a[0]+a[1],,,,,,,,sum[n]=a[0]+,,,a[n];另外二分搜索法中lower_bound()函数的使用参考http://blog.csdn.net/niushuai666/article/details/6734403的博客
 int t=lower_bound(sum+j,sum+n,sum[j]+s)-sum; //返回的找到sum[j]+s的上界,再减去j的位置得到的就是他们的和为s的位置
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[100050],sum[100051];
int main()
{
    int n,s;
    int test;
    cin>>test;
    while(test--)
    {
        cin>>n>>s;
        for(int i=0;i<n;i++)
            cin>>a[i];
        memset(sum,0,sizeof(sum));
        for(int i=0;i<n;i++)                 //将它们的和存在一个sum数组里面
            sum[i+1]=sum[i]+a[i];
        if(sum[n]<s)
        {
            printf("0\n");
            continue;
        }
          int res=n;
         for(int j=0;sum[j]+s<=sum[n];j++)
         {
            int t=lower_bound(sum+j,sum+n,sum[j]+s)-sum;
             if(res>t-j)
             {
                 res=t-j;
             }
         }
         printf("%d\n",res);



    }
    return 0;
}


poj3061---Subsequence

原文:http://blog.csdn.net/qq_qingtian/article/details/45418297

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