1000. Polynomial Addition

     
 
1000. Polynomial Addition
 
 
Total:339 Accepted:104
 
     
     
 
Time Limit: 1sec    Memory Limit:1MB
Description

实现多项式加法。

Input

测试输入包含多组数据:

第一行是测试数据个数m, 以下是m组测试数据。每组数据给出两个多项式,每个多项式由一个表示多项式项数的整数n(0<n<100),以下每一行的两个整数分别表示各项系数和指数。假定多项式按照降幂排列,多项式的最高次数不超过10000次。

 

Output

输出:

对每组测试数据输出多项式的和,并且按照多项式降幂排列,其中第一行表示项数,以下各行输出各项的系数和指数。

Sample Input
 Copy sample input to clipboard
2
2
1 2
3 0
3
1 9
-2 5
-3 0

2
2 4
1 0
0
Sample Output
3
1 9
-2 5
1 2
2
2 4 
1 0




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

int main() {
    int num;
    cin>> num;
    for (int num_i= 0; num_i< num; num_i++) {
        map<int, int> ploy;
        
        int n1;
        cin>> n1;
        for (int i= 0; i< n1; i++) {
            int index, value;
            cin>> value>> index;
            ploy.insert(make_pair(index, value));
        }
        
        /*cout<< endl;
        for (map<int, int>::iterator it= ploy.begin(); it!= ploy.end(); it++) {
            cout<< it->second<< " "<< it->first<< endl; 
        }
        cout<< endl;*/
        
        int n2;
        cin>> n2;
        for (int i= 0; i< n2; i++) {
            int index, value;
            bool if_exist= false;
            cin>> value>> index;
            map<int, int>::iterator it;
            for (it= ploy.begin(); it!= ploy.end(); it++) {
                if (it->first== index) {
                    it->second+= value;
                    if_exist= true;
                    break;
                }
            }
            if (if_exist== false) {
                ploy.insert(make_pair(index, value));
            }
        }
        
        int number= 0; 
        for (map<int, int>::iterator it= ploy.begin(); it!= ploy.end(); it++) {
            if (it->second!= 0) number++;
        }
        cout<< number<< endl;
        for (map<int, int>::reverse_iterator it= ploy.rbegin(); it!= ploy.rend(); it++) {
            if (it->second!= 0) {
                cout<< it->second<< " "<< it->first<< endl;
            }
        }
    }
}


map的key是自动升序排列的,特别注意的是最后的遍历需要用reverse_iterator
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值