POJ3061-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.

思路:用两个指针,一个指向初始点,另一个指向满足区间大于给定值的尾端点,然后不断尺取,每次比较区间长度,记录下最优解。

#include
#include
#include
#include
using namespace std;
typedef long long ll;
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1|1
const int inf = 0x3f3f3f3f;
const int maxn = 1e5 + 10;
int a[maxn];

int main()
{
    int t;
    while(scanf("%d", &t) != EOF)
    {
        while(t--)
        {
            int n;
            ll s, sum = 0;
            scanf("%d%lld", &n, &s);
            for(int i = 1; i <= n; ++i)
            {
                scanf("%d", &a[i]);
                sum += a[i];
            }
            if(sum < s)
            {
                printf("0\n");
                continue;
            }
            int l = 1, r = 1, ans = n;
            ll res = 0;
            while(true)
            {
                while(res < s && r <= n)
                    res += a[r++];
                if(res < s) break;
                ans = min(ans, r - l);
                res -= a[l++];
            }
            printf("%d\n", ans);
        }
    }
    return 0;
}

 

你可能感兴趣的:(技巧)