题意:
有一个旅行家计划乘马车旅行。他所在的国家里共有m个城市,在城市之间有若干道路相连。从某个城市沿着某条道路到相邻的城市需要乘坐马车。而乘坐马车需要使用车票,每用一张车票只可以通过一条道路。每张车票上都记有马的匹数,从一个城市移动到另一个城市的所需时间等于城市之间道路的长度除以马的数量的结果。这位旅行家一共有ñ张车票,第i张车票上马的匹数是Ti等。一张车票只能使用一次,并且换乘所需要的时间可以忽略。求从城市一个到城市b所需要的最短时间。如果无法到达城市b则输出”不可能”。
思路:
状压dp:
(1)状态:
dp[S][v]:=当前点在v,剩余车票的情况为S的最短时间。
(2)状态转移方程:
dp[s&~(1<<i)][u] =min(dp[s&~(1<<i)][u],dp[s][v]+(double)d[v][u] / t[i]);
注意:初始化还是尽量采用循环的方式进行初始化
代码实现:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxn = 2e6 + 5;
const int inf = (1 << 29) - 1;
int n,m,p,a,b;
int t[50];
int G[50][50];
double dp[maxn][50];
int main(){
while(~scanf("%d%d%d%d%d",&n,&m,&p,&a,&b)){
if(n == 0&&m == 0) break;
int x,y,dis;
for(int i = 0;i < n;i++)
scanf("%d",&t[i]);
memset(G,0,sizeof(G));
for(int i = 0;i < p;i++){
scanf("%d%d%d",&x,&y,&dis);
G[x - 1][y - 1] = dis;
G[y - 1][x - 1] = dis;
}
for(int i = 0;i <= (1 << n) - 1;i++){
for(int j = 0;j <= 45;j++){
dp[i][j] = inf;
}
}
dp[(1 << n) - 1][a - 1] = 0;
double res = inf;
for(int S = (1 << n) - 1;S >= 0;S--){
res = min(res,dp[S][b - 1]);
for(int v = 0;v < m;v++){
for(int i = 0;i < n;i++){
if((S >> i) & 1){
for(int u = 0;u < m;u++){
if(G[v][u] == 0) continue;
dp[S&(~(1<<i))][u] = min(dp[S&(~(1<<i))][u],dp[S][v]+(G[v][u]*1.0)/t[i]);
}
}
}
}
}
if(res == inf) printf("Impossible\n");
else{
printf("%.3f\n",res);
}
}
return 0;
}