Pagini recente » Cod sursa (job #3146749) | Cod sursa (job #3216918) | Cod sursa (job #3178136) | Cod sursa (job #1055436) | Cod sursa (job #1502890)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
#define nmax 50001
#define mmax 250001
#define inf 1<<30
int n, m;
int Cost[nmax];
vector < pair <int, int> > G[nmax];
queue < pair <int, int> > q;
ifstream fi("dijkstra.in");
ofstream fo("dijkstra.out");
void read()
{
int a, b, c;
fi >> n >> m;
for (int i = 1; i <= m; i++)
{
// nodul 1, nodul 2, cost
fi >> a >> b >> c;
G[a].push_back(make_pair(b, c));
}
}
void init()
{
// nodul curent, costul de la nodul 1 pana la nodul curent
q.push(make_pair(1, 0));
for (int i = 2; i <= n; i++)
Cost[i] = inf;
}
void dijkstra()
{
init();
while (!q.empty())
{
int nodulCurent = q.front().first;
int costulCurent = q.front().second;
q.pop();
for (int i = 0; i < G[nodulCurent].size(); i++)
{
int vecin = G[nodulCurent][i].first;
int costulVecin = G[nodulCurent][i].second;
if (costulVecin + costulCurent < Cost[vecin])
{
Cost[vecin] = costulVecin + costulCurent;
q.push(make_pair(vecin, Cost[vecin]));
}
}
}
}
void write()
{
for (int i = 2; i <= n; i++)
{
if (Cost[i] == inf)
fo << 0 << " ";
else
fo << Cost[i] << " ";
}
}
int main()
{
read();
dijkstra();
write();
return 0;
}