题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
该说不说,C++
解题真简单,直接搞个map
就解决了,上代码:
#include <iostream>
#include <map>
int main() {
int n = 0, key = 0, val = 0;
std::map<int, int> m;
std::cin >> n;
while (std::cin >> key >> val) {
m[key] += val;
}
for (auto& t : m) {
std::cout << t.firse << " " << t.second << std::endl;
}
return 0;
}
Java
也一样,搞个TreeMap
就行, 上代码:
import java.util.Scanner;
import java.util.TreeMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = 0, key = 0, val = 0;
TreeMap<Integer, Integer> m = new TreeMap<>();
n = sc.nextInt();
for (int i = 0; i < n; ++i) {
key = sc.nextInt();
val = sc.nextInt();
m.put(key, m.getOrDefault(key, 0)+val);
}
for (Map.Entry<Integer, Integer> e : m.entrySet()) {
System.out.println(e.getKey() + " " + e.getValue());
}
}
}