首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

动态数组有关问题,请问下各位什么地方错了

2012-02-10 
动态数组问题,请教下各位什么地方错了这是我的源程序,我原来开的是静态数组,后来将stick和used两个数组改

动态数组问题,请教下各位什么地方错了
这是我的源程序,我原来开的是静态数组,后来将stick和used两个数组改成动态的后,就错了。请教各位下,这样使用NEW是不是用错了,对动态数组还不大会,请教名位下,谢谢了咯。


#include <iostream>
#include <string>

using   namespace   std;

int   *stick=NULL;  
int   *used=NULL;    
int   ok;  
int   length;
int   stickNum;
int   total;  
int   n;


int   cmp   (   const   void   *a   ,   const   void   *b   )   //&acute;&Oacute;&acute;ó&micro;&frac12;&ETH;&iexcl;&Aring;&Aring;&ETH;ò
{  
          return   *(int   *)b   -   *(int   *)a;  
}  


void   match(int   x);
void   search(int   num,int   nowLenth,int   nextStick);

int   main()
{

while(cin> > n){
if(!n)
break;
ok=0;
total=0;

stick   =   new   int[n+1];
used     =   new   int[n+1];
int   i;
for(   i   =   1;i   <=   n;++i){
cin> > stick[i];
total   +=   stick[i];
}
qsort(stick+1,n,sizeof(int),cmp);  

for(i   =   stick[1];i   <=   total;++i){
if   (total   %   i   ==   0   &&   !ok)   {  
stickNum   =   total   /   i;  
memset(used,0,sizeof(used));  
length   =   i;  
match(1);
}  
}
delete   []stick;
                  delete   []used;
stick=0;
used=0;    
}
return   0;  
}  

void   match(int   x)//&AElig;&yen;&Aring;&auml;&micro;&Uacute;X&cedil;ù&sup3;¤°&ocirc;
{
if(x   >   stickNum){
ok   =   1;
cout < <length < <endl;
return;
}
int   i;

for(i   =   1;i   <=   n;++i)
if(!used[i])
break;
used[i]   =   1;
search(x,stick[i],i);
used[i]   =   0;
}

void   search(int   num,int   nowLenth,int   nextStick)
{
if(ok)
return;
if(nowLenth   ==   length){
match(num   +   1);
return;
}
if(nextStick   +   1   >   n)
return;

for   (int   i   =   nextStick   +   1;i   <=   n;i++){
if   (!used[i])  
if(stick[i]   +   nowLenth   <=   length)   {  
used[i]   =   1;  
search(num,nowLenth   +   stick[i],i);  
used[i]   =   0;  
if   (ok)   return;  
if   (stick[i]   ==   length   -   nowLenth)   return;    
}
}
}


[解决办法]
这个程序的错误在于

//memset(used,0,sizeof(used));

应该把它变成
for(int j=0;j <n+1;j++) used[j]=0;

原因: sizeof(used)取的是指针的长度, 也就是4, 所以结果就变成了used第一个元素used[0]变成了0, 其他的还是没有定义. 而程序要用的恰恰是其他的元素.

另外, 这个问题用递归效率是很低的, 所以最好不要用递归, 而且可以不用逐根搜索的办法.

热点排行