[编程题]合并表记录

来源:互联网 发布:四知文言文的意思 编辑:程序博客网 时间:2024/05/27 00:41

Talk is cheap, show me the code.

一、问题描述

数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。

输入描述:

先输入键值对的个数,然后输入成对的index和value值,以空格隔开

输出描述:

输出合并后的键值对(多行)

输入例子:

40 10 21 23 4

输出例子:

0 31 23 4

二、问题分析

可以利用map的自动按key排序的功能。

解题方式1:

#include <iostream>#include <map>#include <iterator>using namespace std;int main(){    int num;    while (cin >> num)    {        int key, value;        map<int, int> ma;        while (cin >> key >> value)        {            if (ma.count(key))            {                ma[key] += value;            } else {                ma[key] = value;            }        }        for (map<int, int>::iterator it = ma.begin(); it != ma.end(); ++it)        {            cout << it->first << " " << it->second << endl;        }    }    return 0;}

解题方式2:

一种书写更简单的方式:

#include <iostream>#include <map>#include <iterator>using namespace std;int main(){    int num;    while (cin >> num)    {        int key, value;        map<int, int> ma;        while (num--)        {            cin >> key >> value;            ma[key] += value;        }        for (pair<int, int> p : ma)        {            cout << p.first << " " << p.second << endl;        }    }    return 0;}
0 0
原创粉丝点击