C++:
#include<iostream>
#include<map>
#include<algorithm>
using namespace std;
typedef long long LL;
// const int N = 1e8;
// int A[N], arrB[N];
map<int, int>mpA, mpB;
int main(){
int n, a, b;
int k, v;
scanf("%d%d%d", &n, &a, &b);
for(int i = 1; i <= a; i++){
scanf("%d%d", &k, &v);
// A[k] = v;
mpA[k] = v;
}
for(int i = 1; i <= b; i++){
scanf("%d%d", &k, &v);
// arrB[k] = v;
mpB[k] = v;
}
LL res = 0;
for(auto it = mpA.begin(); it != mpA.end(); it++){
k = it->first;
v = it->second;
auto itB = mpB.find(k);
if(itB != mpB.end()){
res += (LL)itB->second * v;
}
}
// for(int i = 1; i <= n; i++){
// res += (LL)A[i] * arrB[i];
// }
cout << res << endl;
}
- 这道题如果用注释中的开长度为n的数组的方法,会爆内存。
原因:开一个长度为 的int数组占用的内存会超过512MB。
- map.find()返回的是一个迭代器.
通过map对象的方法获取的iterator数据类型是一个std::pair对象,包括两个数据 iterator->first和 iterator->second分别代表关键字和存储的数据。
java:
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main{
public static void main(String[] args){
int n, a, b;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
a = sc.nextInt();
b = sc.nextInt();
HashMap<Integer, Integer> mpA = new HashMap();
HashMap<Integer, Integer> mpB = new HashMap();
int k, v;
for(int i = 1; i <= a; i++){
k = sc.nextInt();
v = sc.nextInt();
mpA.put(k,v);
}
for(int i = 1; i <= b; i++){
k = sc.nextInt();
v = sc.nextInt();
mpB.put(k,v);
}
Long res = 0L;
for(Map.Entry<Integer, Integer> entry : mpA.entrySet()){
Integer key = entry.getKey();
Integer value = entry.getValue();
if(mpB.get(key) !=null){
res += (long)mpB.get(key) * value;
}
}
System.out.println(res);
}
}
在acwing上可以通过,但是在ccf-csp平台上会爆内存,得分只有60。不知道怎么优化。。。😔