Subsequence 子序列

Subsequence 191221

答案 思路 英文题翻译为中文

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

思路:

1.子序列的和 不够 S 的时候,子序列向右 拓展(rear=rear+1)。
2.子序列的和 足够的时候,子序列向右 收缩(head=head+1)。

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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值