算法分析复习资料 30页

  • 67.47 KB
  • 2022-07-29 发布

算法分析复习资料

  • 30页
  • 当前文档由用户上传发布,收益归属用户
  1. 1、本文档由用户上传,淘文库整理发布,可阅读全部内容。
  2. 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,请立即联系网站客服。
  3. 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细阅读内容确认后进行付费下载。
  4. 网站客服QQ:403074932
算法分析复习资料一、递归与分治策略1、有重复元素的排列问题#include#include#includeusingnamespacestd;longans;intok(charstr[J,intaJntb){if(b>a)for(inti=a;i#include#include#includeintn;doublev,sv;constdoublepi=3.141592653;constdoubleinf=10000000000.0;doublemin(doublea,doubleb){if(av)v=bv;return;}else{for(inti=();i0)dfs(step+1,bv+(4.0/3.0)*pi*p[i].r*p[i].r*p[i].r);elsedfs(step+l,bv);visLiJ=false;}))intmain(){inti;while(scanf(M%du,&n)!=EOF)//输入点数{scanf(H%d%d%d%d%d%du,&b[O].x,&b[0].y,&b[O].z,&b[l]・x,&b[l].y,&b[1].z);〃输入长方体盒子的左卜-低角坐标和右上顶角坐标sv=fabs(b[O].x-b[l].x)*abs(b[O].y-b[l].y)*abs(b[0_|.z-b山.z);〃求出长方体的体积for(i=0;iusingnamespacestd;intk=l;\nvoidmove(charx,chary){\n4、三分查找#include{intscarch(inta[],intx,intn);〃函数申明intleft=();voidmain()intright=n-l;while(left<=right){//主函数{intintmid=(left+right)/3+left;a[26]={(),1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1intmidmid=end-(mid+right)/3;6,17,18,19,20,21,22,23,24,25};〃定义并初if(x==b[mid])始化待查找数组returnmid;inty,n=26;if(x>b[midj)cout«n0,1,2,3,4,5,6,7,&9,10,11,12,13,14left二mid+1;,15,16,17,1&19,20,21,22,23,24,25n«endl;elsecout«"请输入要查找的数:\n"«endl;right=mid-l;cin»y;if(x==b[midniid])inttemp=search(a,y,n);returnmidmid;cout«°您杏找的数是第”vv(cmp+1«nif(x>b[midmidj)个数\n”;left=midmid+l;}elseright=midmid-l;iintsearch(intb[l,intx,intn)/return-1;}5、棋盘覆盖#includesize)#include{usingnamespacestd;if(size==1)inta[1024][1024],tilc;return;voidcheesBoard(intsr,intsc,intdr,intde,intints,t,flag;//必须把全局变量tile赋值给局部变量tcout«n第M«k«H步:n«x«n-一>H«y«endl;k++;}voidhanoi(intn,charone,chartwo,charthree){if(n==l)move(one,three);else{hanoi(n-l,one,three,two);move(one,three);hanoi(n-l,two,one,three);}}intmain()intn;cout«"汉诺塔问题n«endl«endl;cout«"请输入盘了的个数:“;cin»n;cout«cndl;cout«Mu«n«H个盘子的移动顺序为:H«endl«endl;hanoi(n;A,;B,;C,);return0;)\ns=size/2;if(dr二sc+s)〃右上flag=2;elseif(dr>=sr+s&&dcvsc+s)〃左下flag=3;elseflag=4;t=flag;if(dr=sc+s)〃右上cheesBoard(sr,sc+s,dr,de,s);else{a[sr+s-l][sc+s]=t;cheesBoard(sr,sc+s,sr+s-1,sc+s,s);}if(dr>=sr+s&&dc=sr+s&&dc>=sc+s)//右卜cheesBoard(sr+s,sc+s,dr,de,s);else{a[sr+s][sc+s]=t;cheesBoard(sr+s,sc+s,sr+s,sc+s,s);}}voidprint(intk){inti,j;for(i=0;ik){cout«"你输入位置超出范围,请重新输入:\nH;cin»dr;}while(dc<1IIde>k){coutvv”你输入位迸超出范围,请重新输入:W;cin»dc;}cheesBoard(0,0,dr-1,dc-1,k);a[dr-lj[dc-lj=0;print(k);[return();}\ni=lowj=m+l,p=0;*R1;6、划分为根号n的归并排序#include#include//#includetypedefintRecType;/*将两个有序的子文件R[low..m)和R[m+l..high]归并成一个有序的子文件R[low..high]*/voidMerge(RecType*R,intlow,intm,inthigh){int〃置初始值RecType//Rl是局部向量R1=(RecType*)malloc((high-low+1)*sizcof(RccTypc));if(!Rl)return;//申请空间失败while(i<=m&&j<=high)〃两子文件非空吋取其小者输出到Rl[p]I:R1[p++]=(R[i]v二R[j])?R[i++]:R[j++];while(i<=m)〃若第1个子文件非空,则复制剩余记录到R1中Rl[p++]=R[i++];while(j<=high)〃若第2个了文件非空,则复制剩余记录到R1屮Rl[p++]二R[j++];fbr(p=0,i=low;i<=high;p++,i++)RLiJ=RlLpJ;〃归并完成后将结果复制回R[low..high]/*用分治法对R[low..high]进行二路归并排序*/voidMergeSort(RecTypeR[J,intlow,inthigh){Intmid;if(lowusingnamespacestd;constintSIZE=100;inta[SIZE][SIZEJ;voidcopy(intn);//n/2为偶数复制voidtournament(intn);〃求解函数intodd(intn);〃判断奇偶性voidmakecopy(intn);//makecopy区分n/2为奇数或偶数的情形voidcopyodd(intn);//实现n/2为奇数时的复制voidmain(){intn;inti,j;cout«n请输入参赛选手人数:”;cin»n;\ntournament(n);〃求解cout«-经过计算后的结果是(第一列为选手号):\n";严区分n的奇偶性的打印方法*/if(odd(n)==l)//如果n为奇数{for(i=1;i<=n;i++){for(j=1;j<=n+1;j++)if(a[i][j]==n+l){a[i]U]=O;printf(”%3dn,a[i]|j]);}elseprintf(”%3dn,a[i]U]);cout«endl;}}else{for(i=1;i<=n;i++){for(j=1;j<=n;j++)printf(”%3da[i][j]);cout«endl;}}system("pauseH);}/*求解函数*/voidtournament(intn){if(n==1){ari][l]=1;return;}if(odd(n)==l)//如果n为奇数,加1后调用递归调用自身{tournament(n+l);return;}tournament(n/2);〃如果n为偶数,进行二分后递归调用自身makecopy(n);//makecopy与copy算法类似,但是区分了n/2为奇数或偶数的情形}/*判断n的奇偶性*/intodd(intn){if(n%2==l)return1;elsereturn0;/*makccopy与copy算法类似,但是要区分n/2为奇数或偶数的悄形*/voidmakecopy(intn){if(n/2>1&&odd(n/2)==l)copyodd(n);elsecopy(n);)/*实现n/2为奇数时的复制*/voidcopyodd(intn){intblSIZEJ;〃再定义一个一维数组,存放后续需要的数intm=n/2;for(inti=1;i<=m;i++){b[i]=i+m;b[i+mj=b[ij;}for(i=1;i<=m;i++){for(intj=1;jv=m+1;j++){if(a[i][j]>m){a[i]UJ=b[i];a[i+m][j]=(b[i]+m)%n;}elsea[i+m][j]=alij[j]+m;〃左下角等于左上角+n/2}for(j=2;j<=m;j++){aliJlm+j]=b[i+j-lj;//I号选手的后m-1天比赛a[b[i+j-l]][m+j]=i;〃他的对手后m-1天的安排}}}/*实现n/2为偶数时的复制引voidcopy(intn){intm=n/2;for(inti=1;i<=m;i++)for(intj=1;jv=m;j++)8、马的hamiltion周游路线问题#includeinttravel(intx,inty);intboard[8][8]={0};intmain(void){intstartx,starty;\ninti,j;printf(”输入起始点:”);scanf(H%d%d",&startx,&starty);if(travel(startx,starty)){printf(”游历完成!\nu);}else{printfC*游历失败!\nu);}for(i=0;i<8;i++){forO=0;j<&j++){printf(”%2d“,board[i][j]);}putchar(、n');}return();}inttravel(intx,inty){//对应骑士可走的八个方向intktmove1[8]={-2,-1,1,2,2,1,-1,-2};intktmove2[8]={1,2,2,1,-1,-2,-2,-1};//测试下一步的出路intncxti[8]={0};intnextj[8]={0};//记录出路的个数intexists[8]={0};inti,j,k,m,1;inttmpi,tmpj;intcount,min,tmp;i=x;j=y;board[i][j]=1;for(m=2;m<=64;m++){for(l=0;1<8;1++)exists[l]=0;l=0;〃试探八个方向for(k=0;kv&k++){tmpi=i+ktmovelfk];tmpj=j+ktmovc2[k];//如果是边界了,不可走if(tmpi<0IItmpj<0IItmpi>7IItmpj>7)continue;〃如果这个方向可走,记录下來if(board[tmpiJLtmpjJ==0){nexti[l]=tmpi;nextj[l]=tmpj;〃町走的方向加一个1卄;}}count=1;〃如果可走的方向为0个,返回if(count==0){return();}elseif(count==1){//只有一个可走的方向//所以直接是最少出路的方向min=0;}else{//找出下一个位置的出路数for(l=0;17IItmpj>7){continue;}if(board[tmpi]ltmpjj==0)exists[l]++;}tmp=existsfO];min=0;//从可走的方向中寻找授少出路的方向for(l=1;1cout«"X序列的长度:"«lx«endl;#includeusingnamespacestd;ly=strlen(Y+l);#defineN20cout«"Y序列的长度:"«ly«endl;voidLCSLength(intm.intn.charx[N+l],charLCSLength(lx,ly,X,Y,B);y[N+l],charb[N+l][N+l]);LCS(Ix,ly,X,B);}voidLCS(inti,intj,charx[N+l],charvoidLCSLength(intm.intn.charx[]5charbLN+lJLN+lJ);y[],charb[N+l][N+l]){voidmain()intij,s,t;{intc[N+l][N+l];intlxjy;for(i=0;i<=m;i++)charX[N+l],Y[N+l];c[i][0]=0;charB[N+l][N+l];for(i=0;i<=n;i++)cout«"请输入X序列:n«endl;c[OJ[iJ=O;cin»X+l;for(i=l;i<=m;i++)cout«"请输入Y序列:"«endl;for(j=l;j<=n;j++){cin»Y+l;if(x[i]==y[j]){lx=strlen(X+l);c[i][j]=c[i-IJU-l]+l;\nb[i][j]=A;}voidLCS(inti.intj.charx[],charelseif(c[i-l]U]>=c[i]U-l]){b[N+l][N+l]){c[i]U>c[i-l]UJ;if(i==0IIj==0)b[i]U]=U*;}return;else{if(bmuj==w){c[i][j]=c[i][j-l];LCS(i-l,j-l,x,b);b[i]U]=L';}}printf(”%c”,x[i]);for(s=0;s<=m;s++){}for(t=O;t<=n;t++)elseif(b[i]|j]=='U,)printf(M%dn,c[s][t]);LCS(i・l,j,x,b);printf(u\nM);}elseprintf("length=%d\n",c[m][n]);}LCS(i,j・l,x,b);}3、最大字段和#includecoutvv“整数序列的最大子段和是:usingnamespacestd;H«sum«cndl;}voidMaxSum(intn,inta[]){voidmain(){intsum=0;intn,a[100Jjnjnaxsum;intb=0;cout«**请输入報数序列的元素个数for(inti=l;i<=n;i++)n:u«endl;{if(b>0)cin»n;b+=a[i];cout«H请输入各元素的值(一共else”vvnvv”个):”vvendl;b=alij;fbr(m=1;m<=n;m++)if(b>sum)cin»a[m];sum=b;}MaxSum(n,a);}4、0・1背包问题(回溯和分支限界)#includevoidBackTrack(intdepth){#includeif(dcpth>=m_num)〃达到最大深度{usingnamespacestd;if(bcstValucm_p;//N个背包的价格return;}vcctormw://N个背包的Si'S*if(currcntWcight+m_w[dcpth]<=m_c)〃是intm_c;〃背包的容量否满足约束条件{intm_num;//物品的件数currentWeight+=m_w[depth];intbestValue;〃背包最大价值currentValue+=m_p[depthj;intcurrentvalue;〃当前背包中物品〃选取了第i件物品的价值BackTrack(depth+1);〃递归求解下一intcurrentweight;〃当前背包中物品个结点的重量〃恢复背包的容量和价值private:currentWeight-=m_w[depthj;\ncurrentValue-=m_pfdepthl;〃不取第i件物品BackTrack(depth+l);}public:〃构造函数PackBackTrack();PackBackTrack(vector&p,vectoYint>&w,intcjntn):m_p(p),m_w(w),m_c(c),m_num(n){bestValue=0;currentValue=0;currentWeight=0;)〃获取背包内物品的最人值intGetBestValue(){BackTrack(O);returnbestValue;}};intmain(void){〃测试程序intn;coutvv%青输入物品的件数”vvcndl;cin»n;cout«”请输入背包的容量”vvendl;cin»c;vcctorw(n);vectorp(n);cout«”请输入物品的重量«endl;for(inti=();icin»a[ij;}usingnamespacestd;returnn;}#defineN50intmain(){intimport(inta[]){intn;intn;inta[N];cout«”请输入加汕站数:";n=import(a);cin»n;cout«n«endl;cout«”请依次输入该道路上两加油for(inti=0;i<=n;i++){站之间的距离:”;cout«a[i];}a[0]=0;return0;}for(inti=1;i<=n;i++){6、故优二义搜索树#include#include#definemax9999voidOptimalBST(int,float*,float**,int**);voidOptimalBSTPrint(int,int,int**);voidmain(){int[num;FILE*point;〃所有数据均从2.txt中获取,2.txt中第一个数据表示节点个数;从第二个数据开始表示各个节点的概率point=fopen("2.txt","r");if(point==NULL){printf(ucannotopen2.txt.\n");exit(-l);}fscanf(point,"%d",&num);\nprintf("%d\ii",num);Float*p=(float*)malloc(sizeof(float)*(num+1));for(i=1;i请输入文本文件:\n”);//gctchar();i=0;while(IsContinue){c=getchar();if(c!=10){s[i]二c;〃存储输入的文本i++;tcmp[c]++;FilcLcngth++;}elseif(c==10){printf("->是否继续输入?(Y(y)/N(n))\nu);fflush(stdin);scanf("%c'\&IsContinue);if(IsContinue==,Y,IIIsContinue==ryr){IsContinuc=1;brcak;)elseif(IsContinue==,N,IIIsContinue==n'){IsContinue=1;break;}else{printf(u->请重新输入:\n”);}}}for(i=0,j=0;i<256;i++){if(templi]!=0){str[jl=i;cnt[jl=temp[il;j++;}}printf("->完成输入。\n“);CodeLength=strlen(str);//计算输入文本的长度;TreeLength=(2*CodeLength-1);〃计算岀赫夫曼树的长度//printf("Codclcngthis%d\nu,CodeLength);//?//printf("Treelengthis%d\n",TreeLength);//?return0;};〃统计字符串中字符的种类以及各类字符的个数的算法voidSelect(HuffmanTreeHT,int*sl,int*s2){〃函数功能:选择出str中权重最小的两个节点存入sl,s2;???????????????!!!!!!!!!!!!!!!!!!!youbug!!!!inti,j;//printf("进入Select()\n");//printf("每一次选择前的sl=%d,s2=%d\n",*sl,*s2);for(i=l;i<=CurTreelength;i++){\nif(HT[il.parent==O){(*sl)=i;brcak;}}for(i=1;i<=CurTreelength;i++){if((HT[iJ.parent==O)&&HT[i].weighti)){(*s2)=j;break;}}for(j=(i+1);j<=CurTreelength;j++){if((HT[jJ.parent==O)&&HTLj].weight输入的节点数要大于1,请重新输入\n”);return;}for(i=1;i<=CodeLength;i++){//printfC'cnt[i-l]is:%d\nM,cntli-lJ);HT[iJ.weight=cntli-l];HT[i].parent=();HT[i].lchild=O;HT[i].rchild=O;)for(i=CodeLength+1;iv=TreeLength;i++){HT[iJ.weight=O;HT[i].parent=();HT[i].lchild=O;HT[i].rchild=O;)〃打印输出初始化数组/*for(i=1;i=O;j-,k++){HC[i].bits[k]=code[j];//printf("code[jj:%d\t",code[jj);printf(“HC[i].bits[k]:%d\t”,HC[i].bits[k]))}〃fo「结朿}voidHuffmanEnCoding(HuffmanTreeHT,HuffmanCodeHC){inti,j=0;system("CLS");printfC'Function1:HuffmanEnCoding\nn);printfC*\n“);〃输入文本并且分类计数Jsq(cnt,str);systcm(nclsM);printf(MFunction1:HuffmanEnCoding\nn);printfC*\nH);〃输出输入的文木。printf("->您输入的文本为:%s\n”,s);printf(H->您输入的字符有:\n“);printf(nstr\tcnt\nH);for(i=();i有事启奏,无事按0:\nM);fflush(stdin);c=getchar();getchar();switch(c){casc(‘r):HuffmanEnCoding(HT,HC);brcakcase('2'):HuffmanDeCoding(HT,HC);breakcase(f0f):exit(0);default:printf(MPleaseinput1,2orO.\nH);}}return0;}2、最小生成树#includedl.hHtypedefintVRType;typcdcfcharInfoTypc;#defineMAX.NAME3/*顶点字符串的最大长度+1*/#defineMAX_INFO20/*相关信息字符串的最大长度+1*/typcdcfcharVcrtcxTypc[MAX_NAME];#include"c7-l.h"#include"bo7-l.c"typedefstruct{/*记录从顶点集U到v・u的代价最小的边的辅助数组定义*/VertexTypeadjvex;VRTypelowcost;}minside[MAX_VERTEX_NUM];\nintminimum(minsideSZ,MGraphG){/*求SZ.lowcost的最小正值,并返回其在SZ中的序号*/inti=0,j,k,min;while(!SZ[iJ.lowcost)i++;min=SZ[i].lowcost;/*第一个不为0的值*/k=i;for(j=i+l;jvG.vexnum;j++)if(SZ[jJ.lowcost>0&&min>SZ[jJ.lowcost)/*找到新的大于0的最小值*/{min=SZ[j].lowcost;k=j;}returnk;}voidMiniSpanTrcc_PRIM(MGraphG,VertexTypeu){/*用普里姆算法从第u个顶点出发构造网G的最小生成树T,输出T的各条边*/inti,j,k;minsideclosedge;k=LocatcVcx(G,u);/*cl.h(程序名)*/#include#include#include/*malloc()等*/#include/*INT_MAX等*/#include/*EOF(=AZ或F6),NULL*/#include/*atoi()*/#includc/*cof()*/#include/*floor(),ceil(),abs()*//*c7-l.h图的数组(邻接矩阵)存储表示*/#dcfincINFINITYINT.MAX/*用整型垠大值代替8*/#defineMAX_VERTEX_NUM26/*最大顶点个数*/typedefcnum{DG,DN,UDG,UDN}GraphKind;/*{冇向图,有向网,无向图,无向网}*/typedefstruct)VRTypeadj;/*顶点关系类型。对无权for(j=0;j/*exit()*//*函数结果状态代码*/#defineTRUE1#dcfincFALSE0#defineOK1#defineERROR0#defineINFEASIBLE-1typedefintStatus;typedefintBoolean;-*图,用1(是)或0(否)表示相邻否;对带权图,则为权值*/InfoType*info;/*该弧和关信息的指针(可无)*/)ArcCell,AdjMatrixLMAX_VERTEX_NUM1[MAX_VERTEX_NUM];/*二维数纟R*/typedefstruct{VertexTypevexs[MAX_VERTEX_NUM];/*顶点向量*/AdjMatrixarcs;/*邻接矩阵*/intvcxnum,arcnum;/*图的当前顶点数和弧数*/GraphKindkind;/*图的种类标志*/\n/*7.2、算法7.4〜7.6*/intLocateVex(MGraphG,VertexTypeu){/*初始条件:图G存在,u和G中顶点有相同特征*/inti;for(i=0;i=G.vcxnumllv<0)exit(ERROR);return&G.vexs[v];\nStatusPutVex(MGraph*QVertexTypev,VertexTypevalue){/*初始条件:图G存在,v是G屮某个顶点。操作结果:对v赋新值value*/intk;k=LocateVex(*Gv);/*k为顶点v在图G中的序号*/if(k<0)returnERROR;strcpy((*G).vcxs[k],value);returnOK;}intFirstAdjVex(MGraphG,VertexTypev){/*初始条件:图G存在,v是G中某个顶点*//*操作结果:返回v的第一个邻接顶点的序号。若顶点在G中没有邻接顶点,则返回・1*/inti,j=O,k;k=LocatcVcx(G,v);/*k为顶点v在图G中的序号*/if(Gkind%2)/*网*/j=lNFIN!TY;for(i=0;i,若G是无向的,则还增添对称弧*/int订,vl,wl;charslMAXJNFOJ;vl=LocatcVcx(*G,v);/*尾*/wl=LocateVex(*G,w);/*头*/if(vl<0llwl<0)retumERROR;(*G).arcnum++;/*弧或边数加1*/if((*G).kind%2)/*网*/{printf(”请输入此弧或边的权值:“);scanf("%d",&(*G).arcs[v1][w1].adj);)else/*图*/(*G).arcs[vl]fwl].adj=l;printf("是否有该弧或边的相关信息(0:无1:有):”);scanf(“%d%*c”,&i);if(i){printfC请输入该弧或边的相关信息(<%d个字符):“,MAX_1NFO);gets(s);l=strlen(s);if(l){(*G).arcs[vl][wl].info=(char*)malloc((l+l)*sizeof(char));strcpy((*G).arcs[vl][w1].info^s);}}if((*G).kind>l)/*无向*/{(*G).arcs[w1][v1].adj=(*G).arcs[v1][wlJ.adj;(*G).arcs[wl][vlJ.info=(*G).arcs[v1][wlj.info;/*指向同一个相关信息*/}returnOK;}StatusDeleteArc(MGraph*G,VertexTypev,VertexTypew){/*初始条件:图G存在,v和w是G屮两个顶点*//*操作结果:在G中删除弧,若G是无向的,则还删除对称弧vw,v>*/intvl,wl,j=0;if((*G).kind%2)/*网*/j=INFINITY;vl=LocateVex(*G,v);/*尾*/wl二LocateVex(*Gw);/*头*/if(vl<0llwl<0)/*vl>wl的值不合法*/returnERROR;(*G).arcs[vl][wl].adj=j;if((*G).arcs[vl][wl].info){free((*G).arcs[vl][wl].info);(*G).arcs[vl][wl].info=NULL;}if((*G).kind>=2){(*G).arcs[wl][vl].adj=j;(*G).arcs[w1][v1].info=NULL;}(*G).arcnum—;returnOK;}BooleanvisitedlMAX_VERTEX_NUMJ;/*访问标志数组(全局量)*/void(*VisitFunc)(VertexType);/*函数变量*/voidDFS(MGraphG,intv){/*从第V个顶点出发递归地深度优先遍\n历图G。算法7.5*/intw;visited[v]=TRUE;/*设置访问标志为TRUE(已访问)*/VisitFunc(Gvexs[v]);/*访问第v个顶点*/for(w=FirstAdjVex(G,G.vexs[v]);w>=O;w=NextAdjVex(G,G.vexs[vj,Gvexs[w]))if(!visited[w])DFS(G,w);/*对v的尚未访问的序号为w的邻接顶点递归调用DFS*/}voidDFSTraverse(MGraphG,void(*Visit)(VertexType)){严初始条件:图G存在,Visit是顶点的应用函数。算法7.4*//*操作结果:从笫1个顶点起,深度优先遍历图G,并对每个顶点调用函数Visit一次且仅一次*/intv;VisitFunc=Visit;/*便用全局变量VisitFunc,使DFS不必设函数指针参数*/for(v=O;v=();w=NextAdjVcx(GG.vcxs[u],G.vcxs[w]))if(!visited[wj)/*w为u的尚未访问的邻接顶点的序号*/{visitedfw]=TRUE;Visit(G.vexs[w]);EnQueue(&Q,w);}))printf(n\nM);)voidDisplay(MGraphG){/*输出邻接矩阵存储表示的图G*/inti,j;chars[7J;switch(G.kind){caseDG:strcpy(s,"有向图”);break;caseDN:strcpy(s,"有向网”);break;caseUDG:strcpy(s,"无向图”);break;caseUDN:strcpy(s,"无向网”);printf("%d个顶点%d条边或弧的%s。顶点依次是:",G.vexnum,G.arcnum,s);for(i=0;ihalf)&&((*((+1)/2・half=n*(n+l)/2;counter>half))return;inti=0;if(t>n){〃符号填充完毕if(half%2==0)sum++;{〃总数须为偶数,若为奇数则无解cout«”第“«sum«”个:\n”;half/=2;for(i=l;i<=n;i++){p=newuchar*[n+l];for(j=l;j=2时,deletedp;}可以运算出下面行的某些符号,j可代表行cout«u\n总共”vvsum«"个解”vv号{endl;Plj][t-j+l]=pU-l][t-j+l]Ap[j-l][t-j+2];return0;}counter+=p[j][t-j+l];}2、n皇后问题#includeHiostreamHif(abs(k-j)==abs(x[j]-x[k])ll(x[j]==x[k]))usingnamespacestd;returnfalse;}boolPlace(intk);returntrue;)voidBacktrack(intt);voidBacktrack(intt){intn,〃皇后个数if(t>n)sum++;*x;〃当前解Elsefor(inti=1;i<=n;i++){longsum;//已经找到可行解的个数x[t]=i;boolPlace(intk){if(Place(t))Backtrack(t+1);})for(intj=1;jusingnamespacestd;classStamp{friendintMaxStamp(intJnt,int[]);private:intBound(inti);voidBacktrack(inti.intr);intn;〃邮票而值数intm;〃每张信封最多允许贴的邮票数intniaxvalue;//当前最优值intmaxint;//大整数intmaxi;//邮资上界int*x;〃当前解int*y;〃贴出各种邮资所需最少邮票数int*bestx;//当前最优解};voidStamp::Backtrack(inti.intr){for(intj=0;j<=x[i-2]*(m-1);j++)if(y[j]n){if(r-l>maxvalue){maxvaluc=r-l;for(intj=1;j<=n;j++)bestx[j]=x[j];}return;}int*z=newint[maxl+l];for(intk=l;k<=maxl;k++)z[k]=y[k];for(j=x[i-l]+1;j<=r;j++){x[i]=j;Backtrack(i+l,r);for(intk=l;k<=maxl;k++)y[k]=z[k];}delete[]z;}intMaxStamp(intnjntmjntbestx[]){p[i]=();x=p;Backtrack(l);delete[]p;coutvv”一共有”«sum«H个解u«endl;return0;}StampX;intmaxint=32767;intmaxl=1500;X.n=n;X.m=m;X.maxvaluc=0;X.maxint=maxint;X.maxl=maxl;X.bestx=bestx;X.x=newint[n+1];X.y=ncwint[maxl+1];for(inti=0;i<=n;i++)X.xLiJ=O;for(i=l;i<=maxl;i++)X.y[i]=maxint;X.x[l]=l;X.y[0]=0;X.Backtrack(2,l);cout«n当前最优解:“;for(i=l;i<=n;i++)cout«bcstx[i]«Mu;cout«endl;deleteLJX.x;delete[]X.y;returnX.maxvalue;}voidmain(){int*bestx;intn;intm;cout«Hin输入邮票而值数:";cin»n;cout«"请输入每张信封最多允许贴的邮票数:”;cin»m;bestx=newint[n+1J;for(inti=l;iv二n;i++)bestxfi]=0;cout«"最大邮资:M«MaxStamp(n,m,bestx)«endl;}\n第26页\n1、哈希查找#includeHcl.hn#defineNULL_KEY0#defineN1()/*数据元素个数*/typedefintKeyType;typedefstruct}KcyTypckey;intord;JElemType;/*数据元素类型*/#includenc9-7.hn#includeHc9-6.hH#includcHbo9-7.cnvoidprint(intp,ElemTyper){printf("address=%d(%d,%d)\nu,p,r.key,r.ord);}voidmain(){ElcmTypcr[N]二{{17,1},{6O,2},{29,3},{3&4},{1,5},{2,6},{3,7},{4,8},{60,9},{13,10}};HashTableh;inti,p;Statusj;KeyTypek;InitHashTable(&h);for(i=0;i#include#include/*malloc()等*/#include/*1NT_MAX等*/#include/*EOF(=AZ或F6),NULL*/#include/*atoi()*/#includc/*cof()*/#include/*floor(),ceil(),abs()*/#include/*exit()*//*函数结果状态代码*/#defineTRUE1#dcfincFALSE0#defineOK1#defineERROR0#defineINFEASIBLE-1/*#defineOVERFLOW-2因为在math.h中已定义OVERFLOW的值为3,故去掉此行*/typedefintStatus;/*Status是函数的类型,其值是函数结果状态代码,如OK等*/typedefintBoolean;/*Boolean是布尔类型,其值是TRUE或FALSE*//*c9-6.h开放定址哈希表的存储结构*/inthashsize[]={11,19,29,37};/*哈希表容量递增表,一个合适的素数序列*/intm=0;/*哈希表表长,全局变量*/typedefstruct}ElemType*elem;/*数据元素存储基址,动态分配数组*/intcount;/*当前数据元素个数*/intsizeindex;/*hashsize[sizeindex]为当\n前容量*/JHashTable;#defineSUCCESS1#defineUNSUCCESS0#dcfincDUPLICATE-1/*c9-7.h对两个数值型关键字的比较约定为如F的宏定义*/#defineEQ(a,b)((a)==(b))#defineLT(a,b)((a)<(b))#dcfincLQ(a,b)((a)<=(b))/*bo9-7.c哈希函数的棊木操作,包括算法9.17、9.18*/voidInitHashTable(HashTable*H){/*操作结果:构造一个空的哈希表*/inti;(*H).count=0;/*当前元素个数为0*/(*H).sizeindex=O;/*初始存储容量为hashsize[O]*/m二hashsize[0];(*H).clem=(ElemType*)malloc(m*sizeof(ElemType));if(!(*H).elem)exit(OVERFLOW);//存储分配失败for(i=0;ikey!=NULL_KEY)/*该单元有数据*/*p++=*((*H).elem+i);(*H).count=0;(*H).sizeindex++;/*增人存储容量*/m=hashsizef(*H).sizeindex];\np=(ElemType*)realloc((*H).elem,m*sizeof(ElemType));if(!p)exit(OVERFLOW);/*存储分配失败*/(*H).elem=p;for(i=0;i