Pagini recente » Cod sursa (job #440945) | Cod sursa (job #1971512) | Cod sursa (job #1922332) | Cod sursa (job #1027549) | Cod sursa (job #2030936)
#include <fstream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
const int MAX = 50001;
const int INF = 1 << 20;
struct comp
{
bool operator() (const pair<int, int> &a, const pair<int, int> &b)
{
return a.second > b.second;
}
};
priority_queue< pair<int, int>, vector< pair<int, int> >, comp> Q;
vector< pair<int, int> > G[MAX];
int D[MAX];
int N, M;
bool viz[MAX];
void citire()
{
ifstream f ("dijkstra.in");
int x, y, cost;
f >> N >> M;
for (int i = 1; i <= M; i++)
{
f >> x >> y >> cost;
G[x].push_back (pair<int, int> (y, cost) );
if (x == 1) D[y] = cost;
}
f.close();
}
void dijkstra()
{
int i, vf, nod, cost, lg;
while (!Q.empty() )
{
vf = Q.top().first;
Q.pop();
if (viz[vf]) continue;
lg = G[vf].size();
for (i = 0; i < lg; i++)
{
nod = G[vf][i].first;
cost = G[vf][i].second;
if (!viz[nod] && D[vf] + cost < D[nod])
{
D[nod] = D[vf] + cost;
Q.push (pair<int, int> (nod, D[nod]) );
}
}
viz[vf] = true;
}
}
void afisare()
{
ofstream g ("dijkstra.out");
for (int i = 2; i <= N; i++)
if (D[i] < INF) g << D[i] << ' ';
else g << 0 << ' ';
g.close();
}
int main()
{
citire();
for (int i = 1; i <= N; i++) D[i] = INF;
D[1] = 0;
Q.push (pair<int, int> (1, D[1]) );
dijkstra();
afisare();
return 0;
}