在写《数据结构与算法》的基础实验7-2.1 魔法优惠券 (25 分)时,需要定义一些比较大的数组,一开始都是定义在main函数里面,结果提交到oj上时大数据的点始终是断错误,我一直以为时数组越界了,后来才知道大大数组最好不要定义在main函数里面,引用这篇文章的一段话:https://blog.csdn.net/Tesla_meng/article/details/88370299 “全局变量在静态存储区内分配内存,而局部变量是在栈内分配内存空间的。C语言编写的程序会在运行期间创建一个栈堆段,用来保存函数的调用关系和局部变量。而在main函数内部定义大数组相当于在站内需要一个很大的空间,会造成栈的溢出。
因此,当我们需要定义一个极大的数组时,最好在mian 函数外部定义这个大数”。
这个题的思路很简单就不说了,主要是这个大数组的点我以前真没遇到过,特地记录下来以防以后出错。下面是该题的代码:
#include<cstdio>
#include<algorithm>
#include<iostream>
const int maxn = 10000000;
bool cmp1(int a, int b)
{
return a>b;
}
bool cmp2(int a, int b)
{
return a<b;
}
using namespace std;
int PCoupon[maxn],NCoupon[maxn],PStuff[maxn],NStuff[maxn];//大数组应该定义在main函数外部
int main()
{
// int PCoupon[maxn],NCoupon[maxn],PStuff[maxn],NStuff[maxn];//大数组定义在main函数内部会导致堆栈溢出
int N,M,i,tmp,index1 = 0,index2 = 0,index3 = 0,index4 = 0;
cin>>N;
for(i=0; i<N; i++)
{
cin>>tmp;
if(tmp>0)
{
PCoupon[index1] = tmp;
index1++;
}
else if(tmp<0)
{
NCoupon[index2] = tmp;
index2++;
}
}
cin>>M;
for(i=0; i<M; i++)
{
cin>>tmp;
if(tmp>0)
{
PStuff[index3] = tmp;
index3++;
}
else if(tmp<0)
{
NStuff[index4] = tmp;
index4++;
}
}
sort(PCoupon,PCoupon+index1,cmp1);
sort(NCoupon,NCoupon+index2,cmp2);
sort(PStuff,PStuff+index3,cmp1);
sort(NStuff,NStuff+index4,cmp2);
int p1 = 0,p2 = 0;
int cnt = 0;
while(p1<index1&&p2<index3)
{
cnt += PCoupon[p1]*PStuff[p2];
p1++; p2++;
}
p1 = p2 = 0;
while(p1<index2&&p2<index4)
{
cnt += NCoupon[p1]*NStuff[p2];
p1++; p2++;
}
printf("%d\n",cnt);
}