uva 11367 - Full Tank?(最短路)

该博客主要探讨了如何解决UVA在线判题系统的11367题——Full Tank问题。内容涉及通过建立状态转移方程,结合最短路径算法,来确定在确保到达目的地的同时,所需的最小油量策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:uva 11367 - Full Tank?


增加一维表示油量,每个状态可以考虑向下一个节点移动,也可以选择加一单位油。


#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;
typedef pair<int,int> pii;
const int maxn = 1005;
const int maxm = 105;
const int inf = 0x3f3f3f3f;

int N, M, P[maxn], D[maxn][maxm], vis[maxn][maxm];
vector<pii> G[maxn];

struct State {
	int u, l, d;
	State(int u = 0, int l = 0, int d = 0): u(u), l(l), d(d) {}
	bool operator < (const State& a) const { return d > a.d; }
};

void init () {
	for (int i = 0; i < N; i++) {
		G[i].clear();
		scanf("%d", &P[i]);
	}

	int u, v, w;
	while (M--) {
		scanf("%d%d%d", &u, &v, &w);
		G[u].push_back(make_pair(v, w));
		G[v].push_back(make_pair(u, w));
	}
}

int dijkstra(int s, int e, int c) {
	memset(D, inf, sizeof(D));
	memset(vis, 0, sizeof(vis));

	D[s][0] = 0;
	priority_queue<State> Q;
	Q.push(State(s, 0, D[s][0]));

	while (!Q.empty()) {
		State cur = Q.top(); Q.pop();

		int u = cur.u, l = cur.l;
		if (vis[u][l]) continue;
		vis[u][l] = 1;
		//printf("%d %d %d\n", u, l, D[u][l]);

		for (int i = 0; i < G[u].size(); i++) {
			int v = G[u][i].first, w = G[u][i].second;
			if (w > l) continue;
			if (D[v][l-w] > D[u][l]) {
				D[v][l-w] = D[u][l];
				Q.push(State(v, l-w, D[v][l-w]));
			}
		}

		if (l < c && D[u][l+1] > D[u][l] + P[u]) {
			D[u][l+1] = D[u][l] + P[u];
			Q.push(State(u, l + 1, D[u][l+1]));
		}
	}
	/*
	int ret = inf;
	for (int i = 0; i <= c; i++)
		ret = min(ret, D[e][i]);
	return ret;
	*/
	return D[e][0];
}

int main () {
	while (scanf("%d%d", &N, &M) == 2) {
		init();
		int q, s, e, c;
		scanf("%d", &q);
		while (q--) {
			scanf("%d%d%d", &c, &s, &e);
			int ans = dijkstra(s, e, c);
			if (ans == inf) printf("impossible\n");
			else printf("%d\n", ans);
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值