Polynomial Addition多项式加法

img

样例输入 Copy
3
4 5
6 1
2 3
4
2 2
3 1
-4 5
6 7
0
样例输出 Copy
内容重复显示不了,参考图片

  • 以下回答由chatgpt基于相关博客总结生成:

    解决方案:

    我们可以用一个数组来存储每个多项式的系数和指数,然后再分别对两个数组进行遍历,将同一指数的系数相加得到结果数组。最后再输出结果数组即可。具体实现可以参考以下代码:

    def poly_add(n, poly1, m, poly2):
        # 初始化结果数组
        res = [0] * 10010
        # 将多项式1的系数和指数存入数组中
        for i in range(n):
            a, b = input().split()
            a, b = int(a), int(b)
            res[b] += a
        # 将多项式2的系数和指数加入结果数组中
        for i in range(m):
            a, b = input().split()
            a, b = int(a), int(b)
            res[b] += a
        # 获取结果数组的最高项的指数
        max_idx = 0
        for i in range(len(res)-1, -1, -1):
            if res[i] != 0:
                max_idx = i
                break
        # 输出最高项的系数和指数以及结果多项式
        ans = ""
        for i in range(max_idx, -1, -1):
            if res[i] != 0:
                if i != max_idx and res[i] > 0:
                    ans += "+"
                ans += str(res[i])
                if i != 0:
                    ans += "x^" + str(i)
        print("最高项系数为{},多项式相加的结果为:{}".format(max_idx, ans))
    
    n = int(input())
    poly1 = [0] * n
    m = int(input())
    poly2 = [0] * m
    poly_add(n, poly1, m, poly2)
    

    其中,res数组存储结果多项式的系数,下标表示指数。在遍历多项式1和2时,将系数加到res的相应下标位置即可。获取最高项的指数时,从数组末尾开始遍历即可。最后再遍历一遍res数组,输出结果多项式即可。

    输入样例:

    3
    4 5
    6 1
    2 3
    4
    2 2
    3 1
    6 7
    0
    

    输出样例:

    最高项系数为7,多项式相加的结果为:10x^7+4x^5+9x^2+9x^1+2