Pagini recente » Cod sursa (job #2351738) | Cod sursa (job #3253608)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 50001
#define INF 1000000000
using namespace std;
vector <pair<int,int>> edges[NMAX];
int d[NMAX];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int,int>>> pq;
// M log N
ifstream fin( "dijkstra.in" );
ofstream fout( "dijkstra.out" );
void djikstra( int source, int n ) {
for( int i = 2; i <= n; i++ ) d[i] = INF;
d[source] = 0;
pq.push( { d[source], source } );
while( !pq.empty() ) {
pair<int,int> pr = pq.top();
int dist = pr.first;
int node = pr.second;
pq.pop();
for( auto pr : edges[node] ) {
int newnode = pr.first;
int cost = pr.second;
if( d[newnode] > dist + cost ) {
d[newnode] = dist + cost;
pq.push( { d[newnode], newnode } );
}
}
}
}
int main() {
int n, m, x, y, c;
fin >> n >> m;
for( int i = 0; i < m; i++ ) {
fin >> x >> y >> c;
edges[x].push_back( { y, c } );
}
djikstra( 1, n );
for( int i = 2; i <= n; i++ ) {
if( d[i] == INF ) fout << 0 <<' ';
else fout << d[i] << ' ';
}
return 0;
}