注:请注意对应题号,以下内容仅为个人代码,不代表最终答案,仅供参考。
目录
DC05PE04根据给定的递归函数,编写递归算法
int G(int m, int n)
{ // Add your code here
if(m==0 and n>=0) return 0;
if(m<0 or n<0) return -1;
return G(m-1,2*n)+n;
}
DC05PE05根据给定的递归函数F(n)编写递归算法
int F(int n)
{ // Add your code here
if(n<0) return -1;
if(n==0) return n+1;
int res;
res = n*F(n/2);
return res;
}
DC05PE06利用递归算法求解平方根
float Sqrt(float A, float p, float e)
{ // Add your code here
if(pow(p*p-A, 2) < pow(e,2)) return p;
float res=0;
res = Sqrt(A,(p+A/p)/2,e);
return res;
}
DC05PE07请写出Ackerman函数的递归求解算法
int Akm(int m, int n)
{ // Add your code here
if(m<0 or n<0) return -1;
if(m==0) return n+1;
int res;
if(n==0) res = Akm(m-1,1);
else res = Akm(m-1,Akm(m,n-1));
return res;
}
DC05PE15试写出求递归函数F(n)的非递归算法
int F(int n)
{ // Add your code here
if(!n) return 1;
long long res=1;
while(n){
res*=n;
n/=2;
}
return res;
}
DC05PE16试写出求解平方根的非递归算法
#include <math.h>
float Sqrt(float A, float p, float e)
{ // Add your code here
if(pow(p*p-A, 2) < pow(e,2)) return p;
float res=0;
res = Sqrt(A,(p+A/p)/2,e);
return res;
}
DC05PE20将给定点元素同色区域的颜色进行置换
void ChangeColor(GTYPE g, int m, int n, char c, int i0, int j0)
{ // Add your code here
if(i0==0 or j0==0 or m<1 or n<1) return;
char color = g[i0][j0];
int x[4] = {-1,0,1,0};
int y[4] = {0,1,0,-1};
for(int i=0;i<4;i++){
if(((i0+x[i] > 0 and i0+x[i] <= m) and (j0+y[i] > 0 and j0+y[i] <= n)) and g[i0+x[i]][j0+y[i]]==color ) ChangeColor(g,m,n,c,i0+x[i],j0+y[i]);
else g[i0][j0]=c;
}
}
DC05PE26求广义表的长度
int GListLength(GList L)
{ // Add your code here
int res = 0;
while(L){
res++;
L=L->un.ptr.tp;
}
return res; //Temporary code. Modify it if necessary
}
DC05PE30求广义表的深度
int GListDepth(GList ls)
{ // Add your code here
if(!ls) return 1;
if(ls->tag == ATOM) return 0;
int res1,res2;
res1=res2=0;
res1 = GListDepth(ls->un.ptr.hp)+1;
res2 = GListDepth(ls->un.ptr.tp);
return res1>res2 ? res1 : res2;
}
DC05PE32判别两个广义表是否相等
Status Equal(GList A, GList B)
{ // Add your code here
if(!A and !B) return 1;
if(!A or !B) return 0;
if(A->tag == ATOM and B->tag == ATOM and A->un.atom == B->un.atom) return 1;
if(A->tag == LIST and B->tag == LIST) return Equal(A->un.ptr.tp, B->un.ptr.tp) and Equal(A->un.ptr.hp, B->un.ptr.hp);
return 0;
}
DC05PE33输出广义表中所有原子项及其所在的层次
void OutAtom(GList A, int layer, void(*Out2)(char, int))
{ // Add your code here
if(!A) return;
if(A->tag == ATOM) Out2(A->un.atom, layer);
else {
OutAtom(A->un.ptr.hp, layer+1, Out2);
OutAtom(A->un.ptr.tp, layer, Out2);
}
}