用一个Edge类描述顶点与边
#pragma once
#include <iostream>
#include <cassert>
using namespace std;
template<typename Weight>
class Edge {
private:
int a, b;
Weight weight;
public:
Edge(int a, int b, Weight weight) {
this->a = a;
this->b = b;
this->weight = weight;
}
Edge() {
}
~Edge(){
}
int v() {
return a; }
int w() {
return b; }
Weight wt() {
return weight; }
int other(int x) {
assert(x == a || x == b);
return x == a ? b : a;
}
friend ostream& operator<<(ostream& os, const Edge& e) {
os << e.a << "-" << e.b << ":" << e.weight;
return os;
}
bool operator<(Edge<Weight>& e) {
return weight < e.wt();
}
bool operator<=(Edge<Weight>& e) {
return weight <= e.wt();
}
bool operator>(Edge<Weight>& e) {
return weight > e.wt();
}
bool operator>=(Edge<Weight>& e) {
return weight >= e.wt();
}
bool operator==(Edge<Weight>& e) {
return weight == e.wt();
}
};
在DenseGraph 和 SparseGraph中加上权值信息
- DenseGraph
#pragma once
#include <iostream>
#include <vector>
#include <cassert>
#include "Edge.h"
using namespace std;
template<typename Weight>
class DenseGraph {
private:
int n, m;
vector<vector<Edge<Weight>*>> g;
bool directed;
public:
DenseGraph(int n, bool directed) {
assert(n >= 0