HDU 2544 最短路——dijlstra

来源:互联网 发布:图书管理系统java需求 编辑:程序博客网 时间:2024/06/03 22:50

这题c++编译器有坑,用g++吧。

套用了dijkstra模板,没什么坑,WA的话检查一下初始化,以及模板是否写错

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <utility>#include <queue>using namespace std;const int INF = 0x3f3f3f3f;const int maxn = 110;typedef pair<int, int> P;struct Edge {    int to, cost;};vector<Edge> G[maxn];int n, m, d[maxn], vis[maxn];void dijkstra(int s) {    priority_queue<P, vector<P>, greater<P> > q;    memset(vis, 0, sizeof(vis));    for (int i = 0; i <= n; i++) d[i] = INF;    d[s] = 0;    q.push(P(0, s));    while (!q.empty()) {        P p = q.top(); q.pop();        int pos = p.second;        if (vis[pos]) continue;        vis[pos] = 1;        int len = G[pos].size();        for (int i = 0; i < len; i++) {            Edge e = G[pos][i];            if (d[e.to] > d[pos] + e.cost) {                d[e.to] = d[pos] + e.cost;                q.push(P(d[e.to], e.to));            }        }    }}void input() {    for (int i = 0; i <= n; i++) G[i].clear();    int a, b, c;    while (m--) {        scanf("%d %d %d", &a, &b, &c);        Edge e1, e2;        e1.to = b, e1.cost = c;        e2.to = a, e2.cost = c;        G[a].push_back(e1);        G[b].push_back(e2);    }}int main(){    while (scanf("%d %d", &n, &m) == 2 && (n || m)) {        input();        dijkstra(1);        printf("%d\n", d[n]);    }    return 0;}