This time, you are supposed to find A+B where A and B are two polynomials.

Input Specification:

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:

K N1 aN1 N2 aN2 ... *N**K* aNK

where K is the number of nonzero terms in the polynomial, *N**i* and aNi (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤*N**K<⋯<N2<N*1≤1000.

Output Specification:

For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.

Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 2 1.5 1 2.9 0 3.2
思路
  • 统计个数的时候要注意如果两个系数相加为0,最后是不输出的,这里要注意一下,所以先全部读进来再进行统计cnt
代码
#include<bits/stdc++.h>
using namespace std;
double coefficient[1010] = {0};
bool vis[1010] = {0};
int main()
{
    int k;
    int max_coe = -1;
    int id;
    double tmp;
    int cnt = 0; //统计不同系数的个数,要非零

    cin >> k;
    while(k--)
    {
        cin >> id >> tmp;
        coefficient[id] += tmp;
        if(!vis[id])
        {
            vis[id] = true;
            cnt++;
        }
        max_coe = max(max_coe, id);
    }
    cin >> k;
    while(k--)
    {
        cin >> id >> tmp;
        coefficient[id] += tmp;
        if(!vis[id])
        {
            vis[id] = true;
            cnt++;
        }
        max_coe = max(max_coe, id);
    }

    cout << cnt << " ";
    for(int i=max_coe;i>=0;i--)
    {
        if(vis[i] && cnt != 1)
        {
            cout << i << " " << coefficient[i] << " ";
        }
        if(vis[i] && cnt == 1)
        {
            cout << i << " " << coefficient[i];
        }
        cnt--;
        if(cnt == 0)
            break;
    }

    return 0;
}
引用

https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000

02-14 00:17