
输入样例:
3 3
1 2 2
2 3 1
1 3 4
输出样例:
3
题解:
对于求解最短路径的最优方法当然是依次求得每个点的最短,然后遍历更新起点到所有点的最短路径,并储存在点里。
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>
using namespace std;
typedef long long ll;
const int maxx = 1000050;
ll n, m, t, now, l, r, c, b ,T ,k ;
const int INF = 0x3f3f3f3f;
const double pi = acos(-1.0);
int pie[] = {3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4,6,2,6,4,3,3,8,3,2,7,9,5,0,2,8,8,4,1,9,7,1,6,9,3,9,9,3,7,5,1,0};
ll ans;
int step[50][50][50];
int nx, ny, nz, ex, ey, ez;
int e[maxx];
int sum[20221199];
int w[510][510];
int dp[225][225];
ll mod = 1e9 + 7;
bool st[maxx];
int node()
{
memset(e, 0x3f, sizeof(e));//由于是在求最小值所以将其都初始化为无穷
e[1] = 0;//将第一步初始化为起点
for (int i = 0; i < n; i++)//开始遍历
{
int t = -1;//没有确定最短路径的结点中距离原点最近的点
for (int j = 1; j <= n; j++)//遍历e步数数组,找到没有确定最短路径的结点中距离原点最近的点t
{
if (!st[j] && (t == -1 || e[t] > e[j]))
{
t = j;
}
}
st[t] = true;
for (int j = 1; j <= n; j++)//遍历寻找最短路径
{
e[j] = min(e[j], e[t] + w[t][j]);
}
}
if (e[n] == 0x3f3f3f3f)//如果没找到最短的路径甚至于到达不了
{
return -1;//返回-1
}
else//否则返回最短
{
return e[n];
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
memset(w, 0x3f, sizeof(w));
for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
w[a][b] = min(w[a][b], c);
}
int num = node();
cout << num << endl;
return 0;
}