题目解读:
题目的意思就是有两个数组(先假设用数组),index相同时,如果value都不等于0,那么就把这两个值相乘,累加得到内积。
实现过程中的坑:
- 测试点数值很大,sum会溢出,要使用long long 类型。
- 读题容易出现误区,其实这道题跟N没什么关系(我就被迷惑了,最后for循环用n做条件,就运行错误了...)
- 根据别的博主总结得到如下,所以如果使用数组来解决,要设置全局数组,否则会出现运行错误(60分)
- 1.局部变量在栈上分配,最大2MB
- 2.全局变量在静态区分配,理论上是2GB
- 局部变量的char数组最大能开4*518028,int最大能开到518028
- 局部二维int数组能开到724*724
- 全局一维int数组能开到很大很大…(2GB)
- 全局二维int数组能开到20000*20000
满分代码:
#include <iostream>
#include <string.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
const int N = 5*100000+5;//测试点里给出的a/b最大值+5,设置长度用const 比较不容易出错
//我的思路是用struct+数组,别的博主也有用vector、map,或者拆成4个全局数组
struct svector {
int index;
int value;
};
svector u[N], v[N];//数组要设置成全局
int main(int argc, char** argv) {
memset(u, 0, sizeof(u));//使用memset初始化struct数组,头文件 string.h
memset(v, 0, sizeof(v));
int n, a, b;
long long sum = 0;#sum使用long long,避免溢出
cin >> n >> a >> b;
for (int i = 0; i < a; i++) {
cin >> u[i].index >> u[i].value;
}
for (int i = 0; i < b; i++) {
cin >> v[i].index >> v[i].value;
}
int i =0;int j=0;
while(i<a && j<b) {
int z=u[i].index,w=v[j].index;
if(z == w) {
sum += u[i].value*v[j].value;
i++;j++;
}
if(z > w) j++;
if(z < w) i++;
}
cout << sum << endl;
return 0;
}
数组长度上限:
debug小知识
运行错误大概率是内存溢出、指针越界(考虑定义数组的时候扩大长度)。
参考博文
原文链接:https://blog.csdn.net/qq_39685968/article/details/108234147
原文链接:https://blog.csdn.net/qq_39685968/article/details/108234147