描述
数据表记录包含表索引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
思路
- 看到键值对,并且最后还要以升序的方式输出,第一反应就是使用std::map。std::map的第三个模板参数就是用于指定如何排序的,默认为less(key),即按键值升序排列。
代码
Combiner.h
#pragma once
#include <mutex>
class Combiner
{
public:
static Combiner* getInstance();
public:
void combine();
private:
Combiner() = default;
~Combiner() = default;
private:
static Combiner* instance;
static std::mutex iMutex;
};
Combiner.cpp
#include <iostream>
#include <map>
#include <algorithm>
#include "Combiner.h"
Combiner* Combiner::instance = nullptr;
std::mutex Combiner::iMutex;
Combiner* Combiner::getInstance()
{
std::unique_lock<std::mutex> lock(iMutex);
if (nullptr == instance) {
instance = new Combiner();
}
return instance;
}
void Combiner::combine()
{
/* input */
uint32_t count = 0;
std::cin >> count;
uint32_t index = 0;
uint32_t value = 0;
std::map<uint32_t, uint32_t> mapTable; //按KEY升序
//std::map<uint32_t, uint32_t, std::greater<uint32_t>> mapTable;//按KEY降序
mapTable.clear();
while (count) {
std::cin >> index >> value;
/* verify validity */
if (index > 11111111) {
std::cout << "An index greater than 11111111" << std::endl;
continue;
}
if (value < 1 || value > 100000) {
std::cout << "A value less than 1 or greater than 100000" << std::endl;
continue;
}
/* combine */
auto idx = mapTable.begin();
for (; idx != mapTable.end(); idx++) {
if (index == idx->first) {
idx->second += value;
break;
}
}
if (idx == mapTable.end()) {
mapTable[index] = value;
}
count--;
}
/* output */
for (auto& ele:mapTable) {
std::cout << ele.first << " " << ele.second << std::endl;
}
}
main.cpp
#include "Combiner.h"
int main(int argc, char** argv)
{
auto combiner = Combiner::getInstance();
combiner->combine();
return 0;
}
测试
测试环境
visual studio 2019
测试结果
输入:
4
0 1
0 2
1 2
3 4
输出:
0 3
1 2
3 4
输入:
3
0 1
0 2
8 9
输出:
0 3
8 9
输入:
5
1 1
2 3
1 3
2 5
输出:
1 4
2 8
5 7