910A - The Way to Home - CodeForces Solution


dfs and similar dp greedy implementation *800

Please click on ads to support us..

Python Code:

dp = [0]
n, d = map(int, input().split())
s = input()

for i in range(1, len(s)):

    if s[i] == '0':
        dp.append(10 ** 10)
    else:

        mn = 10 ** 10
        for j in range(max(0, i - d), i):
            mn = min(mn, dp[j])
        if mn == 10 ** 10:
            dp.append(10 ** 10)
        else:    
            dp.append(mn + 1)
abc = 1
if dp[-1] == 10 ** 10:
    print(-1)
else:
    print(dp[-1])

    

C++ Code:

#include<bits/stdc++.h>

using namespace std;


bool dfs(string &save, int start, int dis, int m){
    //cout<<start<<'\n';
    if(start >= save.size() - 1){
        if(start == save.size() - 1){
            // cout<<start<<' '<<dis<<'\n';
            cout<<dis;
            return true;
        }
        else if(start >= save.size()) return false;
    }
    else{
        if(save[start] == '0') return false;
        for(int i = m; i >= 1; i--){
            if(dfs(save, start + i, dis + 1, m)) return true;
        }
    }
    return false;
}

int main(){
    int n, m;
    cin>>n>>m;
    string save;
    cin>>save;
    int c = 0;
    for(int i = 0; i < save.size(); i++){
        if(c == m){
            cout<<-1;
            return 0;
        }
        if(save[i] == '1') c = 0;
        else c++;
    }
    if(!dfs(save, 0, 0, m)) cout<<-1;
}


Comments

Submit
0 Comments
More Questions

1537A - Arithmetic Array
1370A - Maximum GCD
149A - Business trip
34A - Reconnaissance 2
59A - Word
462B - Appleman and Card Game
1560C - Infinity Table
1605C - Dominant Character
1399A - Remove Smallest
208A - Dubstep
1581A - CQXYM Count Permutations
337A - Puzzles
495A - Digital Counter
796A - Buying A House
67A - Partial Teacher
116A - Tram
1472B - Fair Division
1281C - Cut and Paste
141A - Amusing Joke
112A - Petya and Strings
677A - Vanya and Fence
1621A - Stable Arrangement of Rooks
472A - Design Tutorial Learn from Math
1368A - C+=
450A - Jzzhu and Children
546A - Soldier and Bananas
32B - Borze
1651B - Prove Him Wrong
381A - Sereja and Dima
41A - Translation