Pagini recente » Cod sursa (job #1012645) | Cod sursa (job #851037) | Cod sursa (job #2978656) | Cod sursa (job #3200724) | Cod sursa (job #3216853)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int NMAX = 100001; ///MMAX = 250001
const int INF = 0;
struct muchie
{
int y, w; ///w - cost muchie
bool operator <(const muchie &m) const ///am supraincarcat '<' -> operatorul de supraincarcare;
{
return m.w < w;
}
};
int N, M;
int D[NMAX]; ///D DE i = dist min de la p la i
vector <muchie> G[NMAX]; /// g de i = lista muchiilor incidente cu i -> avem nu doar muchiile, ci si costurile asociate
priority_queue<muchie> Q;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
void citire()
{
int x, y, w; ///w = cost asociat muchiei x, y;
f >> N >> M;
for (int i = 1 ; i <= M ; ++i)
{
f >> x >> y >> w;
G[x].push_back({y, w});
G[y].push_back({x, w});
}
}
void Dijkstra(int nod)
{
D[nod] = 0;
Q.push({nod, 0});
while (!Q.empty())
{
muchie crt = Q.top(); ///Se extrage un nod din coada cu cel mai mic cost (cea mai mica distanta asociata)
Q.pop();
if (crt.w > D[crt.y]) ///if (crt.w != D[crt.y])
continue;
for (muchie& m : G[crt.y])
{
int cost = D[crt.y] + m.w;
if (D[m.y] > cost)
{
D[m.y] = cost;
Q.push({m.y, D[m.y]});
}
}
}
}
int main()
{
int i;
citire();
//
for (i = 1 ; i <= N ; ++i)
{
D[i] = INF;
}
Dijkstra(1);
//
for (i = 1 ; i <= N; ++i)
if (D[i] == INF)
g << "-1 ";
else
g << D[i] << ' ';
return 0;
}