POJ - 3061 Subsequence(二分+尺取法)

Subsequence

Descriptions:
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

题目链接:
https://vjudge.net/problem/POJ-3061
题解:
老规矩,先写写翻译吧
给定长度为n的数列a0,a1,a2,a3…以及一个整数s。求总和不小于s的连续子序列的长度的最小值,如果不存在,输出0。
题解来了
如果一个一个一个数去加,肯定会超时,这就要优化一下。
设置新数组sum,sum[i]=a0+a1+a2+a3+…+a[i-1].
这样一来,a[i]+a[i+1]+a[i+2]+…+a[t-1]=sum[t]-sum[i]
这就省去了大把时间、、、、

补充
二分查找的函数有 3 个:
lower_bound(起始地址,结束地址,要查找的数值) 地址:前闭后开。返回的是第一个大于或等于数值出现的位置,如果数值大于数组中全部元素,返回的是结束地址。
upper_bound(起始地址,结束地址,要查找的数值) 地址:前闭后开。返回的是第一个大于数值出现的位置,如果数值大于数组中全部元素,返回的是结束地址。
binary_search(起始地址,结束地址,要查找的数值) 返回的是是否存在这么一个数,是一个bool值。

AC代码

#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <sstream>
#define EPS 1e-10
using namespace std;
int n,s;
int a[100005];
int sum[100005];
int T;
int main()
{
    cin >> T;
    while(T--)
    {
        memset(sum,0,sizeof(sum));//多组测试,每次都需要刷新数组
        memset(a,0,sizeof(a));
        cin >> n >> s;
        for(int i=0; i<n; i++)
            cin >> a[i];
        for(int i=0; i<n; i++)//计算sum
            sum[i+1]+=sum[i]+a[i];
        if(sum[n]<s)//解不存在
            cout << "0" << endl;
        else
        {
            int ans=n;//先随意写一下答案是n个数,与下文判断
            for(int i=0; sum[i]+s<=sum[n]; i++)
            {
                int t=lower_bound(sum+i,sum+n,sum[i]+s)-sum;
                //lower_bound(起始地址,结束地址,要查找的数值) 地址:前闭后开。
                //返回的是第一个大于或等于数值出现的位置,如果数值大于数组中全部元素,返回的是结束地址。
                ans=min(ans,t-i);//t-i表示有几个数
            }
            cout << ans << endl;
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值