Codeforces Round #650 (Div. 3) C. Social Distance (前缀和)

  • 题意:有一排座位,要求每人之间隔\(k\)个座位坐,\(1\)代表已做,\(0\)代表空座,问最多能坐几人.

  • 题解:我们分别从前和从后跑个前缀和,将已经有人坐的周围的位置标记,然后遍历求每一段连续的\(0\),对于每一段最多能坐\(\lceil len/(k+1) \rceil\),求个和就可.

  • 代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    #include <stack>
    #include <queue>
    #include <vector>
    #include <map>
    #include <set>
    #include <unordered_set>
    #include <unordered_map>
    #define ll long long
    #define fi first
    #define se second
    #define pb push_back
    #define me memset
    const int N = 1e6 + 10;
    const int mod = 1e9 + 7;
    const int INF = 0x3f3f3f3f;
    using namespace std;
    typedef pair<int,int> PII;
    typedef pair<ll,ll> PLL;
     
    int t;
    int n,k;
    string s;
    bool st[N];
    vector<int> v;
     
    int main() {
        ios::sync_with_stdio(false);cin.tie(0);
        cin>>t;
        while(t--){
            cin>>n>>k;
            cin>>s;
            int len=s.size();
            int cnt=0;
            v.clear();
            me(st,0,sizeof(st));
            for(int i=0;i<len;++i){
                if(!st[i] && cnt>0){
                    st[i]=true;
                }
                cnt--;
                if(s[i]=='1'){
                    cnt=k;
                }
            }
            cnt=0;
            for(int i=len-1;i>=0;--i){
                if(!st[i] && cnt>0){
                    st[i]=true;
                }
                cnt--;
                if(s[i]=='1'){
                    cnt=k;
                }
            }
            int pos=-1;
            for(int i=0;i<len;++i){
                if(s[i]=='1' || st[i]){
                    if(i-pos-1>0) v.pb(i-pos-1);
                    pos=i;
                }
            }
            if(s[len-1]=='0' && !st[len-1]){
                if(len-1-pos>0) v.pb(len-1-pos);
            }
            int ans=0;
            for(auto w:v){
                ans+=(w-1)/(k+1)+1;
            }
            cout<<ans<<endl;
        }
        return 0;
    }
    

猜你喜欢

转载自www.cnblogs.com/lr599909928/p/13162350.html