多项式相乘求组合数RC(n,r)

设集合S={n1*e1, n2*e2, ... nt*et}, n1 + n2 +...+nt = n, 从S中任取r个,求其组合数RC(n, r)。

设多项式

 

则RC(n,r)就是多项式中xr的系数, 即  RC(n, r) = ar。

根据上述方法,编程实现:求任意的从S中任取r个的组合数RC(n,r),且输出ai(i = 1, 2...r)。

解决思路:

1. 用面向对象的思想,把多项式抽象为类。私有成员即为多项式的系数和幂, 公有方法即为对多项式的操作。

2. 运用运算符重载的方法,重载多项式的乘法运算。

编程实现如下:

#include
using namespace std;

typedef int datatype;

class MN
{
   public:
           MN(datatype newx = 1, int newhighpower = 0)
           {
              int i = 0;
     
              x = newx;
              highpower = newhighpower;
    
              for (i = 0; i <= highpower; i++)
              {
                  coe[i] = 1;
              }
           }
           MN operator*(const MN &other)
           {
              int i = 0, j = 0;
              int k = 0;
              MN t;
              t.x = this->x;
              t.highpower = this->highpower + other.highpower;
             
              for (i = 0; i <= t.highpower; i++)
              {
                  t.coe[i] = 0;
              }
             
              for (i = 0; i <= other.highpower; i++)
              {
                  for (j = 0; j <= this->highpower; j++)
                  {
                      k = i + j;
                      t.coe[k] += this->coe[j]* other.coe[i];
                  }
              }       

              return t;
           }
           void show()
           {
              int i = 0;
             
              cout << endl;
              for (i = 0; i <= highpower; i++)
              { 
                 cout << " " << coe[i] << "×X<" << i << ">" << "  ";
              }  
              cout << endl;
           }
          
           void show_r (int r)
           { 
              cout << coe[r] << endl; 
           }
   private:
           datatype x;
           int coe[100];
           int highpower;
};

int main (void)
{    
    int t = 0, m[100] = {0};
    datatype e[50] = {0};
    int i = 0, j = 0;
    int n = 0, r = 0;
   
    cout << "                  求组合数RC(n,r)的程序实现    "<< endl << endl;
    cout << endl << "请输入元素类型数t: ";
    cin >> t;
    cout << endl << "请输入各元素:";  //元素类型在程序中并未涉及
   
    for (i = 0; i < t; i++)
    {
        cin >> e[i];
    }
    cout << endl << "请输入相应的元素个数n[i]: ";
    for (i = 0; i < t; i++)
    {
        cin >> m[i];
        n = n + m[i];
    }
    cout << endl << "请输入r的值(r < " << n << ")";
    cin >> r;
   
    cout << endl << endl;
   
    MN multinomial;
    
     for (i = 0; i < t; i++)
     {
        MN multinom(e[i], m[i]);
        multinomial = multinomial * multinom;
     }
    
     cout << endl << t << "个多项式相乘的结果如下: " << endl;
     multinomial.show();
    
     cout << endl << "RC(n, r)=RC(" << n << ", " << r << ")=";
     multinomial.show_r(r);
     cout << endl;
    
    system("pause()");
   
    return 0;
}


 



你可能感兴趣的:(组合数学)