算法分析与设计教程(习题答案)_第1页
算法分析与设计教程(习题答案)_第2页
算法分析与设计教程(习题答案)_第3页
算法分析与设计教程(习题答案)_第4页
算法分析与设计教程(习题答案)_第5页
已阅读5页,还剩86页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

算法分析与设计教程解答指计算机执行程序中的某一条语句的执行次数。指某算法的计算时间只能使用指数函数限界的算法。3.解:事前分析是指求出某个算法的一个时间限界函数(它是一些有关参数的函数);事间和占用空间的统计资料。能分{fnreturn1;}tc{fn{bmoveaba}}②f(n)=O(n*logn)(Cn0|T(n)=〈typedefstruct{klagoidNRpostOrderBiTreebStacktypeStack[MAX_TREE_SIZE];BiTreep;topsignifbNULLreturn;top=-1;/*栈顶位置初始化*/p=b;pifp=NULL){/*结点第一次进栈*/toplinkpopflagp=p->lchild;/*找该结点的左孩子*/}p=Stack[top].link;tacktopflagifsign){/*结点第二次进栈*/toplinkpStack[top].flag=2;/*标记第二次出栈*/p=p->lchild;}p=NULL;}}}}nn。idmaxminintAintemaxintlowinthigh{h}h}}midlow+high)/2;maxminA,x1,y1,low,mid);maxminA,x2,y2,mid+1,high);maxxxminxx}}{loatrrrrnewfloatn-1];rnewfloatn-1];rnewfloatn-1];foriini+)riri]=r2[i]=r3[i]=0;roductpqcpolyproductpqrk);polyproductpkqkr1+2*k,k);plusppkrk,k);plusqqkr,k);polyproductrkr,r2+k,k);mins(r2+k,r0,2*k-1);mins(r2+k,r1+2*k,2*k-1);plus(r0+k,r2+k,r0+k,2*k-1);plusrk,r1+2*k,r0+2*k,2*k-1);}}voidproductfloatpfloatq[],floatc[]){pqpqcpp)*(q[0]+q[1])-c[0]-c[2];}voidplusfloatpfloatq[],floatc[],intn){iiniqi}voidminsfloatp,floatq[],intn){iinipipiq[i];}FOI10+2/3*5+15+6+18+3=166/3;Pi,0,1,0);FGI=10+15+4/7*7+18=47;(2)按wi的非降次序列输入时的序列为(1,1,4/5,0,1,1,1);I背包容量为13,有7件物品,它们的容量组成的向量为(1,2,4,5,3,3,7),它们的效益值组成的向量为(6,10,18,14,8,7,7)。ncludeiostreamgnamespacestdconstintN2;oidOutputResultintSelectN{rintiiNi}{intBeginN,8,15,15};intEndN4,15,18,19,20};intSelectN0,0,0};while(i<N){art{ctiimeStartEndi}}utResultSelectresult;}小长度。deiendvoidGreedyJobNodeintintoidmainvoidiceratorintconstreturntimeateineNodeiendvoidGreedyJobNodeintintbliceratorintconstreturnavailatesTypevoidGreedyTypeaintn,intm)rn}nMinHeapMachineNodeH(m);MachineNodex;forintiimiailiHInsertx;}forintiniiHDeleteMinx);coutxID<<“从”<<x.avail<<“到”xavailaitime;HInsertx;}}cludeiostreamincludecstringngnamespacestdvoiddeleteSchar*p){while(*p){p(p+1);p}}{cout:"<<endl;Scout多少个数:N"<<endl;do{coutN数字串的长度"<<endl;whilemmint)strlen(S));while(m>0){while(i<(int)strlen(S)&&(S[i]<=S[i+1]))eSSi}whileS[0]=='0')deleteS(&S[0]);rlenSSendlreturn;}ncludeiostreamncludecmathusingnamespacestd;definemaxn05{blelrublexmaxnymaxnPOINTpointsmaxn];maxnintcompconstvoidaconstvoidb序比较函数*/{POINTaabb;aaPOINTabb=(POINT*)b;/*强制类型转换*/return;return-1;return1;}oidinit初始化*/{orcaniini{安装区域*/{pointsilxi]-sqrt(double(d)*d-y[i]*y[i]);pointsirxi]+sqrt(double(d)*d-y[i]*y[i]);}}}idsolve{eofPOINTcomp*/foriinimki=0;oransiini{mki]=1;/*进行贪心策略选择*/orjijnjifmkjpointsjlpointsire)mkj1;}}{{endl}{endl}}return;x01234f1(x)7d1(x)01234x01234f2(x)d2(x)00or11or21x01234f3(x)d3(x)01222includeiostream>usingnamespacestdconstintMAXN=100;nrMAXNMAXNmMAXNMAXNsMAXNMAXNneyintiintj{n{returnmij;}umij];orkikjk{oneyikmoneykj{mp}}turnu}{while(cin>>n){{mcout<<"Case"<<num<<":"<<endl;iiniorjijnj{ijarij5535;mi[j]=r[i][j];money0,n);coutmoneynendl}}turn}Bjb初始条件为:d(i,0)=i,i=0~m;d(0,j)=j,j=0~n。includecstdioincludeiostreamincludestringusingnamespacestd;tb{returnabb:a;}rppcharccharc{returnc2;return0;}charchangecharc{creturn";return";return0;}charscatconstcharschars2){charscharcallocstrlens)+strlen(s2)+1,sizeof(char));returns;}charctoscharc){charscharcallocsizeof(char));returns;}{arstrregsprintf("请输入括号个数:");nm=(int**)calloc(n+1,sizeof(int*));regschar**)calloc(n+1,sizeof(char**));foriini){m[i]=(int*)calloc(n+1,sizeof(int));regsi(char**)calloc(n+1,sizeof(char*));forjjnj){regsij=(char*)calloc(2*n,sizeof(char));}}hstdincharcallocnsizeofcharprintf("请输入以()和[]组合的括号串:");foriinicstriprintf:%s\n",str);forllnl){foriinl++i){jil1;ntminlwforkikj++k){ifppstristrkminmi1][k-1]+m[k+1][j])){minm[i+1][k-1]+m[k+1][j];w=k;}}w{m[i][j]=min;strcpyregsijscatscatscatctosstriregsi+1][w-1]),ctos(pp(str[istrwregsw[j]));}{strcpyregsijscatchangestriregsi[j]));}}}nreturn0;}–L表示有多少“段”不同的颜色方块jijk,设这“若干段”中最后面的那一段是p(i<=p<j),得分olorjowshopfriendFlowintintint)vatevoidBacktrack(inti);xtf所需的处理时间*/业调度*/优作业调度*/和*/值*//voidFlowshop::Backtrack(inti){forintjjnjbestxjxj;estff}forintjijnj{Mxjfifif1)?f2[i-1]:f1)+M[x[j]][2];fwapxixjBacktracki1);wapxixj}Mxj}}tMintnintbestx{lowshopXXxnewintn];Xfnewintn+1];MMnnestxbestxstfubXf;XfforintiiniXfi,X.x[i]=i;XBacktrack;teXfturnXbestf}orfriendintmColoringintintint);ivateboolOkintk);m//a;boolColor::Ok(intk){orintjjnj/用性*/akjxjxkturnfalseturntrue}voidColor::Backtrack(intt){forintiinii}orintiimiBacktrackt;}}ingintnintminta{orXnmasumrintiinipi;pXBacktrackurnXsum}mpriendintMaxStampintintintvatevoidBacktrackintiintrintn/*邮票面值数*/maxvalueaxintaxlvoidStampBacktrackinti,intr){forintjjxi*(m-1);j++)forintkkmyjk+)yjxiky[j]+k;while(y[r]<maxint)maxvaluer1;forintj=1;j<=n;j++)bestxjxj}lorintkkmaxlkforintjxij=r;j++){jBacktrackir)forintkkmaxlk+)zk}}}mpintnintmintbestx{允许贴的邮票数*/值*//界*/所需最少邮票数*/解*/XnnmmaxvaluemaxintmaxintmaxlmaxlestxbestxXxnewintn1];Xynewintmaxl+1];orintiiniXxi0;orintiimaxliXyimaxint;Xx1;Xy0;XBacktrack);xynXmaxvalue}includeiostream>usingnamespacestdconstintNormalize=9;intNumboolC9];boolL17];boolR17];voidTryinti{forintjjj){ifCjtrueLijNormalizetrueRij)==true){falseijNormalizefalsefalse{ryi}{Num++;coutNum:"<<;orkkk}jtrueLijNormalizetrue;Rijtrue;}}}{Num0;oriiitrueforiiiLiRi=true;ryreturn;}includeiostream>usingnamespacestddefineMAX200defineMAXN20intbMAXN];intcompconstvoidaconstvoidb数*/{returnintb-*(int*)a;}oidNonRecursComput{MAXNboolflag;x[0]=-1;while(lev>=0){法主要程序*/xlevxlev{}{ifcmbxlev&&(cn>0))/*如(cm>=b[x[lev]]≥0,则尝试再用b[x[lev]]*/{evbxlev{Possibleendlrn}vtxlevt}/点位置*/{ak}}}iflev/*回溯到根部又无路可走,则无解*/tImpossibleendlturn}{while(cin>>m>>n>>k){ak{coutCasecnt":"<<endl;foriikiqsortbksizeofintcompnmincnint(cm/b[0]);mpossibleendlnRecursComput}}return;}ludeiostream的个数下界*/usingnamespacestddefineMAXN35structnode/*结点结构*/{nodeNODENODEp[MAXN];/*表示结点数组*/oidinitintm{maxb1<<m)-1/*记有向图的顶点最大数-1*/riimaxbi{pileft1;piright-1;pivisited=-1;ikk)&maxb;ileftkkpirightk}右孩子、无访问标记*/点-左支*//点-右支*/}{boolflagtrue;foriiki){{ak}}turnflag}dCompt{boolflagfalsepvisited=0;}while(true){树*/while(i<=maxb&&p[a[i-1]].left!=-1&&p[a[i-1]].left!=0{aipai-1]].left;pai.visited=0;}值*/子标志*/入右子树的标志*/{rjjmaxbjcoutajm-1)))>>(m-1));/*按字符串输出*/}else/*如个数未满足要求*/{ifpairightpairight0NotEquali-1,p[a[i-1]].right))/*如右子树可行,进入右子树*/{aipai].right;pai].visited=0;}}while(!flag)子的值*/右孩子标志*/进入左子树的标志*/溯*/{while(i>0&&p[a[i-1]].visited==1){a[i]=-1;pai.visited=-1;}树返回*/问标志*/ifpairightpairight!=0right{aipairightpai].visited=0;}}}}{oriini{timpossibleendl{pt}}return0;}值*/子标志*/子树的标志*/ludeiostreamludecstdlibusingnamespacestdt*/使用的情况*/已经找到解*/voidaconstvoidb{returnint*)a-*(int*)b;}idfindintx{ifx/*已经找到目标*/{}foriini+)/*找到第一个未使用过的元素作为下一个集合的第一个元素*/{ak}usedi;Trackxiseti;usedi;/*对于找不到的情况,按原路返回*/}intkintsum{{umrn}多重复判断*/{isumsetiquarter{usediTracknumisunseti);usedi}}}{while(T--){memsetused0,sizeof(used));oriini{seti}{oendl}erqsortsetnsizeofset,cmp);{oendl}sendlcoutnoendl}return;}ludeiostreamudecstringudecstdlibefineH#defineW6#defineJH3#defineJW1usingnamespacestdrtableHWbooliswH[W];ewjJHJWlflag的高度*/的宽度*/宝石的高度*/宝石的宽度*/宝石的状态*/当前格是否为空*/的状态*/downOp{orjjWj{x=H-1;foriHii一遍得到下一个状态(宝石下落后)*/,依次将为空的位置填满*/{tablexjtableij}forixii/*最后为空的赋值为‘W’*/bleijW}}voidsearch/*消去宝石*/{flagtrue/*默认本次操作没有消去宝石*/oriiHijjWj{jjWj{{{ifistepk件,将不符合条件、越界的舍去*/{iftableistepkjstepktablei][j]&&tableistepkjstepk][1]]==table[i][j]){while(i+t*step[k][0]>=0&&tableitstepkjtstepk][1]]==table[i][j])到该方向上的所有能消的宝石*/{sWitstepkjtstepktrue}}}}}}e}{while(T--){iiHi{ei}riiJHi{i}oriHii{{ak}}forihJHihi+)/*将新增的宝石放入容器*/{}while1){ak}iiHi{jjWj{ableij}}}turn}化算法ncludeiostreamcludecstdlibncludectimeusingnamespacestd;{ignedinttimeNULLforkkk+)utfloatrandendlreturn0;}2.解:tn{randomseedxrandomnwhile(i<n){xxx)%n;lidnyxkik}}returnd;}eclassTypeBOOLmajority_monte<TypeA[],Type&x,intn,doublee){BOOLflagFALSE;randomseedforttst{njjnjiak}}turnflag}为O(nlog(1/e))。boolQueen:QueensLV(intstopVegas){omNumberrndwhile((k<=stopVegas)&&(count>0)){forintiini{unti}}returncount;}dnQueenintn{enXnforintiini{pi;}pqlfoundfalsewhile(!X.QueensLV(stop));opforintiinicout<<p[i]<<"";e}rnfound}图论与网络流问题ncludeiostreamusingnamespacestd;defineINF5535nstintMAXN限*/voidinit/*首先输入有向图的信息*/foriini)forjjnj)Fforiiei){labl}}/中无边的元素设为无穷大*/,构造网络矩阵*/ntmaxflowintnintcMAXNintsourceintsinkintflowMAXN流*/{urnINFmemset(flow,0,sizeof(flow));while(1){foriiniprevi与汇点相同,则返回*/可行流*/分量初始化*/previsourcesource;{ifnewccijflowijvivj,flow[i][j]<c[i][j],则给vj(vi,d(vj))*/prevqueqj]=i+1;inewcdinewcfnewcflowjiprevqueq=j]=i-1;jdinewcdinewc}vj列*/Path入调入过程*/flowpreviidsink;ielseflowiprevid[sink];evi}forjiinjflowsourcei+]);/*统计计算从源点发出的流量*/returnj;}{owwhile(cin>>n>>e){nkn边数*/息*/MaxFlow=max_flow(n,g,source,sink,flow);coutMaxFlowendl/*输出最大流*/}return;}cludecstdioludequeueludealgorithmcludemapusingnamespacestd;defineMAX01defineMAXL01defineMAXR01uctedge{intleftrightEdgeedge0000];boolconMAX[MAX];boolyesintusedMAX];CH最大值*/最大值*/的左右点的数目*/阵*/能否形成二部图*/{vateightLrMatchLMAXRolvisitedMAXRindAugmentintreverseintintdinitlicoolbuildvoidMATCHinit){forintiicountlefti+)tchRiforintiicountrighti+)rMatchL[i]=-1;}voidMATCHreverseintleft,intright){MatchLrightleftwhile(prev[left]!=-1){leftrMatchLnextRprevleft;ghtnextR}t}voidMATCHfindAugmentintstart){forintiicountlefti+)prev[i]=-1;forintiicountrighti+)visitedifalse}intQQpushstart;boolfoundfalse;while(!Q.empty()&&!found){popforinttotocountright!found;to++){{itedtotruefrMatchLto{ersefromto}{pushrMatchLtoprevrMatchLtofrom}}}}}h{forintiicountleftientiforintiicountleftiiflMatchRi)max;rnmax}oolMATCHbuild{eftightforintiicountlefti+)forintjjcountrightjmapij]=false;rintiimi{{wv;}mapatw][at[v]]=true;}urntrue}voidmarkintiintside){forintjjnj{sedj{usedj-side;markj,1-side);}usedjside{rn}}}{MATCHmatch;whilescanf("%d%d",&n,&m)!=EOF){forintiini{forintjjnjalseused[i]=-1;}orintiimi{scanfddedgeiwedgeivconedgeiwedgeivconedgei].v][edge[i].w]=true;}eforintiinyesi++)sedi{sedimarki;}{printfNon);}leftright部分点数*/forintiini{t}{tght}printfdn,match.maxMatch());}}ncludeiostreamncludestdiohincludestdlibhusingnamespacestddefineCourse_MAX101defineStudMAX301boolusedStud_MAX];Num课程和学生最大数目*/数、学生数*/XmapidInput{scanfddCourseNumStudNum输入课程数、学生数*/memsetmap,0,sizeof(map));iiCourseNumi{forjjkj{mapix1]=true;}}}boolDFSintt)/生编号*/{{{{}}}nfalse}{orjjTj{moriiCourseNumi{}rintfYESnintfNOn}return;}上ncludeiostreamncludecmathusingnamespacestd;defineMAXN;defineINF000000XNMAXNBoyMAXNMAXNmn{oriimijjnjoyijoriimiforjjnj{gjigirlBoyji;}}intkuhnmunkresintmintnintmatMAXNintmatchintmatch{AXNtMAXNlMAXNpqijkoriinioriimiforliINFjjnj++)limatijlimatijl[i];memsetmatch2,0xff,sizeof(int)*n);foriimi{memsettxffsizeof(t));forppqmatchi0;p++)forkspjjnmatch1[i]<0;j++)lkljmatkjtj{pjp合*/}{Fkkqkjjnjiftjlskljmatskj]<p)plsk]]+l2[j]-mat[s[k]][j];jjnjkkqk}}riimiretmatimatch1[i]];rnret}最优匹配值*/{matchMAXNiwhile(cin>>m){MM=kuhn_munkres(m,n,g,match1,match2);endl}return;}defineMAXN0{intcf/*容量,流量*/}matrixedge[MAXN][MAXN];/*流及容量(邻接矩阵)*/intm,n;/*读入的排水沟(即弧)数目和汇合结点(即顶点)数目*/ints,t;/*源点(结点1)、汇点(结点N)*/sidualMAXNMAXNqeintpreMAXNintvisMAXNmaxflowminaugmentidfindaugmentpath{队列头和尾*/流流量、每次增广时的可改进量*/memsetvis,0,sizeof(vis));ressssmemsetresidual0,sizeof(residual));memsetpre,0,sizeof(pre));whileqs<qe&&pre[t]==0){foriini{{gecuicedgecuif{residualcu][i]=edge[cu][i].c-edge[cu][i].f;icui}eifedgecuif{residual[cu][i]=edge[cu][i].f;icui}}}}}voidaugmentflow{{minaugment0;}while(i!=s){改进量*/广路上可改进量的最小值*/iijlpreii}minaugment=j;}voidupdateflow{rnwhile(i!=s){dgepreiicedgepreiifepreiifminaugmentelseifedgepreiifepreiifminaugment}dsolve{maxflow0;while(1){mentpathtflowmaxflowminaugment;dateflow}}{while(scanf("%d%d",&m,&n)!=EOF){memsetedge0,sizeof(edge));mi{量*//uvcc}printfdnmaxflow);}return;}includecstdioincludevectorincludecassert>includealgorithmusingnamespaces

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论