最短路例题 HDU 2544

题目连接:点击打开链接

Problem Description
在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt。但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要寻找最短的从商店到赛场的路线,你可以帮助他们吗?

 

Input
输入包括多组数据。每组数据第一行是两个整数N、M(N<=100,M<=10000),N表示成都的大街上有几个路口,标号为1的路口是商店所在地,标号为N的路口是赛场所在地,M则表示在成都有几条路。N=M=0表示输入结束。接下来M行,每行包括3个整数A,B,C(1<=A,B<=N,1<=C<=1000),表示在路口A与路口B之间有一条路,我们的工作人员需要C分钟的时间走过这条路。
输入保证至少存在1条商店到赛场的路线。
 

Output
对于每组输入,输出一行,表示工作人员从商店走到赛场的最短时间
 

Sample Input
 
  
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
 

Sample Output
 
  
3 2


    使用前向星来存图:

struct Node {
    int v,w;
    int next;
} edge[maxn];

int head[maxn],cnt = 0,n,m;
int dis[maxn],vis[maxn];

void add (int u, int v, int w){
    edge[cnt].v = v;
    edge[cnt].w = w;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}

#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int maxn = 100000 + 10;
const int inf = 0x3f3f3f3f;

struct Node {
    int v,w;
    int next;
} edge[maxn];

int head[maxn],cnt = 0,n,m;
int dis[maxn],vis[maxn];

void add (int u, int v, int w){
    edge[cnt].v = v;
    edge[cnt].w = w;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}

void spfa (){
    fill(vis,vis+maxn,0);
    for (int i = 1; i <= n; i++){
        dis[i] = inf;
    }
    queue <int> que;
    dis[1] = 0;
    vis[1] = 1;
    que.push(1);
    while (!que.empty()){
        int q = que.front();
        que.pop();
        vis[q] = 0;
        for (int i = head[q]; i != -1; i = edge[i].next){
            int v = edge[i].v;
            if (dis[v] > dis[q] + edge[i].w){
                dis[v] = dis[q] + edge[i].w;
                if (!vis[v]){
                    que.push(v);
                    vis[v] = 1;
                }
            }
        }
    }
}

int main (){
    int u, v, w;
    while (~scanf("%d%d",&n,&m) && (n&&m)){
        fill(head,head+maxn,-1);
        for (int i = 1; i <= m; i++){
            scanf("%d%d%d",&u,&v,&w);
            add(u,v,w);
            add(v,u,w);
        }
        spfa();
        printf("%d\n",dis[n]);
    }
}

写过的为数不多的spfa,,学了前向星,水了一个题。

猜你喜欢

转载自blog.csdn.net/weixin_41190227/article/details/80170774