HDU 2544 最短路

来源:互联网 发布:房产软件有哪些 编辑:程序博客网 时间:2024/06/13 12:58

SPFA算法:

#include <cstdio>#include <cstring>#include <queue>#include <iostream>#define inf 0x3fffffff#define maxn 1005  using namespace std;struct Edge{    int v, w, next;}edge[10005];int head[maxn], tot, dis[maxn],m, n;bool vis[maxn];void init(){    tot = 0;    memset(head, -1, sizeof(head));}void addEdge(int u, int v, int w){    edge[tot].v = v;    edge[tot].w = w;    edge[tot].next = head[u];           head[u] = tot++;               }void SPFA(int u){    int v, w, i;    for(i = 1; i <= n; i++)          dis[i] = inf, vis[i] = false;    dis[u] = 0;    queue<int> q;    q.push (u);    vis[u] = true;    while(!q.empty())    {        u = q.front();        q.pop();        vis[u] = false;        for(i = head[u]; i != -1; i = edge[i].next)        {            w = edge[i].w;            v = edge[i].v;            if (dis[u] + w < dis[v])            {                dis[v] = dis[u] + w;                if (!vis[v])                {                    q.push (v);                    vis[v] = true;                }            }        }    }    cout << dis[n]<<endl;}int main(){    int i,j,a,b,c;    while(scanf("%d%d",&n,&m)==2&&m+n)    {        init();        for(i=0; i<m; i++)        {            scanf("%d%d%d",&a,&b,&c);            addEdge(a,b,c);            addEdge(b,a,c);        }        SPFA(1);    }    return 0;}
dijkstra算法:

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <utility>#include <queue>using namespace std;const int maxn = 500;const int INF = 0x3f3f3f3f;typedef pair<int, int> P;struct Edge {    int to, cost;};vector<Edge> G[maxn];int n, m, s, t, vis[maxn], d[maxn];void dijkstra(int s) {    memset(vis, 0, sizeof(vis));    for (int i = 1; i <= n; i++) d[i] = INF;    d[s] = 0;    priority_queue<P, vector<P>, greater<P> > q;    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);    }    //scanf("%d %d", &s, &t);}int main(){    while (scanf("%d %d", &n, &m) == 2 && m+n) {        input();        dijkstra(1);        printf("%d\n", d[n]);    }}


原创粉丝点击