描述
数据表记录包含表索引index和数值value(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出。
提示:
0 <= index <= 11111111
1 <= value <= 100000
输入描述:
先输入键值对的个数n(1 <= n <= 500)
接下来n行每行输入成对的index和value值,以空格隔开
输出描述:
输出合并后的键值对(多行)
示例1
输入:
4 0 1 0 2 1 2 3 4
复制输出:
0 3 1 2 3 4
复制
示例2
输入:
3 0 1 0 2 8 9
复制输出:
0 3 8 9
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <string.h>
#include <malloc.h>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <map>
#include <set>
void print(std::multimap<int, int> numMap)
{
std::multimap<int, int>::iterator iter = numMap.begin();
while (iter != numMap.end())
{
std::cout << iter->first << "," << iter->second << std::endl;
iter++;
}
}
void print(std::set<int> keySet)
{
std::set<int>::iterator iterSet = keySet.begin();
while (iterSet != keySet.end())
{
std::cout << *iterSet++ << std::endl;
}
}
//统计同一个key的value总和
void MergeRecord(std::multimap<int, int> numMap)
{
std::set<int> keySet; //存放所有的key值
std::multimap<int, int>::iterator iterMap = numMap.begin();
while (iterMap != numMap.end())
{
keySet.insert(iterMap->first);
iterMap++;
}
// print(keySet);
std::set<int>::iterator iterSet = keySet.begin();
while (iterSet != keySet.end())
{
int size = 0;
int rtnsum = 0;
int rtnkey = 0;
std::multimap<int, int>::iterator iter = numMap.find(*iterSet); //根据set集合中存储的key值找map集合中的value和
rtnkey = iter->first;
size = numMap.count(*iterSet);
while (size-- > 0)
{
rtnsum += iter->second;
iter++;
}
std::cout << rtnkey << " " << rtnsum << std::endl;
iterSet++;
}
}
int main()
{
// int num;
std::multimap<int, int> numMap;
int key;
int value;
int count;
std::cin >> count;
while(count-- > 0)
{
std::cin >> key;
std::cin >> value;
numMap.insert(std::pair<int, int>(key, value));
}
MergeRecord(numMap);
return 0;
}