1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
| #include <stdio.h> #include <stdlib.h>
typedef struct PNode{ int coeff; int expn; struct PNode *next; } PNode, *Poly;
void createPoly(Poly &P, int n);
void printPoly(Poly P);
void mulPoly(Poly P1, Poly P2, Poly &P3);
int main(){ int m, n; Poly p1, p2, p3; scanf("%d %d", &m, &n); createPoly(p1, m); createPoly(p2, n); mulPoly(p1, p2, p3); printPoly(p1); printPoly(p2); printPoly(p3); return 0; }
void createPoly(Poly &P, int n) { P = new PNode; P->next = NULL; while (n--) { Poly s = new PNode; scanf("%d %d", &s->coeff, &s->expn); if (s->coeff == 0) continue; Poly pre = P, q = P->next; while (q && q->expn < s->expn) { pre = q; q = q->next; } s->next = q; pre->next = s; } }
void printPoly(Poly P) { Poly s = P->next; while (s) { if (s != P->next && s->coeff > 0) printf("+"); if (s->expn == 0) { printf("%d", s->coeff); } else if (s->expn == 1) { if (s->coeff != 1) printf("%d", s->coeff); printf("x"); } else { if (s->coeff != 1) printf("%d", s->coeff); printf("x^%d", s->expn); } s = s->next; } printf("\n"); }
void addPoly(Poly P1, Poly P2, Poly &P3) { Poly i = P1->next, j = P2->next, k = P3; k->next = NULL; while (i && j) { Poly t = new PNode; t->next = NULL; if (i->expn == j->expn) { if (i->coeff + j->coeff == 0) { i = i->next; j = j->next; continue; } t->coeff = i->coeff + j->coeff; t->expn = i->expn; i = i->next; j = j->next; } else if (i->expn < j->expn) { t->coeff = i->coeff; t->expn = i->expn; i = i->next; } else { t->coeff = j->coeff; t->expn = j->expn; j = j->next; } k->next = t; k = t; } while (i) { Poly t = new PNode; t->coeff = i->coeff; t->expn = i->expn; t->next = NULL; k->next = t; k = t; i = i->next; } while (j) { Poly t = new PNode; t->coeff = j->coeff; t->expn = j->expn; t->next = NULL; k->next = t; k = t; j = j->next; } }
void cal(Poly P1, Poly P2, Poly &P3) { Poly p2 = P2->next; Poly p = P3; while (p2) { Poly t = new PNode; t->expn = P1->expn + p2->expn; t->coeff = P1->coeff * p2->coeff; t->next = NULL; p->next = t; p = t; p2 = p2->next; } }
void mulPoly(Poly P1, Poly P2, Poly &P3) { P3 = new PNode; P3->next = NULL; Poly p1 = P1->next; while (p1) { Poly t = new PNode; t->next = NULL; cal(p1, P2, t); addPoly(t, P3, P3); p1 = p1->next; } }
|