CSES - Graph Girth

Authors: Benjamin Qi, Andi Qu

Table of Contents


Edit on Github

Let's consider a simpler problem: given a graph, find the shortest cycle that passes through node 1.

What does a cycle through node 1 look like? In any cycle through node 1, there exists two nodes and on that cycle such that there is a path from 1 to and 1 to , and there is an edge between and . The length of this cycle is .

One might now try to use BFS to find for each in time and then check for each edge whether is minimal.

Of course, this means that we might count a "cycle" like . However, this doesn't matter for our original problem, since the shortest cycle will always be shorter than such a "cycle".

There's one problem with this approach though: if the edge is on the path from node 1 to node , then isn't a cycle! And this time, it does matter in our original problem!

Fortunately, there's a relatively simple fix.

Instead of first finding all and then checking for the minimum, do both at the same time during the BFS.

Now to prevent "backtracking", we only consider as a minimum if we're currently at node and .

This algorithm runs in time. Since and are so small, we can just apply this algorithm for all nodes instead of just node 1.

The final complexity of this solution is thus .

1#include <bits/stdc++.h>
2using namespace std;
3
4using ll = long long;
5using ld = long double;
6using db = double;
7using str = string; // yay python!
8
9using pi = pair<int,int>;
10using pl = pair<ll,ll>;
Optional: BFS-Cycle

We can modify the algorithm above to return either the length of the shortest cycle or the length of the shortest cycle plus one in time. See here for details.

1#include <bits/stdc++.h>
2using namespace std;
3
4using ll = long long;
5using ld = long double;
6using db = double;
7using str = string; // yay python!
8
9using pi = pair<int,int>;
10using pl = pair<ll,ll>;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

Give Us Feedback on CSES - Graph Girth!