Pagini recente » Cod sursa (job #2762248) | Cod sursa (job #2676345)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define Nmax 50005
#define PI pair < int, int >
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int vf, muchii, x, y, cost;
int Distanta[Nmax];
vector < pair < int, int > > Numbers[Nmax];
priority_queue < PI, vector < PI >, greater< PI > > Coada;
void Dijkstra( int Nod_S )
{
int Nod, Vecin, Cost;
for( int i = 1; i <= vf; ++ i )
Distanta[i] = 1e9;
Distanta[Nod_S] = 0;
Coada.push({0, Nod_S});
while( !Coada.empty() )
{
Nod = Coada.top().second;
Cost = Coada.top().first;
Coada.pop();
if( Cost > Distanta[Nod] ) // daca avem deja o distanta in vector si gasim un cost mai mare, n are rost sa continuam
continue;
for( unsigned int i = 0; i < Numbers[Nod].size(); ++ i )
{
Vecin = Numbers[Nod][i].first;
Cost = Numbers[Nod][i].second;
if( Distanta[Nod] + Cost < Distanta[Vecin] )
{
Distanta[Vecin] = Distanta[Nod] + Cost;
Coada.push({Distanta[Vecin], Vecin});
}
}
}
}
int main()
{
fin >> vf >> muchii;
for( int i = 1; i <= muchii; ++ i )
{
fin >> x >> y >> cost;
Numbers[x].push_back({y, cost});
}
Dijkstra(1);
for( int i = 2; i <= vf; ++ i )
fout << Distanta[i] << " ";
return 0;
}