AlgoPlus v0.1.0
Loading...
Searching...
No Matches
hill_climbing.h
1#ifndef HILL_CLIMBING_H
2#define HILL_CLIMBING_H
3
4#ifdef __cplusplus
5#include <climits>
6#include <iostream>
7#include <limits>
8#include <queue>
9#include <unordered_map>
10#endif
11
15template <typename T> class hill_climbing {
16 private:
17 std::unordered_map<T, std::vector<std::pair<T, double>>> adj;
18 std::unordered_map<T, double> nodes;
19
20 public:
28 explicit hill_climbing(std::unordered_map<T, std::vector<std::pair<T, double>>> v = {},
29 std::unordered_map<T, double> nodes = {}) {
30 if (!v.empty()) {
31 this->adj = v;
32 }
33 if (!nodes.empty()) {
34 this->nodes = nodes;
35 }
36 }
37
43 inline void insert_node(T u, double val) { nodes[u] = val; }
44
52 inline bool has_edge(T u, T v) {
53 if (adj.find(u) != adj.end()) {
54 for (std::pair<T, double>& x : adj[u]) {
55 if (x.first == v) {
56 return true;
57 }
58 }
59 }
60 return false;
61 }
62
68 inline void add_edge(T u, T v) {
69 try {
70 if (nodes.find(u) != nodes.end() && nodes.find(v) != nodes.end()) {
71 adj[u].push_back(std::make_pair(v, nodes[v]));
72 } else {
73 throw std::logic_error("One of the two nodes that passed to the "
74 "function do not exist in the graph");
75 }
76 } catch (std::logic_error& e) {
77 std::cerr << e.what() << '\n';
78 }
79 }
80
88 inline bool search(T start, T end) {
89 if (adj.empty()) {
90 return false;
91 }
92 std::unordered_map<T, bool> visited;
93 std::queue<T> q;
94 q.push(start);
95 visited[start] = true;
96 while (!q.empty()) {
97 int64_t size = q.size();
98 for (int64_t i = 0; i < size; i++) {
99 T current = q.front();
100 if (current == end) {
101 return true;
102 }
103 q.pop();
104 double minim = std::numeric_limits<double>::max();
105 T neigh = current;
106 for (std::pair<T, double>& x : adj[current]) {
107 if (visited.find(x.first) == visited.end()) {
108 visited[x.first] = true;
109 minim = std::min(minim, x.second);
110 neigh = x.first;
111 }
112 }
113 if (minim != INT_MAX && neigh != current) {
114 if (current == start || minim <= nodes[current]) {
115 q.push(neigh);
116 }
117 }
118 }
119 }
120 return false;
121 }
122};
123
124#endif
hill_climbing(std::unordered_map< T, std::vector< std::pair< T, double > > > v={}, std::unordered_map< T, double > nodes={})
hill_climbing constructor
Definition hill_climbing.h:28
bool has_edge(T u, T v)
has_edge function
Definition hill_climbing.h:52
bool search(T start, T end)
search function
Definition hill_climbing.h:88
void add_edge(T u, T v)
add_edge function
Definition hill_climbing.h:68
void insert_node(T u, double val)
insert_node function
Definition hill_climbing.h:43