1
$\begingroup$

Given a directed graph $G=(V,E)$, such that the nodes are colored with $k=\lfloor{log_2(n)\rfloor}$ colors. Describe an algorithm that determines whether a cycle of length $k$ containing every color exists.

My idea was to use dynamic programming like so: I denote the colors as $C=\{1,2,...,k\}$. For every pair of vertices $x,y$ and subset $S \subseteq C$, $dp[x,y,S]=true$ if there exists a path from $x$ to $y$ of length $|S|$ that uses all the colors in $S$.

We start building the table by $dp[x,x,\{color(x)\}]=true$ for every $x\in V$ where $color(x)$ denotes the color of vertex $x$. And then, for every pair of vertices $x,y$ and subset $S$:

If $dp[x,y,S]$ is not yet filled, then we go over every neighbor $z$ of $x$: If $color(z)\in S$ then let $S'=S\backslash\{color(z)\}$, and we check whether $dp[y,z,S']=true$. If both of the above conditions are met for some neighbor $z$, then $dp[x,y,S]=true$.

This solution seems like it works to me, but my issue is efficiency. It seems like this problem can be solved in $O(n^3)$ time, but this solution takes $O(n^4)$ time.

$\endgroup$
2
  • 1
    $\begingroup$ Perhaps if you check carefully, you will discover that your algorithm runs in time $O(n \cdot m \cdot 2^k) = O(n^2 m)$. Why do you say that the problem seems to be solvable in $O(n^3)$ time? $\endgroup$ Commented Oct 9 at 14:24
  • $\begingroup$ @JohnKemeny Can you explain why the algorithm runs in $O(n^2 m)$ time? I have $O(n^2)$ pairs of vertices, and $O(n)$ subsets of $X$, and every vertex can have at most $O(n)$ neighbors. So Iterating over pairs of vertices and subsets totaling $O(n^3)$ iterations, and in each iteration going over $O(n)$ neighbors, so I get a run time of $O(n^4)$ $\endgroup$
    – Muffinator
    Commented Oct 13 at 8:09

1 Answer 1

0
$\begingroup$

Continuing from the comment.

A classic observation is that $\sum_{v \in V} \deg(v) = 2m = O(m)$.

This means that when you run two for loops:

for v in V:
    for u in N(v):
        counter = counter + 1

the inner instruction happens exactly $2m$ times (ie you visit each edge twice).

So, yes, while your DP table has $n^2 2^k$ many cells and each cell takes time $O(n)$ time to compute, a more careful analysis shows that you can compute it all in $O(n^2 m)$ time, simply because you don't use $\Theta(n)$ time to fill in the cell of a specific vertex $v$, but $\Theta(\deg(v))$.

I encourage you to implement it, in eg. Python, and observe that the inner loop runs precisely $2 n m 2^k$ times.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.