hdu-2544-最短路(SPFA模板)

时间:2022-05-19 14:57:14

题目链接

题意很清晰,入门级题目,适合各种模板,可用dijkstra, floyd, Bellman-ford, spfa

Dijkstra链接

Floyd链接

Bellman-Ford链接

SPFA链接

 /*
Name:HDU-2544-最短路
Copyright:
Author:
Date: 2018/4/17 10:34:47
Description:
SPFA
*/
#include <cstring>
#include <cstdio>
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
const int MAXN = ;
int n, m;
vector <pair<int, int>> g[MAXN];
int dist[MAXN];
bool inQue[MAXN];
queue<int> que;
void spfa() {
memset(inQue, , sizeof(inQue));
memset(dist, 0x3f, sizeof(dist));
dist[] = ;
while (!que.empty()) que.pop();
que.push();
inQue[] = true;
while (!que.empty()) {
int u = que.front();
que.pop();
inQue[u] = false;
for (int i=; i<g[u].size(); i++) {
if(dist[u]+g[u][i].second < dist[g[u][i].first]) {
dist[g[u][i].first] = dist[u] + g[u][i].second;
if (!inQue[g[u][i].first]) {
inQue[g[u][i].first] = true;
que.push(g[u][i].first);
}
}
}
}
}
int main()
{
// freopen("in.txt", "r", stdin);
while (~scanf("%d %d", &n, &m) && (n+m)) {
for (int i=; i<=; i++) {
while (!g[i].empty()) {// while
g[i].pop_back();
}
}
for (int i=; i<=m; i++) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
g[a].push_back(make_pair(b, c));
g[b].push_back(make_pair(a, c));
}
spfa();
printf("%d\n", dist[n]);
}
return ;
}