POJ3635 Full Tank? 优先队列BFS

题目链接

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,fuelw), 无代价。

由于代价并不相同,所以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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值