资源描述:
《几种常见的算法源代码c语言版》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、几种常见的算法源代码C语言版1.回溯法(背包问题)#includeboolContains(intt,intn,intx[],intweight[],intmaxweight){intcountweight=0;for(inti=1;i<=t;i++){countweight+=x[i]*weight[i];}if(countweight<=maxweight)returntrue;elsereturnfalse;}boolBound(){returntrue;}voidBacktrack(intt,intn,intx[],intweight[],intvalue[],in
2、tmaxweight){if(t>n){intcountvalue=0;for(inti=1;i<=n;i++){countvalue+=x[i]*value[i];printf("%4d",x[i]);}printf("总价值为:%dr",countvalue);}else{for(inti=0;i<=1;i++){x[t]=i;if(Contains(t,n,x,weight,maxweight)&&Bound())Backtrack(t+1,n,x,weight,value,maxweight);第6/6页}}}voidmain(){intn,maxweight,a[50],we
3、ight[50],value[50];printf("请输入物品的总个数:");scanf("%d",&n);printf("r请分别输入%d个物品的重量:r",n);for(inti=1;i<=n;i++){scanf("%d",&weight[i]);}printf("请分别输入%d个物品的价值:r",n);for(intj=1;j<=n;j++){scanf("%d",&value[j]);}printf("请输入背包所能容纳物品的最大重量:");scanf("%d",&maxweight);printf("r");Backtrack(1,n,a,weight,
4、value,maxweight);}1.全排列(未考虑重复元素)#includevoidSwap(int&a,int&b){inttemp;temp=a;a=b;b=temp;}voidPerm(intnum[],intk,intm){if(k==m){for(inti=0;i<=m;i++)printf("%4d",num[i]);printf("");}第6/6页else{for(inti=k;i<=m;i++){Swap(num[k],num[i]);Perm(num,k+1,m);Swap(num[k],num[i]);}}}voidmain(){inta[10
5、0];printf("请输入要进行全排列的个数:r");intn;scanf("%d",&n);for(inti=0;ivoidSwap(int&a,int&b){inttemp;temp=a;a=b;b=temp;}voidPerm(intnum[],intk,intm){if(k==m){for(inti=0;i<=m;i++)printf("%4d",num[i]);printf("r");}els
6、e{第6/6页for(inti=k;i<=m;i++){if(num[i]==num[k]&&i!=k)continue;else{Swap(num[i],num[k]);Perm(num,k+1,m);Swap(num[i],num[k]);}}}}voidmain(){inta[5];intm,n;printf("请输入要进行全排列的数的个数(不能超过5):r");scanf("%d",&m);printf("请输入%d个整数(可重复):r",m);for(inti=0;i7、归实现)#includevoidPrintComposition(intsource[],booltemplete[],intn){for(inti=0;i