这道题就是经典的Dijstra,只需知道一个点出发到其他点的最短路程,注意在初始化的时候要进行重边判断(所有的最短路问题都需要注意这个,除非题意很明显不可能出现重边)
#include<cstdio>
#include<cstring>
const int INF = 0x3f3f3f3f;
const int VN = 205;
int main()
{
int n, m, v0, t0, x, y, d, min, u;
int a[VN][VN], s[VN], dist[VN];
while (~scanf("%d%d", &n, &m))
{
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
a[i][j] = INF;
for (int i = 1; i <= m; i++)
{
scanf("%d%d%d", &x, &y, &d);
if (d < a[x][y])
{
a[x][y] = d;
a[y][x] = d;
}
}
scanf("%d%d", &v0, &t0); //先处理一般,再处理特殊
for (int i = 0; i < n; i++)
{
dist[i] = a[v0][i];
s[i] = false;
//if (dist[i] == INF) prev[i] = -1;
//else prev[i] = v0;
}
dist[v0] = 0;
s[v0] = true;
for (int i = 2; i <= n; i++)
{
int min = INF;
int u = v0; // 为了防止后面的条件不成立,但是某些语句的正常执行
for (int j = 0; j < n ; j++)
if (!s[j] && dist[j] < min)
{
u = j;
min = dist[j];
}
s[u] = true;
for (int j = 0; j < n; j++)
if (!s[j] && a[u][j] != INF)
{
if (dist[u] + a[u][j] < dist[j])
{
dist[j] = dist[u] + a[u][j];
// prev[j] = u;
}
}
}
if (dist[t0] == INF) printf("-1\n"); else printf("%d\n", dist[t0]);
}
return 0;
}