hdu2544 最短路-邻接表+优先队列实现dijkstra
Problem Description
在每年的校賽里,所有進(jìn)入決賽的同學(xué)都會(huì)獲得一件很漂亮的t-shirt。但是每當(dāng)我們的工作人員把上百件的衣服從商店運(yùn)回到賽場(chǎng)的時(shí)候,卻是非常累的!所以現(xiàn)在他們想要尋找最短的從商店到賽場(chǎng)的路線,你可以幫助他們嗎?
Input
輸入包括多組數(shù)據(jù)。每組數(shù)據(jù)第一行是兩個(gè)整數(shù)N、M(N<=100,M<=10000),N表示成都的大街上有幾個(gè)路口,標(biāo)號(hào)為1的路口是商店所在地,標(biāo)號(hào)為N的路口是賽場(chǎng)所在地,M則表示在成都有幾條路。N=M=0表示輸入結(jié)束。接下來(lái)M行,每行包括3個(gè)整數(shù)A,B,C(1<=A,B<=N,1<=C<=1000),表示在路口A與路口B之間有一條路,我們的工作人員需要C分鐘的時(shí)間走過(guò)這條路。
輸入保證至少存在1條商店到賽場(chǎng)的路線。
Output
對(duì)于每組輸入,輸出一行,表示工作人員從商店走到賽場(chǎng)的最短時(shí)間
Sample Input
2 1
1 2 3
3 3
1 2 5
2 3 5
3 1 2
0 0
Sample Output
3
2
解題思路:
dijkstra單源最短路徑算法就ok了!!!
代碼如下:
#include <iostream> #include <queue> #include <vector> #include <string> using namespace std; const int INF = 1 << 30; const int N = 110; int dis[N]; bool done[N]; int n, m;struct edge {int from;int to;int w; };struct node {int id;int dis;friend bool operator<(const node &a, const node &b) {return a.dis > b.dis;} };vector<edge>e[N];void dijkstra() {priority_queue<node>q;int s = 1;for (int i = 1; i <= n; i++)dis[i] = INF;memset(done, 0, sizeof(done));dis[s] = 0;q.push({s, dis[s]});while (q.size()) {node t = q.top();q.pop();if (done[t.id])continue;done[t.id] = true;for (int i = 0; i < e[t.id].size(); i++) {edge y = e[t.id][i];if (done[y.to])continue;if (dis[y.to] > y.w + t.dis) {dis[y.to] = y.w + t.dis;q.push({y.to, dis[y.to]});}}}cout << dis[n] << endl; }int main() {while (cin >> n >> m, n, m) {for (int i = 1; i <= n; i++)e[i].clear();while (m--) {int a, b, c;cin >> a >> b >> c;e[a].push_back({a, b, c});e[b].push_back({b, a, c});}dijkstra();}return 0; }總結(jié)
以上是生活随笔為你收集整理的hdu2544 最短路-邻接表+优先队列实现dijkstra的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: hdu2544 最短路-Floyd算法
- 下一篇: 爷爷的平板车小孩的平板车