B. Repainting Street(枚举+贪心)Technocup 2021 - Elimination Round 2
原题链接: http://codeforces.com/contest/1415/problem/B

 测试样例
input
3
10 2
1 1 2 2 1 1 2 2 2 1
7 1
1 2 3 4 5 6 7
10 3
1 3 3 3 3 1 2 1 3 3
output
3
6
2
题意: 给定一个长度为 n n n的颜色序列 a a a和一个限制常数 k k k,你可以进行如下操作:选定一个区间 [ l , r ] [l,r] [l,r],这个区间长度必须小于等于 k k k。然后将这个区间中的颜色换成你想要的颜色。现在请你计算出至少需要进行多少次操作才能将颜色序列中的颜色值都相同。
解题思路: 由于颜色序列的值只有 1 1 1~ 100 100 100,故我们完全可以枚举我们最后想要将颜色序列的值变为什么样的。而如果我们确定了,那么我们肯定是将其他的不同的变为相同的。故我们遍历计算取最优值即可。尤其要注意的就是我们在计算最少操作次数的时候利用贪心,即若确定了一个值要用,那么从这个值开始的 k − 1 k-1 k−1的单位都被它维护。一定会被修改。 具体看AC代码。
AC代码
/*
*blog:https://blog.csdn.net/hzf0701
*邮箱:unique_powerhouse@qq.com
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*/
#include<bits/stdc++.h>
#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,n,a) for(int i=n;i>=a;i--)
using namespace std;
typedef long long ll;
const int maxn=1e5+10;//数组所开最大值
const int mod=1e9+7;//模
const int inf=0x3f3f3f3f;//无穷大
int t;
int n,k;
int a[maxn];
int cal(int x){
    int ans=0,len=0;
    rep(i,1,n){
        if(i<=len)continue;
        if(a[i]==x)continue;
        ans++,len=i+k-1;
    }
    return ans;
}
void solve(){
    int minn=inf;
    rep(i,1,100){
        minn=min(minn,cal(i));
    }
    cout<<minn<<endl;
}
int main(){
    while(cin>>t){
        while(t--){
            cin>>n>>k;
            rep(i,1,n){
                cin>>a[i];
            }
            solve();
        }
    }
    return 0;
}

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号