TZOJ 1937 Hie with the Pie(floyd+状压dp)

描述

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 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.

输出

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.

样例输入

3
0 1 10 10
1 0 1 2
10 1 0 10
10 2 10 0
0

样例输出

8

题意

从0出发,走n个城市后回到0,所经过的最短路径

题解

dp[i][j]表示状态i最后到点j的最短路径,1表示到达过,0表示还未到达

我们可以从子推出它的父,就是从子状态i经过j点到最后的k点,就变成父状态(i<<k)|i

dp[i][j]+d[j][k]=dp[(i<<k)|i][[k]

上面的d为从j到k的最短路,可以用floyd跑出任意两个点的最短路

代码

 1 #include<stdio.h>
 2 #include<string.h>
 3 
 4 int G[15][15],d[15][15],dp[1<<11][15];
 5 int main()
 6 {
 7     int n;
 8     while(scanf("%d",&n)!=EOF,n)
 9     {
10         for(int i=0;i<=n;i++)
11             for(int j=0;j<=n;j++)
12                 scanf("%d",&G[i][j]),d[i][j]=G[i][j];
13 
14         for(int k=0;k<=n;k++)
15             for(int i=0;i<=n;i++)
16                 for(int j=0;j<=n;j++)
17                     if(d[i][j]>d[i][k]+G[k][j])
18                         d[i][j]=d[i][k]+G[k][j];
19 
20         memset(dp,-1,sizeof dp);
21         dp[1][0]=0;
22         for(int i=1;i<(1<<(n+1));i++)
23         {
24             i|=1;
25             for(int j=0;j<=n;j++)
26             {
27                 if(dp[i][j]==-1)continue;
28                 for(int k=0;k<=n;k++)
29                 {
30                     if(j!=k&&(dp[(1<<k)|i][k]==-1||dp[(1<<k)|i][k]>dp[i][j]+d[j][k]))
31                         dp[(1<<k)|i][k]=dp[i][j]+d[j][k];
32                 }
33             }
34         }
35         printf("%d
",dp[(1<<(n+1))-1][0]);
36     }
37     return 0;
38 }
原文地址:https://www.cnblogs.com/taozi1115402474/p/9328971.html