我的PAT系列文章更新重心已移至Github,歡迎來看PAT題解的小伙伴請(qǐng)到Github Pages瀏覽最新內(nèi)容。此處文章目前已更新至與Github Pages同步。歡迎star我的repo。
題目
This time, you are supposed to find where
and
are 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:
...
where is the number of nonzero terms in the polynomial,
and
(
) are the exponents and coefficients,
respectively. It is given that ,
.
Output Specification:
For each test case you should output the sum of and
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.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 2 1.5 1 2.9 0 3.2
思路
最初由于數(shù)學(xué)概念的理解錯(cuò)誤,糾結(jié)了半天。0是零多項(xiàng)式,在題中將之歸于“0項(xiàng)”多項(xiàng)式。當(dāng)然了,實(shí)際是沒有0項(xiàng)多項(xiàng)式的,只有零多項(xiàng)式,但是非要輸出個(gè)結(jié)果,0還是合理的。我一開始把0當(dāng)成只有常數(shù)項(xiàng)的一項(xiàng)多項(xiàng)式,結(jié)果最后一測(cè)試點(diǎn)老過不去。。。。
很多人都用1000長(zhǎng)度的數(shù)組存儲(chǔ)多項(xiàng)式,確實(shí)思路簡(jiǎn)單,且并不是很浪費(fèi)空間。我用了另一種思路,用數(shù)組模仿鏈表的實(shí)現(xiàn)。將A、B兩多項(xiàng)式由次數(shù)從高到低依次計(jì)算,存入新數(shù)組。
疑問:最初最后一個(gè)測(cè)試點(diǎn)沒過的時(shí)候,我以為又是小負(fù)數(shù)近似格式的問題(見PAT Basic 1051. 復(fù)數(shù)乘法 (15)(C語言實(shí)現(xiàn))),便將系數(shù)絕對(duì)值小于0.05的項(xiàng)全忽略了。當(dāng)然這么做也通過了,可能輸入保證了精度也只有1位小數(shù),這樣就沒有這個(gè)必要了。
代碼
最新代碼@github,歡迎交流
#include <stdio.h>
#include <math.h>
typedef struct Poly{
double coef;
int exp;
} Poly[20];
int main()
{
int KA, KB, Ksum = 0;
Poly A, B, sum;
scanf("%d", &KA);
for(int i = 0; i < KA; i++)
scanf("%d %lf", &A[i].exp, &A[i].coef);
scanf("%d", &KB);
for(int i = 0; i < KB; i++)
scanf("%d %lf", &B[i].exp, &B[i].coef);
int i = 0, j = 0;
while(i < KA || j < KB)
{
if(i == KA || (j < KB && A[i].exp < B[j].exp))
{
sum[Ksum].exp = B[j].exp;
sum[Ksum].coef = B[j++].coef;
}
else if(j == KB || (i < KA && A[i].exp > B[j].exp))
{
sum[Ksum].exp = A[i].exp;
sum[Ksum].coef = A[i++].coef;
}
else
{
sum[Ksum].exp = A[i].exp;
sum[Ksum].coef = A[i++].coef + B[j++].coef;
}
if(fabs(sum[Ksum].coef) >= 0.05) Ksum++;
}
printf("%d", Ksum);
for(int i = 0; i < Ksum; i++)
printf(" %d %.1lf", sum[i].exp, sum[i].coef);
return 0;
}