Please read the new rule regarding the restriction on the use of AI tools. ×

Naithani's blog

By Naithani, history, 4 years ago, In English

I was learning Paint fence algorithm: n fences, k colors, how many ways to paint the n fences such that atmost 2 adjacent fences have the same color. For more details link.

I tried the standard solution, but I think this is wrong, or I did understand the problem wrong.

Look for the test case n = 4, k = 3, result from the standard algorithm is 66, but if I try the brute force method, then I got 60.

Standard DP approach counts 6 more than brute force.

My brute force code:

string s;
int n;
int ans;
void permute(int idx){
    if(idx == n){
        int cnt = 0;
        for (int i = 0; i < n-1; ++i){
            if(s[i] == s[i+1]) cnt++;
        }
        if(cnt <= 1){
            cout << s << endl;
            ans++;
        }
        return;
    }

    for (char ch: {'A', 'B', 'C'}){
        s[idx] = ch;
        permute(idx+1);
    }
}


int main(){
    cin >> n;
    s = "ABCD";
    permute(0);
    cout << ans;

    return 0;
}

I think standard code also counts these 6 permutations:

[AABB], [BBAA], [CCAA], [AACC], [BBCC], [CCBB]

Could you please explain what is wrong.

  • Vote: I like it
  • +3
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
Rev. 2   Vote: I like it +3 Vote: I do not like it
My code(C++)
Sample tests

You probably messed up the transitions.

  • »
    »
    4 years ago, # ^ |
    Rev. 2   Vote: I like it +3 Vote: I do not like it

    No, if I remove the cnt <= 1 condition then, it will print all the permutations. 3*3*3*3 = 81, but If I apply the condition then the result is 60. The algorithm you used, it is well known, but I have doubt in it, that's why I tried all permutations. I have doubt because of when I'm at ith, I will do

    dp[i][0]= (dp[i-1][0] + dp[i-1][1])*(k-1)

    dp[i][1] = dp[i-1][0]

    But I think this causes the more adjacent same color fences.

    I think standard code also counts these 6 permutations:

    [AABB], [BBAA] [CCAA] [AACC] [BBCC] [CCBB]

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Naithani (previous revision, new revision, compare).