This repository has been archived on 2022-06-22. You can view files and clone it, but cannot push or open issues or pull requests.
usaco-guide/content/5_Gold/Cyc.mdx
2020-06-26 23:07:31 -04:00

94 lines
No EOL
2.4 KiB
Text

---
id: cyc
title: Cycle Detection
author: Siyong Huang
prerequisites:
- Gold - Topological Sort
description: A simple cycle is a non-empty path of distinct edges that start and end at the same vertex such that no vertex appears more than once. Describes how to detect cycles in both directed and undirected graphs.
frequency: 0
---
import { Problem } from "../models";
export const metadata = {
problems: {
und: [
new Problem("CSES", "Round Trip", "1669", "Easy", false, ["Cycle"]),
],
dir: [
new Problem("CSES", "Round Trip II", "1678", "Easy", false, ["Cycle"]),
],
general: [
new Problem("CSES", "Graph Girth", "1707", "Easy", false, ["Cycle"]),
],
}
};
*Cycle detection* determines properties of cycles in a directed or undirected graph, such as whether each node of the graph is part of a cycle or just checking whether a cycle exists.
## Undirected Graphs
<problems-list problems={metadata.problems.und} />
<optional-content title="+1 Approximation for Shortest Cycle">
An algorithm known as **BFS-Cycle** returns an integer that is at most one more than the length of the shortest cycle in $O(N^2)$ time; see page 4 [here](https://people.csail.mit.edu/virgi/6.890/lecture9.pdf) for details.
</optional-content>
## Directed Graphs
<problems-list problems={metadata.problems.dir} />
The same general idea is implemented below to find any cycle in a directed graph (if one exists). Note that this is almost identical to the DFS algorithm for topological sorting.
```cpp
//UNTESTED
bool visited[MAXN], on_stack[MAXN];
vector<int> adj[MAXN];
vector<int> cycle;
bool dfs(int n)
{
visited[n] = on_stack[n] = true;
for(int u:adj[n])
{
if(on_stack[u])
return cycle.push_back(v), cycle.push_back(u), on_stack[n] = on_stack[u] = false, true;
else if(!visited[u])
{
if(dfs(u))
if(on_stack[n])
return cycle.push_back(n), on_stack[n] = false, true;
else
return false;
if(!cycle.empty())
return false;
}
}
on_stack[n] = false;
return false;
}
int main()
{
//take input, etc
for(int i = 1;cycle.empty() && i <= N;i++)
dfs(i);
if(cycle.empty())
printf("No cycle found!\n");
else
{
reverse(cycle.begin(), cycle.end());
printf("Cycle of length %u found!\n", cycle.size());
for(int n : cycle) printf("%d ", n);
printf("\n");
}
}
```
## Problems
<problems-list problems={metadata.problems.general} />
VT-HSPC 2019?