构建图:
DiWeightGraph.h
#pragma once
#include <memory>
#include <fstream>
#include <string>
template <typename T>
class BellmanFordSP;
template <typename T>
class DoCycle;
template <typename T>
class DiDoCycle;
template <typename T>
class NoCycleSP;
template <typename T>
class DiWeightGraph
{
public:
class AdjacentcyList
{
public:
class Edge
{
public:
int v;
int w;
T weight;
std::shared_ptr<Edge> next;
public:
Edge(const int& v, const int& w, const T& weight) :v(v), w(w), weight(weight), next(nullptr)
{
}
Edge(const Edge& e):v(e.from()),w(e.to()),weight(e.weight),next(nullptr)
{
}
int from()const
{
return v;
}
int to()const
{
return w;
}
};
class Iterator
{
private:
std::shared_ptr<Edge> it;
public:
Iterator(std::shared_ptr<Edge> e) :it(e)
{
}
Iterator operator ++()
{
if (it == nullptr)
return *this;
it = it->next;
return *this;
}
bool operator !=(const Iterator& rhs)const
{
return it != rhs.it;
}
bool operator == (const Iterator& rhs)const
{
return it == rhs.it;
}
Edge operator *()
{
if (it == nullptr)
throw std::out_of_range("* nullptr");
return *it;
}
};
std::shared_ptr<Edge> head;
public:
AdjacentcyList():head(nullptr)
{
}
void addEdge(const Edge& e)
{
if (head == nullptr)
{
head = std::make_shared<Edge>(Edge(e.from(),e.to(),e.weight));
return;
}
std::shared_ptr<Edge> curr = head;
while (curr->next != nullptr)
{
curr = curr->next;
}
curr->next = std::make_shared<Edge>(Edge(e.from(),e.to(),e.weight));
return;
}
Iterator begin()const
{
return Iterator(head);
}
Iterator end()const
{
return Iterator(nullptr);
}
};
private:
std::unique_ptr<AdjacentcyList[]> adj;
int nV;
int nE;
public:
void addedge(const typename AdjacentcyList::Edge& e)
{
adj[e.from()].addEdge(e);
++nE;
}
public:
DiWeightGraph(const std::string& file)
{
std::ifstream in(file);
if (in.fail())
throw std::domain_error("文件打开失败\n");
in >> nV;
adj = std::move(std::unique_ptr<AdjacentcyList[]>(new AdjacentcyList[nV]));
while (!in.eof())
{
int v, w;
T weight;
in >> v >> w >> weight;
addedge(AdjacentcyList::Edge(v, w, weight));
}
}
DiWeightGraph(const int& v):nV(v),adj(new AdjacentcyList[v])
{
}
void display()
{
for (int i = 0; i < nV; ++i)
{
for (auto &e : adj[i])
cout << e.from() << ends << e.to() << ends << e.weight << endl;
}
}
friend class BellmanFordSP<T>;
friend class DoCycle<T>;
friend class DiDoCycle<T>;
friend class NoCycleSP<T>;
};
核心算法: BellmanFord.h
#pragma once
#include "DiWeightGraph.h"
#include <queue>
#include "DiDoCycle.h"
template <typename T>
class BellmanFordSP
{
using Ed = typename DiWeightGraph<T>::AdjacentcyList::Edge;
private:
std::queue<int> q;
std::unique_ptr<T[]> disTo;
Ed** edge;
int count;
std::unique_ptr<bool[]> onQueue;
bool isnegativeCycle;
int start;
private:
void findNegativeCycle()
{
DiWeightGraph<T> *dwg = new DiWeightGraph<T>(count);
for (int i = 0; i < count; ++i)
{
if (edge[i] != nullptr)
{
dwg->addedge(*(edge[i]));
}
}
DiDoCycle<T> ddc(dwg);
isnegativeCycle = ddc.negative();
}
void relax(DiWeightGraph<T> *dwg,const int& s)
{
for (auto& e : dwg->adj[s])
{
int w = e.to();
if (disTo[w] > disTo[s] + e.weight)
{
edge[w] = new Ed(e.from(), e.to(), e.weight);
disTo[w] = disTo[s] + e.weight;
if (!onQueue[w])
{
q.push(w);
onQueue[w] = true;
}
}
}
if (++count % dwg->nV == 0)
findNegativeCycle();
}
public:
BellmanFordSP(DiWeightGraph<T> *dwg,const int& s) :disTo(new T[dwg->nV]), edge(new Ed*[dwg->nV]), count(0),onQueue(new bool[dwg->nV]),isnegativeCycle(false),start(s)
{
for (int i = 0; i < dwg->nV; ++i)
{
disTo[i] = std::numeric_limits<T>::max();
edge[i] = nullptr;
onQueue[i] = false;
}
disTo[s] = T{};
q.push(s);
onQueue[s] = true;
while (!q.empty() && !isnegativeCycle)
{
int v = q.front();
q.pop();
onQueue[v] = false;
relax(dwg, v);
}
}
void display_path(const int& e)
{
std::stack<int> sk;
sk.push(e);
for (auto ed = edge[e]; ed != nullptr; ed = edge[ed->from()])
{
sk.push(ed->from());
if (ed->from() == start)
break;
}
while (sk.size() > 1)
{
std::cout << sk.top() << "--> ";
sk.pop();
}
if (sk.size() == 1)
{
std::cout << sk.top() << endl;
sk.pop();
}
}
};
处理有无环问题:
DoCycle.h
#pragma once
#include "DiWeightGraph.h"
#include <memory>
#include <unordered_set>
#include <stack>
template <typename T>
class DoCycle
{
using Ed = typename DiWeightGraph<T>::AdjacentcyList::Edge;
class Equal
{
public:
Equal()
{
}
bool operator()(std::stack<Ed> lhs,std::stack<Ed> rhs)const
{
while (!lhs.empty())
{
int v1 = lhs.top().from();
if (rhs.empty())
return false;
int v2 = rhs.top().from();
if (v1 != v2)
return false;
lhs.pop();
rhs.pop();
}
if (!rhs.empty())
return false;
return true;
}
};
class Hash
{
public:
Hash()
{
}
size_t operator ()(const std::stack<Ed>& sk)const
{
size_t ret = std::hash<T>()(sk.top().weight);
return ret;
}
};
private:
bool iscycle;
std::unique_ptr<bool[]> onStacked;
std::unique_ptr<bool[]> marked;
std::unique_ptr<std::shared_ptr<Ed>[]> edge;
public:
std::unordered_set<std::stack<Ed>, Hash, Equal> cycle;
private:
void init(DiWeightGraph<T> *dwg)
{
for (int i = 0; i < dwg->nV; ++i)
{
onStacked[i] = false;
marked[i] = false;
edge[i] = nullptr;
}
}
void dfs(DiWeightGraph<T> *dwg,const int& s)
{
marked[s] = true;
onStacked[s] = true;
for (auto &e : dwg->adj[s])
{
int w = e.to();
if (!onStacked[w])
{
edge[w] = std::make_shared<Ed>(Ed(e.from(), e.to(), e.weight));
if (!marked[w])
dfs(dwg, w);
}
else
{
std::stack<Ed> sk;
sk.push(Ed(e.from(), e.to(), e.weight));
for (std::shared_ptr<Ed> i = edge[s]; i != nullptr; i = edge[i->from()])
{
sk.push(Ed(i->from(), i->to(), i->weight));
if (i->from() == w)
break;
}
cycle.insert(sk);
}
}
onStacked[s] = false;
}
void dfs(DiWeightGraph<T> *dwg)
{
for (int i = 0; i < dwg->nV; ++i)
{
init(dwg);
dfs(dwg, i);
}
}
public:
DoCycle(DiWeightGraph<T> *dwg):onStacked(new bool[dwg->nV]),marked(new bool[dwg->nV]),edge(new std::shared_ptr<Ed>[dwg->nV]),iscycle(false)
{
dfs(dwg);
if (!cycle.empty())
iscycle = true;
}
void display_cycle()
{
if (!iscycle)
return;
int i = 1;
for (auto sk : cycle)
{
int loop = sk.top().from();
std::cout << "第" << i << "个环: ";
while (!sk.empty())
{
std::cout << sk.top().from() << "--> ";
sk.pop();
}
std::cout << loop << std::endl;
++i;
}
}
bool Is_cycle()
{
return iscycle;
}
};
处理负权重环问题:
#pragma once
#include <stack>
#include "DiWeightGraph.h"
template <typename T>
class DiDoCycle
{
using Ed = typename DiWeightGraph<T>::AdjacentcyList::Edge;
private:
bool isnegative;
T negativeWeight;
public:
DiDoCycle(DiWeightGraph<T> *dwg):isnegative(false),negativeWeight()
{
DoCycle<T> dc(dwg);
std::stack<Ed> get;
for (auto sk : dc.cycle)
{
if (sk.size() == dwg->nE)
{
get = sk;
break;
}
}
while (!get.empty())
{
negativeWeight += get.top().weight;
get.pop();
}
if (negativeWeight < 0)
{
isnegative = true;
}
}
bool negative()
{
return isnegative;
}
T negative_Weight()
{
if (negative)
retrurn negativeWeight;
else
throw std::out_of_range("not is nagative");
}
};
用于可验证处理无环图来验证其正确性(可舍去)
#pragma once
#include "DiWeightGraph.h"
#include <stack>
#include "DoCycle.h"
template <typename T>
class NoCycleSP
{
using Ed = typename DiWeightGraph<T>::AdjacentcyList::Edge;
private:
std::unique_ptr<bool[]> marked;
std::unique_ptr<T[]> disTo;
std::stack<int> resufdfs;
Ed **edge;
int start;
bool iscycle;
private:
void dfs(DiWeightGraph<T> *dwg, const int& s)
{
marked[s] = true;
for (auto &e : dwg->adj[s])
{
int w = e.to();
if (!marked[w])
{
dfs(dwg, w);
}
}
resufdfs.push(s);
}
void dfs(DiWeightGraph<T> *dwg)
{
if (iscycle)
throw std::domain_error("there exist cycle");
for (int i = 0; i < dwg->nV; ++i)
if (!marked[i]) dfs(dwg, i);
}
void relax(DiWeightGraph<T> *dwg,const int& s)
{
for (auto &e : dwg->adj[s])
{
int w = e.to();
if (disTo[w] > disTo[s] + e.weight)
{
disTo[w] = disTo[s] + e.weight;
edge[w] = new Ed(s, w, e.weight);
}
}
}
public:
NoCycleSP(DiWeightGraph<T>* dwg,const int& s):marked(new bool[dwg->nV]),disTo(new T[dwg->nV]),start(s),edge(new Ed*[dwg->nV]),iscycle(false)
{
for (int i = 0; i < dwg->nV; ++i)
{
marked[i] = false;
disTo[i] = std::numeric_limits<T>::max();
edge[i] = nullptr;
}
DoCycle<T> dc(dwg);
iscycle = dc.Is_cycle();
dfs(dwg);
disTo[start] = T{};
while (!resufdfs.empty())
{
int w = resufdfs.top();
resufdfs.pop();
relax(dwg, w);
}
}
T getWeight(const int& e)
{
return disTo[e];
}
void display_path(const int& e)
{
std::stack<int> sk;
sk.push(e);
for (auto ed = edge[e]; ed != nullptr; ed = edge[ed->from()])
{
sk.push(ed->from());
if (ed->from() == start)
break;
}
while (sk.size() > 1)
{
std::cout << sk.top() << "--> ";
sk.pop();
}
if (sk.size() == 1)
{
std::cout << sk.top() << endl;
sk.pop();
}
}
};
负权重环图: test.txt
8
4 5 0.35
5 4 0.35
4 7 0.37
5 7 0.28
7 5 0.28
5 1 0.32
0 4 0.38
0 2 0.26
7 3 0.39
1 3 0.29
2 7 0.34
6 2 -1.20
3 6 0.52
6 0 -1.40
6 4 -1.25
无环图:
8
5 4 0.35
4 7 0.37
5 7 0.28
5 1 0.32
4 0 0.38
0 2 0.26
3 7 0.39
1 3 0.29
7 2 0.34
6 2 0.40
3 6 0.52
6 0 0.58
6 4 0.93
main.cpp
#include <iostream>
#include "DiWeightGraph.h"
#include "DoCycle.h"
#include "DiDoCycle.h"
#include "BellmanFordSP.h"
#include "NoCycleSP.h"
using namespace std;
int main()
{
DiWeightGraph<double> dwg("Text.txt");
cout << "BellmanFordSP:" << endl;
BellmanFordSP<double> bfsp(&dwg, 5);
bfsp.display_path(6);
cout << "NoCycleSP: " << endl;
NoCycleSP<double> ncsp(&dwg,5);
ncsp.display_path(6);
system("pause");
return 0;
}
注释掉NoCycleSP内容:改用 Text.txt 寻 0->1路径