Pagini recente » Cod sursa (job #637467) | Cod sursa (job #422779) | Cod sursa (job #2175442) | Cod sursa (job #2918341) | Cod sursa (job #2930092)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int N = 5e4 + 1;
vector <pair<int, int>> L[N];
vector<int> dist;
priority_queue< pair<int, int>, vector<pair <int, int> >, greater<pair<int, int> > > pq;
int n;
void Read()
{
ifstream fin ("dijkstra.in");
int m;
fin >> n >> m;
while(m--)
{
int x, y, c;
fin >> x >> y >> c;
L[x].push_back({y, c});
}
fin.close();
}
void Dijkstra()
{
dist.resize(n + 1, 2e9);
dist[1] = 0;
pq.push({0, 1});
while (!pq.empty())
{
pair <int, int> curr = pq.top(); // curr.first = distanta, curr.second = nod
pq.pop();
for (auto& next : L[curr.second]) //next.first = nod adiacent, next.second = costul muchiei pana la next.first
if (dist[next.first] > next.second + curr.first)
{
dist[next.first] = next.second + curr.first;
pq.push({dist[next.first], next.first});
}
}
ofstream fout ("dijkstra.out");
for (int i = 2; i <= n; i++)
(dist[i] == 2e9) ? fout << "-1 " : fout << dist[i] << " ";
fout.close();
}
int main() {
Read();
Dijkstra();
return 0;
}