Subsequence

    xiaoxiao2025-04-28  12

    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

    尺取法,第一次接触到,看了很多博客,渐渐懂了一点;明白了它的应用是在这样一类问题,在一组数据中找出不大于某个数的

    “最优连续子序列”。

    思路:

     这幅图便是尺取法怎么“取”的过程了。

      整个过程分为4布:

        1.初始化左右端点

        2.不断扩大右端点,直到满足条件

        3.如果第二步中无法满足条件,则终止,否则更新结果

        4.将左端点扩大1,然后回到第二步

    <span style="font-family:KaiTi_GB2312;font-size:18px;">#include<cstdio> #include<cstring> #include<algorithm> #define size 100009 using namespace std; int a[size],n,s; void solve() { int sum=0,ans=n+1,x=0,j=0; while(1) { while(j<n&&sum<s) sum+=a[j++]; if(sum<s) break; ans=min(ans,j-x); sum-=a[x++]; } if(ans>n) ans=0; printf("%d\n",ans); } int main() { int i,t; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&s); for(i=0;i<n;i++) scanf("%d",&a[i]); solve(); } return 0; }</span>

    转载请注明原文地址: https://ju.6miu.com/read-1298544.html
    最新回复(0)