F : DS线性表—多项式相加

Description

对于一元多项式
p(x)=p0+p1x+p2x2+ … +pnxn,
每个项都有系数和指数两部分,例如p2x2的系数为p2,指数为2。

编程实现两个多项式的相加。

例如
5+x+2x2+3x3,-5-x+6x2+4x4,
两者相加结果:
8x2+3x3+4x4
其中系数5和-5都是x的0次方的系数,相加后为0,所以不显示。x的1次方同理不显示。

可用顺序表或单链表实现。

Input

第1行:输入t表示有t组测试数据

第2行:输入n表示有第1组的第1个多项式包含n个项

第3行:输入第一项的系数和指数,以此类推输入n行

接着输入m表示第1组的第2个多项式包含m项

同理输入第2个多项式的m个项的系数和指数

参考上面输入第2组数据,以此类推输入t组

假设所有数据都是整数

Output

对于每1组数据,先用两行输出两个原来的多项式,再用一行输出运算结果,不必考虑结果全为0的情况

输出格式参考样本数据,格式要求包括:

1.如果指数或系数是负数,用小括号括起来。

2.如果系数为0,则该项不用输出。

3.如果指数不为0,则用符号 ^ 表示,例如x的3次方,表示为 x^3

4.多项式的每个项之间用符号+连接,每个+两边加1个空格隔开。

Sample Input

2
4
5 0
1 1
2 2
3 3
4
-5 0
-1 1
6 2
4 4
3
-3 0
-5 1
2 2
4
9 -1
2 0
3 1
-2 2

 Sample Output

5 + 1x^1 + 2x^2 + 3x^3
(-5) + (-1)x^1 + 6x^2 + 4x^4
8x^2 + 3x^3 + 4x^4
(-3) + (-5)x^1 + 2x^2
9x^(-1) + 2 + 3x^1 + (-2)x^2
9x^(-1) + (-1) + (-2)x^1

 

AC代码:

#include<iostream>
#include<cstring>
using namespace std;
struct Node {
	int coe, pow;
	Node* next;
	Node() {
		coe = pow = 0;
		next = NULL;
	}
};

void add(Node*& head, int n) {
	for (int i = 0; i < n; i++) {
		int coe, pow;
		cin >> coe >> pow;
		Node* res = new Node;
		res->coe = coe;
		res->pow = pow;
		Node* node = head;
		while (node->next) {
			node = node->next;
		}
		node->next = res;
	}
};

void display(Node* head) {
	Node* node = head;
	int flag = 0;
	while (node->next) {
		node = node->next;
		if (node->coe == 0) continue;
		if (!flag) flag = 1;
		else cout << " + ";
		if (node->coe > 0)
		{
			cout << node->coe;
		}
		else {
			cout << "(" << node->coe << ")";
		}
		if (node->pow == 0) continue;
		else {
			cout << "x^";
			if (node->pow > 0) {
				cout << node->pow;
			}
			else {
				cout << "(" << node->pow << ")";
			}
		}
	}
	cout << endl;
};

int main() {
	int t;
	cin >> t;
	while (t--) {
		int n;
		cin >> n;
		Node* head = new Node;
		add(head, n);
		display(head);
		cin >> n;
		Node* head1 = new Node;
		add(head1, n);
		display(head1);
		
		Node* a = head;
		Node* b = head1->next;
		while (b && a->next) {
			if (b->pow == a->next->pow) {
				a = a->next;
				a->coe += b->coe;
				b = b->next;
			}
			else if (b->pow < a->next->pow) {
				Node* res = new Node;
				res->coe = b->coe;
				res->pow = b->pow;
				res->next = a->next;
				a->next = res;
				a = a->next;
				b = b->next;
			}
			else if (b->pow > a->next->pow) {
				a = a->next;
			}
		}
		if (b) {
			a->next = b;
		}
		display(head);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值