伪码描述过于抽象,于是决定自己动手按照逻辑实现一次。看到AC的时候实在是太过激动,于是决定另开一篇文章分享一下实现源码。
代码写的及其的不美观,要是能再精简一下就好了
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
| #include <iostream> using namespace std; typedef struct PNode{ float coef; int expn; struct PNode* next; }PNode,*Polynomal; void MergeList_L(Polynomal LA,Polynomal LB,Polynomal &LC){ PNode* p = LA -> next;PNode* q = LB -> next; PNode* r = LC; while(p != NULL && q != NULL){ if(p -> expn == q -> expn){ if(p -> coef + q -> coef == 0){ p = p -> next; q = q -> next; continue; } else{ PNode* s = (PNode*)malloc(sizeof(PNode)); s -> next = NULL; s -> coef = p -> coef + q -> coef; s -> expn = p -> expn; r -> next = s; r = r -> next; p = p -> next; q = q -> next; } } else if(p -> expn < q -> expn){ r -> next = p; p = p -> next; r = r -> next; } else{ r -> next = q; q = q -> next; r = r -> next; } } r -> next = p ? p : q; } int main() { int m , n; cin >> m; cin >> n; Polynomal LA = (PNode*)malloc(sizeof(PNode)); Polynomal LB = (PNode*)malloc(sizeof(PNode)); Polynomal LC = (PNode*)malloc(sizeof(PNode)); LA -> expn = 0;LA -> coef = 0; LB -> expn = 0;LB -> coef = 0; LC -> expn = 0;LC -> coef = 0; LA -> next = NULL;LB -> next = NULL;LC -> next = NULL; PNode* p = LA; PNode* q = LB; int i; for(i = 0;i< m;i++){ int t1; int t2; cin >> t1; cin >> t2; Polynomal t = (PNode*)malloc(sizeof(PNode)); t -> next = NULL; t -> expn = t1; t -> coef = t2; p -> next = t; p = p -> next; } for(i = 0;i< n;i++){ int t1; int t2; cin >> t1; cin >> t2; Polynomal t = (PNode*)malloc(sizeof(PNode)); t -> next = NULL; t -> expn = t1; t -> coef = t2; q -> next = t; q = q -> next; } MergeList_L(LA,LB,LC); PNode* r = LC -> next; while (r != NULL) { printf("%d %.0f\n",r -> expn,r -> coef); r = r -> next; } }
|
测试用例
1
| 3 6 0 1 1 2 3 5 0 -1 1 3 2 6 3 7 4 8 5 9
|
答案
