Count Four Cycles
(graph/count_four_cycles.hpp)
- View this file on GitHub
- Last update: 2026-08-13 01:41:40+09:00
- Include:
#include "graph/count_four_cycles.hpp"
Overview
This header counts subgraphs isomorphic to the four-edge cycle $C_4$. It can return either the total number of four-cycles or, for every graph edge id, the number of four-cycles containing that particular edge.
The implementation compresses parallel edges into multiplicities, orders vertices by degree, and counts pairs of oriented length-two paths. This avoids enumerating vertex quadruples.
Graph Behavior
Every active edge is interpreted as undirected, including an edge inserted with
add_directed_edge. Inactive edges are ignored and receive a per-edge count of
zero. Parallel edges are supported and remain distinct choices: replacing one
side of a four-cycle by k parallel edges creates k different four-edge
subgraphs. Self-loops are not supported.
The per-edge result has graph.edge_count() entries indexed by original edge
id. Each count refers to one particular edge copy, not its whole parallel-edge
group.
Functions
| Function | Exact signature | Description | Complexity |
|---|---|---|---|
count_four_cycles_per_edge |
template <class T> std::vector<long long> count_four_cycles_per_edge(const Graph<T>& graph) |
Returns the number of four-cycles containing every edge id. | $O(N + M\sqrt M)$ time and $O(N + M)$ memory |
count_four_cycles |
template <class T> long long count_four_cycles(const Graph<T>& graph) |
Returns the total number of four-cycles. | $O(N + M\sqrt M)$ time and $O(N + M)$ memory |
M denotes the number of active edges, including parallel copies. Counts must
fit in long long.
Example
#include "graph/count_four_cycles.hpp"
#include "graph/graph.hpp"
#include <cassert>
int main() {
m1une::graph::Graph<> graph(4);
graph.add_edge(0, 1);
graph.add_edge(1, 2);
graph.add_edge(2, 3);
graph.add_edge(3, 0);
graph.add_edge(0, 2);
assert(m1une::graph::count_four_cycles(graph) == 1);
auto per_edge = m1une::graph::count_four_cycles_per_edge(graph);
assert(per_edge[4] == 0); // The diagonal is not in the four-cycle.
}
Depends on
Required by
Verified with
verify/graph/count_four_cycles.test.cpp
verify/graph/cow_game.test.cpp
verify/graph/graph_algorithms.test.cpp
verify/graph/range_edge_graph.test.cpp
Code
#ifndef M1UNE_GRAPH_COUNT_FOUR_CYCLES_HPP
#define M1UNE_GRAPH_COUNT_FOUR_CYCLES_HPP 1
#include <algorithm>
#include <cassert>
#include <tuple>
#include <utility>
#include <vector>
#include "graph.hpp"
namespace m1une {
namespace graph {
namespace four_cycle_detail {
// Counts C4s containing one particular copy of each edge in a simple graph
// whose edge weights represent parallel-edge multiplicities.
inline std::vector<long long> count_simple_per_edge(
int vertex_count,
std::vector<int> first,
std::vector<int> second,
const std::vector<long long>& multiplicity
) {
const int edge_count = int(first.size());
assert(second.size() == first.size());
assert(multiplicity.size() == first.size());
std::vector<int> degree(vertex_count, 0);
for (int edge = 0; edge < edge_count; edge++) {
degree[first[edge]]++;
degree[second[edge]]++;
}
int maximum_degree = 0;
for (int value : degree) maximum_degree = std::max(maximum_degree, value);
std::vector<int> degree_start(maximum_degree + 2, 0);
for (int value : degree) degree_start[value + 1]++;
for (int value = 0; value <= maximum_degree; value++) {
degree_start[value + 1] += degree_start[value];
}
std::vector<int> cursor = degree_start;
std::vector<int> order(vertex_count);
for (int vertex = 0; vertex < vertex_count; vertex++) {
order[cursor[degree[vertex]]++] = vertex;
}
std::vector<int> rank(vertex_count);
for (int i = 0; i < vertex_count; i++) rank[order[i]] = i;
for (int edge = 0; edge < edge_count; edge++) {
first[edge] = rank[first[edge]];
second[edge] = rank[second[edge]];
if (first[edge] < second[edge]) {
std::swap(first[edge], second[edge]);
}
}
std::vector<int> start(vertex_count + 1, 0);
for (int vertex = 0; vertex < vertex_count; vertex++) {
start[vertex + 1] = start[vertex] + degree[order[vertex]];
}
std::vector<int> end = start;
std::vector<int> edge_at(2 * edge_count);
std::vector<int> to(2 * edge_count);
for (int edge = 0; edge < edge_count; edge++) {
int position = end[first[edge]]++;
edge_at[position] = edge;
to[position] = second[edge];
}
std::vector<int> downward_end = end;
for (int vertex = 0; vertex < vertex_count; vertex++) {
for (int i = start[vertex]; i < downward_end[vertex]; i++) {
int edge = edge_at[i];
int neighbor = to[i];
int position = end[neighbor]++;
edge_at[position] = edge;
to[position] = vertex;
}
}
std::vector<long long> path_count(vertex_count, 0);
std::vector<long long> result(edge_count, 0);
for (int vertex = vertex_count - 1; vertex >= 0; vertex--) {
for (int i = start[vertex]; i < end[vertex]; i++) {
int first_edge = edge_at[i];
int middle = to[i];
end[middle]--;
for (int j = start[middle]; j < end[middle]; j++) {
int second_edge = edge_at[j];
int opposite = to[j];
path_count[opposite] +=
multiplicity[first_edge] * multiplicity[second_edge];
}
}
for (int i = start[vertex]; i < end[vertex]; i++) {
int first_edge = edge_at[i];
int middle = to[i];
for (int j = start[middle]; j < end[middle]; j++) {
int second_edge = edge_at[j];
int opposite = to[j];
long long other_paths =
path_count[opposite] -
multiplicity[first_edge] * multiplicity[second_edge];
result[first_edge] +=
other_paths * multiplicity[second_edge];
result[second_edge] +=
other_paths * multiplicity[first_edge];
}
}
for (int i = start[vertex]; i < end[vertex]; i++) {
int middle = to[i];
for (int j = start[middle]; j < end[middle]; j++) {
path_count[to[j]] = 0;
}
}
}
return result;
}
} // namespace four_cycle_detail
// Returns, for every graph edge id, the number of C4 subgraphs containing it.
// Parallel active edges are distinct choices; inactive edges receive zero.
template <class T>
std::vector<long long> count_four_cycles_per_edge(const Graph<T>& graph) {
struct ActiveEdge {
int first;
int second;
int id;
};
std::vector<ActiveEdge> active_edges;
active_edges.reserve(graph.edge_count());
for (const Edge<T>& edge : graph.edges()) {
assert(edge.from != edge.to);
assert(0 <= edge.id && edge.id < graph.edge_count());
if (edge.from == edge.to) continue;
active_edges.push_back(ActiveEdge{
std::min(edge.from, edge.to),
std::max(edge.from, edge.to),
edge.id
});
}
std::sort(
active_edges.begin(),
active_edges.end(),
[](const ActiveEdge& left, const ActiveEdge& right) {
return std::tie(left.first, left.second) <
std::tie(right.first, right.second);
}
);
std::vector<int> first;
std::vector<int> second;
std::vector<long long> multiplicity;
std::vector<int> group_of_edge(graph.edge_count(), -1);
first.reserve(active_edges.size());
second.reserve(active_edges.size());
multiplicity.reserve(active_edges.size());
for (const ActiveEdge& edge : active_edges) {
if (first.empty() || first.back() != edge.first ||
second.back() != edge.second) {
first.push_back(edge.first);
second.push_back(edge.second);
multiplicity.push_back(0);
}
multiplicity.back()++;
group_of_edge[edge.id] = int(first.size()) - 1;
}
std::vector<long long> simple_result =
four_cycle_detail::count_simple_per_edge(
graph.size(),
std::move(first),
std::move(second),
multiplicity
);
std::vector<long long> result(graph.edge_count(), 0);
for (const ActiveEdge& edge : active_edges) {
result[edge.id] = simple_result[group_of_edge[edge.id]];
}
return result;
}
template <class T>
long long count_four_cycles(const Graph<T>& graph) {
std::vector<long long> per_edge = count_four_cycles_per_edge(graph);
long long incidence_count = 0;
for (long long count : per_edge) incidence_count += count;
assert(incidence_count % 4 == 0);
return incidence_count / 4;
}
} // namespace graph
} // namespace m1une
#endif // M1UNE_GRAPH_COUNT_FOUR_CYCLES_HPP#line 1 "graph/count_four_cycles.hpp"
#include <algorithm>
#include <cassert>
#include <tuple>
#include <utility>
#include <vector>
#line 1 "graph/graph.hpp"
#include <array>
#line 8 "graph/graph.hpp"
namespace m1une {
namespace graph {
template <class T = int>
struct Edge {
using cost_type = T;
int from;
int to;
T cost;
int id;
bool alive;
Edge() : from(-1), to(-1), cost(T()), id(-1), alive(true) {}
Edge(int from_, int to_, T cost_ = T(1), int id_ = -1, bool alive_ = true)
: from(from_), to(to_), cost(cost_), id(id_), alive(alive_) {}
int other(int v) const {
assert(v == from || v == to);
return from ^ to ^ v;
}
};
template <class T = int>
struct Graph {
using edge_type = Edge<T>;
using cost_type = T;
private:
struct EdgePositions {
std::array<std::pair<int, int>, 2> value{};
int size = 0;
void push_back(std::pair<int, int> position) {
assert(size < 2);
value[size++] = position;
}
};
int _n;
int _edge_count;
std::vector<std::vector<edge_type>> _g;
std::vector<EdgePositions> _edge_positions;
public:
Graph() : _n(0), _edge_count(0) {}
explicit Graph(int n) : _n(n), _edge_count(0), _g(n) {
assert(0 <= n);
}
int size() const {
return _n;
}
bool empty() const {
return _n == 0;
}
int edge_count() const {
return _edge_count;
}
int add_vertex() {
_g.emplace_back();
return _n++;
}
int add_directed_edge(int from, int to, T cost = T(1)) {
assert(0 <= from && from < _n);
assert(0 <= to && to < _n);
int id = _edge_count++;
int idx = int(_g[from].size());
_g[from].push_back(edge_type(from, to, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({from, idx});
return id;
}
int add_edge(int u, int v, T cost = T(1)) {
assert(0 <= u && u < _n);
assert(0 <= v && v < _n);
int id = _edge_count++;
int u_idx = int(_g[u].size());
_g[u].push_back(edge_type(u, v, cost, id));
int v_idx = int(_g[v].size());
_g[v].push_back(edge_type(v, u, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({u, u_idx});
_edge_positions.back().push_back({v, v_idx});
return id;
}
void set_edge_alive(int id, bool alive) {
assert(0 <= id && id < _edge_count);
for (int i = 0; i < _edge_positions[id].size; ++i) {
auto [v, idx] = _edge_positions[id].value[i];
_g[v][idx].alive = alive;
}
}
void erase_edge(int id) {
set_edge_alive(id, false);
}
void revive_edge(int id) {
set_edge_alive(id, true);
}
bool is_edge_alive(int id) const {
assert(0 <= id && id < _edge_count);
assert(_edge_positions[id].size != 0);
auto [v, idx] = _edge_positions[id].value[0];
return _g[v][idx].alive;
}
const std::vector<edge_type>& operator[](int v) const {
assert(0 <= v && v < _n);
return _g[v];
}
std::vector<edge_type>& operator[](int v) {
assert(0 <= v && v < _n);
return _g[v];
}
const std::vector<std::vector<edge_type>>& adjacency() const {
return _g;
}
std::vector<std::vector<edge_type>>& adjacency() {
return _g;
}
std::vector<edge_type> edges(bool include_inactive = false) const {
std::vector<edge_type> result;
result.reserve(_edge_count);
std::vector<char> used(_edge_count, false);
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
if (!include_inactive && !e.alive) continue;
if (0 <= e.id && e.id < _edge_count) {
if (used[e.id]) continue;
used[e.id] = true;
}
result.push_back(e);
}
}
return result;
}
Graph reversed() const {
Graph result(_n);
result._edge_count = _edge_count;
result._edge_positions.assign(_edge_count, {});
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
int idx = int(result._g[e.to].size());
result._g[e.to].push_back(edge_type(e.to, e.from, e.cost, e.id, e.alive));
if (0 <= e.id && e.id < _edge_count) result._edge_positions[e.id].push_back({e.to, idx});
}
}
return result;
}
};
} // namespace graph
} // namespace m1une
#line 11 "graph/count_four_cycles.hpp"
namespace m1une {
namespace graph {
namespace four_cycle_detail {
// Counts C4s containing one particular copy of each edge in a simple graph
// whose edge weights represent parallel-edge multiplicities.
inline std::vector<long long> count_simple_per_edge(
int vertex_count,
std::vector<int> first,
std::vector<int> second,
const std::vector<long long>& multiplicity
) {
const int edge_count = int(first.size());
assert(second.size() == first.size());
assert(multiplicity.size() == first.size());
std::vector<int> degree(vertex_count, 0);
for (int edge = 0; edge < edge_count; edge++) {
degree[first[edge]]++;
degree[second[edge]]++;
}
int maximum_degree = 0;
for (int value : degree) maximum_degree = std::max(maximum_degree, value);
std::vector<int> degree_start(maximum_degree + 2, 0);
for (int value : degree) degree_start[value + 1]++;
for (int value = 0; value <= maximum_degree; value++) {
degree_start[value + 1] += degree_start[value];
}
std::vector<int> cursor = degree_start;
std::vector<int> order(vertex_count);
for (int vertex = 0; vertex < vertex_count; vertex++) {
order[cursor[degree[vertex]]++] = vertex;
}
std::vector<int> rank(vertex_count);
for (int i = 0; i < vertex_count; i++) rank[order[i]] = i;
for (int edge = 0; edge < edge_count; edge++) {
first[edge] = rank[first[edge]];
second[edge] = rank[second[edge]];
if (first[edge] < second[edge]) {
std::swap(first[edge], second[edge]);
}
}
std::vector<int> start(vertex_count + 1, 0);
for (int vertex = 0; vertex < vertex_count; vertex++) {
start[vertex + 1] = start[vertex] + degree[order[vertex]];
}
std::vector<int> end = start;
std::vector<int> edge_at(2 * edge_count);
std::vector<int> to(2 * edge_count);
for (int edge = 0; edge < edge_count; edge++) {
int position = end[first[edge]]++;
edge_at[position] = edge;
to[position] = second[edge];
}
std::vector<int> downward_end = end;
for (int vertex = 0; vertex < vertex_count; vertex++) {
for (int i = start[vertex]; i < downward_end[vertex]; i++) {
int edge = edge_at[i];
int neighbor = to[i];
int position = end[neighbor]++;
edge_at[position] = edge;
to[position] = vertex;
}
}
std::vector<long long> path_count(vertex_count, 0);
std::vector<long long> result(edge_count, 0);
for (int vertex = vertex_count - 1; vertex >= 0; vertex--) {
for (int i = start[vertex]; i < end[vertex]; i++) {
int first_edge = edge_at[i];
int middle = to[i];
end[middle]--;
for (int j = start[middle]; j < end[middle]; j++) {
int second_edge = edge_at[j];
int opposite = to[j];
path_count[opposite] +=
multiplicity[first_edge] * multiplicity[second_edge];
}
}
for (int i = start[vertex]; i < end[vertex]; i++) {
int first_edge = edge_at[i];
int middle = to[i];
for (int j = start[middle]; j < end[middle]; j++) {
int second_edge = edge_at[j];
int opposite = to[j];
long long other_paths =
path_count[opposite] -
multiplicity[first_edge] * multiplicity[second_edge];
result[first_edge] +=
other_paths * multiplicity[second_edge];
result[second_edge] +=
other_paths * multiplicity[first_edge];
}
}
for (int i = start[vertex]; i < end[vertex]; i++) {
int middle = to[i];
for (int j = start[middle]; j < end[middle]; j++) {
path_count[to[j]] = 0;
}
}
}
return result;
}
} // namespace four_cycle_detail
// Returns, for every graph edge id, the number of C4 subgraphs containing it.
// Parallel active edges are distinct choices; inactive edges receive zero.
template <class T>
std::vector<long long> count_four_cycles_per_edge(const Graph<T>& graph) {
struct ActiveEdge {
int first;
int second;
int id;
};
std::vector<ActiveEdge> active_edges;
active_edges.reserve(graph.edge_count());
for (const Edge<T>& edge : graph.edges()) {
assert(edge.from != edge.to);
assert(0 <= edge.id && edge.id < graph.edge_count());
if (edge.from == edge.to) continue;
active_edges.push_back(ActiveEdge{
std::min(edge.from, edge.to),
std::max(edge.from, edge.to),
edge.id
});
}
std::sort(
active_edges.begin(),
active_edges.end(),
[](const ActiveEdge& left, const ActiveEdge& right) {
return std::tie(left.first, left.second) <
std::tie(right.first, right.second);
}
);
std::vector<int> first;
std::vector<int> second;
std::vector<long long> multiplicity;
std::vector<int> group_of_edge(graph.edge_count(), -1);
first.reserve(active_edges.size());
second.reserve(active_edges.size());
multiplicity.reserve(active_edges.size());
for (const ActiveEdge& edge : active_edges) {
if (first.empty() || first.back() != edge.first ||
second.back() != edge.second) {
first.push_back(edge.first);
second.push_back(edge.second);
multiplicity.push_back(0);
}
multiplicity.back()++;
group_of_edge[edge.id] = int(first.size()) - 1;
}
std::vector<long long> simple_result =
four_cycle_detail::count_simple_per_edge(
graph.size(),
std::move(first),
std::move(second),
multiplicity
);
std::vector<long long> result(graph.edge_count(), 0);
for (const ActiveEdge& edge : active_edges) {
result[edge.id] = simple_result[group_of_edge[edge.id]];
}
return result;
}
template <class T>
long long count_four_cycles(const Graph<T>& graph) {
std::vector<long long> per_edge = count_four_cycles_per_edge(graph);
long long incidence_count = 0;
for (long long count : per_edge) incidence_count += count;
assert(incidence_count % 4 == 0);
return incidence_count / 4;
}
} // namespace graph
} // namespace m1une