一道算法题引发的动态内存管理的思考

一道算法题引发的动态内存管理的思考

在做PKU2762时,需要建邻接表。
于是按部就班写了下面一个插入边到邻接表中的函数:

const   int  VMAX  =   1010 ;
typedef struct Graph
{
    
int  vex;
    Graph
*   next ;
}Graph;
Graph ArcGraph[VMAX];
void insert(
int  u,  int  v)
{
    Graph
*  t  =   new  Graph;
    Graph
*  p  =  ArcGraph[u].next;
    t
-> vex  =  v;
    t
-> next   =  p;
    ArcGraph[u].next 
=  t;
}


完成完整的程序提交上去,得到结果
Memory:25796K  Time:375MS
Language:C++  Result:Accepted

再对比别人的程序
Memory:296K Time:109MS

无论是时间还是空间都相差很大。
于是就考虑怎么优化自己的程序。
第一个问题:规模只有1000,为什么会用那么多内存呢?
仔细一想数据是多case的,每次插入新节点时都要动态创建一个节点。
一来动态创建耗时间,二来每个case结束的邻接表中的节点没有释放,故耗费大量内存。
然后就想到了下面的算法,首先初始化一块内存Graph use[100*VMAX];这样每次需要新节点时,
就从use中获取。如果use使用完毕就再动态创建。

依此算法优化后,得到的结果比较满意
Memory:1000K  Time:218MS
Language:C++  Result:Accepted

const   int  VMAX  =   1010 ;
typedef struct Graph
{
    
int  vex;
    Graph
*   next ;
}Graph;
Graph ArcGraph[VMAX];
Graph use[
100 * VMAX];
int  size  =   0 ;
void insert(
int  u,  int  v)
{
    Graph
*  t;
    
if (size  <   100 * VMAX)
    {
        t 
=   & use[size];
        size
++ ;
    }
    
else  t  =   new  Graph;
    Graph
*  p  =  ArcGraph[u].next;
    t
-> vex  =  v;
    t
-> next   =  p;
    ArcGraph[u].next 
=  t;
}

你可能感兴趣的:(一道算法题引发的动态内存管理的思考)