Pagini recente » Cod sursa (job #2169987) | Cod sursa (job #1980569) | Cod sursa (job #1998346) | Cod sursa (job #993259) | Cod sursa (job #3257054)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int n, m;
int main()
{ int a, b, c;
f >> n >> m;
vector<vector<pair<long long, int>>> graf(n+1);
vector<long long>cost((n+1),(1<<30));
priority_queue<pair<long long, int>>s;
vector<bool>viz(n+1);
for (int i=1; i<=m; i++)
{ f >> a >> b >> c;
graf[a].push_back({c, b});
graf[b].push_back({c, a});
}
s.push({0, 1});
cost[1] = 0;
while(!s.empty())
{
pair<long long, int> smallest = s.top();
s.pop();
if(viz[smallest.second]) continue;
viz[smallest.second] = 1;
for(int i=0; i<graf[smallest.second].size(); i++)
{
int node = graf[smallest.second][i].second;
int val = graf[smallest.second][i].first;
if(-smallest.first + val < cost[node])
{
cost[node] = -smallest.first + val;
s.push({-cost[node], node});
}
}
}
for (int i=2; i<=n; i++) g << cost[i] << ' ';
return 0;
}