zoukankan      html  css  js  c++  java
  • 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 }
    
    
    
     
  • 相关阅读:
    day13-web前端之JS与JQuery
    day16-python项目Django框架之基础
    day12-HTML、CSS与blog页面讲解
    day11-MySQL数据操作索引备份触发器
    day10-python并发编程之多线程协程及MySQL
    day9-python并发编程之多进程多线程
    day8-异常处理与网络编程
    面向对象实战扩展(课外阅读)
    day7-面向对象之继承组合多态封装等
    python学习大纲
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/13271184.html
Copyright © 2011-2022 走看看