最短路——链式向前星,迪杰斯特拉算法的典型例题

HDU 1874:题目链接: 点击打开链接
大神链接: 深度理解链式向前星

畅通工程续

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 61960    Accepted Submission(s): 23232


Problem Description
某省自从实行了很多年的畅通工程计划后,终于修建了很多路。不过路多了也不好,每次要从一个城镇到另一个城镇时,都有许多种道路方案可以选择,而某些方案要比另一些方案行走的距离要短很多。这让行人很困扰。

现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。
 

Input
本题目包含多组数据,请处理到文件结束。
每组数据第一行包含两个正整数N和M(0接下来是M行道路信息。每一行有三个整数A,B,X(0<=A,B再接下一行有两个整数S,T(0<=S,T
 

Output
对于每组数据,请在一行里输出最短需要行走的距离。如果不存在从S到T的路线,就输出-1.
 

Sample Input

3 30 1 10 2 31 2 10 23 10 1 11 2
 

Sample Output

2-1
//最短路——链式向前星,优先队列
#include 
#define mp make_pair
using namespace std;

const int MAXN = (int)207;
const int MAXM = (int)1e3+7;
const int INF = (int)0x3f3f3f3f;
typedef pair pi;
int Head[MAXN];
int dis[MAXN];
int cnt,N,M;

struct Node{
    int next;
    int to;
    int w;
}edge[MAXM];

void emp(){
    memset(Head,-1,sizeof(Head));
    memset(dis,0x3f,sizeof(dis));
    cnt = 0;
}

void Add(int x,int y,int w){
    edge[cnt].next = Head[x];
    edge[cnt].to = y;
    edge[cnt].w = w;
    Head[x] = cnt;
    cnt ++;
}

void show(){
    int i,t;
    for(i = 1;i <= N;i ++){
        t = Head[i];
        while(~t){
            cout << i << "-->" << edge[t].to << " need " << edge[t].w << endl;
            t = edge[t].next;
        }
    }
}

int main()
{
    while (cin >> N >> M){
        emp();

        int x,y,w;
        for (int i = 0;i < M;i ++){
            cin >> x >> y >> w;
            Add(x,y,w);
            Add(y,x,w);
        }

        int s,t;
        cin >> s >> t;

        priority_queue  Q;
        Q.push(mp(0,s));
        dis[s] = 0;

        while (!Q.empty()){
            int k = Q.top().second;
            Q.pop();

            for (int i = Head[k]; ~i;i = edge[i].next){
                if (dis[edge[i].to] > dis[k] + edge[i].w){
                    dis[edge[i].to] = dis[k] + edge[i].w;
                    Q.push(mp(-dis[edge[i].to],edge[i].to));
                }
            }
        }
        if (dis[t] != INF) cout << dis[t] << endl;
        else cout << -1 << endl;

        show();
    }
}
//这是我用链式向前星和使用优先队列所形成的hdu1874题目的答案。

你可能感兴趣的:(模板,复习,最短路,不短)