CCF 202006-2 稀疏向量 满分代码
发布日期:2021-05-06 19:32:41 浏览次数:26 分类:技术文章

本文共 2141 字,大约阅读时间需要 7 分钟。

作者:its_ycm 来源:CSDN 原文:https://blog.csdn.net/its_ycm/article/details/110069713版权声明:本文为博主原创文章,转载请附上博文链接!

试题编号: 202006-2

试题名称: 稀疏向量
时间限制: 2.0s
内存限制: 512.0MB
在这里插入图片描述
在这里插入图片描述
样例输入

10 3 44 57 -310 11 104 205 307 40

如果使用数组存储,下标会错误,n最大是1e9!

s是 long long 型,要注意大数相乘!

方法一:

在这里插入图片描述

#include
using namespace std;int main(){
map
u; map
v; int n,a,b,x,y; long long s=0; cin>>n>>a>>b; while(a--) {
cin >> x >> y; u[x] = y; } while(b--) {
cin >> x >> y; v[x] = y; } for(map
::iterator uit = u.begin();uit!=u.end();++uit){
if(uit->second!=0) s += uit->second * v[uit->first]; } cout << s << endl; return 0;}

方法二:

这个方法是第二组数 边存边计算结果。

在这里插入图片描述

#include 
using namespace std;int main(){
// ios::sync_with_stdio(false);加上这个速度更快 map
u; int n,a,b,x,y; long long s=0; cin>>n>>a>>b; for(int i=1;i<=a;++i){
cin>>x>>y; u[x]=y; } for(int i=1;i<=b;++i){
cin>>x>>y; if(u[x]!=0) s += u[x]*y; } cout << s << endl; return 0;}

方法三:

下面代码使用了map容器里的 find函数 和 ios::sync_with_stdio(false); 这个加速。

在这里插入图片描述

#include
using namespace std;const int N = 5e5;//a最大是5*10^5 struct node{
int dex; int val;}nod[N];int main(){
ios::sync_with_stdio(false);//此处代码加速不少 map
m; long long sum =0; int n,a,b,x,y; cin>>n>>a>>b; for(int i=1;i<=a;++i){
cin>>x>>y;// scanf("%d %d",&x,&y);scanf也没有ios::sync_with_stdio(false);快 nod[i].dex = x; nod[i].val = y; } map
::iterator it; for(int i=1;i<=b;++i){
cin>>x>>y;// scanf("%d %d",&x,&y); m[x] = y; } for(int i=1;i<=a;++i){
it = m.find(nod[i].dex); if(it!=m.end()) sum += it->second * nod[i].val; } cout << sum << endl;// printf("%lld\n",sum); return 0;}

方法四:(错误代码)

下面代码运行超时,还是要用迭代器处理

在这里插入图片描述

#include
using namespace std;int main(){
map
u; map
v; int n,a,b,x,y; long long s=0; cin>>n>>a>>b; while(a--) {
cin >> x >> y; u[x] = y; } while(b--) {
cin >> x >> y; v[x] = y; } //此处导致运行超时,用ios::sync_with_stdio(false);也还是超时 for(int i=1;i<=n;++i){
if( u[i]!=0 && v[i]!=0 ) s += u[i] * v[i]; } cout << s << endl; return 0;}
上一篇:CCF 201912-1 报数 满分代码
下一篇:CSP-CCF 202006-1 线性分类器 满分代码

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年03月18日 17时25分30秒