LightOJ - 1254 Prison Break(最短路+大剪枝)

题目大意:给你每个加油站加一升油需要的费用和一张地图。
现在有Q个询问,询问的是当车的油箱容量为C时,从S到T所需要花费的最少钱

解题思路:还是多维最短路,用dp[i][j]表示到达i点时,油箱里还剩有j升油时的最小花费,这里有一个剪枝,就是如果到达那边时,费用比上次到达时还大的话,就不用更新后面的了
这里用的是Dijkstra,所以只要走到终点了,不管油箱还有多少油,都表示最小费用了

#include 
#include 
#include 
#include 
using namespace std;
const int M = 1010;
const int N = 110;
const int INF = 0x3f3f3f3f;

struct Edge{
    int v, dis, next;
    Edge() {}
    Edge(int v, int dis, int next): v(v), dis(dis), next(next) {}
}E[2 * M];

struct Node {
    int pos, cap, val;
    Node() {}
    Node(int pos, int cap, int val): pos(pos), cap(cap), val(val) {}
    bool operator < (const Node &a) const {
        return val > a.val;
    }
};

int price[N], head[N], dp[N][N];
int n, m, tot, cap, s, t, cas = 1;
bool vis[N][N];

void AddEdge(int u, int v, int dis) {
    E[tot] = Edge(v, dis, head[u]);
    head[u] = tot++;
    E[tot] = Edge(u, dis, head[v]);
    head[v] = tot++;
}

void init() {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) scanf("%d", &price[i]);

    memset(head, -1, sizeof(head));
    tot = 0;
    int u, v, dis;
    for (int i = 0; i < m; i++) {
        scanf("%d%d%d", &u, &v, &dis);
        AddEdge(u, v, dis);
    }
}

void dijkstra() {
    memset(dp, 0x3f, sizeof(dp));
    memset(vis, 0, sizeof(vis));
    priority_queue Q;
    //刚开始的时候加了多少的油
    for (int i = 0; i <= cap; i++) {
        dp[s][i] = i * price[s];
        Q.push(Node(s, i, dp[s][i]));
    }

    while (!Q.empty()) {
        int u = Q.top().pos;
        int c = Q.top().cap;
        Q.pop();
        if (vis[u][c]) continue;
        vis[u][c] = true;
        if (u == t) break;

        for (int i = head[u]; ~i; i = E[i].next) {
            int v = E[i].v;
            int dis = E[i].dis;
            if (c < dis) continue;
            if (dp[v][c - dis] > dp[u][c]) {
                for (int j = c - dis; j <= cap; j++)
                    if (dp[v][j] > dp[u][c] + (j - c + dis) * price[v]) {
                        dp[v][j] = dp[u][c] + (j - c + dis) * price[v];
                        Q.push(Node(v, j, dp[v][j]));
                    }
            }
        }
    }
}

void solve() {
    int q;
    scanf("%d", &q);
    printf("Case %d:\n", cas++);
    while (q--) {
        scanf("%d%d%d", &cap, &s, &t);
        dijkstra();
        int ans = INF;
        for (int i = 0; i <= cap; i++)
            if (ans > dp[t][i]) 
                ans = dp[t][i];

        if (ans == INF) printf("impossible\n");
        else printf("%d\n", ans);
    }

}

int main() {
    int test;
    scanf("%d", &test);
    while (test--) {
        init();
        solve();
    }
    return 0;
}

你可能感兴趣的:(ACM-图论-最短路)