Dijkstra

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dreams___/article/details/79971815

img

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
using namespace std;
typedef long long LL;
const int inf = 1 << 30;
const LL INF = 1LL << 60;
const int MaxN = 2000;

int n, T;
int all;
int pre[2 * MaxN + 5], last[MaxN + 5], other[2 * MaxN + 5];
int cost[2 * MaxN + 5];
int dis[MaxN + 5];

struct Node {
    int id, d;
    Node () {}
    Node (int a, int b) : id(a), d(b) {}
    bool friend operator < (Node a, Node b) {
        return a.d > b.d;
    }
};

void build(int x, int y, int w) {
    pre[++all] = last[x];
    last[x] = all;
    other[all] = y;
    cost[all] = w;
}

void Dijkstra(int s) {
    for(int i = 1; i <= n; i++) dis[i] = inf;
    dis[s] = 0;
    priority_queue <Node> pq;
    pq.push(Node(s, 0));
    while(!pq.empty()) {
        Node now = pq.top();
        pq.pop();
        int ed = last[now.id];
        while(ed != -1) {
            int dr = other[ed];
            if(dis[now.id] + cost[ed] < dis[dr]) {
                dis[dr] = dis[now.id] + cost[ed];
                pq.push(Node(dr, dis[dr]));
            }
            ed = pre[ed];
        }
    }
}

int main() 
{
    while(scanf("%d %d", &T, &n) != EOF)
    {
        all = -1; memset(last, -1, sizeof(last));
        for(int i = 1; i <= T; i++) {
            int u, v, w;
            scanf("%d %d %d", &u, &v, &w);
            build(u, v, w); build(v, u, w);
        }
        Dijkstra(1);
        printf("%d\n", dis[n]);
    }
    return 0;
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页