欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

1221 Subsequence 子序列

程序员文章站 2024-03-18 23:34:34
...

title 题目:

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.
对于每个测试用例,程序必须打印结果在单独的一行上。
(此题的输出应该是输出子序列的长度)

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

C++ 代码:

#include <cmath>
#include <iostream>

typedef long long ll;
using namespace std;
const int inf = 0x7fffffff;   //无限大
int num[100001];

int main() {
    int cycle;
    cin >> cycle;
    while (cycle--) {
        int N, S;
        cin >> N >> S;
        for (int i = 0; i < N; i++) {
            cin >> num[i];
        }
        ll sum = num[0];    //子序列和
        int head = 0, rear = 0;
        int answerLength = inf;
        while (rear != N && head <= rear) {
            if (sum >= S) {
                answerLength = min(answerLength, rear - head + 1);
                sum -= num[head];
                head++; //当前子序列长度剪短
            } else {
                rear++; //当前子序列长度增加 //因为总和不够S
                sum += num[rear];
            }
        }
        if (answerLength == inf) {
            cout << "0" << endl;
        } else {
            cout << answerLength << endl;
        }
    }
    return 0;
}
相关标签: 算法 c++