很多方法用链表写,感觉代码量好大。用数组写会好一点,检测耗时也不是很长
#include<iostream>
#define N 10000
using namespace std;
int main()
{
int a[N] = { 0 };
int b[N] = { 0 };
int c[N] = { 0 };
int d[N] = { 0 };
//读入数据
int n1, n2;
int C, n;//n是指数,C是系数
bool flag = false;
bool space = false;//没输出空格
cin >> n1;
for (int i = 0; i < n1; i++)
{
cin >> C >> n;
a[n] += C;
}
cin >> n2;
for (int i = 0; i < n2; i++)
{
cin >> C >> n;
b[n] += C;
}
//乘法,存入c[n]
for (int i = 0; i < N; i++)
{
if(a[i])
for (int j = 0; j < N; j++)
{
if (b[j])
{
c[i + j] += a[i] * b[j];
}
}
}
//输出结果
space = false;
flag = false;
for (int i = N - 1; i >= 0; i--)
{
if (c[i])
{
if (space)
cout << " ";
cout << c[i] << " " << i;
flag = true;
space = true;
}
}
if (!flag)
cout << "0 0" ;
cout << endl;
//加法,存入d[n]
for (int i = 0; i < N; i++)
{
if (a[i])
d[i] += a[i];
}
for (int i = 0; i < N; i++)
{
if (b[i])
d[i] += b[i];
}
//输出结果
space = false;
flag = false;
for (int i = N-1; i >= 0; i--)
{
if (d[i])
{
if (space)
cout << " ";
cout << d[i] << " " << i;
flag = true;
space = true;
}
}
if (!flag)
cout << "0 0" << endl;
system("pause");
return 0;
}