problemreductions/models/graph/
monochromatic_triangle.rs1use crate::registry::{FieldInfo, ProblemSchemaEntry, VariantDimension};
9use crate::topology::{Graph, SimpleGraph};
10use crate::traits::Problem;
11use crate::variant::VariantParam;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14
15inventory::submit! {
16 ProblemSchemaEntry {
17 name: "MonochromaticTriangle",
18 display_name: "Monochromatic Triangle",
19 aliases: &[],
20 dimensions: &[
21 VariantDimension::new("graph", "SimpleGraph", &["SimpleGraph"]),
22 ],
23 category: crate::registry::ProblemCategory::Graph,
24 module_path: module_path!(),
25 description: "2-color edges so that no triangle is monochromatic",
26 fields: &[
27 FieldInfo { name: "graph", type_name: "G", description: "The underlying graph G=(V,E)" },
28 ],
29 }
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
61#[serde(bound(deserialize = "G: serde::Deserialize<'de>"))]
62pub struct MonochromaticTriangle<G> {
63 graph: G,
65 triangles: Vec<[usize; 3]>,
67 edge_list: Vec<(usize, usize)>,
69}
70
71impl<G: Graph> MonochromaticTriangle<G> {
72 pub fn new(graph: G) -> Self {
74 let edge_list = graph.edges();
75 let mut edge_index: HashMap<(usize, usize), usize> = HashMap::new();
77 for (idx, &(u, v)) in edge_list.iter().enumerate() {
78 let key = if u < v { (u, v) } else { (v, u) };
79 edge_index.insert(key, idx);
80 }
81
82 let n = graph.num_vertices();
85 let mut triangles = Vec::new();
86 for u in 0..n {
87 for v in (u + 1)..n {
88 if !graph.has_edge(u, v) {
89 continue;
90 }
91 for w in (v + 1)..n {
92 if graph.has_edge(u, w) && graph.has_edge(v, w) {
93 let e_uv = edge_index[&(u, v)];
94 let e_uw = edge_index[&(u, w)];
95 let e_vw = edge_index[&(v, w)];
96 triangles.push([e_uv, e_uw, e_vw]);
97 }
98 }
99 }
100 }
101
102 Self {
103 graph,
104 triangles,
105 edge_list,
106 }
107 }
108
109 pub fn graph(&self) -> &G {
111 &self.graph
112 }
113
114 pub fn num_vertices(&self) -> usize {
116 self.graph.num_vertices()
117 }
118
119 pub fn num_edges(&self) -> usize {
121 self.graph.num_edges()
122 }
123
124 pub fn triangles(&self) -> &[[usize; 3]] {
126 &self.triangles
127 }
128
129 pub fn num_triangles(&self) -> usize {
131 self.triangles.len()
132 }
133
134 pub fn edge_list(&self) -> &[(usize, usize)] {
136 &self.edge_list
137 }
138}
139
140impl<G> Problem for MonochromaticTriangle<G>
141where
142 G: Graph + VariantParam,
143{
144 const NAME: &'static str = "MonochromaticTriangle";
145 type Solution = Vec<bool>;
146 type Value = crate::types::Or;
147
148 crate::problem_parameters![
149 ("num_edges", num_edges),
150 ("num_triangles", num_triangles),
151 ("num_vertices", num_vertices),
152 ];
153
154 fn variant() -> Vec<(&'static str, &'static str)> {
155 crate::variant_params![G]
156 }
157
158 fn evaluate(
159 &self,
160 config: &Self::Solution,
161 ) -> Result<crate::types::Or, crate::traits::EvaluationError> {
162 Ok({
163 crate::types::Or({
164 if config.len() != self.edge_list.len() {
165 return Err(crate::traits::EvaluationError::InvalidConfiguration(
166 "edge-coloring length does not match the graph".into(),
167 ));
168 }
169
170 for tri in &self.triangles {
173 let c0 = config[tri[0]];
174 let c1 = config[tri[1]];
175 let c2 = config[tri[2]];
176 if c0 == c1 && c1 == c2 {
177 return Ok(crate::types::Or(false));
178 }
179 }
180
181 true
182 })
183 })
184 }
185}
186
187impl<G> crate::solvers::BruteForceProblem for MonochromaticTriangle<G>
188where
189 G: Graph + VariantParam,
190{
191 fn dimensions(&self) -> Vec<usize> {
192 vec![2; self.edge_list.len()]
193 }
194}
195
196crate::declare_variants! {
197 default MonochromaticTriangle<SimpleGraph> => "2^num_edges",
198}
199
200crate::register_brute_force! {
201 MonochromaticTriangle<SimpleGraph> decode |_, indices: Vec<usize>| crate::config::config_to_bits(&indices),
202}
203
204#[cfg(feature = "example-db")]
205pub(crate) fn canonical_model_example_specs() -> Vec<crate::example_db::specs::ModelExampleSpec> {
206 vec![crate::example_db::specs::ModelExampleSpec {
214 id: "monochromatic_triangle_simplegraph",
215 instance: Box::new(MonochromaticTriangle::new(SimpleGraph::new(
216 4,
217 vec![(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)],
218 ))),
219 optimal_config: serde_json::json!(vec![false, false, true, true, false, true]),
220 optimal_value: serde_json::json!(true),
221 }]
222}
223
224#[cfg(test)]
225#[path = "../../unit_tests/models/graph/monochromatic_triangle.rs"]
226mod tests;