poj 3061 Subsequence

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

前缀和+二分or尺取

二分
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int t,n,m,s[100001],mi;

int main()
{
    scanf("%d",&t);
    while(t --)
    {
        scanf("%d%d",&n,&m);
        mi = n + 1;
        for(int i = 1;i <= n;i ++)
        {
            scanf("%d",&s[i]);
            s[i] += s[i - 1];
        }
        for(int i = 1;i <= n;i ++)
        {
            if(s[i] < m)continue;
            int l = 0,r = i,mid;
            while(l <= r)
            {
                mid = (l + r) / 2;
                if(s[i] - s[mid] < m)r = mid - 1;
                else mi = min(mi,i - mid),l = mid + 1;
            }
        }
        if(mi <= n)printf("%d\n",mi);
        else printf("0\n");
    }
}

尺取

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int t,n,m,s[100001];
int main()
{
    int head,tail,mi;
    scanf("%d",&t);
    while(t --)
    {
        head = tail = 0;
        mi = 200000;
        scanf("%d%d",&n,&m);
        for(int i = 1;i <= n;i ++)
        {
            scanf("%d",&s[i]);
            s[i] += s[i - 1];
        }
        if(s[n] >= m)
        while(tail <= n)
        {
            while(tail <= n && s[tail] - s[head] < m)tail ++;
            while(tail <= n && s[tail] - s[head] >= m)head ++;
            mi = min(mi,tail - head + 1);
        }
        else mi = 0;
        printf("%d\n",mi);
    }
}
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int t,n,m,s[100001];
int main()
{
    int head,tail,mi;
    scanf("%d",&t);
    while(t --)
    {
        head = tail = 0;
        mi = 200000;
        scanf("%d%d",&n,&m);
        for(int i = 1;i <= n;i ++)
        {
            scanf("%d",&s[i]);
            s[i] += s[i - 1];
        }
        if(s[n] >= m)
        while(tail <= n)
        {
            while(tail <= n && s[tail] - s[head] < m)tail ++;
            while(tail <= n && s[tail] - s[head] >= m)head ++;
            mi = min(mi,tail - head + 1);
        }
        else mi = 0;
        printf("%d\n",mi);
    }
}

猜你喜欢

转载自www.cnblogs.com/8023spz/p/9002103.html
今日推荐