您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页HNU程序设计训练2023—— 多项式加法

HNU程序设计训练2023—— 多项式加法

来源:伴沃教育

【问题描述】

一个多项式可以表示为一组数对,数对中第一个数始终为整数,且唯一,表示多项式的次数,另一数表示为对应的系数且不为0。输入两组数对,每组以0 0作为结束,实现对两个多项式的加法并按降幂输出结果数对

【输入形式】

每行输入一个数对,以空格为分隔符,以0 0结束

【输出形式】

每行输出一个数对,以空格为分隔符

【样例输入】

5 12
3 8
1 2
15 5
0 10
0 0
3 12
30 1
15 5
0 0

【样例输出】

30 1
15 10
5 12
3 20
1 2
0 10

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

struct Pair
{
	int c = 0;//次数
	int x = 0;//系数
};
vector<Pair> s1,s2,s3;
bool cmp(Pair a, Pair b)
{
	return a.c > b.c;//按次数从大到小排列
}
int main()
{
	int c, x;
	while (cin >> c >> x, c != 0 || x!= 0)
	{
		Pair temp;
		temp.c = c, temp.x = x;
		s1.push_back(temp);
	}
	sort(s1.begin(),s1.end(),cmp);
	while (cin >> c >> x, c != 0 || x != 0)
	{
		Pair temp;
		temp.c = c, temp.x = x;
		s2.push_back(temp);
	}
	sort(s2.begin(), s2.end(), cmp);
	int n1 = s1.size(),n2= s2.size();
	int p1 = 0, p2 = 0;
	while(p1< n1 ||p2< n2)
	{
		if (p1 == n1)
		{
			s3.push_back(s2[p2++]);
			continue;
		}
		if (p2 == n2)
		{
			s3.push_back(s1[p1++]);
			continue;
		}
		if (s1[p1].c == s2[p2].c)
		{
			Pair temp;
			temp.c = s1[p1].c;
			temp.x = s1[p1].x + s2[p2].x;
			s3.push_back(temp);
			p1++, p2++;
		}
		else
		{
			if (s1[p1].c > s2[p2].c)
			{
				s3.push_back(s1[p1]);
				p1++;
			}
			else
			{
				s3.push_back(s2[p2]);
				p2++;
			}
		}
	}
	for (auto it = s3.begin(); it != s3.end(); it++)
	{
		if (it->x == 0)
			continue;
		cout << it->c <<" " << it->x << endl;
	}
	return 0;
} 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务