Let G=(V,E,w) be a directed and weighted graph with edge weights w(e), whi...
Feb 11, 2024
Let G=(V,E,w) be a directed and weighted graph with edge weights w(e), which can be negative or positive or zero, for each edge e∈E. You may assume that G has no negatively weighted cycles. Additionally, each vertex is coloured either red or blue. Recall that a walk is a sequence of edges joining a sequence of vertices; there are no restrictions on the edges or vertices (i.e. they may repeat or not repeat).
Given an integer k≥2, describe an O(kn(km+n)) algorithm that returns a walk with the smallest weight, satisfying the following conditions:
- The walk starts and ends on a vertex coloured red, and
- The number of vertices coloured blue in the walk is divisible by k.
Note. For a directed and weighted graph G=(V,E,w) where the edge weights can be negative, BellmanFord will compute the shortest distance from a vertex u to every vertex in time O(∣V∣⋅∣E∣). We will see how it works later but for now, you may use it as a black box.
Hint. Try constructing your edges in layers modulo k. You should have km+2n edges and kn+2 vertices in your new graph.
Solution by Steps
step 1
Construct a new graph G′ with k layers to account for the number of blue vertices modulo k. Each layer represents a different remainder when dividing the count of blue vertices by k
step 2
For each vertex v in the original graph G, create k copies in G′, one for each layer. This results in k⋅∣V∣ vertices. Additionally, add two special vertices: a source s and a sink t
step 3
For each edge e=(u,v) in G, create k directed edges in G′ connecting the corresponding vertices in consecutive layers, with the same weight w(e). This results in k⋅∣E∣ edges
step 4
Add edges with weight 0 from the source s to every copy of the red vertices in the first layer and from every copy of the red vertices in the last layer to the sink t. This adds 2⋅∣V∣ edges
step 5
Use the Bellman-Ford algorithm to find the shortest path from s to t in G′. Since Bellman-Ford runs in O(∣V∣⋅∣E∣), and G′ has k⋅∣V∣+2 vertices and k⋅∣E∣+2⋅∣V∣ edges, the total time complexity is O(k⋅∣V∣⋅(k⋅∣E∣+2⋅∣V∣))
Answer
The algorithm described above will return a walk with the smallest weight that starts and ends on a vertex coloured red, with the number of vertices coloured blue in the walk being divisible by k, in O(k⋅∣V∣⋅(k⋅∣E∣+2⋅∣V∣)) time.
Key Concept
Graph Transformation and Layering
Explanation
The key concept is transforming the original graph into a layered graph that encodes the condition of having a number of blue vertices divisible by k and then applying a shortest path algorithm to find the desired walk.