zoukankan      html  css  js  c++  java
  • 尺取法——POJ3061

    #include <iostream>   //nlogn复杂度的写法
    #include <cstdio>
    #include <algorithm>
    using namespace std;
    typedef long long  ll;
    const int INF = 0x3f3f3f3f;
    const int moder = 1e9 + 7;
    const int maxn = 100005;
    
    int a[maxn];
    
    int main()
    {
        int t;
        cin >> t;
        while(t--)
        {
            int n,s;
            scanf("%d%d",&n,&s);
            for(int i=1;i <= n;i++)
                scanf("%d",&a[i]);
    
            for(int i=2;i <= n;i++)
            {
                a[i] = a[i] + a[i-1];
            }
            if(a[n] < s) printf("0
    ");
            else
            {
                int res = n;
                for(int i=1;a[n]-a[i] >= s;i++)
                {
                    int t = lower_bound(a+1,a+n+1,s+a[i]) - a; // - a 非 - a - 1
                    res = min(res,t-i);
                }
                printf("%d
    ",res);
            }
        }
        return 0;
    }
    /*2
    10 15
    5 1 3 5 10 7 4 9 2 8
    5 11
    1 2 3 4 5 */

     O(n)复杂度的写法

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    using namespace std;
    typedef long long  ll;
    const int INF = 0x3f3f3f3f;
    const int moder = 1e9 + 7;
    const int maxn = 100005;
    
    int a[maxn];
    
    int main()
    {
        int t;
        cin >> t;
        while(t--)
        {
            int n,s;
            scanf("%d%d",&n,&s);
            for(int i=1;i <= n;i++)
                scanf("%d",&a[i]);
            int i=1,j=1;
            int sum=0;
            int res = n+1;
            for(;;)
            {
                while(i <= n && sum < s)
                {
                    sum += a[i];
                    i++;
                }
                if(sum < s) break;
                res = min(res,i-j);
                sum = sum - a[j];
                j++;
            }
            if(res > n) res = 0;
            printf("%d
    ",res);
        }
        return 0;
    }
    /*2
    10 15
    5 1 3 5 10 7 4 9 2 8
    5 11
    1 2 3 4 5 */

    ——

  • 相关阅读:
    介绍自己
    第六周作业
    第五周作业
    第四周作业
    秋季学期学习总结
    币值转化
    justintime compiler
    PostgreSQL windows下安装出现问题的解决办法
    Java语言的异常处理,完全理解下面4点就可以了
    Ultraedit用途【来自网络】
  • 原文地址:https://www.cnblogs.com/cunyusup/p/8446801.html
Copyright © 2011-2022 走看看