Pagini recente » Cod sursa (job #1984963) | Cod sursa (job #2811925) | Cod sursa (job #1995068) | Cod sursa (job #2181953) | Cod sursa (job #3148804)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int NMAX = 50001;
int n,m;
int cost[NMAX];
/// neighbour, cost
vector < pair<int, int> > v[NMAX];
bool marca[NMAX];
struct compara
{
bool operator()(int x, int y)
{
return cost[x] > cost[y];
}
};
priority_queue<int, vector<int>, compara> q;
void citire()
{
ifstream in("dijkstra.in");
in>> n>> m;
for (int i = 1; i <= m ; i ++)
{
int x,y,c;
in >> x >> y >> c;
v[x].push_back(make_pair(y,c));
}
}
void Dijkstra(int startNode)
{
q.push(startNode);
while(!q.empty())
{
int nod = q.top();
marca[nod] = false;
q.pop();
for (auto item : v[nod])
{
int neigh = item.first;
int c = item.second;
if(cost[neigh] == 0 || cost[neigh] > cost[nod] + c)
{
cost[neigh] = cost[nod] + c;
if(!marca[neigh]){
marca[neigh] = true;
q.push(neigh);
}
}
}
}
}
void afisare()
{
ofstream out("dijkstra.out");
for (int i = 2; i <= n; i ++)
{
out<< cost[i]<<" ";
}
}
int main()
{
citire();
Dijkstra(1);
afisare();
return 0;
}