-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.h
71 lines (60 loc) · 1.67 KB
/
graph.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
typedef int NodeIndex;
template <typename NodeName>
class Graph
{
public:
Graph()
{
}
void addEdge(NodeName fromName, NodeName toName, int weight)
{
NodeIndex fromIndex = getOrCreateNodeIndex(fromName);
NodeIndex toIndex = getOrCreateNodeIndex(toName);
_edgeWeights[fromIndex][toIndex] = weight;
}
NodeIndex getNodeIndex(NodeName name) const
{
auto itr = find(_nodeNames.begin(), _nodeNames.end(), name);
return (itr == _nodeNames.end()) ? -1 : itr - _nodeNames.begin();
}
NodeName getNodeName(NodeIndex index) const
{
return _nodeNames[index];
}
NodeIndex getOrCreateNodeIndex(NodeName name)
{
NodeIndex index = getNodeIndex(name);
if (index >= 0)
return index;
else
return createNode(name);
}
size_t getNodeCount() const { return _nodeNames.size(); }
void dump()
{
cout << "Nodes: " << _nodeNames.size() << endl;
for (size_t i = 0; i < _nodeNames.size(); i++)
{
cout << " " << _nodeNames[i] << ": ";
for (auto weights: _edgeWeights[i])
{
cout << _nodeNames[weights.first] << " " << weights.second << " ";
}
cout << endl;
}
}
protected:
NodeIndex createNode(NodeName name)
{
_nodeNames.push_back(name);
_edgeWeights.push_back(map<NodeIndex,int>());
return _nodeNames.size() - 1;
}
vector<NodeName> _nodeNames;
vector<map<NodeIndex,int>> _edgeWeights;
};