Codeforces Round #650 (Div. 3)C-Social Distance

题目链接

题意:给你一串01串,每个1之间要至少相隔K个单位,问你最多能插入几个1。

思路:分成三段1.从头到第一个1出现,2.从结尾到最后一个1出现,3.中间部分,其中1,2两种情况都是可以插入dis(1出现的位置)/(k+1)个1.第三种情况是每2个1之间的距离x可以插入(x-k)/(k+1),因为从插入第一个1开始要与最前面的1间隔K所以要先减去k。最后对全零的情况进行特判。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
typedef pair<int,int> PII;
const int mod=1e4+7;
const int N=2e6+10;
const int inf=0x7f7f7f7f;


ll gcd(ll a,ll b)
{
    return b==0?a:gcd(b,a%b);
}

ll lcm(ll a,ll b)
{
    return a*(b/gcd(a,b));
}

template <class T>
void read(T &x)
{
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
        write(x / 10);
    putchar('0' + x % 10);
}
int dis[N];
int main()
{
    SIS;
    int t;
    cin>>t;
    while(t--)
    {
        string s;
        int n,k;
        cin>>n>>k;
        cin>>s;
        int cnt=0,one=0;

        for(int i=0;i<n;i++)
        {
            if(s[i]=='1')one++,dis[++cnt]=i+1;

        }
        if(one==0)
        {
            int ans=(n-1)/(k+1)+1;
            cout<<ans<<endl;
        }else{

            int ans=0;
            ans+=(dis[1]-1)/(k+1);
            ans+=(n-dis[cnt])/(k+1);
            for(int i=2;i<=cnt;i++)
            {
                int x=dis[i]-dis[i-1]-1;
                x-=k;
                if(x>=0)ans+=x/(k+1);
            }
            cout<<ans<<endl;

        }
    }

    return 0;
}








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章