- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this problem, we are given two integers n and m, where n is the number of paintings and m is the number of colors available. Our task is to create a program that will find the total number of ways in which we can paint the paintings in such a way that no to consecutive paintings have the same color.

Let’s take an example to understand the problem,

n = 3, m =3

12

P1 P2 P3 C1 C2 C3 C1 C3 C2 C1 C2 C1 C1 C3 C1 C2 C1 C2 C2 C3 C2 C2 C1 C3 C2 C3 C1 C3 C1 C3 C3 C2 C3 C3 C1 C2 C3 C2 C1

To solve this problem, we can paint all n paintings with m colors, now the next paintings can be painted using n-1 color excluding the color used to paint the last painting. So, the total number of ways is,

n*(m-1)^{(n-1)}

Program to show the implementation of our solution,

#include <iostream> #define modd 1000000007 using namespace std; unsigned long calcPower(unsigned long base, unsigned long power, unsigned long p){ unsigned long result = 1; base = base % p; while (power > 0) { if (power & 1) result = (result * base) % p; power = power >> 1; base = (base * base) % p; } return result; } int colorPainting(int n, int m){ return calcPower(m - 1, n - 1, modd) * m % modd; } int main(){ int n = 5, m = 7; cout<<"The number of ways to color the given paintings is : "<<colorPainting(n, m); return 0; }

The number of ways to color the given paintings is : 9072

- Related Questions & Answers
- Ways to paint N paintings such that adjacent paintings don’t have same colors in C programming
- Ways to paint stairs with two colors such that two adjacent are not yellow in C++
- Handshakes That Don't Cross in C++
- What are Maandana paintings? Do they still exit?
- Number of Ways to Paint N × 3 Grid in C++
- Number of Ways to Paint N × 3 Grid in C++ program
- What are some signs that tell me that I don't have enough protein in my diet?
- Don’t Miss the Milestones – Sequence the Activities
- I have a unique startup idea, but don’t know where to start? What should I do?
- C program that won’t compile in C++
- Why don’t we create green top pitches in India?
- Maximum sum such that no two elements are adjacent in C++
- Maximum sum in a 2 x n grid such that no two elements are adjacent in C++
- Functions that can’t be overloaded in C++
- Why I don’t get that feel when I say any swear word (gaali) in English?

Advertisements