(1) 实现一个模板函数FathestVex返回距离索引为v的顶点最远的顶点索引;
时间: 2023-12-03 13:46:09 浏览: 26
以下是一个实现模板函数FathestVex的示例代码:
```c++
template<typename T>
int FarthestVex(Graph<T>& G, int v) {
int n = G.VertexNum();
vector<bool> visited(n, false);
vector<T> dist(n, numeric_limits<T>::max());
dist[v] = 0;
queue<int> q;
q.push(v);
while (!q.empty()) {
int u = q.front();
q.pop();
if (visited[u]) continue;
visited[u] = true;
for (auto& e : G.AdjList(u)) {
int w = e.to;
T new_dist = dist[u] + e.weight;
if (new_dist < dist[w]) {
dist[w] = new_dist;
q.push(w);
}
}
}
int farthest = v;
for (int i = 0; i < n; ++i) {
if (dist[i] > dist[farthest]) {
farthest = i;
}
}
return farthest;
}
```
该函数接受一个图对象G和一个起点v索引,返回距离v最远的顶点索引。函数使用BFS算法计算每个顶点到v的最短距离,然后找到具有最大距离的顶点索引。函数模板参数T表示边权值的类型,可以是整数、浮点数等,但必须支持无穷大,例如使用numeric_limits<T>::max()表示无穷大。