NPC problem, there is no polynomial-time algorithm, but in the algorithm can be done pruning optimization:
1. First write algorithm, missing pruning: The shortest path calculated before the current path >=, the current path does not continue to traverse
#include <cstdio>#include<iostream>#include<cstring>using namespacestd;intN;intmap[ A][ A];intflag[ A];intSolveintstart) { intI,val, all_visited =1, Min =999999999; for(i =2; I <= N; i++) { if(Flag[i]! =0|| Map[start][i] = =0) { Continue; } all_visited=0; Flag[i]=1;//visitedval = map[start][i] +solve (i); if(Val <min) {min=Val; } Flag[i]=0; } if(all_visited) {returnmap[start][1]; } Else { returnmin; }}intMainintargcChar**argv) { intTC, T, I, J; //freopen ("Input.txt", "R", stdin);CIN >>T; for(TC =0; TC < T; Tc++) {cin>>N; for(i =1; I <= N; i++) { for(j =1; J <= N; J + +) {cin>>Map[i][j]; }} memset (flag,0x00, A*sizeof(int)); printf ("%d\n", Solve (1)); } return 0;}
2. Optimization algorithm, PATH determination pruning
#include <cstdio>#include<iostream>#include<cstring>using namespacestd;intN, cost, min_cost;intmap[ -][ -];intflag[ -];intsum;voidSolveintstart) { inti; if(Sum >=N) {if(map[start][1]!=0&& Cost + map[start][1] <min_cost) {Min_cost= Cost + map[start][1]; } return; } for(i =2; I <= N; i++) { if(Flag[i]! =0|| Map[start][i] = =0|| Cost + map[start][i] >=min_cost) { Continue; } Flag[i]=1;//visitedCost + =Map[start][i]; Sum++; Solve (i); Sum--; Flag[i]=0; Cost-=Map[start][i]; }}intMainintargcChar**argv) { intTC, T, I, J; //freopen ("Input.txt", "R", stdin);CIN >>T; for(TC =0; TC < T; Tc++) {cin>>N; for(i =1; I <= N; i++) { for(j =1; J <= N; J + +) {cin>>Map[i][j]; }} memset (flag,0x00, -*sizeof(int)); Cost=0; Min_cost =99999999999; Sum=1; Solve (1); cout<<min_cost<<Endl; } return 0;}
Notice the red code, don't miss it.
Travel business Issues