您的位置:首页 > 其它

HDU 3001 Travelling 【状态压缩DP】

2012-04-01 11:21 411 查看
[align=left]Problem Description[/align]
After coding so many days,Mr Acmer wants to have a good rest.So travelling is the best choice!He has decided to visit n cities(he insists on seeing all the cities!And he does not mind which city being his start station because superman can bring him to any city at first but only once.), and of course there are m roads here,following a fee as usual.But Mr Acmer gets bored so easily that he doesn't want to visit a city more than twice!And he is so mean that he wants to minimize the total fee!He is lazy you see.So he turns to you for help.
[align=left]Input[/align]
There are several test cases,the first line is two intergers n(1<=n<=10) and m,which means he needs to visit n cities and there are m roads he can choose,then m lines follow,each line will include three intergers a,b and c(1<=a,b<=n),means there is a road between a and b and the cost is of course c.Input to the End Of File.
[align=left]Output[/align]
Output the minimum fee that he should pay,or -1 if he can't find such a route.
Sample Input

2 1 1 2 100 3 2 1 2 40 2 3 50 3 3 1 2 3 1 3 4 2 3 10

Sample Output

100
90
7
code:

View Code

#include<stdio.h>
#include<string.h>
#define min(a,b)(a)<(b)?(a):(b)
#define inf 0x1f1f1f1f
int dp[60000][12];  // dp[i][j] 状态为 i 的情况下 到达 j 点的最短路
int dis[12][12];
int f[60000][11];   // f[i][j]  状态 i 的情况下 i 的 第 j 位
int fac[12];
int main()
{
int va,ns,t,x,i,j,s,p,q,len,n,m,res;
fac[1]=1;
for(i=2;i<11;i++)
fac[i]=fac[i-1]*3;
for(i=0;i<59050;i++){
t=i;
for(j=1;j<=10;j++){
f[i][j]=t%3;
t/=3;
if(t==0)
break;
}
}
//freopen("D:ce.txt","r",stdin);
while(scanf("%d%d",&n,&m)!=EOF)
{
res=inf;
memset(dis,inf,sizeof(dis));
while(m--)
{
scanf("%d%d%d",&p,&q,&len);
if(len<dis[p][q])
dis[p][q]=dis[q][p]=len;
}
memset(dp,inf,sizeof(dp));
x=fac
*3;
for(i=1;i<=n;i++)     //  边界处理 状态为 fac[i] 表明只经过i 这一个点
dp[fac[i]][i]=0;  //  这一个点 这个点到本身的距离自然为 0
for(s=0;s<x;s++)
{
va=1;
for(i=1;i<=n;i++)
{
if(f[s][i]==0)
va=0;
if(dp[s][i]==inf)
continue;

for(j=1;j<=n;j++)
{
if(i==j) continue;
// 如果 j 经过了两次 或者 i j 之间没有道路 就不再更新
if(dis[i][j]==inf||f[s][j]>=2) continue;
ns=s+fac[j];
dp[ns][j]=min(dp[s][i]+dis[i][j],dp[ns][j]);
}
}
// 如果能 到达所有点
if(va){
for(j=1;j<=n;j++)
res=min(dp[s][j],res);
}
}
if(res==inf){
printf("-1\n");
continue;
}
printf("%d\n",res);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: