Блог пользователя Naithani

Автор Naithani, история, 5 лет назад, По-английски

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.

  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

»
5 лет назад, # |
Rev. 2   Проголосовать: нравится +3 Проголосовать: не нравится
My code(C++)
Sample tests

You probably messed up the transitions.

  • »
    »
    5 лет назад, # ^ |
    Rev. 2   Проголосовать: нравится +3 Проголосовать: не нравится

    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]

»
5 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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