第六届福建省大学生程序设计竞赛——E The Longest Straight(尺取法)

题目链接:http://acm.fzu.edu.cn/problem.php?pid=2216

题目大意:给出一个N和M,再给出N个数,这N个数都是在0~M这个范围内的。其中的0当做1~M的任意数,不同的0,可以当做不同的数。问最多的连续的数有多少个(重复算一个)?

解题思路:先把N个数映射到1~M的数组上,并同时记录0的个数。然后直接尺取法,当[l, r]区间内0的个数小于等于原有的0的个数时,r就往前挪一个位置,否则l往前挪一个。每次挪动r时判断是否需要更新答案就行了。

Show me the code!

#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1e5 + 1;
int arr[maxn];
int max(int a, int b) {
    return a >= b ? a : b;
}
int main() {
    int T;
    scanf("%d", &T);
    while (T--) {
        memset(arr, 0, sizeof arr);
        int N, M, joker = 0, num;
        scanf("%d%d", &N, &M);
        for (int a = 0; a < N; ++a) {
            scanf("%d", &num);
            if (!num) joker += 1;
            else arr[num] = 1;
        }
        int l = 1, r = 1, count = arr[l] == 0, res = 1;
        while (r <= M) {
            if (l < r && count > joker) {
                if (arr[l] == 0) count -= 1;
                l += 1;
            }
            else {
                r += 1;
                if (r <= M && arr[r] == 0) count += 1;
                if (r <= M && count <= joker) res = max(res, r - l + 1);
            }
        }
        printf("%d\n", res);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值