PAT甲級1002 A+B for Polynomials (25分)附測試點6段錯誤原因
阿新 • • 發佈:2020-08-03
This time, you are supposed to findA+BwhereAandBare two polynomials.
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
KN1aN1N2aN2...NKaNK
whereKis the number of nonzero terms in the polynomial,NiandaNi(,) are the exponents and coefficients, respectively. It is given that1,0.
Output Specification:
For each test case you should output the sum ofAandBin one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
這個題可以用連結串列寫,也可以用雜湊表寫,用雜湊會更簡單一些,不過最近在看嚴老師的資料結構,裡面專門有再講多項式的加減,於是用連結串列重新寫了一遍。 測試點6要求輸出0,也就是多項式每一項相加減抵消了。 附程式碼:3 2 1.5 1 2.9 0 3.2
#include <iostream> using namespace std; struct Node{ int expn;//表示指數 double coef;//表示係數 Node*next; }; void InitList(Node*L,int n){ for(int i=0;i<n;i++){ Node*a=(Node*)malloc(sizeof(Node)); cin>>a->expn>>a->coef; L->next=a; L=a; } L->next=NULL; } int main() { Node*La=(Node*)malloc(sizeof(Node)); Node*Lb=(Node*)malloc(sizeof(Node)); //La和Lb分表代表著兩個連結串列 int n; cin>>n; InitList(La,n); cin>>n; InitList(Lb,n); Node*pa=La->next,*pb=Lb->next;//工作指標 Node*Lc=La,*pc=Lc;//用La的頭結點作為Lc的頭結點 while(pa&&pb){ if(pa->expn>pb->expn){ pc->next=pa; pc=pa; pa=pa->next; } else if(pa->expn<pb->expn){ pc->next=pb; pc=pb; pb=pb->next; } else if(pa->expn==pb->expn){ pa->coef+=pb->coef; if(pa->coef!=0.0){ pc->next=pa; pc=pa; } pa=pa->next; pb=pb->next; } } if(pa) pc->next=pa; else { pc->next=pb; } pc=Lc; int len=0; while(pc->next!=NULL){ len++; pc=pc->next; } cout<<len; pc=Lc->next; while(pc!=NULL){ printf(" %d %.1f",pc->expn,pc->coef); pc=pc->next; } return 0; }