递归算法代码.doc

上传人:鲁** 文档编号:543341685 上传时间:2023-03-14 格式:DOC 页数:14 大小:42.51KB
返回 下载 相关 举报
递归算法代码.doc_第1页
第1页 / 共14页
递归算法代码.doc_第2页
第2页 / 共14页
递归算法代码.doc_第3页
第3页 / 共14页
递归算法代码.doc_第4页
第4页 / 共14页
递归算法代码.doc_第5页
第5页 / 共14页
点击查看更多>>
资源描述

《递归算法代码.doc》由会员分享,可在线阅读,更多相关《递归算法代码.doc(14页珍藏版)》请在金锄头文库上搜索。

1、#include #include #include /#include #define N1 100 /物品总种数不是常量,没法根据它来决定数组的长度,只有先定义个长度了int n1;/物品总种数double limitW;/限制的总重量double totV;/全部物品的总价值double maxV;/解的总价值int optN1;/解的选择int copN1;/当前解的选择struct /物品结构double weight;double value;aN1;/参数为物品i,当前选择已经达到的重量和tw,本方案可能达到的总价值void find(int i,double tw,double

2、 tv)int k;/物品i包含在当前方案的可能性if(tw+ai.weight = limitW)copi=1;if(in1-1)find(i+1,tw+ai.weight,tv);elsefor(k=0;kmaxV)if(in1-1)find(i+1,tw,tv-ai.value);elsefor(k=0;kn1;+k)optk=copk;maxV=tv-ai.value;void N()int k,c=0;double w,v;printf(enter the object number:);scanf(%d,&n1);printf(enter each objects weight a

3、nd value:n);for(totV=0.0,k=0;kn1;+k)scanf(%lf %lf,&w,&v);ak.weight = w;ak.value = v;totV += v;printf(enter the limit-weight:);scanf(%lf,&limitW);maxV=0.0;for(k=0;kn1;+k)copk=0;find(0,0.0,totV);printf(the chosed objects number is:n);for(k=0;k%c n,s,t);void hanoi(int n,char a,char b,char c) /*递归函数*/if

4、 (n=1) output(a,c);else hanoi(n-1,a,c,b); /*a借助b到c*/output(a,c); hanoi(n-1,b,a,c); /*b借助a到c*/ void H()int n;printf(输入层数: );scanf(%d,&n);printf(noutput:n);hanoi(n,A,B,C);/*2*/#define N3 50int a3N3;int n3,k3;void init(int aN3,int n)int i;for(i=0;in;)ai+=1;for(;i2*n;)ai+=0;a2*n=a2*n+1=-1;void output(in

5、t aN3,int n)for(int i=0;i2*n+2;i+)if(ai=1)printf(*);if(ai=0)printf(0);if(ai=-1)printf(_);printf(n);void swap(int *a,int *b)int temp;temp=*a;*a=*b;*b=temp;void swap2(int *a,int *b,int *c, int *d)swap(a,c);swap(b,d);void move(int aN3,int n,int m)if(n=4)swap2(&a3,&a4,&a8,&a9);output(a,m);swap2(&a7,&a8,

6、&a3,&a4);output(a,m);swap2(&a1,&a2,&a7,&a8);output(a,m);swap2(&a6,&a7,&a1,&a2);output(a,m);swap2(&a0,&a1,&a6,&a7);output(a,m);k3+=5;return;swap2(&an-1,&an,&a2*n,&a2*n+1);output(a,m);k3+;if(n4)printf(error !);return;/*/swap2(&an-1,&an,&a2*n-2,&a2*n-1);output(a,m);move(a,n-1,m);k3+;void C()printf(ente

7、r the chess number:t);scanf(%d,&n3);init(a3,n3);printf(the starting order:n);output(a3,n3);printf(move as the following:n);k3=0;move(a3,n3,n3);printf(nstep=%dn,k3);/*3*/#define N4 20int s; int listN4;void init_4(int list,int n)for(int i=0;i m) for(i = 0; i = m; i+) printf(%d , listi); printf(n); s+;

8、 else for(i = k; i outn,+c,pos+1);/输出 basepos=0;/踢掉 while(j-k5)if(basepos=(pos+1)%n)j+;/递归点 ,每次数到几这个k5就改到几 make(base,n,pos,c);/递归 void Y() int n,c=0,pos=2;/从N开始数,则把pos改为N-1就行了. printf(enter the total number of people: );scanf(%d,&n);printf(enter the order number: );scanf(%d,&k5); int *base=new intn; for(int i=0;in;i+)basei=1; make(base,n,pos,c); deletebase;/*5*/13

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 生活休闲 > 社会民生

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号