POJ3311 Hie with the Pie
The Pizazz Pizzeria prides itself in delivering pizzas to its customers as fast as possible. Unfortunately, due to cutbacks, they can afford to hire only one driver to do the deliveries. He will wait for 1 or more (up to 10) orders to be processed before he starts any deliveries. Needless to say, he would like to take the shortest route in delivering these goodies and returning to the pizzeria, even if it means passing the same location(s) or the pizzeria more than once on the way. He has commissioned you to write a program to help him.
Input
Input will consist of multiple test cases. The first line will contain a single integer n indicating the number of orders to deliver, where 1 ≤ n ≤ 10. After this will be n + 1 lines each containing n + 1 integers indicating the times to travel between the pizzeria (numbered 0) and the n locations (numbers 1 to n). The jth value on the ith line indicates the time to go directly from location i to location j without visiting any other locations along the way. Note that there may be quicker ways to go from i to j via other locations, due to different speed limits, traffic lights, etc. Also, the time values may not be symmetric, i.e., the time to go directly from location i to j may not be the same as the time to go directly from location j to i. An input value of n = 0 will terminate input.
Output
For each test case, you should output a single number indicating the minimum time to deliver all of the pizzas and return to the pizzeria.
Sample Input
3 0 1 10 10 1 0 1 2 10 1 0 10 10 2 10 0 0
Sample Output
8
1 /*by SilverN*/ 2 #include<algorithm> 3 #include<iostream> 4 #include<cstring> 5 #include<cstdio> 6 #include<cmath> 7 #include<vector> 8 #include<queue> 9 using namespace std; 10 const int mxn=1<<12; 11 int read(){ 12 int x=0,f=1;char ch=getchar(); 13 while(ch<'0' || ch>'9'){if(ch=='-')f=-1;ch=getchar();} 14 while(ch>='0' && ch<='9'){x=x*10+ch-'0';ch=getchar();} 15 return x*f; 16 } 17 int f[mxn][13]; 18 int mp[13][13]; 19 bool inq[mxn]; 20 int main(){ 21 int i,j; 22 int n; 23 while(scanf("%d",&n) && n){ 24 for(i=0;i<=n;i++) 25 for(j=0;j<=n;j++) 26 mp[i][j]=read(); 27 memset(f,0x3f,sizeof f); 28 int ed=(1<<(n+1))-1; 29 f[1][0]=0; 30 queue<int>q; 31 q.push(0); 32 while(!q.empty()){ 33 int u=q.front();q.pop();inq[u]=0; 34 for(i=0;i<=n;i++){ 35 if(i==u)continue; 36 for(int k=1;k<=ed;k++){ 37 if(!(k&(1<<u)))continue; 38 if(f[k|(1<<i)][i]>f[k][u]+mp[u][i]){ 39 f[k|(1<<i)][i]=f[k][u]+mp[u][i]; 40 if(!inq[i]){ 41 inq[i]=1; 42 q.push(i); 43 } 44 } 45 } 46 } 47 } 48 printf("%d\n",f[ed][0]); 49 } 50 return 0; 51 }