// C++ program to count number of ways to arrange three
// types of balls such that no two balls of same color
// are adjacent to each other
#include <iostream>
using namespace std;
// Returns count of arrangements where last placed ball is
// 'last'. 'last' is 0 for 'p', 1 for 'q' and 2 for 'r'
int countWays(int p, int q, int r, int last)
{
// if number of balls of any color becomes less
// than 0 the number of ways arrangements is 0.
if (p < 0 || q < 0 || r < 0)
return 0;
// If last ball required is of type P and the number
// of balls of P type is 1 while number of balls of
// other color is 0 the number of ways is 1.
if (p == 1 && q == 0 && r == 0 && last == 0)
return 1;
// Same case as above for 'q' and 'r'
if (p == 0 && q == 1 && r == 0 && last == 1)
return 1;
if (p == 0 && q == 0 && r == 1 && last == 2)
return 1;
// if last ball required is P and the number of ways is
// the sum of number of ways to form sequence with 'p-1' P
// balls, q Q Balls and r R balls ending with Q and R.
if (last == 0)
return countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2);
// Same as above case for 'q' and 'r'
if (last == 1)
return countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2);
if (last == 2)
return countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1);
}
// Returns count of required arrangements
int countUtil(int p, int q, int r)
{
// Three cases arise:
return countWays(p, q, r, 0) + // Last required balls is type P
countWays(p, q, r, 1) + // Last required balls is type Q
countWays(p, q, r, 2); // Last required balls is type R
}
// Driver code to test above
int main()
{
int p = 1, q = 1, r = 1;
cout << countUtil(p, q, r) << endl;
return 0;
}
不同颜色的球排列
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 房子装修选什么颜色是不可忽视部分,颜色选配决定家居整体风格,不同的颜色对人的心理和情绪有不同的影响,装修颜色如何搭...
- 1.当代种种事件不同于历史之处,在于我们不知道它们会产生什么后果。 2.经验和利益的偶然结合,往往会向人们揭示...
- 文/雪中萍 二十三年同窗情,携手相约恰西行。九零级初中二班开启了一场领略故乡风光,回忆青葱岁月的旅行,是为记。 ...