牛客網 - 線上程式設計 - 華為機試 - 合併表記錄
阿新 • • 發佈:2018-11-21
題目描述
資料表記錄包含表索引和數值,請對錶索引相同的記錄進行合併,即將相同索引的數值進行求和運算,輸出按照key值升序進行輸出。
輸入描述:
先輸入鍵值對的個數
然後輸入成對的index和value值,以空格隔開
輸出描述:
輸出合併後的鍵值對(多行)
示例1
輸入
4
0 1
0 2
1 2
3 4
輸出
0 3
1 2
3 4
C++:
參考map詳解
#include <iostream>
#include <map>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
map<int, int> mymap;
while (n--)
{
int a, b;
cin >> a; cin >> b;
auto it = mymap.find(a);
if (it != mymap.end())
mymap[a] += b;
else
mymap[a] = b;
}
for (auto it = mymap.begin(); it != mymap.end(); ++it)
{
cout << it->first << " " << it->second << endl;
}
}
return 0;
}
Python:
n = int(input())
dic = {}
for i in range(n):
key, val = map(int, input().split())
if key in dic:
dic[key] += val
else:
dic[key] = val
for i,j in sorted(dic.items()):
print(i,j)