Pagini recente » Cod sursa (job #35334) | Cod sursa (job #2311427) | Cod sursa (job #943471) | Cod sursa (job #2541437) | Cod sursa (job #2390259)
#include <iostream>
#include <stdio.h>
#include <queue>
#define NMAX 50000
#define MMAX 250000
#define INFINIT 1000000000
using namespace std;
struct muchie {
int u ;
int v ;
int cost ;
bool operator < ( const muchie& aux) const {
return cost > aux.cost ;
}
};
struct nod {
int v ;
int cost ;
};
int dist [ NMAX + 1 ] ;
priority_queue <muchie> q ;
vector <nod> g [ NMAX + 1 ] ;
void dijkstra (int sursa) {
dist[sursa] = 0 ;
for (auto y : g[sursa] )
q.push({sursa, y.v, y.cost}) ;
while (!q.empty()) {
int dela = q.top().u ;
int catre = q.top().v ;
int cost = q.top().cost ;
q.pop() ;
if (dist[catre] == INFINIT ) {
dist[catre] = dist[dela] + cost ;
for (auto y : g[catre])
q.push({catre, y.v, y.cost}) ;
}
}
}
int main() {
FILE *fin, *fout ;
fin = fopen ("dijkstra.in", "r" ) ;
fout = fopen ("dijkstra.out", "w" ) ;
int n, m, i, a, b, cost ;
fscanf (fin, "%d%d", &n, &m ) ;
for (i = 0 ; i < m ; i++ ) {
fscanf (fin, "%d%d%d", &a, &b, &cost ) ;
g[a].push_back({b, cost}) ;
}
for (i = 1 ; i <= n ; i++ )
dist[i] = INFINIT ;
dijkstra(1) ;
for (i = 2 ; i <= n ; i++ ) {
if (dist[i] == INFINIT )
fprintf (fout, "%d ", 0 ) ;
else
fprintf (fout, "%d ", dist[i] ) ;
}
return 0;
}