数据结构与算法——多项式

在《算法设计技巧与分析》5.5节介绍了多项式求值的嵌套乘法,也称作Horner规则,即Pn(x)=anxn+an-1xn-1+...+a1x+a0=((...(((anx+an-1)x+an-2)x+an-3)...)x+a1)x+a0。这个是很容易就实现的。这里要求次数是连续的并且大于等于0。

如果定义多项式的数据结构poly.h如下,

 1 #ifndef POLY_H_
2 #define POLY_H_
3
4 #include <vector>
5 #include <iostream>
6 #include <iomanip>
7 using namespace std;
8
9 class Poly
10 {
11 public:
12 vector<double> coef;
13 vector<int> powr;
14 public:
15 Poly() {}
16 Poly(const Poly& A)
17 {
18 coef = A.coef;
19 powr = A.powr;
20 }
21 void outputPoly()
22 {
23 unsigned int i = 0;
24 cout << "coef : ";
25 for(i=0;i<coef.size();i++)
26 cout << setw(12) << setprecision(4) <<coef[i];
27 cout << endl;
28 cout << "power: ";
29 for(i=0;i<powr.size();i++)
30 cout << setw(12) << powr[i];
31 cout << endl;
32 }
33 };
34
35 #endif

并且实现了多项式加法和乘法,如下

  1 #include "poly.h"
2
3 void PolyAdd(Poly& C,Poly& A,Poly& B);
4 void PolyMul(Poly& C,Poly& A,Poly& B);
5
6 int main()
7 {
8 Poly A;
9 A.coef={1.2,2.3,3.4};
10 A.powr={0,1,3};
11 Poly B;
12 B.coef={2.1,3.2,4.3,8.9};
13 B.powr={-1,1,2,4};
14 Poly C;
15 PolyAdd(C,A,B);
16 Poly D;
17 PolyMul(D,A,B);
18 cout << "A:" << endl;
19 A.outputPoly();
20 cout << "B:" << endl;
21 B.outputPoly();
22 cout << "C=A+B:" << endl;
23 C.outputPoly();
24 cout << "D=A*B:" << endl;
25 D.outputPoly();
26 return 0;
27 }
28
29 void PolyAdd(Poly& A, Poly& B)
30 {
31 Poly C;
32 PolyAdd(C,A,B);
33 A = Poly(C);
34 }
35
36 void PolyAdd(Poly& C,Poly& A,Poly& B)
37 {
38 int m = A.coef.size();
39 int n = B.coef.size();
40 int i = 0, j = 0, k = 0;
41 if(m==0)
42 {
43 C = Poly(B);
44 return;
45 }
46
47 C.coef.clear();
48 C.powr.clear();
49
50 //Poly C;
51 for(i=0,j=0;i<m && j<n;)
52 {
53 if(A.powr[i]==B.powr[j])
54 {
55 C.powr.push_back(A.powr[i]);
56 C.coef.push_back(A.coef[i]+B.coef[i]);
57 i++;
58 j++;
59 }
60 else if(A.powr[i]<B.powr[j])
61 {
62 C.powr.push_back(A.powr[i]);
63 C.coef.push_back(A.coef[i]);
64 i++;
65 }
66 else
67 {
68 C.powr.push_back(B.powr[j]);
69 C.coef.push_back(B.coef[j]);
70 j++;
71 }
72 }
73 if(i==m && j<n)
74 {
75 for(;j<n;j++)
76 {
77 C.powr.push_back(B.powr[j]);
78 C.coef.push_back(B.coef[j]);
79 }
80 }
81 else if(i<m && j==n)
82 {
83 for(;i<m;i++)
84 {
85 C.powr.push_back(A.powr[i]);
86 C.coef.push_back(A.coef[i]);
87 }
88 }
89 //return C;
90 }
91
92 void PolyMul(Poly& C,Poly& A,Poly& B)
93 {
94 int m = A.coef.size();
95 int n = B.coef.size();
96 if(m>n)
97 PolyMul(C,B,A);
98 // m < n
99 vector<Poly> T = vector<Poly>(m,B);
100 int i = 0, j = 0;
101 for(i=0;i<m;i++)
102 {
103 for(j=0;j<n;j++)
104 {
105 T[i].coef[j]=A.coef[i]*B.coef[j];
106 T[i].powr[j]=A.powr[i]+B.powr[j];
107 }
108 }
109
110 for(i=0;i<m;i++)
111 {
112 PolyAdd(C,T[i]);
113 }
114 }

那么该怎么来实现多项式求值呢?

比较直接的是将它扩展成次数连续且是大于等于0的多项式,然后求值,可以直接使用嵌套乘法吗?

下面的链接中,对嵌套乘法和直接计算求多项式的值进行比较,结果很有意思,可以关注下。http://www.cnblogs.com/skyivben/archive/2012/05/13/2497900.html

posted @ 2012-03-24 13:53  Frandy.CH  阅读(630)  评论(0编辑  收藏  举报