Codeforces Round #642 (Div. 3)-E K-periodic Garland(字符串,贪心)

题目链接

题意:

给你一个长度为n的01串,每次操作可以将其中一个0变成1,求使得字符串中所有1的距离都是k的最小操作数。

思路:

双层循环,第一层跑k的余数,第二层跑该余数所在的间隔串里最多有多少连续的间隔为k的“1”,最后用字符串中所有的1的个数,减去最多且连续的间隔为k的“1”的个数得出结果。

代码:

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int N=1e6+5;
const int inf=0x3f3f3f3f;
signed main()
{
    IOS;
    int t;
    cin>>t;
    while(t--)
    {
        int n,k,mx=0,num=0;
        string str;
        cin>>n>>k;
        cin>>str;
        for(int i=0;i<k;i++)
        {
            int sum=0;
            for(int j=i;j<n;j+=k)
            {
                if(str[j]=='1')
                {
                    sum++;
                    num++;//求出字符串中一共有多少1
                }
                else
                {
                    sum--;
                }
                sum=max(0LL,sum);//避免间隔的0过多
                mx=max(mx,sum);//求连续的间隔为k的1最多有多少个
            }
        }
        cout<<num-mx<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ACkingdom/article/details/106243778