PAT甲級1002題解
阿新 • • 發佈:2018-12-23
This time, you are supposed to find A+B where A and B are two polynomials.
Input
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:K N1 aN1 N2 aN2 ... NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi
Output
For each test case you should output the sum of A and B in 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.
2 1 2.4 0 3.2 2 2 1.5 1 0.5Sample Output
3 2 1.5 1 2.9 0 3.2 注:此題應注意和係數為0的項不符合題意,需要忽略。且輸入資料已經按exponents降序排列,無需使用sort進行排列。 程式碼如下所示: #include<stdio.h> #include<stdlib.h> #include<algorithm> #include<iostream> using namespace std; struct stru { int exponents; float coefficients; }; stru stru1[1000], stru2[1000];//分別儲存第一行和第二行多項式 int main() { int K1, K2; while (scanf("%d", &K1) != EOF) { int i = 0; for (i = 0; i < K1; i++) { scanf("%d%f", &stru1[i].exponents, &stru1[i].coefficients); } scanf("%d", &K2); for (i = 0; i < K2; i++) { scanf("%d%f", &stru2[i].exponents, &stru2[i].coefficients); } stru stru3[1000];//儲存結果的多項式 int m = 0, n = 0,k=0; while (m < K1&&n < K2) { if (stru1[m].exponents == stru2[n].exponents) { if (stru1[m].coefficients + stru2[n].coefficients != 0) { stru3[k].coefficients = stru1[m].coefficients + stru2[n].coefficients; stru3[k].exponents = stru1[m].exponents; k++; m++; n++; } else { m++; n++; } } else if (stru1[m].exponents < stru2[n].exponents) { stru3[k].exponents = stru2[n].exponents; stru3[k].coefficients = stru2[n].coefficients; n++; k++; } else { stru3[k].exponents = stru1[m].exponents; stru3[k].coefficients = stru1[m].coefficients; m++; k++; } } while (m < K1) { stru3[k].exponents = stru1[m].exponents; stru3[k].coefficients = stru1[m].coefficients; k++; m++; } while (n < K2) { stru3[k].exponents = stru2[n].exponents; stru3[k].coefficients = stru2[n].coefficients; k++; n++; } printf("%d", k); for (i = 0; i < k; i++) { printf(" %d %.1f", stru3[i].exponents, stru3[i].coefficients); } printf("\n"); } return 0; }