使用C++写一个SPF算法,找到最短路径,并输出所花费时间。要求分成三个文件,分别是SPF.cpp, SPF.h, Test.cpp,
时间: 2024-02-15 19:02:46 浏览: 120
spf.rar_spf_操作系统spf
以下是使用C++实现SPF算法的代码,共分为SPF.cpp、SPF.h、Test.cpp三个文件:
SPF.h:
```cpp
#ifndef SPF_H
#define SPF_H
#include <vector>
using namespace std;
class SPF {
public:
SPF(int n);
void add_edge(int u, int v, int w);
void shortest_path(int s);
vector<int> get_dist();
vector<int> get_prev();
private:
struct edge {
int to, weight;
edge(int t, int w) : to(t), weight(w) {}
};
int n;
vector<vector<edge>> graph;
vector<int> dist;
vector<int> prev;
};
#endif
```
SPF.cpp:
```cpp
#include "SPF.h"
#include <vector>
#include <queue>
#include <limits>
using namespace std;
SPF::SPF(int n) : n(n), graph(n), dist(n, numeric_limits<int>::max()), prev(n, -1) {}
void SPF::add_edge(int u, int v, int w) {
graph[u].push_back(edge(v, w));
}
void SPF::shortest_path(int s) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
dist[s] = 0;
pq.push(make_pair(0, s));
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
for (auto& e : graph[u]) {
int v = e.to;
int w = e.weight;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
prev[v] = u;
pq.push(make_pair(dist[v], v));
}
}
}
}
vector<int> SPF::get_dist() {
return dist;
}
vector<int> SPF::get_prev() {
return prev;
}
```
Test.cpp:
```cpp
#include "SPF.h"
#include <iostream>
#include <chrono>
using namespace std;
int main() {
int n = 5;
SPF spf(n);
spf.add_edge(0, 1, 10);
spf.add_edge(0, 3, 30);
spf.add_edge(0, 4, 100);
spf.add_edge(1, 2, 50);
spf.add_edge(2, 4, 10);
spf.add_edge(3, 2, 20);
spf.add_edge(3, 4, 60);
auto start = chrono::high_resolution_clock::now();
spf.shortest_path(0);
auto end = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>(end - start);
vector<int> dist = spf.get_dist();
vector<int> prev = spf.get_prev();
for (int i = 0; i < n; i++) {
cout << "Shortest distance from 0 to " << i << " is " << dist[i] << endl;
}
cout << "Time taken by SPF algorithm: " << duration.count() << " microseconds" << endl;
return 0;
}
```
在这个测试代码中,我们创建一个大小为5的图,并添加了几条边。然后使用SPF算法找到从节点0到其他节点的最短路径,并输出路径长度和运行时间。
阅读全文