EXT 2.2

数据结构基础(C语言版)读书笔记001

2.4 多项式

多项式表示结构

多项式的表示结构有两种:

1)使用数组记录多项式的每一项:

1 #define MAX_DEGREE 101
2 typedef struct {
3   int degree; // 多项式的项数
4   float coef[MAX_DEGREE]; // 多项式每一项的系数
5 }polynomial;

 2) 只记录多项式每一项(非零项)的系数和指数:

1 #define MAX_TERM 100
2 typedef struct {
3   float coef; // 多项式非零项的系数
4   int expon; // 多项式非零项的指数
5 }polynomial;

第一种表示方法简单直观,也方便进行多项式各种方法的实现,但可能极大地浪费了大量的存储空间;

第二种表示方法有效地解决了第一种表示方法存在的不足,对于稀疏多项式的表示极为高效。

 

 

上图是使用第二种表示方法把两个多项式存放在一个数组里面,由此可见,这种结构极为节省存储空间。

 多项式加法

 1)基于上面第一种表示方法的多项式加法实现:

d = a + b, where a, b, and d are polynoimals
d = zero();
while(!IsZero(a) && !IsZero(b))
  do {
    switch(COMPARE(LeadExp(a), LeadExp(b))){
    case -1:
      d = Attach(d, Coef(b, LeadExp(b)), LeadExp(b));
      b = Remove(b, LeadExp(b));
      break;
    case 0:
      sum = Coef(a, LeadExp(a)) + Coef(b, LeadExp(b));
      if(sum){
        Attach(d, sum, LeadExp(a));
        a = Remove(a, LeadExp(a));
        b = Remove(b, LeadExp(b));
      }
      break;
    case 1:
      d = Attach(d, Coef(a, LeadExp(a)), LeadExp(a));
      a = Remove(a, LeadExp(a));
      break;
    }
  }
insert any remaining terms of a or b into d

 2)基于上面第二种表示方法的多项式加法实现:

 1 void padd(int startA, int finishA,
 2           int startB, int finishB,
 3           int startD, int finishD)
 4 {
 5   float coefficient;
 6   *startD = avail;
 7   while(startA <= finishA && startB <= finishB)
 8     switch(COMPARE(terms[startA].expon, terms[startB].expon)){
 9     case -1:
10       attach(terms[startB].coef, terms[startB].expon);
11       startB++;
12       break;
13     case 0:
14       coefficient = termrs[startA].coef + terms[startB].coef;
15       if(coefficient)
16         attach(terms[startB].coef, terms[startA].expon);
17       startA++;
18       startB++;
19       break;
20     case 1:
21       attach(terms[startA].coef, terms[startA].expon);
22       startA++;
23     }
24     for(; startA<=finishA; startA++)
25       attach(terms[startA].coef, terms[startA].expon);
26   for(; startB<=finishB; startB++)
27     attach(terms[startB].coef, terms[startB].expon);
28   *finishD = avail - 1;
29 } 
 1 void attach(float coefficient, int exponent)
 2 {
 3   if(avail>=MAX_TERMS)
 4   {
 5     fprintf(stderr, "Too many terms in the polynomial\n");
 6     exit(EXIT_FAILURE);
 7   }
 8   terms[avail].coef = coefficient;
 9   terms[avail++].expon = exponent;
10 }

 

参考文献:

[1] E.Horowitz S.Sahni S Anderson-Freed 著, 朱忠涛 译,数据结构基础(c语言版)(第2版),清华大学出版社。

posted on 2012-02-19 14:06  jason kung  阅读(858)  评论(0编辑  收藏  举报

导航