NetOptim 1.2.8
Loading...
Searching...
No Matches
primal_dual.hpp
Go to the documentation of this file.
1// -*- coding: utf-8 -*-
2#pragma once
3
4#include <algorithm>
5#include <stdexcept>
6#include <utility>
7
21
64template <typename Graph, typename C1, typename C2>
65auto min_vertex_cover_pd(const Graph& gra, C1& cover, const C2& weight) {
66 using T = typename C2::value_type;
67
68 [[maybe_unused]] auto total_dual_cost = T(0);
69 auto total_primal_cost = T(0);
70 auto gap = weight;
71 for (auto&& edge : gra.edges()) {
72 auto [utx, vtx] = edge.end_points();
73 if (cover[utx] || cover[vtx]) {
74 continue;
75 }
76 if (gap[utx] < gap[vtx]) {
77 std::swap(utx, vtx);
78 }
79 cover[vtx] = true;
80 total_dual_cost += gap[vtx];
81 total_primal_cost += weight[vtx];
82 gap[utx] -= gap[vtx];
83 gap[vtx] = T(0);
84 }
85
86 if (total_dual_cost > total_primal_cost) {
87 throw std::logic_error(
88 "min_vertex_cover_pd: dual cost exceeds primal cost (invalid weights?)");
89 }
90 if (total_primal_cost > 2 * total_dual_cost) {
91 throw std::logic_error(
92 "min_vertex_cover_pd: 2-approximation guarantee violated (invalid weights?)");
93 }
94 return total_primal_cost;
95}
96
146template <typename Graph, typename C1, typename C2>
147auto min_maximal_independant_set_pd(const Graph& gra, C1& indset, C1& dep, const C2& weight) {
148 using T = typename C2::value_type;
149
150 if (&indset == &dep) {
151 throw std::invalid_argument("min_maximal_independant_set_pd: indset and dep must differ");
152 }
153
154 auto cover = [&](const auto& utx) {
155 dep[utx] = true;
156 for (auto&& vtx : gra[utx]) {
157 dep[vtx] = true;
158 }
159 };
160
161 auto gap = weight;
162 auto total_primal_cost = T(0);
163 for (auto&& utx : gra) {
164 if (dep[utx]) {
165 continue;
166 }
167 if (indset[utx]) { // pre-define independant
168 cover(utx);
169 continue;
170 }
171 auto min_val = gap[utx];
172 auto min_vtx = utx;
173 for (auto&& vtx : gra[utx]) {
174 if (dep[vtx]) {
175 continue;
176 }
177 if (min_val > gap[vtx]) {
178 min_val = gap[vtx];
179 min_vtx = vtx;
180 }
181 }
182 cover(min_vtx);
183 indset[min_vtx] = true;
184 total_primal_cost += weight[min_vtx];
185 if (min_vtx == utx) {
186 continue;
187 }
188 for (auto&& vtx : gra[utx]) {
189 gap[vtx] -= min_val;
190 }
191 }
192 return total_primal_cost;
193}
auto min_vertex_cover_pd(const Graph &gra, C1 &cover, const C2 &weight)
Minimum weighted vertex cover using primal-dual algorithm.
Definition primal_dual.hpp:65
auto min_maximal_independant_set_pd(const Graph &gra, C1 &indset, C1 &dep, const C2 &weight)
Minimum maximal independent set using primal-dual algorithm.
Definition primal_dual.hpp:147