|
| 1 | +#include <iostream> |
| 2 | +#include <unordered_map> |
| 3 | +#include <unordered_set> |
| 4 | +#include <vector> |
| 5 | +#include <random> |
| 6 | +#include "Node_impl.h" |
| 7 | + |
| 8 | +namespace CXXGraph { |
| 9 | + |
| 10 | +template <typename T> |
| 11 | +class Graph { |
| 12 | +private: |
| 13 | + std::unordered_map<CXXGraph::id_t, Node<T>> nodes; |
| 14 | + std::unordered_map<CXXGraph::id_t, std::unordered_set<CXXGraph::id_t>> adjacency_list; |
| 15 | + |
| 16 | +public: |
| 17 | + // Other graph methods... |
| 18 | + |
| 19 | + // Function to add an edge between two nodes |
| 20 | + void addEdge(const std::string& from_id, const std::string& to_id) { |
| 21 | + adjacency_list[from_id].insert(to_id); |
| 22 | + adjacency_list[to_id].insert(from_id); |
| 23 | + // Assuming nodes are already added to the graph |
| 24 | + } |
| 25 | + |
| 26 | + // Krager's algorithm for graph partitioning |
| 27 | + std::pair<std::unordered_set<CXXGraph::id_t>, std::unordered_set<CXXGraph::id_t>> kragersAlgorithm() { |
| 28 | + // Initialize clusters |
| 29 | + std::unordered_set<CXXGraph::id_t> cluster1; |
| 30 | + std::unordered_set<CXXGraph::id_t> cluster2; |
| 31 | + for (const auto& node_pair : nodes) { |
| 32 | + cluster1.insert(node_pair.first); |
| 33 | + } |
| 34 | + |
| 35 | + // Perform Krager's algorithm |
| 36 | + std::random_device rd; |
| 37 | + std::mt19937 gen(rd()); |
| 38 | + while (cluster1.size() > 2) { |
| 39 | + // Select a random edge |
| 40 | + std::uniform_int_distribution<size_t> dist(0, adjacency_list.size() - 1); |
| 41 | + size_t rand_index = dist(gen); |
| 42 | + auto it = std::next(std::begin(adjacency_list), rand_index); |
| 43 | + CXXGraph::id_t u = it->first; |
| 44 | + auto& neighbors = it->second; |
| 45 | + std::uniform_int_distribution<size_t> dist_neighbor(0, neighbors.size() - 1); |
| 46 | + size_t rand_neighbor_index = dist_neighbor(gen); |
| 47 | + auto neighbor_it = std::next(std::begin(neighbors), rand_neighbor_index); |
| 48 | + CXXGraph::id_t v = *neighbor_it; |
| 49 | + |
| 50 | + // Merge clusters if the vertices belong to different clusters |
| 51 | + if (cluster1.count(u) && cluster1.count(v)) { |
| 52 | + cluster1.erase(v); |
| 53 | + cluster2.insert(v); |
| 54 | + } else if (cluster2.count(u) && cluster1.count(v)) { |
| 55 | + cluster1.erase(v); |
| 56 | + cluster2.insert(v); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return {cluster1, cluster2}; |
| 61 | + } |
| 62 | +}; |
| 63 | + |
| 64 | +} // namespace CXXGraph |
0 commit comments