hdu1874 畅通工程续

堆优化的dijkstra


需要更新边

边记录要去的顶点和权值

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <queue>
using namespace std;
const int INF = 1 << 30;
const int NIL = -1;
const int MAXN = 205;
int vis[MAXN];
int d[MAXN];
int head[2005];
int n;
int cnt;
struct Edge {
    int to, next, w;
    Edge() {}
} edge[2005];

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

struct Node {
    int u, w;
    Node (int _u, int _w) :u(_u), w(_w) {}
    friend bool operator<(const Node& a, const Node& b)
    {
        return a.w > b.w;
    }
};

void dijkstra(int s, int e)
{
    priority_queue<Node> q;
    for (int i = 0; i < n; ++i)
        d[i] = INF, vis[i] = false;
    d[s] = 0;
    
    Node t(s, 0);
    q.push(t);
    int u, v, w;
    while (!q.empty())
    {
        t = q.top();
        q.pop();
        u = t.u;
        if (d[u] < t.w)
            continue;
        vis[u] = true;
        for (int i = head[u]; i != NIL; i = edge[i].next)
        {
            v = edge[i].to;    //与u相邻的边
            w = edge[i].w;
            if (!vis[v] && d[v] > d[u] + w)
            {
                d[v] = d[u] + w;
                q.push(Node(v, d[v]));
            }
        }
    }
    if (d[e] == INF)
        cout << "-1\n";
    else
        cout << d[e] << endl;

}

int main(void)
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int k, s, e, w, m;
    while (cin >> n >> m)
    {
        memset(head, NIL, sizeof(int) * (m + 1) * 2);
        cnt = 0;
        for (int i = 0; i < m; ++i)
        {
            cin >> s >> e >> w;
            add(s, e, w);
            add(e, s, w);
        }
        cin >> s >> e;
        dijkstra(s, e);
    }

    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值