202006-2 稀疏向量

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的数组的方法,会爆内存。

        原因:开一个长度为10^9 的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。不知道怎么优化。。。😔

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值