今年天津网赛就有一道这样的类似题目,当时有思路感觉和TSP问题很像,就是想不出来怎么做,挺可惜的。因此趁着这段时间搞一下状态压缩DP
状态转移方程 dp[s][i] =min{dp[s][i],dp[s'][j]+dis[j][i]} dp[s][i]表示到达状态s时位于i位置的最小耗费,dis[j][i]表示两点之间的最短路
在DP之前要用floyd预处理一下求出每两个点之间的最短距离。
Hie with the Pie
Time Limit: 2000MS |
Memory Limit: 65536K |
Total Submissions: 2686 |
Accepted: 1368 |
Description
The Pizazz Pizzeria prides itself in delivering pizzasto its customers as fast as possible. Unfortunately, due to cutbacks, they canafford 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 tosay, he would like to take the shortest route in delivering these goodies andreturning to the pizzeria, even if it means passing the same location(s) or thepizzeria more than once on the way. He has commissioned you to write a programto help him.
Input
Input will consist of multiple test cases. The firstline will contain a single integern indicating the number of orders todeliver, where 1 ≤ n ≤ 10. After this will ben + 1 lines eachcontaining n + 1 integers indicating the times to travel between thepizzeria (numbered 0) and then locations (numbers 1 to n). The jthvalue on the ith line indicates the time to go directly from location ito locationj without visiting any other locations along the way. Notethat there may be quicker ways to go fromi to j via otherlocations, due to different speed limits, traffic lights, etc. Also, the timevalues may not be symmetric, i.e., the time to go directly from locationito j may not be the same as the time to go directly from locationjto i. An input value of n = 0 will terminate input.
Output
For each test case, you should output a single numberindicating the minimum time to deliver all of the pizzas and return to thepizzeria.
Sample Input
3
0 1 10 10
1 0 1 2
10 1 0 10
10 2 10 0
0
Sample Output
8
#include<iostream>
#include<bitset>
#include<cstdio>
#include<cstring>
using namespace std;
#define INF 0xFFFFFF
#define min(a,b) (a<b?a:b);
int n,map[12][12],dp[1<<12][12];
int ans;
void floyd()
{
for(int k=0;k<=n;k++)
for(int i=0;i<=n;i++)
{
if(i==k) continue;
for(int j=0;j<=n;j++)
{
if(i==j) continue;
map[i][j]=min(map[i][j],map[i][k]+map[k][j]);
}
}
}
void solve()
{
for(int i=0;i<=n;i++)
for(int j=0;j<=n;j++)
scanf("%d",&map[i][j]);
floyd();
for(int s=0;s<(1<<n);s++)
{
for(int i=1;i<=n;i++)
{
if(s&(1<<(i-1)))
{
if(s==(1<<(i-1)))
dp[s][i]=map[0][i];
else
{
dp[s][i]=INF;
for(int j=1;j<=n;j++)
{
if(s&(1<<(j-1)) && j!=i)
dp[s][i]=min(dp[s][i],dp[s^(1<<(i-1))][j]+map[j][i]);
}
}
}
}
}
ans=dp[(1<<n)-1][1]+map[1][0];
for(int i=2;i<=n;i++)
ans=min(ans,dp[(1<<n)-1][i]+map[i][0]);
printf("%d\n",ans);
}
int main()
{
while(~scanf("%d",&n) && n)
solve();
return 0;
}