# 1002. A+B for Polynomials 解析

#include <iostream>
#include <vector>

using namespace std;

struct Node
{
int k;
float An;
};

void printvet(vector<Node> & poly);

int main() {

vector<Node> poly1;
vector<Node> poly2;
vector<Node> poly3;

Node temp;

int n1, n2;
cin >> n1;
if (n1 > 500) while (1);
for (int i = 0; i < n1; i++) {
cin >> temp.k;
cin >> temp.An;
poly1.push_back(temp);
}

cin >> n2;
for (int i = 0; i < n2; i++) {
cin >> temp.k;
cin >> temp.An;
poly2.push_back(temp);
}

int j = 0, k = 0;
while (j<poly1.size()&&k<poly2.size())
{
if (poly1[j].k == poly2[k].k) {
poly1[j].An += poly2[k].An;
if(poly1[j].An != 0) //和为0不添加
poly3.push_back(poly1[j]);
j++; k++;
}
else if(poly1[j].k < poly2[k].k)
{
poly3.push_back(poly2[k]);
k++;
}
else
{
poly3.push_back(poly1[j]);
j++;
}

}
while (j <poly1.size())
{
poly3.push_back(poly1[j]);
j++;
}
while (k <poly2.size())
{
poly3.push_back(poly2[k]);
k++;
}
printvet(poly3);

system("pause");

return 0;

}

void printvet(vector<Node> & poly) {//打印函数

if (poly.size() == 0) //多项式为0 只输出0
cout << "0" << endl;
else
cout << poly.size() << " ";

for (int i = 0; i < poly.size(); i++)
{
if (i == poly.size() - 1) { //最后一行不能有空格
printf("%d %.1f", poly[i].k,poly[i].An);
}
else {
printf("%d %.1f", poly[i].k, poly[i].An);
cout << " ";
}
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：1002. A+B for Polynomials 解析 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)