poj-3061 Subsequence 双指针

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.
给出一个由N个正整数(10<N<100 000)组成的序列,每个正整数都小于或等于10000,还有一个正整数S(S<100 000 000)。写一个程序,求序列中连续元素的子序列的最小长度,其和大于或等于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.
第一行是测试用例的数量。对于每一个测试用例,程序都要从第一行中读出数字N和S,并以区间隔开。序列的数字在测试用例的第二行中给出,用间隔隔开。输入将以文件的结束而结束。

Output

For each the case the program has to print the result on separate line of the output file.if no answer, print 0.
对于每一种情况,程序都要将结果打印在输出文件的单独一行,如果没有答案,打印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

Submit

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#include <bitset>
#define IO                       
    ios::sync_with_stdio(false); 
    // cin.tie(0);                  
    // cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 10;
const int maxm = 1e5 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 11092019;
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
int a[maxn];
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    IO;
    int T;
    int n, s;
    scanf("%d", &T);
    while (T--)
    {
        scanf("%d %d", &n, &s);
        for (int i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        int L = 1;
        int R = 1;
        int t = a[1];
        int ans = inf;
        while (L <= n && R <= n) // 区间和 >= s
        {
            if (t >= s)
            {
                ans = min(ans, R - L + 1); // 更新答案
                t -= a[L]; // 左端点左移
                ++L; 
            }
            else // 区间和小于 s 时 
            {
                ++R; // 向右拓
                t += a[R];
            }
        }
        if (ans == inf)
            cout << 0 << endl;
        else
            cout << ans << endl;
    }
    return 0;
}

 

原文地址:https://www.cnblogs.com/apex-wzw/p/13830432.html