-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtc.hpp
More file actions
321 lines (297 loc) · 10.6 KB
/
tc.hpp
File metadata and controls
321 lines (297 loc) · 10.6 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/**
* @file tc.hpp
*
* @brief Triangle counting for undirected and directed graphs.
*
* This file provides efficient algorithms for counting triangles in graphs:
* - `triangle_count`: Counts triangles (3-cliques) in undirected graphs.
* - `directed_triangle_count`: Counts directed 3-cycles in directed graphs.
*
* A triangle consists of three vertices where each pair is connected by an edge.
*
* The algorithms require sorted adjacency lists for correctness and optimal performance.
* They use a merge-based set intersection approach that is more efficient than nested loops
* or hash-based methods for sparse graphs.
*
* @copyright Copyright (c) 2022
*
* SPDX-License-Identifier: BSL-1.0
*
* @authors
* Andrew Lumsdaine
* Phil Ratzloff
* Kevin Deweese
*/
#include "graph/graph.hpp"
#include "graph/views/incidence.hpp"
#include <ranges>
#ifndef GRAPH_TC_HPP
# define GRAPH_TC_HPP
namespace graph {
// Using declarations for new namespace structure
using adj_list::adjacency_list;
using adj_list::ordered_vertex_edges;
using adj_list::vertex_id_t;
using adj_list::vertices;
using adj_list::edges;
using adj_list::target_id;
using adj_list::vertex_id;
using adj_list::num_vertices;
/**
* @ingroup graph_algorithms
* @brief Count triangles in an undirected graph with sorted adjacency lists.
*
* A triangle is a set of three vertices {u, v, w} where edges (u,v), (v,w), and (u,w) all exist.
* For each edge (u,v) where u < v, the algorithm uses merge-based set intersection of sorted
* adjacency lists to find common neighbors w > v, ensuring each triangle is counted exactly once.
*
* @tparam G Graph type satisfying adjacency_list with ordered edges.
*
* @param g The graph to analyze. Must be undirected with sorted adjacency lists.
*
* @return Total number of triangles in the graph.
*
* **Mandates:**
* - G must satisfy adjacency_list
* - G must satisfy ordered_vertex_edges (adjacency lists sorted by target ID)
*
* **Preconditions:**
* - Graph must store undirected edges bidirectionally (both (u,v) and (v,u))
* - Adjacency lists must be sorted by target_id in ascending order
*
* **Effects:**
* - Iterates over all edges and computes triangle count
* - Does not modify the graph g
*
* **Postconditions:**
* - Return value is non-negative
* - For empty graphs or graphs with < 3 vertices, returns 0
* - Graph g remains unmodified
*
* **Returns:**
* - Total number of triangles (size_t)
* - Attribute: [[nodiscard]]
*
* **Throws:**
* - Never throws (noexcept). Uses only non-throwing operations (arithmetic, iteration).
* - Exception guarantee: Strong (no-throw guarantee).
*
* **Complexity:**
* - Time: O(V + E) best case (no triangles); O(m^(3/2)) average (sparse, m = E);
* O(V * d_max^2) worst case (d_max = max degree). For dense graphs (E ~ V^2), approaches O(V^3).
* - Space: O(1) auxiliary (excluding graph storage)
*
* **Remarks:**
* - Optimized for sparse graphs; for very dense graphs consider matrix multiplication approaches
* - The ordering constraints (u < v, w > v) ensure each triangle is counted exactly once
* - Uses merge-based intersection of sorted ranges, similar to std::set_intersection
*
* **Supported Graph Properties:**
*
* Directedness:
* - ✅ Undirected graphs (each edge stored bidirectionally)
* - ⚠️ Directed graphs: Results may not be meaningful; counts directed 3-cycles
*
* Edge Properties:
* - ✅ Unweighted edges
* - ✅ Weighted edges (weights ignored)
* - ⚠️ Multi-edges: Each parallel edge contributes to triangle count
* - ✅ Self-loops: Ignored (cannot form triangles)
*
* Graph Structure:
* - ✅ Connected graphs
* - ✅ Disconnected graphs
* - ✅ May contain cycles (triangles are 3-cycles)
*
* ## Example Usage
*
* ```cpp
* #include <graph/algorithm/tc.hpp>
*
* // Create triangle: vertices {0, 1, 2} with edges (0,1), (1,2), (0,2) bidirectional
* Graph g({{0, 1}, {1, 0}, {1, 2}, {2, 1}, {0, 2}, {2, 0}});
*
* size_t count = triangle_count(g);
* // count == 1 (one triangle: {0, 1, 2})
* ```
*
* @see directed_triangle_count
*/
template <adjacency_list G>
requires ordered_vertex_edges<G>
[[nodiscard]] size_t triangle_count(G&& g) noexcept {
size_t triangles = 0;
// ============================================================================
// Main loop: Process each vertex as the "first" vertex in potential triangles
// ============================================================================
for (auto u : vertices(g)) {
auto uid = vertex_id(g, u);
auto u_edges = edges(g, u);
auto u_it = std::ranges::begin(u_edges);
auto u_end = std::ranges::end(u_edges);
// ==========================================================================
// For each neighbor v of u, find triangles containing edge (u,v)
// ==========================================================================
while (u_it != u_end) {
auto vid = target_id(g, *u_it);
// Only process edges where uid < vid to avoid counting the same edge twice
// (since undirected graphs store both (u,v) and (v,u))
if (uid < vid) {
// Get adjacency list for vertex v
auto v_edges = edges(g, vid);
auto v_it = std::ranges::begin(v_edges);
auto v_end = std::ranges::end(v_edges);
// Skip past neighbors we've already processed (uid through vid)
// Start checking for common neighbors after vid
auto u_remaining = std::next(u_it);
// ======================================================================
// Merge-based intersection: Find vertices adjacent to BOTH u and v
// This forms triangles {u, v, w} where w is a common neighbor
// ======================================================================
while (u_remaining != u_end && v_it != v_end) {
auto wid_from_u = target_id(g, *u_remaining); // Candidate from u's adjacency list
auto wid_from_v = target_id(g, *v_it); // Candidate from v's adjacency list
if (wid_from_u < wid_from_v) {
// u's neighbor is smaller - advance u's iterator
++u_remaining;
} else if (wid_from_v < wid_from_u) {
// v's neighbor is smaller - advance v's iterator
++v_it;
} else {
// Found common neighbor w: both u and v are adjacent to w
// This forms a triangle {uid, vid, wid}
// Only count if wid > vid (ensures ordering: uid < vid < wid)
// This guarantees each triangle is counted exactly once
if (wid_from_u > vid) {
++triangles;
}
// Advance both iterators past this common neighbor
++u_remaining;
++v_it;
}
}
}
++u_it; // Move to next neighbor of u
}
}
return triangles;
}
/**
* @ingroup graph_algorithms
* @brief Count directed 3-cycles in a directed graph with sorted adjacency lists.
*
* A directed 3-cycle is a set of three vertices {u, v, w} where directed edges
* u->v, v->w, and u->w all exist. For each edge (u,v) where v != u, the algorithm
* finds common out-neighbors w of both u and v (w != u, w != v) using merge-based
* set intersection. Each ordered triple (u, v, w) is visited exactly once.
*
* @tparam G Graph type satisfying adjacency_list with ordered edges.
*
* @param g The directed graph to analyze. Must have sorted adjacency lists.
*
* @return Total number of directed 3-cycles in the graph.
*
* **Mandates:**
* - G must satisfy adjacency_list
* - G must satisfy ordered_vertex_edges (adjacency lists sorted by target ID)
*
* **Preconditions:**
* - Adjacency lists must be sorted by target_id in ascending order
*
* **Effects:**
* - Iterates over all edges and computes directed 3-cycle count
* - Does not modify the graph g
*
* **Postconditions:**
* - Return value is non-negative
* - For empty graphs or graphs with < 3 vertices, returns 0
* - Graph g remains unmodified
*
* **Returns:**
* - Total number of directed 3-cycles (size_t)
* - Attribute: [[nodiscard]]
*
* **Throws:**
* - Never throws (noexcept). Uses only non-throwing operations (arithmetic, iteration).
* - Exception guarantee: Strong (no-throw guarantee).
*
* **Complexity:**
* - Time: O(m^(3/2)) average (sparse, m = E); O(V * d_max^2) worst case (d_max = max out-degree)
* - Space: O(1) auxiliary
*
* **Remarks:**
* - For undirected graphs stored with bidirectional edges, this counts each undirected
* triangle 6 times (once per permutation). Use triangle_count instead.
* - Self-loops are skipped during enumeration
*
* **Supported Graph Properties:**
*
* Directedness:
* - ✅ Directed graphs (recommended)
* - ⚠️ Undirected graphs: Each triangle counted 6 times; use triangle_count instead
*
* Edge Properties:
* - ✅ Unweighted edges
* - ✅ Weighted edges (weights ignored)
* - ✅ Self-loops: Skipped
*
* Graph Structure:
* - ✅ Connected graphs
* - ✅ Disconnected graphs
*
* ## Example Usage
*
* ```cpp
* #include <graph/algorithm/tc.hpp>
*
* // Directed 3-cycle: 0->1, 1->2, 0->2
* size_t count = directed_triangle_count(g);
* // count == 1
* ```
*
* @see triangle_count
*/
template <adjacency_list G>
requires ordered_vertex_edges<G>
[[nodiscard]] size_t directed_triangle_count(G&& g) noexcept {
size_t triangles = 0;
for (auto u : vertices(g)) {
auto uid = vertex_id(g, u);
auto u_edges = edges(g, u);
auto u_it = std::ranges::begin(u_edges);
auto u_end = std::ranges::end(u_edges);
while (u_it != u_end) {
auto vid = target_id(g, *u_it);
// Skip self-loops
if (vid != uid) {
// Get adjacency list for vertex v
auto v_edges = edges(g, vid);
auto v_it = std::ranges::begin(v_edges);
auto v_end = std::ranges::end(v_edges);
// Scan all of u's out-neighbors (not just those after v)
auto u_remaining = std::ranges::begin(u_edges);
// Merge-based intersection of u's and v's out-neighbor lists
while (u_remaining != u_end && v_it != v_end) {
auto wid_from_u = target_id(g, *u_remaining);
auto wid_from_v = target_id(g, *v_it);
if (wid_from_u < wid_from_v) {
++u_remaining;
} else if (wid_from_v < wid_from_u) {
++v_it;
} else {
// Common out-neighbor w found; skip if w is u or v (self-loop)
if (wid_from_u != uid && wid_from_u != vid) {
++triangles;
}
++u_remaining;
++v_it;
}
}
}
++u_it;
}
}
return triangles;
}
} // namespace graph
#endif //GRAPH_TC_HPP