题目描述
1002. A+B for Polynomials (25)
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 (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.
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.
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
解题思路
有以下几种解决方法:
- 使用传统链表来实现多项式,遍历链表和多项式相加都基本需要 θ(n) 的时间复杂度。
- 分配一个足够大的数组,以数组下标为指数,数组内的值为系数,对于这道题不存在内存分配不足的问题,因为Ni的值在[0, 1000]以内。
- 我自己想出来的方法是是使用哈希表来做,以指数为key,系数为value,这样比较节省空间,并且在相加第二项多项式的时候计算下标的时间复杂度为常数级 θ(1) 。
解题注意点
题目里说的保持一位精度,个人来说有点理解偏差,这里说的是只保留第一位小数然后之后的小数全都省略呢,还是说保留的第一位小数是根据第二位小数四舍五入得来的呢?经过数据测试,是根据四舍五入得到的。
- 在Python3中round函数跟常理解的四舍五入可能有些差入,对于.5四舍五入的时候得到的是最为接近的偶数:
>>> a = 5.5 >>> round(a, 0) 6.0 >>> a = 6.5 >>> round(a, 0) 6.0
- 如果是第一种情况不考虑四舍五入需要自己写一个函数搞定:
def trunc(num, n): num_list = str(num).split('.') s1 = num_list[0] s2 = num_list[1] if len(num_list) > 1 else '' if n == 0: return s1 if n <= len(s2): return s1 + '.' + s2[:n] return s1 + '.' + s2 + '0' * (n - len(s2))
- 有一种边缘情况没有考虑到,导致一半的测试点没过,即如果两个多项式的系数相加等于0的时候不需要输出这个多项式。
- 最后注意一下输出格式,输出结尾没有多余的空格。
代码
运行环境Python3
from decimal import Decimal
def main():
first = input()
first = [Decimal(num) for num in first.split()]
first_length = first[0] * 2
first_dict = {}
first = first[1:]
i = 0
while i < first_length:
first_dict[first[i]] = first[i + 1]
i += 2
second = input()
second = [Decimal(num) for num in second.split()]
second_length = second[0] * 2
second = second[1:]
i = 0
while i < second_length:
if second[i] not in first_dict:
first_dict[second[i]] = second[i + 1]
else:
first_dict[second[i]] += second[i + 1]
i += 2
res = []
for k, v in first_dict.items():
if v != 0:
res.append((k, v))
res = sorted(res, key=lambda x: x[0])
res = res[::-1]
print(len(res), end='')
for i in range(len(res)):
a, n = res[i]
print(" {} {}".format(int(a), round(n, 1)), end='')
if __name__ == '__main__':
main()