您的位置:首页 > 其它

POJ 2686 Traveling by Stagecoach (状压DP)

2017-05-22 23:47 316 查看
题意:有一个人从某个城市要到另一个城市, 有n个马车票,相邻的两个城市走的话要消耗掉一个马车票。花费的时间呢,是马车票上有个速率值

,问最后这个人花费的最短时间是多少。

析:和TSP问题差不多,dp[s][i] 表示当前在第 i 个城市,还剩余集合 s的票,需要的最短时间。状态转移方程:

dp[s][i] = min{dp[s|j][k] + d[i][k] }

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e16;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1e6 + 10;
const int mod = 100000000;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
return r >= 0 && r < n && c >= 0 && c < m;
}
double dp[1<<8][31];
int a[31][31];
double tt[10];

int main(){
//  freopenr;
int s, t, p;
while(scanf("%d %d %d %d %d", &n, &m, &p, &s, &t) == 5 && n+m+p+s+t){
int all = 1 << n;
for(int i = 0; i < all; ++i)
fill(dp[i], dp[i]+m+1, inf);
for(int i = 0; i < n; ++i)  scanf("%lf", tt+i);
memset(a, INF, sizeof a);
for(int i = 0; i < p; ++i){
int u, v, d;
scanf("%d %d %d", &u, &v, &d);
a[u][v] = a[v][u] = d;
}
dp[all-1][s] = 0;
for(int i = all-2; i >= 0; --i)
for(int j = 0; j < n; ++j)  if(!(i&(1<<j))){
for(int u = 1; u <= m; ++u){
for(int v = 1; v <= m; ++v){
if(a[u][v] == INF)  continue;
if(dp[i|(1<<j)][v] == inf)  continue;
dp[i][u] = min(dp[i][u], dp[i|(1<<j)][v] + a[u][v] * 1.0 / tt[j]);
}
}
}
double ans = inf;
for(int i = 0; i < all; ++i)
ans = min(ans, dp[i][t]);
if(ans >= inf)  printf("Impossible\n");
else  printf("%.3f\n", ans);
}
return 0;
}


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