Pagini recente » Cod sursa (job #969217) | Cod sursa (job #2497508) | Cod sursa (job #1979833) | Cod sursa (job #2569588) | Cod sursa (job #3216869)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
//https://www.infoarena.ro/problema/dijkstra
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
const int NMAX = 100001;
struct PATH{
int nod,cost;
};
//nod, cost to nod
vector<PATH>v[NMAX];
int cost[NMAX];
bool masca[NMAX];
struct compara
{
bool operator()(int x, int y)
{
return cost[x] > cost[y];
}
};
priority_queue<int, vector<int>, compara> q;
int n, m;
void reading(){
in>> n>> m;
for (int i = 0; i < m; i++){
int x, y, c;
in>> x >> y >> c;
v[x].push_back({y,c});
}
}
void Dijkstra(int start){
for (int i = 1; i <=n;i++)
cost[i]=-1;
cost[start] = 0;
q.push(start);
while(!q.empty()){
int nod = q.top();
q.pop();
for( PATH neigh_path : v[nod]){
int neigh = neigh_path.nod;
int c = neigh_path.cost;
int NewC = cost[nod] + c;
if(cost[neigh]==-1 || NewC < cost[neigh]){
cost[neigh] = NewC;
q.push(neigh);
}
}
}
}
void output(){
for (int i = 2; i <= n; i++){
if(cost[i]!=-1)
out << cost[i] << " ";
else out << "0 ";
}
}
int main(){
reading();
Dijkstra(1);
output();
}