• POJ


    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


    经典的尺取法,用来判断一段连续的序列的加和,自然而然的想到尺取法。
    以前对尺取法理解的不够到位,没有明白尺取法的精妙所在,如今知道了,不得不赞佩其什么的复杂度。

    当第一次发现成立的连续段时,不要退出,继续推进,可以得到所有的满足条件的连续段,进而得到最短的那个段。

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<string.h>
     4 #include<math.h>
     5 #include<algorithm>
     6 #include<queue>
     7 #include<stack>
     8 #include<deque>
     9 #include<iostream>
    10 using namespace std;
    11 int con[100009];
    12 int main()
    13 {
    14     int i,p,j;
    15     int n,s,t,head,tail,flag,mid;
    16     int big;
    17     long long sum=0;
    18     while(scanf("%d",&t)!=EOF)
    19     {
    20         for(i=1; i<=t; i++)
    21         {
    22             scanf("%d%d",&n,&s);
    23             for(j=0; j<n; j++)
    24                 scanf("%d",&con[j]);
    25             big=1000000000;
    26 
    27             head=tail=0;
    28             flag=0;
    29             sum=con[0];
    30             while(1)
    31             {
    32                 if(head<tail||head>=n||tail>=n||head<0||tail<0)
    33                     break;
    34                 if(sum<s)
    35                 {
    36                     head++;
    37                     sum+=con[head];
    38                 }
    39                 else if(sum>=s)
    40                 {
    41                     mid=head-tail+1;
    42                     if(mid<big)
    43                         big=mid;
    44                     sum-=con[tail];
    45                     tail++;
    46 
    47                 }
    48             }
    49             if(big==1000000000)
    50                 printf("0
    ");
    51             else
    52                 printf("%d
    ",big);
    53         }
    54     }
    55 
    56 return 0;
    57 }
    View Code
  • 相关阅读:
    批量重命令文件名称的几种方式
    SecureCRT常用快捷键
    ipv4地址从最后一位按步长递增
    win32
    GDI根据位图和透明度创建蒙版
    git bash的一些使用
    win32
    win32
    win32
    QT
  • 原文地址:https://www.cnblogs.com/daybreaking/p/9375532.html
Copyright © 2020-2023  润新知