您的位置:首页 > 其它

POJ3311:Hie with the Pie(floyd+状态压缩DP)

2014-04-26 14:56 423 查看
Description

ThePizazzPizzeriapridesitselfindeliveringpizzastoitscustomersasfastaspossible.Unfortunately,duetocutbacks,theycanaffordtohireonlyonedrivertodothedeliveries.Hewillwaitfor1ormore(upto10)orderstobeprocessedbefore
hestartsanydeliveries.Needlesstosay,hewouldliketotaketheshortestrouteindeliveringthesegoodiesandreturningtothepizzeria,evenifitmeanspassingthesamelocation(s)orthepizzeriamorethanonceontheway.Hehascommissionedyou
towriteaprogramtohelphim.

Input

Inputwillconsistofmultipletestcases.Thefirstlinewillcontainasingleinteger
nindicatingthenumberoforderstodeliver,where1≤n≤10.Afterthiswillbe
n+1lineseachcontainingn+1integersindicatingthetimestotravelbetweenthepizzeria(numbered0)andthe
nlocations(numbers1ton).Thejthvalueonthe
ithlineindicatesthetimetogodirectlyfromlocationitolocation
jwithoutvisitinganyotherlocationsalongtheway.Notethattheremaybequickerwaystogofrom
itojviaotherlocations,duetodifferentspeedlimits,trafficlights,etc.Also,thetimevaluesmaynotbesymmetric,i.e.,thetimetogodirectlyfromlocation
itojmaynotbethesameasthetimetogodirectlyfromlocation
jtoi.Aninputvalueofn=0willterminateinput.

Output

Foreachtestcase,youshouldoutputasinglenumberindicatingtheminimumtimetodeliverallofthepizzasandreturntothepizzeria.

SampleInput
3
011010
1012
101010
102100
0

SampleOutput
8


一个送外卖的人,要将外卖全部送去所有地点再回到店离,求最短路

首先用floyd求出最短路,然后再进行DP即可


dp[i][j]表示i这个状态下,目标是j的最短路,i是用二进制表示每个地点是否去过


#include<stdio.h>
#include<string.h>
#include<algorithm>
usingnamespacestd;

intmap[20][20],dis[20][20],dp[1<<11][20];

intmain()
{
intn,i,j,k;
while(~scanf("%d",&n),n)
{
for(i=0;i<=n;i++)
for(j=0;j<=n;j++)
{
scanf("%d",&map[i][j]);
dis[i][j]=map[i][j];
}
for(j=0;j<=n;j++)
for(i=0;i<=n;i++)
for(k=0;k<=n;k++)
if(dis[i][j]>dis[i][k]+map[k][j])
dis[i][j]=dis[i][k]+map[k][j];
memset(dp,-1,sizeof(dp));
dp[1][0]=0;
for(i=1;i<1<<(n+1);i++)
{
i=i|1;
for(j=0;j<=n;j++)
{
if(dp[i][j]!=-1)
{
for(k=0;k<=n;k++)
{
if(j!=k&&(dp[(1<<k)|i][k]==-1||dp[(1<<k)|i][k]>dp[i][j]+dis[j][k]))
dp[(1<<k)|i][k]=dp[i][j]+dis[j][k];
}
}
}
}
printf("%d\n",dp[(1<<(n+1))-1][0]);
}

return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: