HDU1874 (畅通工程续,最短路模板题)

版权声明: https://blog.csdn.net/weixin_39778570/article/details/82026691

题目链接
求两点间最短路,模版题

AC code

#include <iostream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#define LL long long
#define INF 0x3f3f3f3f
#define maxn 1024
#define Pair pair<int, int>
#define mem(a, b) memset(a, b, sizeof(a))
#define _  ios_base::sync_with_stdio(0),cin.tie(0)
//freopen("1.txt", "r", stdin);
using namespace std;
/*一:最短路*/
/*1.dijstra算法*/
/* void dijkstra(int s)  无向图
   邻接表 + 优先队列
   参数 s : 出发点
    */
typedef pair<int, int> P;
struct edge
{
    int to, cost;
};
int V;
vector<edge> G[maxn];
int d[maxn];
void dijkstra(int s)
{
    priority_queue<Pair, vector<Pair>, greater<Pair> > que;
    fill(d, d + V + 2, INF);
    d[s] = 0;
    que.push(Pair(0, s));
    while (!que.empty()) {
        Pair p = que.top();
        que.pop();
        int v = p.second;
        if (d[v] < p.first) continue;//到v点的距离如果已经被更新 这无须执行以下操作
        for (int i = 0; i < G[v].size(); ++i) {
            edge e= G[v][i];
            if (d[e.to] > d[v] +e.cost) {
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to], e.to));
            }
        }
    }
}
int main()
{
    int m, str, end;
    while(scanf("%d%d", &V,&m) != EOF){
    for(int i=0; i<maxn; i++) G[i].clear();
    for (int i = 0; i < m; ++i) {
        int from, to, cost;
        cin >> from >> to >> cost;
        edge var;
        var.to = to;
        var.cost = cost;
        G[from].push_back(var);
        var.to = from;
        G[to].push_back(var);//无向图
    }
    scanf("%d%d", &str, &end);
    dijkstra(str);
    if(d[end]!=INF) printf("%d\n", d[end]);
    else printf("%d\n",-1);
    }
    /*for (int i = 1; i <= V; ++i)
        cout << d[i] << endl;*/   //到i的距离
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_39778570/article/details/82026691