graph - Dijkstra's Algorithm With Negative Weights (But No Negative Cycles) -
i believe implementation of dijkstra's algorithm below works graphs negative weights no cycles negative sum.
however, have seen many people dijkstra's doesn't work graphs negative weights, believing either algorithm wrong or execution time far slower dijkstra's algorithm.
i wondering if please me code? thank help!
(edit: question different others since wondering if execution time of algorithm far longer dijkstra's algorithm since nodes may visited multiple times)
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > g[n]; int cost[n]; int main() { queue<int> q; q.push(0); cost[0] = 0; for(int i=1; i<n; i++) { cost[i] = infinity; } while(! q.empty()) { int v = q.front(); q.pop(); for(int i=0; i<g[v].size(); i++) { if(cost[g[v][i].first] > cost[v] + g[v][i].second) { cost[g[v][i].first] = cost[v] + g[v][i].second; q.push(g[v][i].first); } } } }
even if correct (didn't prove it, seems be), your algorithm suffers bad time complexity.
specifically, if @ complete dag:
g = (v, e, w) v = {1, ..., n} e = { (i,j) | < j } w(u,v) = 2^ (v - u) and simplicity of example assume algorithm traverses edges in reverse order ((u,v) before (u,x) if x < v) (note simplification, , without can build counter example reversing directions of edges).
note algorithm reopens each edge every time opens it. means traverse paths in graph, exponential in number of nodes.
Comments
Post a Comment