UVA - 11367 Full Tank? (二维最短路 好题)

题目链接:https://vjudge.net/problem/UVA-11367

思路:多加了一个状态表示在这个点的油量,在一个点既可以加油,一单位一单位的加,也可以向其他点扩展

#include 
using namespace std;
const int MAXN = 2050;
const int MAXM = 20050;
const int INF = 0x3f3f3f3f;
struct Edge{
	int from,to,dist;
	Edge(int u,int v,int d):from(u),to(v),dist(d){} 
}; 
struct HeapNode{ 
	int d,u,fuel;
	HeapNode(int _d,int _u,int _fuel):d(_d),u(_u),fuel(_fuel){}
	bool operator < (const HeapNode& rhs) const{
		return d > rhs.d;
	}
};
struct Dijkstra
{
	int n,m;
	vector edges;
	vector G[MAXN];
	bool done[MAXN][105];   
	int d[MAXN][105];
	int val[MAXN];         
	void init(int n) { 
		this -> n = n;
		for(int i = 0; i < n; i++) {
			G[i].clear();
		}
		edges.clear();
	}
	void AddEdge(int from,int to,int dist) {
		edges.push_back(Edge(from,to,dist));
		m = edges.size();
		G[from].push_back(m - 1);
	}
	int dijkstra(int s,int e,int c) {
		priority_queue Q;
		memset(d,INF,sizeof(d));
		d[s][0] = 0;
		memset(done,0,sizeof(done));
		Q.push(HeapNode(0,s,0));
		while(!Q.empty()) {
			HeapNode x = Q.top();
			Q.pop();
			int u = x.u,fuel = x.fuel;
			if(done[u][fuel]) continue;
			if(u == e) return d[u][fuel];
			done[u][fuel] = true;
			//一单位一单位的加油 
			if(fuel < c && d[u][fuel] + val[u] < d[u][fuel + 1]) {
				d[u][fuel + 1] = d[u][fuel] + val[u];
				Q.push(HeapNode(d[u][fuel + 1],u,fuel + 1));
			}
			for(int i = 0; i < G[u].size(); i++) {
				Edge& e = edges[G[u][i]];
				if(fuel >= e.dist && d[e.to][fuel - e.dist] > d[u][fuel]) {
					d[e.to][fuel - e.dist] = d[u][fuel];
					Q.push(HeapNode(d[u][fuel],e.to,fuel - e.dist));
				}
			}
		}
		return -1;
	}
}dij;
int val[MAXN];
int main(void)
{
	int n,m,u,v,w,q,c,ans;
	scanf("%d %d",&n,&m);
	dij.init(n);
	for(int i = 0; i < n; i++) {
		scanf("%d",&dij.val[i]);
	}
	while(m--) {
		scanf("%d %d %d",&u,&v,&w);
		dij.AddEdge(u,v,w);
		dij.AddEdge(v,u,w);
	}
	scanf("%d",&q);
	while(q--) {
		scanf("%d %d %d",&c,&u,&v);
		ans = dij.dijkstra(u,v,c);
		if(ans == -1) printf("impossible\n");
		else printf("%d\n",ans);
	}
	return 0;
}
/*
5 5
10 10 20 12 13
0 1 9
0 2 8
1 2 1
1 3 11
2 3 7
2
10 0 3
20 1 4
*/

 

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