I believe that the implementation of Dijkstra's Algorithm below works for all graphs with negative weights but no cycles with a negative sum.
However, I have seen many people say that Dijkstra's doesn't work for graphs with negative weights, so I am believing that either the algorithm is wrong or the execution time is far slower than Dijkstra's Algorithm.
I was just wondering if someone could please help me with this code? Thank you very much for all your help!
(Edit: This question is different from others since I am also wondering if the execution time of this algorithm is far longer than Dijkstra's Algorithm since nodes may be 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);
}
}
}
}