zoukankan      html  css  js  c++  java
  • POJ 3061 Subsequence 尺取法,一个屌屌的O(n)算法

    Subsequence
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 9050   Accepted: 3604

    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
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <ctime>
    #include <iostream>
    #include <algorithm>
    #include <set>
    #include <vector>
    #include <sstream>
    #include <queue>
    #include <typeinfo>
    #include <fstream>
    typedef long long ll;
    using namespace std;
    //freopen("D.in","r",stdin);
    //freopen("D.out","w",stdout);
    #define sspeed ios_base::sync_with_stdio(0);cin.tie(0)
    #define maxn 100001
    const int inf=0x7fffffff;   //无限大
    int a[maxn];
    int main()
    {
        int t;
        cin>>t;
        while(t--)
        {
            int n,s;
            cin>>n>>s;
            for(int i=0;i<n;i++)
            {
                cin>>a[i];
            }
            ll sum=a[0];
            int st=0,en=0;
            int minn=inf;
            while(en!=n&&st<=en)
            {
                //cout<<st<<" "<<en<<" "<<sum<<endl;
                if(sum>=s)
                {
                    minn=min(minn,en-st+1);
                    sum-=a[st];
                    st++;
                }
                if(sum<s)
                {
                    en++;
                    sum+=a[en];
                }
            }
            if(minn==inf)
                cout<<"0"<<endl;
            else
                cout<<minn<<endl;
        }
        return 0;
    }
  • 相关阅读:
    (二)Spring Security 入门体验之——用户密码配置
    (一)Spring Security 入门体验
    (十二)权限之RBAC
    (十一)jwt详解
    (十)登录拦截器之前后端
    (九)优化登录页面
    (八)前后端整合之跨域问题
    SecureCRT 8.1.4 破解教程
    centOS配置网络(6.8)securCRT连接虚拟机
    二叉树的下一个节点(给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点)
  • 原文地址:https://www.cnblogs.com/qscqesze/p/4248633.html
Copyright © 2011-2022 走看看