POJ 3311 Hie with the Pie【状态压缩DP】

Description

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
View Code
题意:给出n+1个点两两间距离,计算从原点出发经过所有点后再回到原点的最短路(每个都可以重复走)。
思路:用n位二进制数i表示一个状态,其中i的每位表示某个目的地是(1)否(0)已经经过。用dp[i][j]表示在状态i的情况下以目的地j为终点的最短路。状态转移方程:
dp[i&(1<<k)][k] = min(dp[i][j] + a[j][k] , dp[i&(1<<k)][k]).
其中a[j][k]表示j到k的最短路,可由floyd算法求得。


#include<stdio.h>
#include<string.h>
#define clr(x)memset(x,0,sizeof(x))
#define min(a,b)(a)<(b)?(a):(b)
#define inf 9999999999
int dp[1<<11][12];
int dis[12][12];
int main()
{
int i,j,k,n,m,s,ans;
while(scanf("%d",&n),n)
{
for(i=0;i<=n;i++)
for(j=0;j<=n;j++)
scanf("%d",&dis[i][j]);
for(k=0;k<=n;k++) //floyd 求最短路
for(i=0;i<=n;i++)
for(j=0;j<=n;j++)
if(dis[i][k]+dis[k][j]<dis[i][j])
dis[i][j]=dis[i][k]+dis[k][j];
s=(1<<n)-1; // 所有状态
for(i=0;i<=s;i++)
{
for(j=1;j<=n;j++)
{
if(i&(1<<(j-1))) //枚举城市
{
if(i==(1<<(j-1))) //边界条件 只经过 j 点的最小距离 为dis[0][j]
dp[i][j]=dis[0][j];
else
{
dp[i][j]=inf;
for(k=1;k<=n;k++)
{
if(i&(1<<(k-1))&&k!=j) // 如果状态 I 中有K点存在 dp 一次
dp[i][j]=min(dp[i^(1<<(j-1))][k]+dis[k][j],dp[i][j]);
// 状态转移,在没经过城市j的状态中,寻找合适的中间点k使得距离更短
}
}
}
}
}
ans=dp[(1<<n)-1][1]+dis[1][0]; // 最终状态 (1<<n)-1 表示每个点都经过了
for(i=2;i<=n;i++)
if(dp[(1<<n)-1][i]+dis[i][0]<ans)
ans=dp[(1<<n)-1][i]+dis[i][0];
printf("%d\n",ans);
}
return 0;
}

 
 
posted @ 2012-03-31 19:45  'wind  阅读(602)  评论(0编辑  收藏  举报