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 }
    
    
    
     
  • 相关阅读:
    javascript如何处理字符串中的u
    查看postgresql的日志show queries log in PostgreSQL?
    angular7 promiss
    解决echarts的叠堆折线图数据出现坐标和值对不上的问题
    微信小程序将图片数据流添加到image标签中
    深入理解flex布局的flex-grow、flex-shrink、flex-basis
    优先级:content –> width –> flex-basis (limted by max|min-width)
    ubuntu17.10 python3.6 install plugins for AI
    tensorflow import 没找到cudnn库问题解决
    ubuntu17.10 安装ssh
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/8457108.html
Copyright © 2011-2022 走看看