• 【二分】Subsequence


    [POJ3061]Subsequence
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 15908   Accepted: 6727

    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

     
    题目大意:问最小区间长度K使得序列中有长度为K的连续子序列相加大于等于S,不够输出0
    试题分析:二分序列长度,滑动窗口
     
    代码:
    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<algorithm>
    using namespace std;
    inline int read(){
        int x=0,f=1;char c=getchar();
        for(;!isdigit(c);c=getchar()) if(c=='-') f=-1;
        for(;isdigit(c);c=getchar()) x=x*10+c-'0';
        return x*f;
    }
    #define LL long long
    const int MAXN=1000001;
    const int INF=999999;
    const int mod=999993;
    int N,S;
    int a[1000001];
    int tmp;
    
    bool check(int k){
        long long sum=0;
        for(int i=1;i<=k;i++){
            sum+=a[i];
        }
        if(sum>=S) return true;
        for(int i=2;i+k-1<=N;i++){
            sum-=a[i-1];sum+=a[i+k-1];
            if(sum>=S) return true;
        }
        return false;
    }
    
    int main(){
        int T=read();
        while(T--){
            N=read(),S=read();long long k=0;
            for(int i=1;i<=N;i++) a[i]=read(),k+=a[i];
            if(k<S) {printf("0
    ");continue;}
            int l=1,r=N;
            while(l<=r){
                int mid=(l+r)>>1;
                if(check(mid)) r=mid-1;
                else l=mid+1;
            }
            printf("%d
    ",l);
        }
    }
  • 相关阅读:
    Ext js必包含的几个文件
    设计模式之三:装饰者模式(简单实现(星巴兹咖啡))
    SQLSERVER排查CPU占用高的情况
    函数题练习52找两个数中最大者
    函数题练习53数字金字塔
    JavaScript面向对象tab栏增删改查操作
    JavaScriptObject.defineProperty方法
    Javascript面向对象迭代forEach、some、filter方法以及查询商品案例
    函数题练习51符号函数
    Javascript构造函数和原型
  • 原文地址:https://www.cnblogs.com/wxjor/p/7301448.html
Copyright © 2020-2023  润新知