线性表-多项式加法(数据结构基础 第2周)

问题描述:
线性表-多项式加法(数据结构基础 第2周)_第1张图片
线性表-多项式加法(数据结构基础 第2周)_第2张图片

分析
这道题用map应该是最容易实现的,没用链表。

源码

#include <iostream>
#include <map>
using namespace std;

int main() {
    int n;
    cin >> n;
    int value, power;
    while(n--) {
        map<int, int, greater<int> > poly;
        while((cin>>value>>power) && power>=0) {
            poly[power] += value;
        }

        while((cin>>value>>power) && power>=0) {
            poly[power] += value;
        }
        for (map<int, int, greater<int> >::iterator i=poly.begin(); i!=poly.end(); i++) {
            if (i->second != 0)
            {
                cout << "[ " << i->second << ' ' << i->first << " ] ";
            }           
        }
        cout << endl;
    }   
    return 0;
}

你可能感兴趣的:(线性表-多项式加法(数据结构基础 第2周))