用c++解决这个问题:描述 After finishing the "Village Construction Project", the provincial government built more roads to make the trips between two villages more convenient. Then there is a new problem, which path is the shortest path between village V1 and V2? 输入 The first line of each test case contains four integers N, M, V1, V2 (1<=N, M, V1, V2<=1000; V1 != V2). Still, N and M represent the number of villages and the number of roads respectively. Then N lines follow, and every line contains three integers Ai, Bi, and Vi (1<=Ai, Bi <=N, Ai != Bi, 1<=Vi<=1000 ), meaning there is a road between village Ai and village Bi with its cost Vi. The inputs terminate at the end of the file (EOF). 输出 For each test case, output the cost of the shortest path between V1 and V2. If there is no path between V1 and V2, print -1.
时间: 2024-03-02 22:51:00 浏览: 128
vc++实现最短路径算法
这是一道图论问题,可以使用 Dijkstra 算法或者 Floyd 算法来解决。下面我以 Dijkstra 算法为例,给出解题思路:
首先读入输入数据,建立邻接矩阵。然后,以 V1 为起点,使用 Dijkstra 算法求出 V1 到所有点的最短路径。最终输出 V1 到 V2 的最短路径长度,如果不存在则输出 -1。
具体实现可以参考以下代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
int n, m, v1, v2;
int graph[1005][1005], dist[1005];
bool vis[1005];
void dijkstra(int s)
{
memset(vis, false, sizeof(vis));
memset(dist, INF, sizeof(dist));
dist[s] = 0;
for (int i = 1; i <= n; i++)
{
int k = -1, min_dist = INF;
for (int j = 1; j <= n; j++)
{
if (!vis[j] && dist[j] < min_dist)
{
k = j;
min_dist = dist[j];
}
}
if (k == -1) break;
vis[k] = true;
for (int j = 1; j <= n; j++)
{
if (!vis[j] && graph[k][j] != INF)
dist[j] = min(dist[j], dist[k] + graph[k][j]);
}
}
}
int main()
{
while (cin >> n >> m >> v1 >> v2)
{
memset(graph, INF, sizeof(graph));
for (int i = 1; i <= n; i++) graph[i][i] = 0;
for (int i = 1; i <= m; i++)
{
int a, b, v;
cin >> a >> b >> v;
graph[a][b] = graph[b][a] = v;
}
dijkstra(v1);
if (dist[v2] == INF) cout << -1 << endl;
else cout << dist[v2] << endl;
}
return 0;
}
```
阅读全文