poj 2686 Traveling by Stagecoach TSP 图 状压dp

来源:互联网 发布:幼儿园区域阅美工图片 编辑:程序博客网 时间:2024/05/17 02:31

题目

题目链接:http://poj.org/problem?id=2686

题目来源:《挑战》例题。

简要题意:有票子,/=,求ab的最小代价。

题解

dp[i][j]表示停留在i,票子状态为j的最小代价。

用二进制位去压缩状态然后进行递推。

TSP的基础题目,也可以最短路那样去推。

代码

#include <iostream>#include <cstdio>#include <cmath>#include <algorithm>#include <cstring>#include <stack>#include <queue>#include <string>#include <vector>#include <set>#include <map>#define fi first#define se secondusing namespace std;typedef long long LL;typedef pair<int,int> PII;// headconst int N = 8;const int ST = 1 << N;const int M = 35;const double INF = 1e9;const double EPS = 1e-8;bool isINF(double &x) {    return fabs(x - INF) < EPS;}void setMin(double &a, double b) {    if (a > b) a = b;}double dp[M][ST];struct Edge {    int to, nxt, c;    Edge(int to, int nxt, int c) : to(to), nxt(nxt), c(c) {}    Edge() {}};int head[M];Edge e[M * 100];void addEdge(int from, int to, int c, int cnt) {    e[cnt] = Edge(to, head[from], c);    head[from] = cnt;}void init(int n, int m) {    for (int i = 0; i <= m; i++) head[i] = -1;    int mx = 1 << n;    for (int i = 0; i < m; i++) {        fill(dp[i], dp[i] + mx, INF);    }}int t[N];void update(int x, int st, int no) {    int nxtst = st | (1 << no);    for (int i = head[x]; ~i; i = e[i].nxt) {        int to = e[i].to;        setMin(dp[to][nxtst], dp[x][st] + double(e[i].c) / t[no]);    }}int main() {    int n, m, p, a, b, u, v, c;    while (scanf("%d%d%d%d%d", &n, &m, &p, &a, &b) == 5 && n) {        a--, b--;        for (int i = 0; i < n; i++) {            scanf("%d", t+i);        }        init(n, m);        int ec = 0;        for (int i = 0; i < p; i++) {            scanf("%d%d%d", &u, &v, &c);            u--, v--;            addEdge(u, v, c, ec++);            addEdge(v, u, c, ec++);        }        int mx = 1 << n;        double ans = INF;        dp[a][0] = 0.0;        for (int i = 0; i < mx; i++) {            setMin(ans, dp[b][i]);            for (int j = 0; j < m; j++) {                if (isINF(dp[j][i])) continue;                for (int k = 0; k < n; k++) {                    if ((1 << k) & i) continue;                    update(j, i, k);                }            }        }        if (isINF(ans)) {            puts("Impossible");        } else {            printf("%.5f\n", ans);        }    }    return 0;}
0 0
原创粉丝点击