美文网首页
不同颜色的球排列

不同颜色的球排列

作者: tingjieee_19e5 | 来源:发表于2018-09-26 20:03 被阅读0次
// 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;
}

相关文章

  • 不同颜色的球排列

  • 快排之荷兰国旗问题

    荷兰国旗问题 现有红白蓝三个不同颜色的小球,乱序排列在一起,请重新排列这些小球,使得红白蓝三色的同颜色的球在一起。...

  • 2018-09-18 滴滴笔试 排列小球

    三色球,相同颜色不相邻,排列个数。

  • 9. 荷兰国旗问题

    题意:把n个红、白、蓝三种不同颜色的小球,乱序排列在一起,请通过两两交换任意两球的方式,使得从左到右小球的颜色依次...

  • 算法--三色球分类

    现有n个红白蓝三种不同颜色的小球,乱序排列在一起,请通过两两交换任意两个球,使得从左至右,依次是一些红球、一些白球...

  • 触摸球

    言宝满月的时候,我给她买了一组触摸手抓球。六个颜色形状各异的球球,在不同阶段有不同玩法。 三个月以前,让球球在她眼...

  • 【数组】--荷兰国旗问题

    问题:现有红,白,蓝三个不同颜色的小球,乱序排列在一起,请重新排列这些小球,使得红白蓝三色的同颜色球在一起。红白蓝...

  • 小彩虹

    从前有一个彩虹,这个彩虹是很不同的,因为他能把自己的七个颜色变成七个球,那些球的颜色分为,红色,橙色,黄色...

  • 排列和组合 一

    排列 permutation 或者 基本模型就是放球模型. 从 n 个取出 r 个不同的盒子里(盒子有顺序) 全排...

  • 旋转

    沐风 我眼前有几道不同颜色的光,几道不同颜色的光在旋转。是灯球吗?可我没有听见嘈杂的音乐,我想,这应该...

网友评论

      本文标题:不同颜色的球排列

      本文链接:https://www.haomeiwen.com/subject/zidanftx.html