Sandomhet

Shortest Path DP

Wed, Jul 10, 2024 1 min read

Shortest Path DP

Bellman-Ford DP

Setup:

  • Input: A directed graph G=(V,E)G = (V, E) with edge weights w(u,v)w(u, v), a source node ss, and a target node tt.
  • Output: The length of the shortest path from ss to tt.

Steps:

  1. Subproblem: di,vd_{i,v} be the shortest path from source node ss to node vv with at most ii edges.
  2. Recurrence relation:
di,v=min⁡(u,v)∈E{di−1,u+w(u,v)}d_{i,v} = \min\limits_{(u, v) \in E} \{d_{i-1,u} + w(u, v)\}
  1. Answer: dn−1,td_{n-1,t}.

O(nm)O(nm)

int BellmanFord(int n, int m, vector<tuple<int, int, int>> edges, int s, int t) {
    vector<int> d(n, INT_MAX);
    d[s] = 0;
    for (int i = 1; i < n; i++) {
        for (auto [u, v, w] : edges) {
            if (d[u] != INT_MAX) {
                d[v] = min(d[v], d[u] + w);
            }
        }
    }
    return d[t] == INT_MAX ? -1 : d[t];
}

Floyd-Warshall DP

Setup:

  • Input: A directed graph G=(V,E)G = (V, E) with edge weights w(u,v)w(u, v).
  • Output: A matrix DD where D(u,v)D(u, v) is the length of the shortest path from vertex uu to vertex vv.

Steps:

  1. Subproblem: Dk(u,v)D_{k}(u, v) be the length of the shortest path from vertex uu to vertex vv using only intermediate vertices from the set {1,2,…,k}\{1, 2, \ldots, k\}.
  2. Recurrence relation:
Dk(u,v)=min⁡{Dk−1(u,v),Dk−1(u,k)+Dk−1(k,v)}D_{k}(u, v) = \min\{D_{k-1}(u, v), D_{k-1}(u, k) + D_{k-1}(k, v)\}
  1. Answer: Dn(u,v)D_{n}(u, v) for all pairs (u,v)(u, v).

O(n3)O(n^3)

bool floyd_warshall(vector<vector<int>>& dis, vector<vector<int>>& w) {
    int n = dis.size() - 1;
    dis.assign(n + 1, vector<int>(n + 1, INF / 2));
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++)
            dis[i][j] = w[i][j];
        dis[i][i] = min(dis[i][i], 0);
    }
    for (int k = 1; k <= n; k++)
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
                dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);
    
    for (int i = 1; i <= n; i++)
        if (dis[i][i] < 0) return false; // negative cycle exists
    return true;
}
Search

Loading search…