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;
}

全部评论

相关推荐

03-21 08:46
已编辑
门头沟学院 C++
一个什么都不会的学生:当你有硕士学历的时候HR会说就是比本科生强
点赞 评论 收藏
分享
用户64975461947315:这不很正常吗,2个月开实习证明,这个薪资也还算合理,深圳Java好多150不包吃不包住呢,而且也提前和你说了没有转正机会,现在贼多牛马公司骗你说毕业转正,你辛辛苦苦干了半年拿到毕业证,后面和你说没hc了😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务