#include<cstdio> #include<string.h> int citynum,edgenum;//点数和边数 int map_[20][20]; int bestpath[20]; int themost_liubi_path[20]; int themost_xiao_cost=0; int maxnum=9999999; int nowbestcost=maxnum; void wodeswap(int &a,int &b){ //printf("交换前:a的的值%d\t b的值%d\n",a,b); int temp; temp=a^b; a=temp^a; b=temp^b; // printf("a的的值%d\t b的值%d\n",a,b); } void dfs(int i,int currentcost){ if(i==citynum){ // printf("bestpath[最后一个数是]:%d\n",bestpath[citynum]); /* if((map_[i-1][bestpath[citynum]]!=-1)) { printf("第一个条件满足\n"); } if(map_[bestpath[citynum]][1]!=-1){ printf("第二个条件满足\n"); }*/ if(map_[bestpath[i-1]][bestpath[citynum]]!=-1&&map_[bestpath[citynum]][1]!=-1&¤tcost+map_[bestpath[i-1]][bestpath[citynum]]+map_[bestpath[citynum]][1]<nowbestcost){ nowbestcost=currentcost+map_[bestpath[i-1]][bestpath[citynum]]+map_[bestpath[citynum]][1]; // printf("%d\t%d\n",map_[bestpath[i-1]][bestpath[citynum]],map_[bestpath[citynum]][1]); // printf("加上最后两段前的最小花费:%d\n",currentcost); // printf("最小花费:%d\n",nowbestcost); // printf("完成一个次解:这个解的结果是:%d\n",nowbestcost); for(int p=1;p<=citynum;++p){ themost_liubi_path[p]=bestpath[p]; // printf("%d\t",bestpath[p]); } // printf("\n"); } } else{ // printf("这是第%d步\n",i); for(int k=i;k<=citynum;++k){//遍历剩下的城市 // printf("这是第%d步",i);printf("参与循环的城市%d\n",bestpath[k]); // printf("bestpath2的值%d\n",bestpath[2]); // printf("第一个条件的值:%d",map_[bestpath[i-1]][k]); // printf("bestpath[i-1]=%d\tk=%d\n",bestpath[i-1],k); if((map_[bestpath[i-1]][bestpath[k]]!=-1)&&(currentcost+map_[bestpath[i-1]][bestpath[k]])<nowbestcost){ // printf("这是第%d步",i);printf("能进来的k变量%d\n",k); // printf("交换前的两个值%d\t%d \t i的值:%d \tk的值:%d\n",bestpath[i],bestpath[k],i,k); wodeswap(bestpath[i],bestpath[k]); // printf("交换完了之后:bestpath[3]的值%d\n",bestpath[3]); currentcost=currentcost+map_[bestpath[i-1]][bestpath[i]]; dfs(i+1,currentcost); // printf("laile la ma\n"); currentcost=currentcost-map_[bestpath[i-1]][bestpath[i]]; wodeswap(bestpath[i],bestpath[k]); } // printf("这是第%d步",i);printf("走完if之后的变量k:%d\n",k); } } } int main (){ /* int a=50; wodeswap(a,a); printf("huan:%d %d\n",a,a); return 0;*/ int casenum; scanf("%d",&casenum); for(int i=1;i<=casenum;++i){ memset(map_,-1,sizeof(map_)); nowbestcost=maxnum; scanf("%d%d",&citynum,&edgenum); int rows,cols; for(int j=1;j<=edgenum;++j){ scanf("%d%d",&rows,&cols); scanf("%d",&map_[rows][cols]); map_[cols][rows]=map_[rows][cols]; } /*for(int op=1;op<=citynum;++op){ for(int op2=1;op2<=citynum;++op2){ printf("%d ",map_[op][op2]); } puts(""); }*/ for(int j=0;j<=citynum;++j){ bestpath[j]=j; } nowbestcost=maxnum; int currentcost; dfs(2,0); if(nowbestcost==maxnum){ printf("Case %d: -1\n",i); } else{ printf("Case %d: %d\n",i,nowbestcost); } /* printf("路线:"); for(int k=1;k<=citynum;++k){ printf("\t%d",themost_liubi_path[k]); }*/ } }
lvxingshang_wenti
猜你喜欢
转载自www.cnblogs.com/waibizi/p/12070222.html
今日推荐
周排行