ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

CCF 202006-2 稀疏向量【map的使用】

2020-12-11 21:57:47  阅读:220  来源: 互联网

标签:map val 10 int 202006 ++ ind CCF


目录

一、题目

在这里插入图片描述

二、解析

主要用到map的构造和find方法。其中,map的构造如下:

#include <iostream>
#include <map>

using namespace std;

int n, a, b;

map<int, int> u;
map<int, int> v;

int main()
{
	cin >> n >> a >> b;
	for (int i = 0; i < a; i++) {
		int ind, val;
		cin >> ind >> val;
		u[ind] = val;
	}
	for (int i = 0; i < b; i++) {
		int ind, val;
		cin >> ind >> val;
		v[ind] = val;
	}

	cout << "Vector u:" << endl;
	for (map<int, int>::iterator it = u.begin(); it != u.end(); it++)
		cout << (*it).first << " " << (*it).second << endl;

	cout << "Vector v:" << endl;
	for (map<int, int>::iterator it = v.begin(); it != v.end(); it++)
		cout << (*it).first << " " << (*it).second << endl;

	return 0;
}

输入:

10 3 4
4 5
7 -3
10 1
1 10
4 20
5 30
7 40

输出:

Vector u:
4 5
7 -3
10 1
Vector v:
1 10
4 20
5 30
7 40

三、代码

#include <iostream>
#include <map>

using namespace std;

int n, a, b;

map<int, int> u;
map<int, int> v;

long long product = 0;

int main()
{
	cin >> n >> a >> b;
	for (int i = 0; i < a; i++) {
		int ind, val;
		cin >> ind >> val;
		u[ind] = val;
	}
	for (int i = 0; i < b; i++) {
		int ind, val;
		cin >> ind >> val;
		v[ind] = val;
	}

	//	cout<<"Vector u:"<<endl;
	//	for(map<int, int>::iterator it=u.begin(); it!=u.end(); it++)
	//		cout<<(*it).first<<" "<<(*it).second<<endl;
	//
	//	cout<<"Vector v:"<<endl;
	//	for(map<int, int>::iterator it=v.begin(); it!=v.end(); it++)
	//		cout<<(*it).first<<" "<<(*it).second<<endl;

	for (map<int, int>::iterator itU = u.begin(); itU != u.end(); itU++) {
		int ind = (*itU).first;
		map<int, int>::iterator itV = v.find(ind);
		if (itV != v.end())
			product += (*itU).second * (*itV).second;
	}
	cout << product << endl;

	return 0;
}

输入:

10 3 4
4 5
7 -3
10 1
1 10
4 20
5 30
7 40

输出:

-20

四、感想

  1. 第一次使用vector,但只获得30分,后面的超时了。因为vector的查找的时间复杂度为O(n),所以程序的时间复杂度为O(a*b)。

  2. 第二次使用map,但只获得60分,后面的错误了;第三次将累加用的变量product由int类型换为long long类型,就通过了。因为map的查找的时间复杂度为O(log n),所以程序的时间复杂度为O(a*log b);且|ui|、|vi|<=106,故product的类型应该为long long。

标签:map,val,10,int,202006,++,ind,CCF
来源: https://blog.csdn.net/weixin_43826681/article/details/111032370

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有