POJ 3061.Subsequence

633

题目


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  


Many test cases will be given. 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.


Sample Input  


10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5


Sample Output  


2
3



题解


判断最少需要多少个连续的数能使和大于 s

可以采用二分找到到当前数最近的一个能够使和小于 s 的数的位置(最近的不满足的位置)
i-begin+2 就是前 i 个数在以第 i 个数结束的最短位置

最后返回最小的值即可
如果当前的数本身就已经符合要求,可以直接返回 1

如果最后没有答案应该输出 0
虽然答案没说……

代码


/*
By:OhYee
Github:OhYee
Blog:http://www.oyohyee.com/
Email:oyohyee@oyohyee.com

かしこいかわいい?
エリーチカ!
要写出来Хорошо的代码哦~
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <bitset>
using namespace std;

const int INF = 0x7FFFFFFF;
const int maxn = 100005;

int n,s;
int a[maxn];
long long sum[maxn];

bool Could(int n,int i) {
    return sum[i] - sum[n - 1] < s;
}

int Division(int l,int r,int i) {
    if(l == r) {
        return l;
    }
    int mid = (l + r) / 2;
    if(Could(mid,i))
        return Division(l,mid,i);
    else
        return Division(mid + 1,r,i);
}

bool Do() {
    if(!(cin >> n >> s))
        return false;

    int Min = INF;
    sum[0] = 0;
    for(int i = 1;i <= n;i++) {
        cin >> a[i];
        sum[i] = sum[i - 1] + a[i];
        int begin = Division(1,i,i);
        if(a[i] >= s)
            Min = min(Min,1);
        else if(begin != 1)
            Min = min(Min,i - begin + 2);
    }

    if(Min == INF)
        Min = 0;
    cout << Min << endl;

    return true;
}

int main() {
    while(Do());
    return 0;
}
发布评论
  • 点击查看/关闭被识别为广告的评论