map input局部变量和全局变量耗时问题。

dongqishu 2012-11-19 09:29:14
北大ACM1009题

#include <iostream>
#include<map>

using namespace std;

map<int,int> input;
//int input[1002][2];

//int count;

bool insideImage(int x, int y,int w, int s)
{
if(x>=1&&y>=1&&x<=w&&(y-1)*w+x<=s) return true;
else return false;
}



int getPix(int x,int y, int w)
{
int t=(y-1)*w +x;
for(map<int,int>::iterator it=input.begin();it!=input.end();++it)
{
if(t<=it->first) return it->second;
}
//for(int i=1;i<count;i++)

//{

// if(t<=input[i][1]) return input[i][0];

//}
return 0;

}





int getVal(int x,int y, int w, int s)
{
int thisValue = getPix(x,y,w);
int temp = 0,max = 0;

for(int i=x-1;i<=x+1;i++)
{
for(int j=y-1;j<=y+1;j++)
{
if(insideImage(i,j,w,s))
{
temp = abs(thisValue-getPix(i,j,w));
if(temp>max) max = temp;
}
}
}
return max;
}



int main()
{
while(true)
{
map<int,int> output;
map<int,int>::iterator ot;
map<int,int>::iterator otNext;

int width,sum = 0;

//count = 1;

cin>>width;

if(width==0) break;



//memset(input,0x0,1002*2*sizeof(int));
input.clear();

//input[0][1]=0;

input[0] = 0;

while(true)
{

int val,len;

cin>>val>>len;



if(len==0) break;

sum += len;

//input[count][0]=val;

//input[count][1]=sum;

input[sum] = val;

//count++;

}



for(map<int,int>::iterator it=input.begin();it!=input.end();++it)
//for(int i =0;i<count;i++)
{

//int n=input[i][1] + 1;
int n = it->first + 1;

int x = 0,y = 0,dx = 0,dy = 0;

if(n%width == 0)
{
x=width;
y=n/width;
}
else
{
x=n%width;
y=n/width+1;
}



for(dx = x-1;dx<=x+1;dx++)
{
for(dy = y-1;dy<=y+1;dy++)
{
if(insideImage(dx,dy,width,sum))
output[(dy-1)*width+dx] = getVal(dx,dy,width,sum);
}
}

}



cout<<width<<endl;

ot = output.begin();

while(ot!=output.end())
{

otNext = ot;
otNext ++;
for(;otNext!=output.end()&&ot->second==otNext->second;++otNext);
if(otNext == output.end()) break;
else
{
cout<<ot->second<<" "<<otNext->first-ot->first<<endl;
ot = otNext;
}
}

cout<<ot->second<<" "<<sum-ot->first + 1<<endl;
cout<<"0 0"<<endl;

}



cout<<"0"<<endl;
return 0;

}



当input改为局部变量时,需要的时间不能通过验证(>1000ms),请问为什么map<int,int>用局部变量比全局变量耗时间?谢谢。
...全文
147 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
漫步者、 2012-11-19
  • 打赏
  • 举报
回复
为什么map<int,int>用局部变量比全局变量耗时间 答:因为在某个函数中,你每次调用这个函数的时候,都需要时间为之分配空间,作为全局变量,第一次为之分配之后就不需要在花费时间去为之分配了,也就是全局只需要一次,而布局变量在你使用多少次就得分配多少次!
prajna 2012-11-19
  • 打赏
  • 举报
回复
應該與内存操作有關,可以看看生成的匯編代碼。

64,653

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧