Pagini recente » Cod sursa (job #2514208) | Cod sursa (job #2418527) | Cod sursa (job #525781) | Cod sursa (job #1435473) | Cod sursa (job #2312675)
/* Dijkstra's algotithm
- single souce shortest path finding algorithm
- ! does not allow negative weights
- generates a shortest path tree with given source as root
Algorithm approach
1. create a sptSet-shortest path tree set which keeps track of
the vertices whose min distance from source is calculated and finalized
2. initialize all nodes with minimum distance of infinite (and for the source distance value 0)
3. while sptSet doesn't include all nodes
a. pick u-the vertex with the shortest distance from source
b. insert it into the sptSet
c. relax all edges incident to u and update the min dist for adjacent vertices
*/
#include <bits/stdc++.h>
#define maxN 50002
FILE *fin = freopen("dijkstra.in", "r", stdin);
FILE *fout = freopen("dijkstra.out", "w", stdout);
using namespace std;
const int oo = 5e9+10;
int nodes, edges;
int source;
struct Node {
int node;
long long dist;
bool operator < (const Node &oth) const{
return dist > oth.dist;
}
};
vector <Node> g[maxN];
long long ans[maxN];
bitset <maxN> sptSet; // initially empty
// use a queue for not processed nodes(not in sptSet)
priority_queue <Node, vector<Node>> q;
void dijkstra() {
while(!q.empty()) {
Node u = q.top(); q.pop();
if(sptSet.test(u.node)) continue; // check if the node has already been processed
if (ans[u.node] == oo) ans[u.node] = 0;
else{
for(auto v : g[u.node]) // iterate through all neighbours
if (ans[v.node] > ans[u.node] + v.dist){
ans[v.node] = ans[u.node] + v.dist;
q.push(Node{v.node, ans[v.node]});
}
}
sptSet.set(u.node);
}
}
int main() {
source = 1;
scanf ("%d%d",&nodes, &edges);
for (int i = 0; i < edges; ++ i) {
int from, to, distance;
scanf("%d%d%d", &from, &to, &distance);
g[from].push_back(Node{to, distance});
}
for (int i = 1; i <= nodes; ++i)
if(i != source) {
q.push(Node{i, oo});
ans[i] = oo;
}
q.push(Node{source, 0});
dijkstra();
for (int i = 1; i <= nodes; ++i)
if (i != source) {
printf("%lld ", ans[i]);
}
return 0;
}