UVA 10246 - Asterix and Obelix(最短路)

UVA 10246 - Asterix and Obelix

题目链接

题意:给定一个图,每个点有一个代价,边有一个代价,现在有q次询问,每次询问从u到v的最小花费,花费的计算方式为,路径代价加上路径上最大代价结点的代价

思路:枚举最大代价结点,然后做dijkstra,做的过程中忽略掉比枚举点更大代价的点,然后更新所有的答案,预处理完成后每次询问就可以在O(1)时间内完成了

代码:

#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

const int MAXNODE = 85;
const int MAXEDGE = 10005;

typedef int Type;
const Type INF = 0x3f3f3f3f;

struct Edge {
	int u, v;
	Type dist;
	Edge() {}
	Edge(int u, int v, Type dist) {
		this->u = u;
		this->v = v;
		this->dist = dist;
	}
};

struct HeapNode {
	Type d;
	int u;
	HeapNode() {}
	HeapNode(Type d, int u) {
		this->d = d;
		this->u = u;
	}
	bool operator < (const HeapNode& c) const {
		return d > c.d;
	}
};

int n, m, q, cost[MAXNODE], ans[MAXNODE][MAXNODE];

struct Dijkstra {
	int n, m;
	Edge edges[MAXEDGE];
	int first[MAXNODE];
	int next[MAXEDGE];
	bool done[MAXNODE];
	Type d[MAXNODE];
	int p[MAXNODE];

	void init(int n) {
		this->n = n;
		memset(first, -1, sizeof(first));
		m = 0;
	}

	void add_Edge(int u, int v, Type dist) {
		edges[m] = Edge(u, v, dist);
		next[m] = first[u];
		first[u] = m++;
	}

	void dijkstra(int s) {
		priority_queue<HeapNode> Q;
		for (int i = 0; i < n; i++) d[i] = INF;
		d[s] = 0;
		p[s] = -1;
		memset(done, false, sizeof(done));
		Q.push(HeapNode(0, s));
		while (!Q.empty()) {
			HeapNode x = Q.top(); Q.pop();
			int u = x.u;
			if (done[u]) continue;
			done[u] = true;
			for (int i = first[u]; i != -1; i = next[i]) {
				Edge& e = edges[i];
				if (cost[e.v] > cost[s]) continue;
				if (d[e.v] > d[u] + e.dist) {
					d[e.v] = d[u] + e.dist;
					p[e.v] = i;
					Q.push(HeapNode(d[e.v], e.v));
				}
			}
		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				ans[i][j] = min(ans[i][j], d[i] + d[j] + cost[s]);
			}
		}
	}
} gao;

int main() {
	int cas = 0;
	int bo = 0;
	while (~scanf("%d%d%d", &n, &m, &q) && n) {
		if (bo) printf("\n");
		else bo = 1;
		gao.init(n);
		for (int i = 0; i < n; i++) scanf("%d", &cost[i]);
		int u, v, d;
		while (m--) {
			scanf("%d%d%d", &u, &v, &d);
			u--; v--;
			gao.add_Edge(u, v, d);
			gao.add_Edge(v, u, d);
		}
		memset(ans, INF, sizeof(ans));
		for (int i = 0; i < n; i++) gao.dijkstra(i);
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++)
				if (ans[i][j] == INF) ans[i][j] = -1;
		printf("Case #%d\n", ++cas);
		while (q--) {
			scanf("%d%d", &u, &v);
			u--; v--;
			printf("%d\n", ans[u][v]);
		}
	}
	return 0;
}


你可能感兴趣的:(UVA 10246 - Asterix and Obelix(最短路))