• POJ 3061 Subsequence(尺取法)


     

    Subsequence
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 18145   Accepted: 7751

    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

     
    尺取法-->挑战详解
    我们设以a[s] 开始总和最初大于S时的连续子序列为a[s] + ... + a[t-1],这时a[s+1] + ... + a[t-2] < a[s] + ... + a[t-2] < S,所以从a[s+1]开始总和最初超过S的连续子序列如果是a[s+1] + ... + a[t'-1]的话,则必然有t <= t'。
    算法思路:
    (1)初始化s = t = sum = 0.
    (2)只要依然有sum < S,就不断将sum增加a[t],并将t增加一。
    (3)如果(2)中无法满足sum >= S则终止。否则 更新结果ans = min(ans, t-s)。
    (4)将sum减去a[t],s增加1然后回到(2)。

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <algorithm>
     4 #define inf 0x3f3f3f3f
     5 using namespace std;
     6 int a[100005];
     7 int main()
     8 {
     9     int t;
    10     scanf_s("%d", &t);
    11     while (t--)
    12     {
    13         int n, s;
    14         cin >> n >> s;
    15         int i;
    16         for (i = 1; i <= n; i++)
    17         {
    18             scanf_s("%d", &a[i]);
    19         }
    20         int st = 1;
    21         int ed = 1;
    22         int sum = 0;
    23         int ans = inf;
    24         while (1)
    25         {
    26             while (ed <=n&&sum < s) 
    27                 sum += a[ed++];
    28             if (sum < s) break;
    29             ans = min(ans, ed - st);
    30             sum -= a[st++];
    31         }
    32         if (ans == inf) printf("%d
    ", 0);
    33         else printf("%d
    ", ans);
    34     }
    35     return 0;
    36 }
    
    
    
     
  • 相关阅读:
    A标签几种状况下的样式问题
    接口Comparator和Comparable的区别和联系
    Hash算法的讲解
    我所理解的面向对象
    MySQL中select * for update锁表的范围
    Java中使用同步关键字synchronized需要注意的问题
    大数据量下高并发同步的讲解(不看,保证你后悔)
    Apache、Tomcat、JBoss、Weblogic四个常用的JavaEE服务器
    ibatis基本内容简介
    Java常见排序算法之归并排序
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/8457108.html
Copyright © 2020-2023  润新知