ZOJ 3790 Consecutive Blocks(尺取法)

本文探讨了在给定的彩色块序列中,通过移除一定数量的块并重新排列,以达到创建最长连续相同颜色块的目标。通过实例分析了解算法实现及优化策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Consecutive Blocks

Time Limit: 2 Seconds      Memory Limit: 65536 KB

There are N (1 ≤ N ≤ 105) colored blocks (numbered 1 to N from left to right) which are lined up in a row. And the i-th block's color is Ci (1 ≤ Ci ≤ 109). Now you can remove at most K (0 ≤ K ≤ N) blocks, then rearrange the blocks by their index from left to right. Please figure out the length of the largest consecutive blocks with the same color in the new blocks created by doing this.

For example, one sequence is {1 1 1 2 2 3 2 2} and K=1. We can remove the 6-th block, then we will get sequence {1 1 1 2 2 2 2}. The length of the largest consecutive blocks with the same color is 4.

Input

Input will consist of multiple test cases and each case will consist of two lines. For each test case the program has to read the integers N and K, separated by a blank, from the first line. The color of the blocks will be given in the second line of the test case, separated by a blank. The i-th integer means Ci.

Output

Please output the corresponding length of the largest consecutive blocks, one line for one case.

Sample Input
8 1
1 1 1 2 2 3 2 2
Sample Output
4

题意:求在n个数的数列中最多去掉k个数能得到的连续相同数字的最大数量。
思路:这题有很多方法,刚学了尺取法,我就用尺取法做,其中循环结束条件应为是s == n - 1 && t == n,开始我设为t == n,wa了几发。

#include<cstdio>
#include<algorithm>
#include<map>

using namespace std;

int a[100010];
int main()
{
    int n, K;
    while(~scanf("%d%d", &n, &K))
    {
        map<int, int> coun;
        for(int i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
        }
        int res = 0, s = 0, t = 0, k = 0;

        for(;;)
        {
            while(k < K && t < n )
            {
                if(a[t] != a[s])
                {
                    k++;
                    coun[a[t++]]++;
                }
                else
                {
                    coun[a[t++]]++;
                }
            }
            while(k == K && t < n && a[t] == a[s])
            {
                coun[a[t++]]++;
            }
            res = max(res, coun[a[s]]);
            if(s == n - 1 && t == n) break; //结束条件应为 s == n - 1 && t == n 而不是只有 t == n;
            if(a[s] == a[s + 1])
            {
                coun[a[s]]--;
                s++;
            }
            else
            {
                coun[a[s]]--;
                s++;
                k = (t - s) - coun[a[s]];
            }
        }
        printf("%d\n", res);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值