题目概述
给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环,所有边权均为正值。
请你求出 1 号点到 n 号点的最短距离,如果无法从 1 号点走到 n 号点,则输出 −1。
输入格式
第一行包含整数 n 和 m。
接下来 m 行每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z。
输出格式
输出一个整数,表示 1 号点到 n 号点的最短距离。
如果路径不存在,则输出 −1。
数据范围
1≤n≤500,
1≤m≤105,
图中涉及边长均不超过10000。
输入样例:
3 3
1 2 2
2 3 1
1 3 4
输出样例:
3
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510;
int n,m;
int g[N][N];//稠密图一般使用邻接矩阵
int dist[N];//用于存储每个点到起点的最短距离
bool st[N];//True表示已经确定最短路 属于t集合
int dijkstra()
{
memset(dist,0x3f,sizeof dist);//void *memset(void *str, int c, size_t n) 复制字符 c(一个无符号字符)到参数 str 所指向的字符串的前 n 个字符。
dist[1] = 0;//起点距离自己的距离为零
for(int i = 0; i < n; ++i)//迭代n次,每次可以确定一个点到起点的最短路
{
int t = -1;//t存储当前访问的点,将t设置为-1 因为Dijkstra算法适用于不存在负权边的图
for(int j = 1;j <= n;++j)//这里的j代表的是从1号点开始
{
if(!st[j] && (t == -1||dist[j] < dist[t]))
//不在s集合且未更新过,则进行更新,或者发现更短的路径,则进行更新
{
t = j;//更新t集合
}
}
st[t] = true;
for(int j = 1;j <=n;++j)
{
dist[j] = min(dist[j],dist[t] + g[t][j]);//依次更新每个点所到相邻的点路径值
}
}
if(dist[n] == 0x3f3f3f3f)//如果第n个点路径为无穷大即不存在最低路径
return -1;
return dist[n];
}
int main()
{
cin >> n >> m;
memset(g,0x3f,sizeof g);
//初始化图 因为是求最短路径
//所以每个点初始为无限大
while (m--)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
g[a][b] = min(g[a][b],c);//如果发生重边的情况则保留最短的一条边
}
cout << dijkstra() << endl;
return 0;
}
p.s.语法小灶
memset()函数基础用法
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int main ()
{
char str[50];
strcpy(str,"This is string.h library function");
puts(str);
memset(str,'$',7);
puts(str);
return(0);
}
输出:
This is string.h library function
$$$$$$$ string.h library function