forked from matanb1238/NumberWithUnits-A
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.cpp
85 lines (78 loc) · 2.33 KB
/
graph.cpp
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
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <string>
#include <iterator>
#include <map>
#include <queue>
#include <set>
#include <list>
#include <stack>
using namespace std;
class graph{
protected:
map<string, map<string, double>> the_graph;
set<string> nodes;
map<string,set<string>> edges_from;
public:
bool checkExist(const string& node){
return (nodes.count(node) > 0);
}
void addOut(const string &src, const string &dst){
if (edges_from.count(src) > 0)
{
edges_from[src].insert(dst);
}else{
set<string> temp{dst};
edges_from[src] = temp;
}
}
void addEdge(const string &src, const string &dst, double weight){
addNode(src);addNode(dst);
the_graph[src][dst] = weight;
the_graph[dst][src] = ((double)1)/weight;
addOut(src,dst);
addOut(dst,src);
}
void addNode(const string &_node){
nodes.insert(_node);
}
double getWeight(const string &src, const string &dst){
if(the_graph[src][dst] <= 0){
return -1;
}
return the_graph[src][dst];
}
// void print(std::list<std::string> const &list)
// {
// for (auto const &i : list)
// {
// std::cout << i << " |-> ";
// }
// cout << endl;
// }
double getConv(const string &src, const string &dst){
stack<string> s;
set<string> visited;
map<string, double> con;
s.push(src);
con[src] = 1;
while(!s.empty()){
string cur = s.top();
s.pop();
if(visited.count(cur) < 1){
visited.insert(cur);
if (cur == dst){
return con[cur];
}
for (string str : edges_from[cur])
{
if (visited.count(str) < 1)
{
con[str] = getWeight(cur, str) * con[cur];
s.push(str);
}
}
}
}
return -1;
}
};