ccf-csp认证 稀疏向量 202006-2

题目

在这里插入图片描述

队列法

因为是输入是有顺序的,所以直接用“先进先出”的队列就行;
如果是无序的,那么只能用unordered_map了

#include <iostream>
#include <queue>

using namespace std;
#define _for(i, a, b) for (int i = a; i < b; i++)
struct point {
    int id;
    int e;
};
int main() {
    //	freopen("in.txt","r",stdin);
    ios::sync_with_stdio(false);
    int n, a, b;
    cin >> n >> a >> b;
    int y;
    int x;
    queue<point> q;
    _for(i, 0, a) {
        cin >> x >> y;
        q.push({x, y});
    }

    long long int sum = 0;
    _for(i, 0, b) {
        cin >> x >> y;
        while (!q.empty()) {
            int i = q.front().id, j = x;
            if (i < j) {
                q.pop();
            } else if (i == j) {
                sum += (q.front().e * y);
                q.pop();
                break;
            } else {
                break;
            }
        }
    }
    cout << sum;
    return 0;
}

哈希表法

//这是一道简单题
#include<iostream>
#include<map>
#define _for(i,a,b) for(int i=a;i<b;i++)
using namespace std;
int main()
{
	ios::sync_with_stdio(false);
	int n, a, b;//维数,a,b向量的非零值个数
	cin >> n >> a >> b;
	map<int, int> mp;
	int pos, val;
	long long int sum = 0; //最终结果
	_for(i,0,a) {
		cin >> pos;
		cin >> val;
		mp[pos] = val;
	}
	_for(i,0,b) {
		cin >> pos;
		cin >> val;
		if (mp[pos] != 0)
			sum+= (mp[pos] * val);
	}
	cout << sum<< endl;
	return 0;
}

快的是队列法,空间也少
在这里插入图片描述

测试样例

10 3 4
4 5
7 -3
10 1
1 10
4 20
5 30
7 50
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值