1506B - Partial Replacement - CodeForces Solution


greedy implementation *1100

Please click on ads to support us..

Python Code:

import sys
N = int (2e5 + 5)
sys.setrecursionlimit (N)

def charming () :
  n, k = map (int, input ().split ())
  s = input (); pos = list ();
  for i in range (len (s)) :
    if s[i] == '*' : pos.append (i)
  res = 0; last = pos[0]; i = 1
  if len (pos) <= 1 : print (1); return
  while True :
    j = i
    while j < len (pos) and pos[j] - last <= k : j += 1
    if j == len (pos) : break
    res += 1; i = j; last = pos[j - 1]
  print (res + 2)
    
for t in range (int (input ())) : charming ()

C++ Code:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    int t;
    cin>>t;
    for (;t --> 0;) {
        int n,k;
        cin>>n>>k;
        string s;
        cin>>s;
        int last=-10000,prev=-10000,ans=0;
        for (int i=0;i<n;i++) {
            if (s[i]=='*') {
                if (ans==0) {
                    last=prev=i;
                    ++ans;
                } else if (i-last>k) {
                    last=prev;
                    prev=i;
                    ++ans;
                } else
                    prev=i;
            }
        }
        if (last!=prev)
            ++ans;
        cout<<ans<<'\n';
    }
    return 0;
}
    


Comments

Submit
0 Comments
More Questions

236A - Boy or Girl
271A - Beautiful Year
520B - Two Buttons
231A - Team
479C - Exams
1030A - In Search of an Easy Problem
158A - Next Round
71A - Way Too Long Words
160A - Twins
1A - Theatre Square
1614B - Divan and a New Project
791A - Bear and Big Brother
1452A - Robot Program
344A - Magnets
96A - Football
702B - Powers of Two
1036A - Function Height
443A - Anton and Letters
1478B - Nezzar and Lucky Number
228A - Is your horseshoe on the other hoof
122A - Lucky Division
1611C - Polycarp Recovers the Permutation
432A - Choosing Teams
758A - Holiday Of Equality
1650C - Weight of the System of Nested Segments
1097A - Gennady and a Card Game
248A - Cupboards
1641A - Great Sequence
1537A - Arithmetic Array
1370A - Maximum GCD