1002 A+B for Polynomials

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:

N1​​ aN1​​​​ N2​​ aN2​​​​ ... NK​​ aNK​​​​

where K is the number of nonzero terms in the polynomial, Ni​​ and aNi​​​​ (,) are the exponents and coefficients, respectively. It is given that 1,0.

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-1000,而且是整数,所以定义一个1001大小的数组就ok了,数组下标代表指数,对应的值代表系数
poly[exp] = cof;
然后直接吧指数相同的多项式的系数盲加一波就行了
 
注意
1.系数为0,则不输出(考虑系数为负数的情况)
2.系数为0,不计数
3.按指数逆序输出
 
#include <iostream>
#include <string.h>
#include <cstdio>
#include <algorithm>
using namespace std;

#define maxNum 1001
float poly[maxNum] = { 0 };

int main()
{
    for (int i = 0; i < 2; i++) {
        int k,exp;
        float cof;
        cin >> k;
        for (int j = 0; j < k; j++) {
                cin >> exp >> cof;
                poly[exp] += cof;//同指数的,系数相加
        }

    }
    //统计多项式的个数
    int cnt = 0;
    for (int i = 0; i < maxNum; i++) {
        if (poly[i] != 0) {//系数不为0
            cnt++;
        }
    }
    //输出
    cout << cnt;
    for (int i = maxNum-1; i >=0; i--) {
        if (poly[i] != 0) {
            printf(" %d %.1f", i, poly[i]);
        }
    }
    return 0;
}

 

 
 
posted @ 2020-08-15 19:42  houyz  阅读(100)  评论(0)    收藏  举报