zoukankan      html  css  js  c++  java
  • Sequence(尺取)

    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
    11
    1 2 3 4 5

    Sample Output

    2
    3
    题解:求连续子序列和大于等于s的最小长度。可以尺取,若sum<s,左指针右移,若sum>=s右指针左移,当sum<s时左指针继续右移,满足条件打擂台即可。
     1 #include<cstring>
     2 #include<cstdio>
     3 #include<algorithm>
     4 #define Inf 0x3f3f3f3f
     5 #define  ll   long long
     6 using namespace std;
     7 ll str[123400];
     8 int main()
     9 {
    10     ll i,j,m,n,t;
    11     scanf("%lld",&t);
    12     while(t--)
    13     {
    14         scanf("%lld%lld",&m,&n);
    15         for(i=0;i<m;i++)
    16         {
    17             scanf("%lld",&str[i]);
    18         }
    19         ll sum=0,cnt=0,cur=0,flag=0,ans=Inf,count1=0;
    20         while(cur<m)
    21         {
    22             while(count1<m&&sum<=n)
    23             {
    24                 sum+=str[count1++];
    25             }
    26             if(sum<n)
    27                 break;
    28                 flag=1;
    29             sum-=str[cur];
    30             ans=min(ans,count1-cur);
    31             cur++;
    32         }
    33         if(flag)
    34         printf("%lld
    ",ans);
    35         else
    36             puts("0");
    37     }
    38     return 0;
    39 
    40 }
  • 相关阅读:
    2.16.8.内核启动的C语言阶段5
    2.16.7.内核启动的C语言阶段4
    2.16.6.内核启动的C语言阶段3
    2.16.5.内核启动的C语言阶段2
    JAVA_SE基础——34.static修饰成员变量
    JAVA_SE基础——33.this关键字的练习
    JAVA_SE基础——32.this关键字调用本类的构造方法
    JAVA_SE基础——31.this关键字
    JAVA类的方法调用和变量(全套)
    JAVA_SE基础——30.构造代码块
  • 原文地址:https://www.cnblogs.com/moomcake/p/9343255.html
Copyright © 2011-2022 走看看