题目描述
输入样例
3 3
1 2 2
2 3 1
1 3 4
输出样例
3
参考代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
// 数据范围是500个点
const int N = 510;
int n, m; // n个点,m条边
int g[N][N]; // 用于存储输入的边的距离
int dist[N]; // 用于存储每个点到源点的距离
bool st[N]; // 用于标志该点是否处理过
int dijkstra()
{
memset(dist, 0x3f, sizeof dist); // 将dist初始化为正无穷
dist[1] = 0; // 1号点作为源点,距离源点为0
// 处理n次得到结果
for (int i = 0; i < n; i++)
{
// 每次都需要重新寻找未处理过的距离源点最近的点
int t = -1;
for (int j = 1; j <= n; j++)
{
// 判断条件是:1、该点没有处理过 2、该点dist最近
if (!st[j] && (t == -1 || dist[j] < dist[t]))
{
t = j;
}
}
// 找到该点后,标记已找到
st[t] = true;
// 用该点更新所有点
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];
}
int main()
{
// 处理输入
memset(g, 0x3f, sizeof g); // 将邻接矩阵初始化为正无穷
scanf("%d%d", &n, &m);
while (m -- )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
g[a][b] = min(g[a][b], c); // 因为可能存在自环和重边,取最小值
}
// 计算源点到n号点的最短路
int t = dijkstra();
printf("%d\n", t);
return 0;
}
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int N = 100010;
typedef pair<int ,int> PII;
int n, m;
int h[N], e[N], ne[N], w[N], idx;
int dist[N];
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b; // 记录边的终点
w[idx] = c; // 记录边的权重
ne[idx] = h[a]; // 将下一条边指向节点a此时的第一条边指向的终点
h[a] = idx; // 将节点a的第一条边的编号改为此时的idx
idx++; // 递增边的编号idx
}
int dijkstra()
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
priority_queue<PII, vector<PII>, greater<PII>> heap; // 优先队列可以自动排序
heap.push({0, 1}); // 第一个是距离,第二个是节点编号
while (heap.size())
{
auto t = heap.top();
heap.pop();
int ver = t.second, distance = t.first;
if (st[ver]) continue;
st[ver] = true;
// 处理该节点所有邻边的距离, i指的是边
for (int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i]; // 取到了边的终点
if (dist[j] > distance + w[i])
{
dist[j] = distance + w[i];
heap.push({dist[j], j});
}
}
}
if (dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
int main()
{
memset(h, -1, sizeof h);
scanf("%d%d", &n, &m);
while (m -- )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
int t = dijkstra();
printf("%d\n", t);
return 0;
}