Pagini recente » Cod sursa (job #1146378) | Cod sursa (job #2590839) | Cod sursa (job #2319374) | Cod sursa (job #2306741) | Cod sursa (job #2420671)
#include<bits/stdc++.h>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
constexpr int NX = 50002;
constexpr int inf = 20002;
int N, M;
int viz[NX];
stack <int> S;
int dist[NX];
vector <pair <int, int>> V[NX];
priority_queue < pair <int, int> , vector <pair <int, int>>, greater <pair <int, int>> > pq;
int main()
{
fin>>N>>M; //citesc nr de noduri si muchiile
int x, y, c;
for(int i=1; i<=M; ++i)
{
fin>>x>>y>>c;
V[x].push_back( {y, c} ); //le bag in lista de vecini
}
//iau nodul 1 ca sursa
dist[1] = 0; //ii fac dist 0
pq.push( {0, 1} ); //bag in pq nodul 1 cu costul 0
for(int i=2; i<=N; ++i)
{
dist[i] = inf;
pq.push( {dist[i], i} ); //pun nodurile in pq
}
while(!pq.empty())
{
int nod = pq.top().second;
for(auto &i: V[nod])
{
int oDist = dist[nod] + i.second; //distanta nodului plus cea a vecinului
if(oDist < dist[i.first]) //optimizez
{
dist[i.first] = oDist;
}
}
pq.pop(); //scot
}
for(int i=2; i<=N; ++i) //afisez
{
if(dist[i]==inf)
fout << 0 <<" ";
else
fout<<dist[i]<<" ";
}
return 0;
}