题目链接
http://poj.org/problem?id=3635
分析
设状态为 ( c i t y , f u e l ) (city, fuel) (city,fuel),表示所处的城市及当前油量;
对于每个位置,若 f u e l fuel fuel 小于油箱容量,可以扩展到 ( c i t y , f u e l + 1 ) (city, fuel + 1) (city,fuel+1),代价是当前城市油费;
若 f u e l fuel fuel 大于 c i t y city city 到某城市的边权 w w w,可以扩展到 ( c i t y ′ , f u e l − w ) (city', fuel - w) (city′,fuel−w), 无代价。
由于代价并不相同,所以BFS扩展状态时需要用优先队列,类似堆优化Dijkstra。
AC代码
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
inline int read() {
int num = 0;
char c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9')
num = num * 10 + c - '0', c = getchar();
return num;
}
const int maxn = 1e3 + 5, maxm = 1e4 + 5, maxc = 105, inf = 0x3f3f3f3f;
int head[maxn], eid;
struct Edge {
int v, w, next;
} edge[2 * maxm];
inline void insert(int u, int v, int w) {
edge[++eid].v = v, edge[eid].w = w;
edge[eid].next = head[u];
head[u] = eid;
}
struct Node {
int c, f, d;
Node(int c, int f, int d) : c(c), f(f), d(d) {}
bool operator < (const Node& rhs) const {
return d > rhs.d;
}
};
int cost[maxn], d[maxn][maxc];
priority_queue<Node> q;
inline int bfs(int c, int s, int e) {
memset(d, inf, sizeof(d));
while (!q.empty()) q.pop();
d[s][0] = 0;
q.push(Node(s, 0, 0));
while (!q.empty()) {
Node t = q.top();
q.pop();
int u = t.c, f = t.f;
if (u == e) return d[u][f];
if (t.d > d[u][f]) continue;
if (f < c && d[u][f + 1] > d[u][f] + cost[u]) {
d[u][f + 1] = d[u][f] + cost[u];
q.push(Node(u, f + 1, d[u][f + 1]));
}
for (int p = head[u]; p; p = edge[p].next) {
int v = edge[p].v, w = edge[p].w;
if (f >= w && d[v][f - w] > d[u][f]) {
d[v][f - w] = d[u][f];
q.push(Node(v, f - w, d[v][f - w]));
}
}
}
return -1;
}
int main() {
int n = read(), m = read();
for (int i = 0; i < n; ++i) cost[i] = read();
for (int i = 1; i <= m; ++i) {
int u = read(), v = read(), w = read();
insert(u, v, w);
insert(v, u, w);
}
int q = read();
while (q--) {
int c = read(), s = read(), e = read();
int ans = bfs(c, s, e);
if (ans != -1) printf("%d\n", ans);
else printf("impossible\n");
}
return 0;
}