题目入口
题意:给定一个n个点m条边的有向图,图中可能存在重边和自环,所有边权均为正值。
请你求出1号点到n号点的最短距离,如果无法从1号点走到n号点,则输出-1。
输入格式
第一行包含整数n和m。
接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。
输出格式
输出一个整数,表示1号点到n号点的最短距离。
如果路径不存在,则输出-1。
数据范围
1≤n≤500,
1≤m≤10^5,
图中涉及边长均不超过10000。
输入样例:
3 3
1 2 2
2 3 1
1 3 4
输出样例:
3
最短路的几种算法:
- 朴素的Dijkstra适合稠密图的最短路,而堆优化的Dijkstra更适合稀疏图的最短路。
- 还有就是SPFA解决不来那种不超过k条边的最短路问题。
思路:用dist[i]记录i好点到1号点的最短距离,用集合S来统计已确定最短距离的点(这里的作用感觉有点类似于bfs的队列)
- 先将所有的dist[]复制为最大值INF,再取dist[1] = 0(1到1的最短距离当然是0了)。
- 循环遍历找到不在S中的边权最小的点t并将其加入S中;用t来更新(放缩)其他点i(给出的边中有t -> i)的距离,即用1 -> t -> i 的距离和1 -> i的距离取min作为dist[i]。如此依次遍历完就能得到1到任一点x的距离dist[x]了。
代码实现:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#define lowbit(x) (x &(-x))
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const double EXP = 1e-8;
const ll MOD = 1e9 + 7;
const int N = 505;
int n, m;
int g[N][N], dist[N];
bool st[N]; //st值为true表示在S集合里
int Dijkstra()
{
mem(dist, 0x3f);
dist[1] = 0;
for(int i = 0; i < n; i ++){
int t = -1;
//找到还没有确定最短路的边权最小值
for(int j = 1; j <= n; j ++)
if(!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
st[t] = 1;
//用找到的j来更新其他边
for(int j = 1; j <= n; j ++)
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
if (dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
signed main()
{
IOS;
cin >> n >> m;
memset(g, 0x3f, sizeof g);
while(m --){
int u, v, w;
cin >> u >> v >> w;
g[u][v] = min(g[u][v], w);
}
cout << Dijkstra() << endl;
return 0;
}