0
点赞
收藏
分享

微信扫一扫

HDU 1874 畅通工程续——dijkstra

年夜雪 2022-08-17 阅读 63


注意判断-1的条件

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <utility>
#include <queue>

using namespace std;

const int maxn = 500;
const int INF = 0x3f3f3f3f;
typedef pair<int, int> P;

struct Edge {
int to, cost;
};
vector<Edge> G[maxn];

int n, m, s, t, vis[maxn], d[maxn];

void dijkstra(int s) {
memset(vis, 0, sizeof(vis));
for (int i = 0; i < n; i++) d[i] = INF;
d[s] = 0;
priority_queue<P, vector<P>, greater<P> > q;
q.push(P(0, s));
while (!q.empty()) {
P p = q.top(); q.pop();
int pos = p.second;
if (vis[pos]) continue;
vis[pos] = 1;

int len = G[pos].size();
for (int i = 0; i < len; i++) {
Edge e = G[pos][i];
if (d[e.to] > d[pos] + e.cost) {
d[e.to] = d[pos] + e.cost;
q.push(P(d[e.to], e.to));
}
}
}
}

void input() {
for (int i = 0; i < n; i++) G[i].clear();
int a, b, c;
while (m--) {
scanf("%d %d %d", &a, &b, &c);
Edge e1, e2;
e1.to = b, e1.cost = c;
e2.to = a, e2.cost = c;
G[a].push_back(e1);
G[b].push_back(e2);
}
scanf("%d %d", &s, &t);
}

int main()
{
while (scanf("%d %d", &n, &m) == 2) {
input();
dijkstra(s);
if (d[t] == INF) d[t] = -1;
printf("%d\n", d[t]);
}
}



举报

相关推荐

0 条评论