Pagini recente » Borderou de evaluare (job #1293235) | Borderou de evaluare (job #2209715) | Borderou de evaluare (job #1770140) | Borderou de evaluare (job #1035983) | Cod sursa (job #2698194)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int NMax = 50005;
const int inf = (1 << 30);
int N, M;
int D[NMax];
bool InQ[NMax];
vector < pair <int, int> > G[NMax];
struct compara
{
bool operator()(int x, int y)
{
return D[x] > D[y];
}
};
priority_queue<int, vector<int>, compara> Q;
void read()
{
fin >> N >> M;
for (int i = 1; i <= M; i++)
{
int x, y, c;
fin >> x >> y >> c;
G[x].push_back({ y, c });
}
}
void Dijkstra(int nodeStart)
{
// initialie distance vector with inf
for (int i = 1; i <= N; i++)
D[i] = inf;
// distance from frst node to itself is 0
D[nodeStart] = 0;
Q.push(nodeStart);
InQ[nodeStart] = true;
while (!Q.empty())
{
int nodCurent = Q.top();
Q.pop();
InQ[nodCurent] = false;
for (size_t i = 0; i < G[nodCurent].size(); i++)
{
int Vecin = G[nodCurent][i].first;
int Cost = G[nodCurent][i].second;
if (D[nodCurent] + Cost < D[Vecin])
{
D[Vecin] = D[nodCurent] + Cost;
if (InQ[Vecin] == false)
{
Q.push(Vecin);
InQ[Vecin] = true;
}
}
}
}
}
void show()
{
for (int i = 2; i <= N; i++)
{
if (D[i] != inf)
fout << D[i] << " ";
else
fout << "0 ";
}
}
int main()
{
read();
Dijkstra(1);
show();
}