首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

这题为何超内存

2013-01-07 
这题为什么超内存?题目在这里http://acm.hdu.edu.cn/showproblem.php?pid1880#include stdio.h#include

这题为什么超内存?
题目在这里http://acm.hdu.edu.cn/showproblem.php?pid=1880

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <assert.h>
#include <ctype.h>
#include <vector>
#include <iostream>
#include <string>
#include <bitset>
#include <map>
using namespace std;

char line[256] = {NULL};
void getLine(char *line)
{
int i = 0;
char c = 0;
while(scanf("%c", &c) && c != '\n')
{
line[i++] = c;
}
line[i] = NULL;
}
void getString(char *line, string &sa, string &sb)
{
sa = string(line);
int pos = sa.find(']');
sb = sa.substr(pos+2);
sa = sa.substr(0, pos+1);
}
struct Word
{
string _w;
string _f;

Word(string w, string f)
{
_w = w;
_f = f;
}
Word()
{

}
};

bool cmp1(const Word &w1, const Word &w2)
{
return w1._w < w2._w;
}

Word dict[100010];
Word inv_dict[100010];
int idx = 0;

string b_sort(Word *dictA, const string &s)
{
int i = 0; 
int j = idx-1;
while(i<=j)
{
int mid = (i+j)>>1;
if (dictA[mid]._w == s)
{
return dictA[mid]._f;
}
else if (s<dictA[mid]._w)
{
j = mid -1;
}
else
{
i = mid+1;
}
}
return string("");
}

int main()
{
freopen("data.txt", "r", stdin);
idx = 0;
//dictionary
while(true)
{
getLine(line);
if (line[0] =='@')
{
break;
}
string sa, sb;
getString(line, sa, sb);
dict[idx] = Word(sa, sb);
inv_dict[idx] = Word(sb, sa);
idx++;
}
std::sort(dict, dict+idx, cmp1);
std::sort(inv_dict, inv_dict+idx, cmp1);

int num;
char cn;
scanf("%d%c", &num, &cn);
for (int i = 0; i<num; ++i)
{
getLine(line);
string s(line);
//cout<<"s = "<<s<<endl;
if (s[0] == '[')
{
string ret = b_sort(dict, s);
if (ret != string(""))
{
cout<<ret<<endl;
}
else
{
cout<<"What?"<<endl;
}
}
else
{
string ret = b_sort(inv_dict, s);
if (ret != string(""))
{
cout<<ret.substr(1, ret.size()-2)<<endl;
}
else
{
cout<<"What?"<<endl;
}
}
}
return 0;
}

在全局空间开的内存2*100010*(2 string),每两条string最多20+80个字符。用掉字节数2*100010*100/4 = 4883.3K, 怎么也到不了32Mb。
我怀疑是自己算错了,或者在其他地方需要用到额外的内存?
多谢。
[解决办法]
你用string的话你不知道string内部实现里给你分配了多少内存。要是调用的STL里,一个string就给你分配个4K的话……
所以还是char[]吧。
------解决方案--------------------


string会默认给你一个最大内存,不信你用函数查一下
[解决办法]
看了半天也没问题,试了一下,没崩。
只是在最后一个getLine()卡住,随便敲个键就过去。

在data.txt最后加个回车。

写得不怎么样,到处用string复制字符串,不过确实程序能跑出来。

热点排行