使用C++写一个SPF算法,找到最短路径,要求分成三个文件,分别是SPF.cpp, SPF.h, Test.cpp,
时间: 2024-02-15 15:02:40 浏览: 117
好的,下面是我的代码,分别写在SPF.cpp,SPF.h和Test.cpp文件中。
SPF.h
```cpp
#ifndef SPF_H
#define SPF_H
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
#include <cstring>
using namespace std;
const int MAXN = 100;
const int INF = INT_MAX;
class SPF {
public:
SPF();
~SPF();
void addEdge(int u, int v, int w);
void solve(int s);//s为起点
void print();//输出最短路
private:
struct Edge {
int v, w;
Edge(int _v, int _w) : v(_v), w(_w) {}
};
vector<Edge> G[MAXN];
int dist[MAXN];
bool vis[MAXN];
int cnt[MAXN];
int n, m;
void init();
bool spfa(int s);
};
#endif
```
SPF.cpp
```cpp
#include "SPF.h"
SPF::SPF() {
init();
}
SPF::~SPF() {}
void SPF::init() {
memset(vis, false, sizeof(vis));
memset(cnt, 0, sizeof(cnt));
memset(dist, INF, sizeof(dist));
for (int i = 0; i < MAXN; i++) {
G[i].clear();
}
}
void SPF::addEdge(int u, int v, int w) {
G[u].push_back(Edge(v, w));
}
bool SPF::spfa(int s) {
queue<int> q;
q.push(s);
dist[s] = 0;
vis[s] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
vis[u] = false;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i].v;
int w = G[u][i].w;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
cnt[v] = cnt[u] + 1;
if (cnt[v] >= n) {//存在负环
return false;
}
if (!vis[v]) {
q.push(v);
vis[v] = true;
}
}
}
}
return true;
}
void SPF::solve(int s) {
n = MAXN;
if (!spfa(s)) {
cout << "存在负环!" << endl;
} else {
cout << "最短路径为:" << endl;
for (int i = 0; i < n; i++) {
cout << s << "到" << i << "的最短路为:" << dist[i] << endl;
}
}
}
void SPF::print() {
for (int i = 0; i < MAXN; i++) {
for (int j = 0; j < G[i].size(); j++) {
cout << i << "->" << G[i][j].v << " " << G[i][j].w << endl;
}
}
}
```
Test.cpp
```cpp
#include "SPF.h"
int main() {
SPF spf;
spf.addEdge(0, 1, 2);
spf.addEdge(0, 2, 6);
spf.addEdge(1, 2, 3);
spf.addEdge(1, 3, 8);
spf.addEdge(1, 4, 5);
spf.addEdge(2, 4, 7);
spf.addEdge(3, 4, 9);
spf.print();
spf.solve(0);
return 0;
}
```
阅读全文