文章目录
总题解目录
[PAT- Advanced Level] 甲级题解目录(Advanced Level)
A1002 A+B for Polynomials (25point(s))
This time, you are supposed to find A+B where A and B 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:
K
N
1
a
N
1
N
2
a
N
2
.
.
.
N
K
a
N
K
K\quad N_{1}\quad a_{N1}\quad N_{2}\quad a_{N2}\quad ...\quad N_{K}\quad a_{NK}
KN1aN1N2aN2...NKaNK
where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤ K ≤10,0≤ NK < ⋯ < N2 < N1 ≤1000.
Output Specification:
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.
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
Analysis
- 本题是做多项式加法,我的做法是取一个数组,对应编号即为对应次方。输出非零项即可
- 注意结果要精确到小数点后1位哦~
- 突然想吐槽一下为啥我以前这么喜欢写全局变量啊?! 😦
- 原来的写法挺好的,本题在C++中要把最后的输出控制在一个string中会让程序变得过于丑陋(拿不出手)
- 所以写一个Python version。面向对象哦 😃
- 同时贴出AC结果,可以看到时间和空间上两种方法的区别
C++ Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double res[1011];
int main(){
int k, n, cnt = 0;
double a;
memset(res, 0, sizeof(res));
for (int i = 0; i < 2; i++){
scanf("%d", &k);
while (k--){
scanf("%d %lf", &n, &a);
res[n] += a; // 第x的n次方前系数相加
}
}
for (int i = 1010; i >= 0; i--)
if (res[i] != 0)
cnt++;
printf("%d", cnt);
for (int i = 1010; i >= 0; i--){
if (res[i] == 0) continue;
printf(" %d %.1f", i, res[i]);
}
return 0;
}
Python Code
from collections import defaultdict
class polynomial:
def __init__(self, items) -> None:
self.items = items
def __str__(self):
msg = f"{len(self.items)}"
# 本题注意点,系数要求从高到低排序,注意哦~
sortedkeys = sorted(self.items.keys(), reverse=True)
for k in sortedkeys:
msg += f" {k:d} {self.items[k]:.1f}" # 注意系数要保留一位小数
return msg
def __add__(self, other):
for k, v in other.items.items():
# 本题注意点。系数为0的项不用保存(打印),注意规避哦~
if self.items[k] + v == 0:
self.items.pop(k)
else:
self.items[k] += v
return type(self)(self.items)
def main():
polynomials = []
for _ in range(2):
data = input().split()
# 下面这行验证代码瞎写的,大家请不要在意:)
assert int(data[0]) == int((len(data)-1)/2), "impossible, unless the test case is wrong"
items = defaultdict(float) # 这里的float使得默认新key对应的value是0.0
for i in range(1, len(data)):
if i % 2 == 0:
items[int(data[i-1])] += float(data[i])
p = polynomial(items)
polynomials.append(p)
print(polynomials[0] + polynomials[1])
if __name__ == "__main__":
main()