有 n 个点,编号从 1 到 n,其中有 k 个点是关键点,还有 m 条有向边(u为起点,v为终点,l为长度),每条有向边连接一对点,问相距最近的一对关键点的距离。(单向可达即可)c++代码实现
时间: 2024-04-12 13:27:52 浏览: 21
可以使用 Dijkstra 算法来解决这个问题。下面是用 C++ 实现的代码:
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
struct Edge {
int to;
int length;
};
int findShortestDistance(int n, int k, int m, vector<vector<Edge>>& graph) {
// 创建邻接表
// 初始化关键点集合
vector<bool> isKeyPoint(n + 1, false);
for (int i = 0; i < k; i++) {
int keyPoint;
cin >> keyPoint;
isKeyPoint[keyPoint] = true;
}
// 构建邻接表
vector<vector<Edge>> adjList(n + 1);
for (int i = 0; i < m; i++) {
int u, v, l;
cin >> u >> v >> l;
adjList[u].push_back({v, l});
}
// 初始化距离数组
vector<int> distances(n + 1, INT_MAX);
distances[0] = 0;
// 使用优先队列实现 Dijkstra 算法
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, 0});
while (!pq.empty()) {
int currDist = pq.top().first;
int currNode = pq.top().second;
pq.pop();
if (distances[currNode] < currDist) {
continue;
}
for (auto& edge : adjList[currNode]) {
int neighbor = edge.to;
int newDist = currDist + edge.length;
if (newDist < distances[neighbor]) {
distances[neighbor] = newDist;
pq.push({newDist, neighbor});
}
}
}
// 找到相距最近的一对关键点的距离
int shortestDistance = INT_MAX;
for (int i = 1; i <= n; i++) {
if (isKeyPoint[i] && distances[i] < shortestDistance) {
shortestDistance = distances[i];
}
}
return shortestDistance;
}
int main() {
int n, k, m;
cin >> n >> k >> m;
int shortestDistance = findShortestDistance(n, k, m, graph);
cout << "相距最近的一对关键点的距离为:" << shortestDistance << endl;
return 0;
}
```
这段代码首先根据输入的边构建了邻接表表示有向图,并构建了一个布尔数组来标记关键点。然后使用 Dijkstra 算法计算从起点到各个点的最短路径。最后找到距离最近的关键点的距离并返回。
注意:输入需要按照指定格式进行,依次输入n、k、m,然后输入k个关键点的编号,最后输入m行有向边的起点、终点和长度。输出为相距最近的一对关键点的距离。