UVALive 2678 - 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.

Input:

Many test cases will be given. 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

Sample Input:

10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5

Sample Output:

2
3

题目链接

题目要求找出大于等于m的最短序列长度。
直接暴力枚举所有情况肯定会超时,所以枚举终点,然后找到离终点最近的一个满足条件的起点位置,不断维护起点和结果。

AC代码:

#include <bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
typedef long long ll;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const int maxn = 1e5+5;
const double eps = 1e-5;
const double e = 2.718281828459;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n, m;
    int a[maxn], sum[maxn];
    sum[0] = 0;
    while (cin >> n >> m) {
        for (int i = 1; i <= n; ++i) {
            cin >> a[i];
            sum[i] = sum[i - 1] + a[i];
        }
        int left = 1, ans = n + 1;
        for (int i = 1; i <= n; ++i) {
            if (sum[i] - sum[left - 1] < m) {
                continue;
            }
            while (sum[i] - sum[left] >= m) {
                left++;
            }
            ans = ans < i - left + 1 ? ans : i - left + 1;
        }
        ans = ans == n + 1 ? 0 : ans;
        cout << ans << endl;
    }
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务