|
| 1 | +/* |
| 2 | +Problem statement: |
| 3 | +Given a fence with n posts and k colors , find out the number of ways of painting the fence |
| 4 | +such that atmost 2 adjacent posts have the same color. |
| 5 | +Suppose we have a single post, The number of ways of painting the fence with k colors is k |
| 6 | +Now we consider 2 posts, Then the number of ways of painting the second fence with the same |
| 7 | +color as the first post is k, and the number of ways of painting the second post with a different |
| 8 | +color is k*(k-1) as we have k-1 colors that are different from the first post's color. |
| 9 | +So the total number of ways of painting 2 fences is k*(k-1) + k. Now we consider 3 posts, |
| 10 | +Then the number of ways of painting the third fence same as the second fence is the number of |
| 11 | +ways of painting the second fence with a different color that is k*(k-1). The number of ways of |
| 12 | +painting the third fence using a different color is equal to the total number of ways of |
| 13 | +painting the second fence * (k-1). Hence the total number of ways of painting 3 fences is k*(k-1) + (k+k*(k-1))*(k-1). |
| 14 | +This way we can find the total number of ways of painting n fences |
| 15 | +*/ |
| 16 | + |
| 17 | +#include <bits/stdc++.h> |
| 18 | + |
| 19 | +using namespace std; |
| 20 | +unsigned long long MOD = 1000000007; |
| 21 | +//paintfence function uses permutations to find the number of ways of painting fences |
| 22 | +unsigned long long paintfence(int n, int k) |
| 23 | +{ |
| 24 | + unsigned long long total, diff, same; |
| 25 | + same = k; |
| 26 | + diff = k * (k - 1); |
| 27 | + total = k * k; |
| 28 | + for (int i = 1; i < n - 1; i++) |
| 29 | + { |
| 30 | + same = diff; |
| 31 | + diff = total * (k - 1); |
| 32 | + total = same + diff; |
| 33 | + } |
| 34 | + return total%MOD; |
| 35 | +} |
| 36 | + |
| 37 | +int main() |
| 38 | +{ |
| 39 | + int n, k; |
| 40 | + cout << "Enter the number of posts" << endl; |
| 41 | + cin >> n; |
| 42 | + cout << "Enter the number of colors" << endl; |
| 43 | + cin >> k; |
| 44 | + cout << "The number of ways of painting the fence is : " << paintfence(n, k) << endl; |
| 45 | + return 0; |
| 46 | +} |
| 47 | + |
| 48 | +/* |
| 49 | +Sample I/O: |
| 50 | +Enter the number of posts |
| 51 | +2 |
| 52 | +Enter the number of colors |
| 53 | +4 |
| 54 | +The number of ways of painting the fence is : 16 |
| 55 | +
|
| 56 | +Enter the number of posts |
| 57 | +3 |
| 58 | +Enter the number of colors |
| 59 | +2 |
| 60 | +The number of ways of painting the fence is : 6 |
| 61 | +
|
| 62 | +Complexity Analysis |
| 63 | +Time complexity - O(n) |
| 64 | +Space complexity - O(1), where n is the number of posts |
| 65 | +*/ |
0 commit comments