当前位置:
文档之家› 北邮算法与数据结构习题参考标准答案
北邮算法与数据结构习题参考标准答案
}else if( t> weight[k]) Pack( m+1,k+1,t - weight[k] );
}
}
四、判断括号是否配对:
intCorrect( strings )
{
Inistack(Q);
for(i=0;s[i]== ‘=’;i++ )//表达式以‘=’结束
{
switch(s[i] )
=2n–1
所以,梵塔的移动次数为2n–1次。
三、简化的背包问题:
void Pack( intm, int i,int t)//初始值为:11t
{
for (k=i; k<=n;k++)
{
solution[m]=weight[k];
if( t == weight[k])
{
for ( j=1;j<=m;j++) cout<<solution[j];cout<<endl;
{
C=new struct node;C->next=NULL;q=B->next;
While(q)
{
p=A->r= new struct node;r->exp= p->exp+q->exp;
r->inf=p->inf* q->inf;PolyAdd(C,r);
p=p->next;
void Insert (string S, string T, charch)//设块大小为m
{
i=0; p=T;
while ((p->next)&&(!i))
{
for(j=1;j<=m;j++ ) if(p->str[j]==ch) i=j;
if (!i)p=p->next;
}
if (!i)for( j=1;j<=m;j++ )if(p->str[j]==ch)i=j;
}
q=q->next;
}
}
二、梵塔的移动次数:
已知移动次数迭代公式为:M (n)=2M(n-1 ) + 1
初值为:M( 0 )=0
则:M(n)=2(2M(n-2 ) + 1) +1
=4M( n-2 )+3
=8M(n-3 )+ 7
=2iM ( n-i ) + 2i–1
若n=i,则M (n-n)=0,故:M ( n ) =2nM(n-n)+2n–1
if (! i)p->next=S; else//S插在T后
{ //ch所在结点分裂,S插在T中分裂的两结点间
q= newstruct node; q->str=p->str; q->next=p->next;
for(j=i; j<=m; j++)p->str[j]= ‘#’; p->next=S;
}
intEmptyQ ( )
{
if (Empty (S1) &&Empty(S2))return1;return 0;
}
voidEnqueue ( elemtypex)
{
if (Full(S1))if (Empty(S2))while(! Empty (S1))Push(S2,Pop(S1));
if (!Full(S1))Push(S1,x);
return 1;
}
五、堆栈可能的输出:
1234124313241342 14231432
21342143 23142341 24132431
312431423214324134123421
412341324213423143124321
六、用两个堆栈实现一个队列:
intFullQ()
{
if(Full (S1)&&!Empty (S2)) return 1;return0;
for (j=1; j<i; j++ ) q->str[j]= ‘#’;p=S;
while ( p->next )p=p->next;p->next=q;
}
}
九、上三角矩阵的存储:
k=(i-1)*n+j-i*(i-1)/2=(2n-i+1)*i/2+j-n
f1=(2n-i+1)*i/2
f2=j
c=-n
}
elemtype Dequeue( )
{
if (Empty(S2))while(!Empty(S1))Push(S2,Pop(S1));
if (! Empty(S2))returnPop(S2);
}
七、生成新串及字符第一次出现位置:
intIndex ( string S,stringT)
{
for (i=1;i+ Len(T)-1<=Len(S); i++ )
十、循环右移k位:
12345 6 78(n=8, k=3)
if (!Index(T,ch)&& ! Index(R,ch) )
{R=Concat(R, ch);P[j++]=i; }
}
}
八、块链字符串插入:
{为避免字符串内部块间大量的数据移动,最好的方法是定义两种
字符串中不出现的字符作为空标记和串结束标记,如‘#’和‘$’;
也可只使用空标记,串结束以块尾指针为空表示,其算法如下:
{
case‘(’:
case‘[’:
case ‘{’:
Push(Q, s[i]);break;
case‘)’:
case‘]’:
case‘}’:
if( Empty(Q))return0;t=Pop(Q);
if(!Matching( t,s[i]))return 0;
}
}
if(! Empty(Q) ) return0;
作业参考答案
一、(带头结点)多项式乘法C= A×B:
void PolyAdd ( list &C,listR)//R为单个结点
{
p=C;
while((!p->next) &&(p->next->exp>R->exp)) p=p->next;
if ((p->next)||(p->next->exp<R->exp))
ifEqual( Sub ( S,I, Len(T)), T) returni;
return0;
}
voidCreatNewStr (stringS, stringT, stringR, arrant P)
{
R=“”; j=0;
for(i=1;i<=Len(S);i++ )
{
ch=Sub( S, i, 1 );
{R->next=p->next;p->next=R;}else
{p->next->inf +=R->inf;deleteR;
if(!p->next->inf)
{ R=p->next;p->next=R->next;delete R;}
}
}
voidPolyMul(listA, list B,list&C)