程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> UVA 10246 - Asterix and Obelix(最短路)

UVA 10246 - Asterix and Obelix(最短路)

編輯:C++入門知識

UVA 10246 - Asterix and Obelix(最短路)


UVA 10246 - Asterix and Obelix

題目鏈接

題意:給定一個圖,每個點有一個代價,邊有一個代價,現在有q次詢問,每次詢問從u到v的最小花費,花費的計算方式為,路徑代價加上路徑上最大代價結點的代價

思路:枚舉最大代價結點,然後做dijkstra,做的過程中忽略掉比枚舉點更大代價的點,然後更新所有的答案,預處理完成後每次詢問就可以在O(1)時間內完成了

代碼:

#include 
#include 
#include 
#include 
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 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;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved