Pagini recente » Cod sursa (job #869536) | Cod sursa (job #1798924) | Cod sursa (job #1643743) | Cod sursa (job #221375) | Cod sursa (job #2418731)
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
const int inf = 1 << 30;
const int nmax = 50001;
struct node {
int noUrm;
int cost;
node *next;
};
node *graph[nmax];
int distanta[nmax];
int vizitat[nmax];
int n, m;
void add( int n1, int n2, int cost ) {
node * nod = new node;
nod->cost = cost;
nod->next = graph[n1];//adaug la inceput
nod->noUrm = n2;
graph[n1] = nod;
}
void read() {
f >> n >> m;
for( int i = 0; i < m; i++) {
int n1, n2, cost;
f >> n1 >> n2 >> cost;
add( n1, n2, cost);
}
}
void dijkstra() {
for( int i = 2; i <= n; i++)
distanta[i] = inf;
for( int i = 1; i <= n; i++ ) {
int distantaMinim = inf, nodMinim;
for( int j = 1; j <= n; j++)
if( distantaMinim >= distanta[j] && !vizitat[j] )
distantaMinim = distanta[j], nodMinim = j;
vizitat[nodMinim] = 1;
node * start = graph[ nodMinim ];
while( start ) {
if( distanta[ start->noUrm ] > start->cost + distanta[nodMinim] )
distanta[ start->noUrm ] = start->cost + distanta[nodMinim];
start = start->next;
}
}
}
int main() {
read();
dijkstra();
for( int i = 2; i <= n; i++ )
if( distanta[i] == inf ) g << 0 << " ";
else g << distanta[i] << " ";
return 0;
}